text
stringlengths
3
1.05M
var Promise = require('bluebird'); var request = require('request'); var pRequest = function (options) { return new Promise((resolve, reject) => { request(options, (err, response, body) => { if (err) reject(err); resolve({ response, body }); }); }); }; function buildOptions(token, endPoint, path, method, body = {}) { return { uri: endPoint + path, headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'GoCardless-Version': '2015-07-06', 'Content-Type': 'application/json' }, body, method, json: true }; } function goCardlessRedirectRequest(options) { return pRequest(options) .then((response) => { if (!response.body.redirect_flows) throw response.body; else return response.body; }); } function goCardlessRequest(options) { if (options.method === 'GET') delete options.body; return pRequest(options); } function yyyymmdd(date) { var yyyy = date.getFullYear().toString(); var mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based var dd = date.getDate().toString(); return `${yyyy}-${(mm[1] ? mm : `0${mm[0]}`)}-${(dd[1] ? dd : `0${dd[0]}`)}`; // padding } export default class GoCardless { constructor(config) { this.endPoint = config.sandbox ? 'https://api-sandbox.gocardless.com' : 'https://api.gocardless.com'; if (!config.token) throw new Error('missing config.token'); this.token = config.token; } /** * Generic GC API request * @param {string} method "POST", "GET", "PUT", "DELETE" * @param {string} path * @param {mixed} body * @return {Promise<response>} */ request(method, path, body = null) { const options = buildOptions(this.token, this.endPoint, path, method, body); return goCardlessRequest(options); } startRedirectFlow(description, sessionId, succesRedirectUrl) { const body = { redirect_flows: { description, session_token: sessionId, success_redirect_url: succesRedirectUrl } }; const path = '/redirect_flows'; const options = buildOptions(this.token, this.endPoint, path, 'POST', body); return goCardlessRedirectRequest(options); } getRedirectFlow(redirectFlowId) { const path = `/redirect_flows/${redirectFlowId}`; const options = buildOptions(this.token, this.endPoint, path, 'GET'); return goCardlessRedirectRequest(options); } completeRedirectFlow(redirectFlowId, sessionId) { const body = { data: { session_token: sessionId } }; const path = `/redirect_flows/${redirectFlowId}/actions/complete`; const options = buildOptions(this.token, this.endPoint, path, 'POST', body); return goCardlessRedirectRequest(options); } /** * Sends a request for payment creation * https://developer.gocardless.com/pro/2015-07-06/#payments-create-a-payment * @param mandateID REQUIRED ID of the mandate against which payment should be collected * @param amount REQUIRED amount in pence, cents or öre * @param charge_date a future date on which the payment should be collected * @param currency defaults to EUR, either EUR, GBP or SEK * @param description human readable description sent to payer * @param metadata any data up to 3 pairs of key-values * @param internalReference your own internal reference */ createPayment(mandateID, amount, currency = 'EUR', chargeDate = null, description = null, metadata = null, internalReference = null) { const body = { payments: { amount, currency, metadata, charge_date: chargeDate && yyyymmdd(chargeDate), reference: internalReference || '', description: description || '', links: { mandate: mandateID } } }; const path = '/payments'; const method = 'POST'; const options = buildOptions(this.token, this.endPoint, path, method, body); return goCardlessRequest(options); } /** * retrieves single payment by id * https://developer.gocardless.com/pro/2015-07-06/#payments-get-a-single-payment * @param id */ getPayment(id) { const path = `/payments?${id}`; const method = 'GET'; const options = buildOptions(this.token, this.endPoint, path, method, null); return goCardlessRequest(options); } /** * List payments * https://developer.gocardless.com/pro/2015-07-06/#payments-list-payments * @param queryString */ queryPayments(queryString) { const path = `/payments?${queryString}`; const method = 'GET'; const options = buildOptions(this.token, this.endPoint, path, method, null); return goCardlessRequest(options); } /** * Updates a payment Object, accepts only metadata * https://developer.gocardless.com/pro/2015-07-06/#payments-update-a-payment * @param id * @param metadata */ updatePayment(id, metadata) { const path = `/payments?${id}`; const method = 'PUT'; const options = buildOptions(this.token, this.endPoint, path, method, metadata); return goCardlessRequest(options); } /** * Cancels a single payment if not already submitted to the banks, accepts only metadata * https://developer.gocardless.com/pro/2015-07-06/#payments-cancel-a-payment * @param id * @param metadata */ cancelPayment(id, metadata) { const path = `/payments?${id}/actions/cancel`; const method = 'POST'; const options = buildOptions(this.token, this.endPoint, path, method, metadata); return goCardlessRequest(options); } /** * retries a failed payment. you will receive a webhook. * https://developer.gocardless.com/pro/2015-07-06/#payments-retry-a-payment * @param id * @param metadata */ retryPayment(id, metadata) { const path = `/payments?${id}/actions/retry`; const method = 'POST'; const options = buildOptions(this.token, this.endPoint, path, method, metadata); return goCardlessRequest(options); } /** * retrieves single mandate by id * https://developer.gocardless.com/pro/2015-07-06/#mandates-get-a-single-mandate * @param id */ getMandate(id) { const path = `/mandates/${id}`; const method = 'GET'; const options = buildOptions(this.token, this.endPoint, path, method, null); return goCardlessRequest(options); } /** * Sends a request for subscription creation * https://developer.gocardless.com/pro/2015-07-06/#subscriptions-create-a-subscription * @param subscriptionData REQUIRED object to subscription data */ createSubscription(subscriptionData) { var path = '/subscriptions'; var method = 'POST'; var options = buildOptions(this.token, this.endPoint, path, method, subscriptionData); return goCardlessRequest(options); } }
// import formatDistance from './_lib/formatDistance/index.js' // import formatLong from './_lib/formatLong/index.js' // import formatRelative from './_lib/formatRelative/index.js' // import localize from './_lib/localize/index.js' // import match from './_lib/match/index.js' /** * @type {Locale} * @category Locales * @summary Arabic locale (Modern Standard Arabic ). * @language Modern Standard Arabic (Algeria) [ar-dz] * @iso-639-2 ara * @author BADREDDINE BOUMAZA [@BADRE429]{@link https://github.com/badre429} */ // var locale = { // formatDistance: formatDistance, // formatLong: formatLong, // formatRelative: formatRelative, // localize: localize, // match: match, // options: { // weekStartsOn: 6 /* Saturday */, // firstWeekContainsDate: 1 // } // } // export default locale throw new Error( 'ar-DZ locale is currently unavailable. Please check the progress of converting this locale to v2.0.0 in this issue on Github: TBA' )
#!/usr/bin/env python import getopt, re def get_options(args): expected_major_version = None try: opts, _ = getopt.getopt(args, "hnm:", ["not-installed", "major-version="]) except getopt.GetoptError: print('check_install.py [-n] [-m <major_version>]') sys.exit(2) for opt, arg in opts: if opt == '-h': print('check_apt_install.py [-n] [-m <major_version>]') sys.exit() elif opt in ("-n", "--not-installed"): expected_major_version = None elif opt in ("-m", "--major-version"): expected_major_version = arg return expected_major_version def check_major_version(installed_version, expected_major_version): installed_major_version = None if installed_version is not None: installed_major_version = re.match("([0-9]+).*", installed_version).groups()[0] print("Installed Agent major version: {}".format(installed_major_version)) return installed_major_version == expected_major_version
import React from "react"; import './Table.css'; import API from '../../utils/api'; // import Body from '../TableBody/Body'; // // import API from '../../utils/api'; // // import TableHead from "../tableHeader"; // // import TableBody from '../tableBody'; // import './Table.css'; const Table = (props) => { return ( <table className="table table-striped table-sortable text-center"> <thead> <tr> <th scope="col">Image</th> <th scope="col" data-field="name" data-sortable="true"> <span onClick={() => props.sortBy("name", "last", "first")}> Name </span> </th> <th scope="col"> <span onClick={() => props.sortBy("phone")}>Phone</span> </th> <th scope="col"> <span onClick={() => props.sortBy("email")}>Email</span> </th> <th scope="col"> <span onClick={() => props.sortBy("dob", "date")}>DOB</span> </th> </tr> </thead> <tbody> {props.state.filteredEmployees.map((employee) => { const { first, last } = employee.name; const fullName = `${first} ${last}`; const dob = props.formatDate(employee.dob.date); return ( <tr key={employee.login.uuid}> <td> <img src={employee.picture.thumbnail} alt={fullName} /> </td> <td className="align-middle">{fullName}</td> <td className="align-middle"> <a href={`tel:+1${employee.phone}`}>{employee.phone}</a></td> <td className="align-middle email"> <a href={`mailto:${employee.email}`}>{employee.email}</a> </td> <td className="align-middle">{dob}</td> </tr> ); })} </tbody> </table> ); }; export default Table;
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.dialogflow_v2.services.intents import pagers from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import struct_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport class IntentsClientMeta(type): """Metaclass for the Intents client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = OrderedDict() # type: Dict[str, Type[IntentsTransport]] _transport_registry["grpc"] = IntentsGrpcTransport _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None, ) -> Type[IntentsTransport]: """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class IntentsClient(metaclass=IntentsClientMeta): """Service for managing [Intents][google.cloud.dialogflow.v2.Intent].""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "dialogflow.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: IntentsClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info(info) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: IntentsClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> IntentsTransport: """Returns the transport used by the client instance. Returns: IntentsTransport: The transport used by the client instance. """ return self._transport @staticmethod def context_path(project: str,session: str,context: str,) -> str: """Returns a fully-qualified context string.""" return "projects/{project}/agent/sessions/{session}/contexts/{context}".format(project=project, session=session, context=context, ) @staticmethod def parse_context_path(path: str) -> Dict[str,str]: """Parses a context path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/agent/sessions/(?P<session>.+?)/contexts/(?P<context>.+?)$", path) return m.groupdict() if m else {} @staticmethod def intent_path(project: str,intent: str,) -> str: """Returns a fully-qualified intent string.""" return "projects/{project}/agent/intents/{intent}".format(project=project, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str,str]: """Parses a intent path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/agent/intents/(?P<intent>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder, ) @staticmethod def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization, ) @staticmethod def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project, ) @staticmethod def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} def __init__(self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IntentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, IntentsTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: is_mtls = True client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() if is_mtls: client_cert_source_func = mtls.default_client_cert_source() else: client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": if is_mtls: api_endpoint = self.DEFAULT_MTLS_ENDPOINT else: api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " "values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, IntentsTransport): # transport is a IntentsTransport instance. if credentials or client_options.credentials_file: raise ValueError("When providing a transport instance, " "provide its credentials directly.") if client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " "directly." ) self._transport = transport else: Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, always_use_jwt_access=True, ) def list_intents(self, request: Union[intent.ListIntentsRequest, dict] = None, *, parent: str = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListIntentsPager: r"""Returns the list of all intents in the specified agent. Args: request (Union[google.cloud.dialogflow_v2.types.ListIntentsRequest, dict]): The request object. The request message for [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. parent (str): Required. The agent to list all intents from. Format: ``projects/<Project ID>/agent`` or ``projects/<Project ID>/locations/<Location ID>/agent``. Alternatively, you can specify the environment to list intents for. Format: ``projects/<Project ID>/agent/environments/<Environment ID>`` or ``projects/<Project ID>/locations/<Location ID>/agent/environments/<Environment ID>``. Note: training phrases of the intents will not be returned for non-draft environment. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. language_code (str): Optional. The language used to access language-specific data. If not specified, the agent's default language is used. For more information, see `Multilingual intent and entity data <https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity>`__. This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsPager: The response message for [Intents.ListIntents][google.cloud.dialogflow.v2.Intents.ListIntents]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, language_code]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a intent.ListIntentsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, intent.ListIntentsRequest): request = intent.ListIntentsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_intents] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("parent", request.parent), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListIntentsPager( method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response def get_intent(self, request: Union[intent.GetIntentRequest, dict] = None, *, name: str = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> intent.Intent: r"""Retrieves the specified intent. Args: request (Union[google.cloud.dialogflow_v2.types.GetIntentRequest, dict]): The request object. The request message for [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent]. name (str): Required. The name of the intent. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. language_code (str): Optional. The language used to access language-specific data. If not specified, the agent's default language is used. For more information, see `Multilingual intent and entity data <https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity>`__. This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.dialogflow_v2.types.Intent: An intent categorizes an end-user's intention for one conversation turn. For each agent, you define many intents, where your combined intents can handle a complete conversation. When an end-user writes or says something, referred to as an end-user expression or end-user input, Dialogflow matches the end-user input to the best intent in your agent. Matching an intent is also known as intent classification. For more information, see the [intent guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, language_code]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a intent.GetIntentRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, intent.GetIntentRequest): request = intent.GetIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name if language_code is not None: request.language_code = language_code # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_intent] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("name", request.name), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def create_intent(self, request: Union[gcd_intent.CreateIntentRequest, dict] = None, *, parent: str = None, intent: gcd_intent.Intent = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcd_intent.Intent: r"""Creates an intent in the specified agent. Note: You should always train an agent prior to sending it queries. See the `training documentation <https://cloud.google.com/dialogflow/es/docs/training>`__. Args: request (Union[google.cloud.dialogflow_v2.types.CreateIntentRequest, dict]): The request object. The request message for [Intents.CreateIntent][google.cloud.dialogflow.v2.Intents.CreateIntent]. parent (str): Required. The agent to create a intent for. Format: ``projects/<Project ID>/agent``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. intent (google.cloud.dialogflow_v2.types.Intent): Required. The intent to create. This corresponds to the ``intent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. language_code (str): Optional. The language used to access language-specific data. If not specified, the agent's default language is used. For more information, see `Multilingual intent and entity data <https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity>`__. This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.dialogflow_v2.types.Intent: An intent categorizes an end-user's intention for one conversation turn. For each agent, you define many intents, where your combined intents can handle a complete conversation. When an end-user writes or says something, referred to as an end-user expression or end-user input, Dialogflow matches the end-user input to the best intent in your agent. Matching an intent is also known as intent classification. For more information, see the [intent guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, intent, language_code]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a gcd_intent.CreateIntentRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, gcd_intent.CreateIntentRequest): request = gcd_intent.CreateIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent if intent is not None: request.intent = intent if language_code is not None: request.language_code = language_code # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.create_intent] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("parent", request.parent), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def update_intent(self, request: Union[gcd_intent.UpdateIntentRequest, dict] = None, *, intent: gcd_intent.Intent = None, language_code: str = None, update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> gcd_intent.Intent: r"""Updates the specified intent. Note: You should always train an agent prior to sending it queries. See the `training documentation <https://cloud.google.com/dialogflow/es/docs/training>`__. Args: request (Union[google.cloud.dialogflow_v2.types.UpdateIntentRequest, dict]): The request object. The request message for [Intents.UpdateIntent][google.cloud.dialogflow.v2.Intents.UpdateIntent]. intent (google.cloud.dialogflow_v2.types.Intent): Required. The intent to update. This corresponds to the ``intent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. language_code (str): Optional. The language used to access language-specific data. If not specified, the agent's default language is used. For more information, see `Multilingual intent and entity data <https://cloud.google.com/dialogflow/docs/agents-multilingual#intent-entity>`__. This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. The mask to control which fields get updated. This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.dialogflow_v2.types.Intent: An intent categorizes an end-user's intention for one conversation turn. For each agent, you define many intents, where your combined intents can handle a complete conversation. When an end-user writes or says something, referred to as an end-user expression or end-user input, Dialogflow matches the end-user input to the best intent in your agent. Matching an intent is also known as intent classification. For more information, see the [intent guide](\ https://cloud.google.com/dialogflow/docs/intents-overview). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([intent, language_code, update_mask]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a gcd_intent.UpdateIntentRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, gcd_intent.UpdateIntentRequest): request = gcd_intent.UpdateIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if intent is not None: request.intent = intent if language_code is not None: request.language_code = language_code if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.update_intent] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("intent.name", request.intent.name), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def delete_intent(self, request: Union[intent.DeleteIntentRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes the specified intent and its direct or indirect followup intents. Note: You should always train an agent prior to sending it queries. See the `training documentation <https://cloud.google.com/dialogflow/es/docs/training>`__. Args: request (Union[google.cloud.dialogflow_v2.types.DeleteIntentRequest, dict]): The request object. The request message for [Intents.DeleteIntent][google.cloud.dialogflow.v2.Intents.DeleteIntent]. name (str): Required. The name of the intent to delete. If this intent has direct or indirect followup intents, we also delete them. Format: ``projects/<Project ID>/agent/intents/<Intent ID>``. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a intent.DeleteIntentRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, intent.DeleteIntentRequest): request = intent.DeleteIntentRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.delete_intent] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("name", request.name), )), ) # Send the request. rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) def batch_update_intents(self, request: Union[intent.BatchUpdateIntentsRequest, dict] = None, *, parent: str = None, intent_batch_uri: str = None, intent_batch_inline: intent.IntentBatch = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Updates/Creates multiple intents in the specified agent. This method is a `long-running operation <https://cloud.google.com/dialogflow/es/docs/how/long-running-operations>`__. The returned ``Operation`` type has the following method-specific fields: - ``metadata``: An empty `Struct message <https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct>`__ - ``response``: [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] Note: You should always train an agent prior to sending it queries. See the `training documentation <https://cloud.google.com/dialogflow/es/docs/training>`__. Args: request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]): The request object. parent (str): Required. The name of the agent to update or create intents in. Format: ``projects/<Project ID>/agent``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. intent_batch_uri (str): The URI to a Google Cloud Storage file containing intents to update or create. The file format can either be a serialized proto (of IntentBatch type) or JSON object. Note: The URI must start with "gs://". This corresponds to the ``intent_batch_uri`` field on the ``request`` instance; if ``request`` is provided, this should not be set. intent_batch_inline (google.cloud.dialogflow_v2.types.IntentBatch): The collection of intents to update or create. This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.api_core.operation.Operation: An object representing a long-running operation. The result type for the operation will be :class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsResponse` The response message for [Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, intent_batch_uri, intent_batch_inline]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a intent.BatchUpdateIntentsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, intent.BatchUpdateIntentsRequest): request = intent.BatchUpdateIntentsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent if intent_batch_uri is not None: request.intent_batch_uri = intent_batch_uri if intent_batch_inline is not None: request.intent_batch_inline = intent_batch_inline # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.batch_update_intents] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("parent", request.parent), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Wrap the response in an operation future. response = operation.from_gapic( response, self._transport.operations_client, intent.BatchUpdateIntentsResponse, metadata_type=struct_pb2.Struct, ) # Done; return the response. return response def batch_delete_intents(self, request: Union[intent.BatchDeleteIntentsRequest, dict] = None, *, parent: str = None, intents: Sequence[intent.Intent] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Deletes intents in the specified agent. This method is a `long-running operation <https://cloud.google.com/dialogflow/es/docs/how/long-running-operations>`__. The returned ``Operation`` type has the following method-specific fields: - ``metadata``: An empty `Struct message <https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct>`__ - ``response``: An `Empty message <https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty>`__ Note: You should always train an agent prior to sending it queries. See the `training documentation <https://cloud.google.com/dialogflow/es/docs/training>`__. Args: request (Union[google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest, dict]): The request object. The request message for [Intents.BatchDeleteIntents][google.cloud.dialogflow.v2.Intents.BatchDeleteIntents]. parent (str): Required. The name of the agent to delete all entities types for. Format: ``projects/<Project ID>/agent``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): Required. The collection of intents to delete. Only intent ``name`` must be filled in. This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.api_core.operation.Operation: An object representing a long-running operation. The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for Empty is empty JSON object {}. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, intents]) if request is not None and has_flattened_params: raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a intent.BatchDeleteIntentsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, intent.BatchDeleteIntentsRequest): request = intent.BatchDeleteIntentsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent if intents is not None: request.intents = intents # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.batch_delete_intents] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ("parent", request.parent), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Wrap the response in an operation future. response = operation.from_gapic( response, self._transport.operations_client, empty_pb2.Empty, metadata_type=struct_pb2.Struct, ) # Done; return the response. return response def __enter__(self): return self def __exit__(self, type, value, traceback): """Releases underlying transport's resources. .. warning:: ONLY use as a context manager if the transport is NOT shared with other clients! Exiting the with block will CLOSE the transport and may cause errors in other clients! """ self.transport.close() try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-dialogflow", ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ( "IntentsClient", )
from .configloader import DivisionsConfiguration, DivisionRule, DivisionType from .matchrule import MatchRule, MatchUntil, MatchOnly, Collect, Include from .postrules import PostRules, PostRule
!function(a,b){"use strict";function c(a){this.callback=a,this.ticking=!1}function d(b){return b&&"undefined"!=typeof a&&(b===a||b.nodeType)}function e(a){if(arguments.length<=0)throw new Error("Missing arguments in extend function");var b,c,f=a||{};for(c=1;c<arguments.length;c++){var g=arguments[c]||{};for(b in g)f[b]="object"!=typeof f[b]||d(f[b])?f[b]||g[b]:e(f[b],g[b])}return f}function f(a){return a===Object(a)?a:{down:a,up:a}}function g(a,b){b=e(b,g.options),this.lastKnownScrollY=0,this.elem=a,this.debouncer=new c(this.update.bind(this)),this.tolerance=f(b.tolerance),this.classes=b.classes,this.offset=b.offset,this.scroller=b.scroller,this.initialised=!1,this.onPin=b.onPin,this.onUnpin=b.onUnpin,this.onTop=b.onTop,this.onNotTop=b.onNotTop}var h={bind:!!function(){}.bind,classList:"classList"in b.documentElement,rAF:!!(a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame)};a.requestAnimationFrame=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame,c.prototype={constructor:c,update:function(){this.callback&&this.callback(),this.ticking=!1},requestTick:function(){this.ticking||(requestAnimationFrame(this.rafCallback||(this.rafCallback=this.update.bind(this))),this.ticking=!0)},handleEvent:function(){this.requestTick()}},g.prototype={constructor:g,init:function(){return g.cutsTheMustard?(this.elem.classList.add(this.classes.initial),setTimeout(this.attachEvent.bind(this),100),this):void 0},destroy:function(){var a=this.classes;this.initialised=!1,this.elem.classList.remove(a.unpinned,a.pinned,a.top,a.initial),this.scroller.removeEventListener("scroll",this.debouncer,!1)},attachEvent:function(){this.initialised||(this.lastKnownScrollY=this.getScrollY(),this.initialised=!0,this.scroller.addEventListener("scroll",this.debouncer,!1),this.debouncer.handleEvent())},unpin:function(){var a=this.elem.classList,b=this.classes;(a.contains(b.pinned)||!a.contains(b.unpinned))&&(a.add(b.unpinned),a.remove(b.pinned),this.onUnpin&&this.onUnpin.call(this))},pin:function(){var a=this.elem.classList,b=this.classes;a.contains(b.unpinned)&&(a.remove(b.unpinned),a.add(b.pinned),this.onPin&&this.onPin.call(this))},top:function(){var a=this.elem.classList,b=this.classes;a.contains(b.top)||(a.add(b.top),a.remove(b.notTop),this.onTop&&this.onTop.call(this))},notTop:function(){var a=this.elem.classList,b=this.classes;a.contains(b.notTop)||(a.add(b.notTop),a.remove(b.top),this.onNotTop&&this.onNotTop.call(this))},getScrollY:function(){return void 0!==this.scroller.pageYOffset?this.scroller.pageYOffset:void 0!==this.scroller.scrollTop?this.scroller.scrollTop:(b.documentElement||b.body.parentNode||b.body).scrollTop},getViewportHeight:function(){return a.innerHeight||b.documentElement.clientHeight||b.body.clientHeight},getDocumentHeight:function(){var a=b.body,c=b.documentElement;return Math.max(a.scrollHeight,c.scrollHeight,a.offsetHeight,c.offsetHeight,a.clientHeight,c.clientHeight)},getElementHeight:function(a){return Math.max(a.scrollHeight,a.offsetHeight,a.clientHeight)},getScrollerHeight:function(){return this.scroller===a||this.scroller===b.body?this.getDocumentHeight():this.getElementHeight(this.scroller)},isOutOfBounds:function(a){var b=0>a,c=a+this.getViewportHeight()>this.getScrollerHeight();return b||c},toleranceExceeded:function(a,b){return Math.abs(a-this.lastKnownScrollY)>=this.tolerance[b]},shouldUnpin:function(a,b){var c=a>this.lastKnownScrollY,d=a>=this.offset;return c&&d&&b},shouldPin:function(a,b){var c=a<this.lastKnownScrollY,d=a<=this.offset;return c&&b||d},update:function(){var a=this.getScrollY(),b=a>this.lastKnownScrollY?"down":"up",c=this.toleranceExceeded(a,b);this.isOutOfBounds(a)||(a<=this.offset?this.top():this.notTop(),this.shouldUnpin(a,c)?this.unpin():this.shouldPin(a,c)&&this.pin(),this.lastKnownScrollY=a)}},g.options={tolerance:{up:0,down:0},offset:0,scroller:a,classes:{pinned:"headroom--pinned",unpinned:"headroom--unpinned",top:"headroom--top",notTop:"headroom--not-top",initial:"headroom"}},g.cutsTheMustard="undefined"!=typeof h&&h.rAF&&h.bind&&h.classList,a.Headroom=g}(window,document);
/** * simple packaging O(∩_∩)O~ */ var fs = require('fs') let lib = 'c3' let banner = '/*! The MIT License (MIT) https://github.com/vace/c3.js */' var template = code => ` ${banner} (function moduledefine(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["${lib}"] = factory(); else root["${lib}"] = factory(); })(this,function(){ ${code} return c3 }) ` var code = fs.readFileSync('dist/c3-unpack.js') fs.writeFileSync('dist/c3.js',template(code)) console.log('success output~')
const fs = require('fs'); const archiver = require('archiver'); fs.unlinkSync('./dist/main.js'); fs.unlinkSync('./dist/main.css'); let output = fs.createWriteStream('./dist/build.zip'); let archive = archiver('zip', { zlib: { level: 9 } // set compression to best }); const MAX = 13 * 1024; // 13kb output.on('close', function () { const bytes = archive.pointer(); const percent = (bytes / MAX * 100).toFixed(2); if (bytes > MAX) { console.error(`Size overflow: ${bytes} bytes (${percent}%)`); } else { console.log(`Size: ${bytes} bytes (${percent}%)`); } }); archive.on('warning', function (err) { if (err.code === 'ENOENT') { console.warn(err) } else { throw err } }); archive.on('error', function (err) { throw err }); archive.pipe(output); archive.append( fs.createReadStream('./dist/index.html'), { name: 'index.html' } ); archive.finalize();
import React, { useEffect, useState } from 'react'; import { TouchableOpacity } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import api from '~/services/api'; import Background from '~/components/Background'; import { Container, ProvidersList, Provider, Avatar, Name } from './styles'; export default function SelectProvider({ navigation }) { const [providers, setProviders] = useState([]); useEffect(() => { async function loadProviders() { const response = await api.get('/providers'); setProviders(response.data); } loadProviders(); }, []); return ( <Background> <Container> <ProvidersList data={providers} keyExtractor={(provider) => String(provider.id)} renderItem={({ item: provider }) => ( <Provider onPress={() => navigation.navigate('SelectDateTime', { provider }) } > <Avatar source={{ uri: provider.avatar ? provider.avatar.url : `https://api.adorable.io/avatar/50/${provider.name}.png`, }} /> <Name>{provider.name}</Name> </Provider> )} /> </Container> </Background> ); } SelectProvider.navigationOptions = ({ navigation }) => ({ title: 'Select a Provider', headerLeft: () => ( <TouchableOpacity onPress={() => { navigation.navigate('Dashboard'); }} > <Icon name="chevron-left" size={20} color="#fff" /> </TouchableOpacity> ), });
var IS_PURE = require('../internals/is-pure'); var store = require('../internals/shared-store'); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.4', mode: IS_PURE ? 'pure' : 'global', copyright: '© 2020 Acid Chicken (acid-chicken.com), © 2014-2020 Denis Pushkarev (zloirock.ru)' });
const path = require('path'); const withCss = require('@zeit/next-css'); module.exports = { target: 'serverless', ...withCss({ webpack(config) { // CSS config.module.rules.push({ test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/, use: { loader: 'url-loader', options: { limit: 100000, publicPath: './', outputPath: 'static/', name: '[name].[ext]', }, }, }); // Modules alias config.resolve.alias['components'] = path.join(__dirname, 'components'); return config; }, }), env: { CLIENT_URL: process.env.CLIENT_URL, }, };
#! /usr/bin/env node require('dotenv').config(); const puppeteer = require('puppeteer'); const args = require('yargs').argv; const { enterGiveaways } = require('./src/giveaways'); const signIn = require('./src/signIn'); //start index code (async () => { const username = process.env.AMAZON_USERNAME || args.username; const password = process.env.AMAZON_PASSWORD || args.password; if (!username || !password) { console.error('Missing required username and/or password!'); return; } //add to process.env to be used elsewhere if needed process.env.AMAZON_USERNAME = username; process.env.AMAZON_PASSWORD = password; const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); //sign in await signIn(page, username, password); //go to giveaways let url = 'https://www.amazon.com/ga/giveaways'; if (args.page) { url += '?pageId=' + args.page; } await page.goto(url); //enter giveaways await enterGiveaways(page, args.page || 1); await browser.close(); })();
type = ['primary', 'info', 'success', 'warning', 'danger']; demo = { initPickColor: function() { $('.pick-class-label').click(function() { var new_class = $(this).attr('new-class'); var old_class = $('#display-buttons').attr('data-class'); var display_div = $('#display-buttons'); if (display_div.length) { var display_buttons = display_div.find('.btn'); display_buttons.removeClass(old_class); display_buttons.addClass(new_class); display_div.attr('data-class', new_class); } }); }, checkFullPageBackgroundImage: function() { $page = $('.full-page'); image_src = $page.data('image'); if (image_src !== undefined) { image_container = '<div class="full-page-background" style="background-image: url(' + image_src + ') "/>'; $page.append(image_container); } }, initDateTimePicker: function() { if ($(".datetimepicker").length != 0) { $('.datetimepicker').datetimepicker({ icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-chevron-up", down: "fa fa-chevron-down", previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-screenshot', clear: 'fa fa-trash', close: 'fa fa-remove' } }); } if ($(".datepicker").length != 0) { $('.datepicker').datetimepicker({ format: 'MM/DD/YYYY', icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-chevron-up", down: "fa fa-chevron-down", previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-screenshot', clear: 'fa fa-trash', close: 'fa fa-remove' } }); } if ($(".timepicker").length != 0) { $('.timepicker').datetimepicker({ // format: 'H:mm', // use this format if you want the 24hours timepicker format: 'h:mm A', //use this format if you want the 12hours timpiecker with AM/PM toggle icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-chevron-up", down: "fa fa-chevron-down", previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-screenshot', clear: 'fa fa-trash', close: 'fa fa-remove' } }); } }, initFullCalendar: function() { var calendarEl = document.getElementById('fullCalendar'); $calendar = $('#fullCalendar'); var today = new Date(); var y = today.getFullYear(); var m = today.getMonth(); var d = today.getDate(); var calendar = new FullCalendar.Calendar(calendarEl, { plugins: ['interaction', 'dayGrid', 'timeGridPlugin'], editable: true, header: { left: 'title', center: 'dayGridMonth,dayGridWeek,dayGridDay', right: 'prev,next,today' }, selectable: true, droppable: true, rendering: 'background', defaultDate: today, selectable: true, selectHelper: true, select: function(info) { // on select we show the Sweet Alert modal with an input Swal.fire({ title: 'Create an Event', html: '<div class="form-group">' + '<input class="form-control text-default" placeholder="Event Title" id="input-field">' + '</div>', showCancelButton: true, customClass: { confirmButton: 'btn btn-success', cancelButton: 'btn btn-danger' }, buttonsStyling: false }).then(function(result) { var eventData; event_title = $('#input-field').val(); if (event_title) { eventData = { title: event_title, start: info.startStr, end: info.endStr }; calendar.addEvent(eventData); } }); }, editable: true, eventLimit: true, // allow "more" link when too many events events: [{ title: 'All Day Event', start: new Date(y, m, 1), className: 'event-default' }, { title: 'Meeting', start: new Date(y, m, d - 1, 10, 30), allDay: false, className: 'event-green' }, { title: 'Lunch', start: new Date(y, m, d + 7, 12, 0), end: new Date(y, m, d + 7, 14, 0), allDay: false, className: 'event-red' }, { title: 'BD-pro Launch', start: new Date(y, m, d - 2, 12, 0), allDay: true, className: 'event-azure' }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false, className: 'event-azure' }, { title: 'Click for Creative Tim', start: new Date(y, m, 21), end: new Date(y, m, 22), url: 'http://www.creative-tim.com/', className: 'event-orange' }, { title: 'Click for Google', start: new Date(y, m, 21), end: new Date(y, m, 22), url: 'http://www.creative-tim.com/', className: 'event-orange' } ] }); calendar.render(); }, showSwal: function(type) { if (type == 'basic') { Swal.fire({ title: 'Here is a message!', customClass: { confirmButton: 'btn btn-success' }, buttonsStyling: false }) } else if (type == 'title-and-text') { Swal.fire({ title: 'The Internet?', text: 'That thing is still around?', type: 'question', customClass: { confirmButton: 'btn btn-info' }, buttonsStyling: false, }) } else if (type == 'success-message') { Swal.fire({ position: 'center', type: 'success', title: 'Good job!', showConfirmButton: false, timer: 1500 }) } else if (type == 'warning-message-and-confirmation') { const swalWithBootstrapButtons = Swal.mixin({ customClass: { confirmButton: 'btn btn-success', cancelButton: 'btn btn-danger' }, buttonsStyling: false }) swalWithBootstrapButtons.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it!', cancelButtonText: 'No, cancel!', reverseButtons: true }).then((result) => { if (result.value) { swalWithBootstrapButtons.fire( 'Deleted!', 'Your file has been deleted.', 'success' ) } else if ( /* Read more about handling dismissals below */ result.dismiss === Swal.DismissReason.cancel ) { swalWithBootstrapButtons.fire( 'Cancelled', 'Your imaginary file is safe :)', 'error' ) } }) } else if (type == 'warning-message-and-cancel') { Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, customClass: { confirmButton: 'btn btn-success', cancelButton: 'btn btn-danger' }, buttonsStyling: false, confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' ) } }) } else if (type == 'custom-html') { Swal.fire({ title: '<strong>HTML <u>example</u></strong>', type: 'info', html: 'You can use <b>bold text</b>, ' + '<a href="//sweetalert2.github.io">links</a> ' + 'and other HTML tags', showCloseButton: true, showCancelButton: true, customClass: { confirmButton: 'btn btn-success', cancelButton: 'btn btn-danger' }, buttonsStyling: false, focusConfirm: false, confirmButtonText: '<i class="fa fa-thumbs-up"></i> Great!', confirmButtonAriaLabel: 'Thumbs up, great!', cancelButtonText: '<i class="fa fa-thumbs-down"></i>', cancelButtonAriaLabel: 'Thumbs down' }) } else if (type == 'auto-close') { let timerInterval Swal.fire({ title: 'Auto close alert!', html: 'I will close in <strong></strong> milliseconds.', timer: 2000, onBeforeOpen: () => { Swal.showLoading() timerInterval = setInterval(() => { Swal.getContent().querySelector('strong') .textContent = Swal.getTimerLeft() }, 100) }, onClose: () => { clearInterval(timerInterval) } }).then((result) => { if ( /* Read more about handling dismissals below */ result.dismiss === Swal.DismissReason.timer ) { console.log('I was closed by the timer') } }) } else if (type == 'input-field') { Swal.fire({ title: 'Submit your Github username', input: 'text', inputAttributes: { autocapitalize: 'off' }, showCancelButton: true, confirmButtonText: 'Look up', customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-default' }, buttonsStyling: false, showLoaderOnConfirm: true, preConfirm: (login) => { return fetch(`//api.github.com/users/${login}`) .then(response => { if (!response.ok) { throw new Error(response.statusText) } return response.json() }) .catch(error => { Swal.showValidationMessage( `Request failed: ${error}` ) }) }, allowOutsideClick: () => !Swal.isLoading() }).then((result) => { if (result.value) { Swal.fire({ title: `${result.value.login}'s avatar`, imageUrl: result.value.avatar_url }) } }) } }, initWizard: function() { // Code for the Validator var $validator = $('.card-wizard form').validate({ rules: { organizationname: { required: true, minlength: 3 }, lastname: { required: true, minlength: 3 }, email: { required: true, minlength: 3, } }, highlight: function(element) { $(element).closest('.input-group').removeClass('has-success').addClass('has-danger'); }, success: function(element) { $(element).closest('.input-group').removeClass('has-danger').addClass('has-success'); } }); // Wizard Initialization $('.card-wizard').bootstrapWizard({ 'tabClass': 'nav nav-pills', 'nextSelector': '.btn-next', 'previousSelector': '.btn-previous', onNext: function(tab, navigation, index) { var $valid = $('.card-wizard form').valid(); if (!$valid) { $validator.focusInvalid(); return false; } }, onInit: function(tab, navigation, index) { //check number of tabs and fill the entire row var $total = navigation.find('li').length; var $wizard = navigation.closest('.card-wizard'); first_li = navigation.find('li:first-child a').html(); $moving_div = $("<div class='moving-tab'></div>"); $moving_div.append(first_li); $('.card-wizard .wizard-navigation').append($moving_div); refreshAnimation($wizard, index); $('.moving-tab').css('transition', 'transform 0s'); }, onTabClick: function(tab, navigation, index) { var $valid = $('.card-wizard form').valid(); if (!$valid) { return false; } else { return true; } }, onTabShow: function(tab, navigation, index) { var $total = navigation.find('li').length; var $current = index + 1; var $wizard = navigation.closest('.card-wizard'); // If it's the last tab then hide the last button and show the finish instead if ($current >= $total) { $($wizard).find('.btn-next').hide(); $($wizard).find('.btn-finish').show(); } else { $($wizard).find('.btn-next').show(); $($wizard).find('.btn-finish').hide(); } button_text = navigation.find('li:nth-child(' + $current + ') a').html(); setTimeout(function() { $('.moving-tab').html(button_text); }, 150); var checkbox = $('.footer-checkbox'); if (!index == 0) { $(checkbox).css({ 'opacity': '0', 'visibility': 'hidden', 'position': 'absolute' }); } else { $(checkbox).css({ 'opacity': '1', 'visibility': 'visible' }); } refreshAnimation($wizard, index); } }); // Prepare the preview for profile picture $("#wizard-picture").change(function() { readURL(this); }); $('[data-toggle="wizard-radio"]').click(function() { wizard = $(this).closest('.card-wizard'); wizard.find('[data-toggle="wizard-radio"]').removeClass('active'); $(this).addClass('active'); $(wizard).find('[type="radio"]').removeAttr('checked'); $(this).find('[type="radio"]').attr('checked', 'true'); }); $('[data-toggle="wizard-checkbox"]').click(function() { if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).find('[type="checkbox"]').removeAttr('checked'); } else { $(this).addClass('active'); $(this).find('[type="checkbox"]').attr('checked', 'true'); } }); $('.set-full-height').css('height', 'auto'); //Function to show image before upload function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#wizardPicturePreview').attr('src', e.target.result).fadeIn('slow'); } reader.readAsDataURL(input.files[0]); } } $(window).resize(function() { $('.card-wizard').each(function() { $wizard = $(this); index = $wizard.bootstrapWizard('currentIndex'); refreshAnimation($wizard, index); $('.moving-tab').css({ 'transition': 'transform 0s' }); }); }); function refreshAnimation($wizard, index) { $total = $wizard.find('.nav li').length; $li_width = 100 / $total; total_steps = $wizard.find('.nav li').length; move_distance = $wizard.width() / total_steps; index_temp = index; vertical_level = 0; mobile_device = $(document).width() < 600 && $total > 3; if (mobile_device) { move_distance = $wizard.width() / 2; index_temp = index % 2; $li_width = 50; } $wizard.find('.nav li').css('width', $li_width + '%'); step_width = move_distance; move_distance = move_distance * index_temp; $current = index + 1; // if($current == 1 || (mobile_device == true && (index % 2 == 0) )){ // move_distance -= 8; // } else if($current == total_steps || (mobile_device == true && (index % 2 == 1))){ // move_distance += 8; // } if (mobile_device) { vertical_level = parseInt(index / 2); vertical_level = vertical_level * 38; } $wizard.find('.moving-tab').css('width', step_width); $('.moving-tab').css({ 'transform': 'translate3d(' + move_distance + 'px, ' + vertical_level + 'px, 0)', 'transition': 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)' }); } }, initSliders: function() { // Sliders for demo purpose in refine cards section var slider = document.getElementById('sliderRegular'); noUiSlider.create(slider, { start: 40, connect: [true, false], range: { min: 0, max: 100 } }); var slider2 = document.getElementById('sliderDouble'); noUiSlider.create(slider2, { start: [20, 60], connect: true, range: { min: 0, max: 100 } }); }, initVectorMap: function() { var mapData = { "AU": 760, "BR": 550, "CA": 120, "DE": 1300, "FR": 540, "GB": 690, "GE": 200, "IN": 200, "RO": 600, "RU": 300, "US": 2920, }; $('#worldMap').vectorMap({ map: 'world_merc', backgroundColor: "transparent", zoomOnScroll: false, regionStyle: { initial: { fill: '#e4e4e4', "fill-opacity": 0.9, stroke: 'none', "stroke-width": 0, "stroke-opacity": 0 } }, series: { regions: [{ values: mapData, scale: ["#AAAAAA", "#444444"], normalizeFunction: 'polynomial' }] }, }); }, initGoogleMaps: function() { var myLatlng = new google.maps.LatLng(40.748817, -73.985428); var mapOptions = { zoom: 13, center: myLatlng, scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page styles: [{ "featureType": "water", "stylers": [{ "saturation": 43 }, { "lightness": -11 }, { "hue": "#0088ff" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "hue": "#ff0000" }, { "saturation": -100 }, { "lightness": 99 }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "color": "#808080" }, { "lightness": 54 }] }, { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [{ "color": "#ece2d9" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#ccdca1" }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "color": "#767676" }] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "poi", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#b8cb93" }] }, { "featureType": "poi.park", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.sports_complex", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.medical", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.business", "stylers": [{ "visibility": "simplified" }] }] } var map = new google.maps.Map(document.getElementById("map"), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, title: "Hello World!" }); // To add the marker to the map, call setMap(); marker.setMap(map); }, initSmallGoogleMaps: function() { // Regular Map var myLatlng = new google.maps.LatLng(40.748817, -73.985428); var mapOptions = { zoom: 8, center: myLatlng, scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page } var map = new google.maps.Map(document.getElementById("regularMap"), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, title: "Regular Map!" }); marker.setMap(map); // Custom Skin & Settings Map var myLatlng = new google.maps.LatLng(40.748817, -73.985428); var mapOptions = { zoom: 13, center: myLatlng, scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page disableDefaultUI: true, // a way to quickly hide all controls zoomControl: true, styles: [{ "featureType": "water", "stylers": [{ "saturation": 43 }, { "lightness": -11 }, { "hue": "#0088ff" }] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [{ "hue": "#ff0000" }, { "saturation": -100 }, { "lightness": 99 }] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [{ "color": "#808080" }, { "lightness": 54 }] }, { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [{ "color": "#ece2d9" }] }, { "featureType": "poi.park", "elementType": "geometry.fill", "stylers": [{ "color": "#ccdca1" }] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [{ "color": "#767676" }] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "poi", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [{ "visibility": "on" }, { "color": "#b8cb93" }] }, { "featureType": "poi.park", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.sports_complex", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.medical", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.business", "stylers": [{ "visibility": "simplified" }] }] } var map = new google.maps.Map(document.getElementById("customSkinMap"), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, title: "Custom Skin & Settings Map!" }); marker.setMap(map); // Satellite Map var myLatlng = new google.maps.LatLng(40.748817, -73.985428); var mapOptions = { zoom: 3, scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page center: myLatlng, mapTypeId: google.maps.MapTypeId.SATELLITE } var map = new google.maps.Map(document.getElementById("satelliteMap"), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, title: "Satellite Map!" }); marker.setMap(map); }, showNotification: function(from, align) { color = Math.floor((Math.random() * 4) + 1); $.notify({ icon: "nc-icon nc-bell-55", message: "Welcome to <b>Paper Dashboard Pro</b> - a beautiful bootstrap dashboard for every web developer." }, { type: type[color], timer: 8000, placement: { from: from, align: align } }); }, // CHARTS initChartPageCharts: function() { chartColor = "#FFFFFF"; ctx = document.getElementById('chartHours').getContext("2d"); myChart = new Chart(ctx, { type: 'line', data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"], datasets: [{ borderColor: "#6bd098", backgroundColor: "#6bd098", pointRadius: 0, pointHoverRadius: 0, borderWidth: 3, data: [300, 310, 316, 322, 330, 326, 333, 345, 338, 354] }, { borderColor: "#f17e5d", backgroundColor: "#f17e5d", pointRadius: 0, pointHoverRadius: 0, borderWidth: 3, data: [320, 340, 365, 360, 370, 385, 390, 384, 408, 420] }, { borderColor: "#fcc468", backgroundColor: "#fcc468", pointRadius: 0, pointHoverRadius: 0, borderWidth: 3, data: [370, 394, 415, 409, 425, 445, 460, 450, 478, 484] } ] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, //padding: 20 }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent", display: false, }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }); ctx = document.getElementById('chartEmail').getContext("2d"); myChart = new Chart(ctx, { type: 'pie', data: { labels: [1, 2, 3], datasets: [{ label: "Emails", pointRadius: 0, pointHoverRadius: 0, backgroundColor: [ '#e3e3e3', '#4acccd', '#fcc468' ], borderWidth: 0, data: [542, 480, 430] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { display: false }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent" }, ticks: { display: false, } }] }, } }); ctx = document.getElementById('chartActivity').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'bar', data: { labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], datasets: [ { label: "Data", borderColor: '#fcc468', fill: true, backgroundColor: '#fcc468', hoverBorderColor: '#fcc468', borderWidth: 8, data: [100, 120, 80, 100, 90, 130, 110, 100, 80, 110, 130, 140, 130, 120, 130, 80, 100, 90, 120, 130], }, { label: "Data", borderColor: '#4cbdd7', fill: true, backgroundColor: '#4cbdd7', hoverBorderColor: '#4cbdd7', borderWidth: 8, data: [80, 140, 50, 120, 50, 150, 60, 130, 50, 130, 150, 100, 110, 80, 140, 50, 140, 50, 110, 150], } ] }, options: { tooltips: { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, maxTicksLimit: 5, padding: 20 }, gridLines: { zeroLineColor: "transparent", display: true, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 0.4, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }] } } }); ctx = document.getElementById('chartViews').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'bar', data: { labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], datasets: [ { label: "Data", borderColor: '#fcc468', fill: true, backgroundColor: '#fcc468', hoverBorderColor: '#fcc468', borderWidth: 5, data: [100, 120, 80, 100, 90, 130, 110, 100, 80, 110, 130, 140, 130, 120, 130, 80, 100, 90, 120, 130], } ] }, options: { tooltips: { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, maxTicksLimit: 5, padding: 20 }, gridLines: { zeroLineColor: "transparent", display: true, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 0.4, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }] } } }); ctx = document.getElementById('chartStock').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'line', data: { labels: ["6pm", "9pm", "11pm", "2am", "4am", "6am", "8am"], datasets: [{ label: "Active Users", borderColor: "#f17e5d", pointBackgroundColor: "#f17e5d", pointRadius: 3, pointHoverRadius: 3, lineTension: 0, fill: false, borderWidth: 3, data: [200, 250, 300, 350, 280, 330, 400] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, }, gridLines: { drawBorder: false, borderDash: [8, 5], zeroLineColor: "transparent", color: '#9f9f9f' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, borderDash: [8, 5], color: '#9f9f9f', zeroLineColor: "transparent" }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }); ctx = document.getElementById('activeUsers').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'line', data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"], datasets: [{ label: "Active Users", borderColor: "#6bd098", pointRadius: 0, pointHoverRadius: 0, fill: false, borderWidth: 3, data: [542, 480, 430, 550, 530, 453, 380, 434, 568, 610] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, //padding: 20 }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent", display: false, }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }); // General configuration for the charts with Line gradientStroke gradientChartOptionsConfiguration = { maintainAspectRatio: false, legend: { display: false }, tooltips: { bodySpacing: 4, mode: "nearest", intersect: 0, position: "nearest", xPadding: 10, yPadding: 10, caretPadding: 10 }, responsive: 1, scales: { yAxes: [{ display: 0, gridLines: 0, ticks: { display: false }, gridLines: { zeroLineColor: "transparent", drawTicks: false, display: false, drawBorder: false } }], xAxes: [{ display: 0, gridLines: 0, ticks: { display: false }, gridLines: { zeroLineColor: "transparent", drawTicks: false, display: false, drawBorder: false } }] }, layout: { padding: { left: 0, right: 0, top: 15, bottom: 15 } } }; gradientChartOptionsConfigurationWithNumbersAndGrid = { maintainAspectRatio: false, legend: { display: false }, tooltips: { bodySpacing: 4, mode: "nearest", intersect: 0, position: "nearest", xPadding: 10, yPadding: 10, caretPadding: 10 }, responsive: true, scales: { yAxes: [{ gridLines: 0, gridLines: { zeroLineColor: "transparent", drawBorder: false } }], xAxes: [{ display: 0, gridLines: 0, ticks: { display: false }, gridLines: { zeroLineColor: "transparent", drawTicks: false, display: false, drawBorder: false } }] }, layout: { padding: { left: 0, right: 0, top: 15, bottom: 15 } } }; }, initDocChart: function() { ctx = document.getElementById('BarChartExample').getContext("2d"); myChart = new Chart(ctx, { type: 'bar', data: { labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], datasets: [ { label: "Data", borderColor: '#fcc468', fill: true, backgroundColor: '#fcc468', hoverBorderColor: '#fcc468', borderWidth: 8, data: [100, 120, 80, 100, 90, 130, 110, 100, 80, 110, 130, 140, 130, 120, 130, 80, 100, 90, 120, 130], }, { label: "Data", borderColor: '#4cbdd7', fill: true, backgroundColor: '#4cbdd7', hoverBorderColor: '#4cbdd7', borderWidth: 8, data: [80, 140, 50, 120, 50, 150, 60, 130, 50, 130, 150, 100, 110, 80, 140, 50, 140, 50, 110, 150], } ] }, options: { tooltips: { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, maxTicksLimit: 5, padding: 20 }, gridLines: { zeroLineColor: "transparent", display: true, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 0.4, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }] } } }); }, initDashboardPageCharts: function() { chartColor = "#FFFFFF"; var cardStatsMiniLineColor = "#fff", cardStatsMiniDotColor = "#fff"; ctx = document.getElementById('chartActivity').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'bar', data: { labels: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], datasets: [ { label: "Data", borderColor: '#fcc468', fill: true, backgroundColor: '#fcc468', hoverBorderColor: '#fcc468', borderWidth: 8, data: [100, 120, 80, 100, 90, 130, 110, 100, 80, 110, 130, 140, 130, 120, 130, 80, 100, 90, 120, 130], }, { label: "Data", borderColor: '#4cbdd7', fill: true, backgroundColor: '#4cbdd7', hoverBorderColor: '#4cbdd7', borderWidth: 8, data: [80, 140, 50, 120, 50, 150, 60, 130, 50, 130, 150, 100, 110, 80, 140, 50, 140, 50, 110, 150], } ] }, options: { tooltips: { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, maxTicksLimit: 5, padding: 20 }, gridLines: { zeroLineColor: "transparent", display: true, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 0.4, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }] } } }); Chart.pluginService.register({ beforeDraw: function(chart) { if (chart.config.options.elements.center) { //Get ctx from string var ctx = chart.chart.ctx; //Get options from the center object in options var centerConfig = chart.config.options.elements.center; var fontStyle = centerConfig.fontStyle || 'Arial'; var txt = centerConfig.text; var color = centerConfig.color || '#000'; var sidePadding = centerConfig.sidePadding || 20; var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2) //Start with a base font of 30px ctx.font = "30px " + fontStyle; //Get the width of the string and also the width of the element minus 10 to give it 5px side padding var stringWidth = ctx.measureText(txt).width; var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated; // Find out how much the font can grow in width. var widthRatio = elementWidth / stringWidth; var newFontSize = Math.floor(30 * widthRatio); var elementHeight = (chart.innerRadius * 2); // Pick a new font size so it will not be larger than the height of label. var fontSizeToUse = Math.min(newFontSize, elementHeight); //Set font settings to draw it correctly. ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2); var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2); ctx.font = fontSizeToUse + "px " + fontStyle; ctx.fillStyle = color; //Draw text in center ctx.fillText(txt, centerX, centerY); } } }); ctx = document.getElementById('chartDonut1').getContext("2d"); myChart = new Chart(ctx, { type: 'pie', data: { labels: [1, 2], datasets: [{ label: "Emails", pointRadius: 0, pointHoverRadius: 0, backgroundColor: ['#4acccd', '#f4f3ef'], borderWidth: 0, data: [60, 40] }] }, options: { elements: { center: { text: '60%', color: '#66615c', // Default is #000000 fontStyle: 'Arial', // Default is Arial sidePadding: 60 // Defualt is 20 (as a percentage) } }, cutoutPercentage: 90, legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { display: false }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent" }, ticks: { display: false, } }] }, } }); ctx = document.getElementById('chartDonut2').getContext("2d"); myChart = new Chart(ctx, { type: 'pie', data: { labels: [1, 2], datasets: [{ label: "Emails", pointRadius: 0, pointHoverRadius: 0, backgroundColor: ['#fcc468', '#f4f3ef'], borderWidth: 0, data: [34, 66] }] }, options: { elements: { center: { text: '34%', color: '#66615c', // Default is #000000 fontStyle: 'Arial', // Default is Arial sidePadding: 60 // Defualt is 20 (as a percentage) } }, cutoutPercentage: 90, legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { display: false }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent" }, ticks: { display: false, } }] }, } }); ctx = document.getElementById('chartDonut3').getContext("2d"); myChart = new Chart(ctx, { type: 'pie', data: { labels: [1, 2], datasets: [{ label: "Emails", pointRadius: 0, pointHoverRadius: 0, backgroundColor: ['#f17e5d', '#f4f3ef'], borderWidth: 0, data: [80, 20] }] }, options: { elements: { center: { text: '80%', color: '#66615c', // Default is #000000 fontStyle: 'Arial', // Default is Arial sidePadding: 60 // Defualt is 20 (as a percentage) } }, cutoutPercentage: 90, legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { display: false }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent" }, ticks: { display: false, } }] }, } }); ctx = document.getElementById('chartDonut4').getContext("2d"); myChart = new Chart(ctx, { type: 'pie', data: { labels: [1, 2], datasets: [{ label: "Emails", pointRadius: 0, pointHoverRadius: 0, backgroundColor: ['#66615b', '#f4f3ef'], borderWidth: 0, data: [11, 89] }] }, options: { elements: { center: { text: '11%', color: '#66615c', // Default is #000000 fontStyle: 'Arial', // Default is Arial sidePadding: 60 // Defualt is 20 (as a percentage) } }, cutoutPercentage: 90, legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { display: false }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent" }, ticks: { display: false, } }] }, } }); ctx = document.getElementById('activeUsers').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#80b6f4'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)"); myChart = new Chart(ctx, { type: 'line', data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"], datasets: [{ label: "Active Users", borderColor: "#6bd098", pointRadius: 0, pointHoverRadius: 0, fill: false, borderWidth: 3, data: [542, 480, 430, 550, 530, 453, 380, 434, 568, 610] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, //padding: 20 }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent", display: false, }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }); ctx = document.getElementById('emailsCampaignChart').getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#18ce0f'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, hexToRGB('#18ce0f', 0.4)); myChart = new Chart(ctx, { type: 'line', data: { labels: ["12pm", "3pm", "6pm", "9pm", "12am", "3am", "6am", "9am"], datasets: [{ label: "Email Stats", borderColor: "#ef8156", pointHoverRadius: 0, pointRadius: 0, fill: false, backgroundColor: gradientFill, borderWidth: 3, data: [40, 500, 650, 700, 1200, 1250, 1300, 1900] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, //padding: 20 }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent", display: false, }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }); var e = document.getElementById("activeCountries").getContext("2d"); gradientStroke = ctx.createLinearGradient(500, 0, 100, 0); gradientStroke.addColorStop(0, '#2CA8FF'); gradientStroke.addColorStop(1, chartColor); gradientFill = ctx.createLinearGradient(0, 170, 0, 50); gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)"); gradientFill.addColorStop(1, hexToRGB('#2CA8FF', 0.4)); var a = { type: "line", data: { labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October"], datasets: [{ label: "Active Countries", backgroundColor: gradientFill, borderColor: "#fbc658", pointHoverRadius: 0, pointRadius: 0, fill: false, borderWidth: 3, data: [80, 78, 86, 96, 83, 85, 76, 75, 88, 90] }] }, options: { legend: { display: false }, tooltips: { enabled: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", beginAtZero: false, maxTicksLimit: 5, //padding: 20 }, gridLines: { drawBorder: false, zeroLineColor: "transparent", color: 'rgba(255,255,255,0.05)' } }], xAxes: [{ barPercentage: 1.6, gridLines: { drawBorder: false, color: 'rgba(255,255,255,0.1)', zeroLineColor: "transparent", display: false, }, ticks: { padding: 20, fontColor: "#9f9f9f" } }] }, } }; var viewsChart = new Chart(e, a); } };
# coding: utf-8 """ OpsGenie REST API OpsGenie OpenAPI Specification # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import opsgenie_swagger from opsgenie_swagger.models.neustar_integration import NeustarIntegration # noqa: E501 from opsgenie_swagger.rest import ApiException class TestNeustarIntegration(unittest.TestCase): """NeustarIntegration unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNeustarIntegration(self): """Test NeustarIntegration""" # FIXME: construct object with mandatory attributes with example values # model = opsgenie_swagger.models.neustar_integration.NeustarIntegration() # noqa: E501 pass if __name__ == '__main__': unittest.main()
$(document).ready(function() { CKEDITOR.replace("customContent", { height: 300 }); if (window.history.length > 1) { $("#btnGoBack").show(); } else { $("#btnGoBack").hide(); } $("#productPriceId").on("change", function() { let newPriceId = $(this).val(); let newPrice = productPriceSet.find(function(elem) { return elem._id === newPriceId; }); let publishDateStart = $("#publishStart").val(); setPublishEnd(publishDateStart, newPrice.postingDays); }); $("#publishStart").on("change", function() { let priceId = $("#productPriceId").val(); let price = productPriceSet.find(function(elem) { return elem._id === priceId; }); let newPublishDateStart = $(this).val(); setPublishEnd(newPublishDateStart, price.postingDays); }); }); function goBack() { let bu = $("#bu").val(); if (bu) { window.location = window.atob(bu); } else { window.history.back(); } } function setPublishEnd(publishDateStart, postingDays) { let newPublishDateEnd = moment(publishDateStart, "YYYY-MM-DD").add(postingDays - 1, "days").format("YYYY-MM-DD"); $("#publishEnd").val(newPublishDateEnd); }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["roomsession"],{"0c18":function(t,e,n){},ada6:function(t,e,n){"use strict";n.r(e);var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"room-session"},[n("v-container",[n("v-row",{attrs:{justify:"center"}},[n("v-col",{attrs:{cols:"12",sm:"10",md:"8",lg:"4",xl:"3"}},[n("v-card",[n("v-form",{ref:"enterform",on:{submit:function(t){t.preventDefault()}}},[n("v-alert",{attrs:{type:"info",color:t.theme.color}},[t._v(" "+t._s(t.theme.label+"チャンネル")+" ")]),n("v-text-field",{staticClass:"mx-10",attrs:{disabled:!t.enabled,label:"ユーザ名を入力(ex:テスト太郎)",rules:[t.required,t.limitLength],counter:"10"},model:{value:t.username,callback:function(e){t.username=e},expression:"username"}}),n("v-card-actions",{staticClass:"justify-center"},[n("v-btn",{attrs:{disabled:!t.enabled},on:{click:function(e){return e.stopPropagation(),t.showChat(e)}}},[t._v("入室")])],1)],1)],1)],1)],1)],1)],1)},i=[],o=(n("ac1f"),n("5319"),n("96cf"),n("1da1")),a=n("d4ec"),s=n("bee2"),c=n("262e"),l=n("2caf"),u=n("9ab4"),d=n("60a3"),h=n("1709"),f=n("cbe5"),p=n("2c15");d["a"].registerHooks(["beforeRouteEnter"]);var v=function(t){Object(c["a"])(n,t);var e=Object(l["a"])(n);function n(){var t;return Object(a["a"])(this,n),t=e.apply(this,arguments),t.enabled=!0,t.username="",t.theme={textColor:"",color:"",label:""},t.channelType="public",t.required=function(t){return!!t||"必ず入力してください。"},t.limitLength=function(t){return t.length<=10||"10文字以内で入力してください。"},t}return Object(s["a"])(n,[{key:"enableChanged",value:function(t){}},{key:"enabledChanged",value:function(t){this.enableChanged(t)}},{key:"mounted",value:function(){var t=this;this.$route.params.type&&Object(p["d"])(this.$route.params.type)&&(f["a"].SET_CHANNEL_TYPE(this.$route.params.type),this.channelType=this.$route.params.type),window.addEventListener("beforeunload",(function(e){var n;null===(n=t.chatWindow)||void 0===n||n.close()})),this.theme=Object(p["b"])(this.channelType)}},{key:"beforeRouteEnter",value:function(t,e,n){n((function(t){e.matched.length||t.$router.replace({path:"/"})}))}},{key:"showChat",value:function(){var t=Object(o["a"])(regeneratorRuntime.mark((function t(){var e,n,r=this;return regeneratorRuntime.wrap((function(t){while(1)switch(t.prev=t.next){case 0:if(this.$refs.enterform.validate()){t.next=2;break}return t.abrupt("return");case 2:f["a"].setUser(this.username),this.chatWindow=null!==(e=window.open("/chat","_blank","width=600,height=800"))&&void 0!==e?e:void 0,null===(n=this.chatWindow)||void 0===n||n.addEventListener("beforeunload",(function(t){f["a"].disconnect(),r.enabled=!0})),this.enabled=!1;case 6:case"end":return t.stop()}}),t,this)})));function e(){return t.apply(this,arguments)}return e}()}]),n}(d["d"]);Object(u["a"])([Object(d["b"])("headerButtonEnableChanged")],v.prototype,"enableChanged",null),Object(u["a"])([Object(d["e"])("enabled")],v.prototype,"enabledChanged",null),v=Object(u["a"])([Object(d["a"])({components:{Chat:h["a"]}})],v);var b=v,m=b,g=n("2877"),_=n("6544"),y=n.n(_),C=(n("caad"),n("5530")),w=n("ade3"),B=(n("0c18"),n("10d2")),$=n("afdd"),j=n("9d26"),O=n("f2e7"),E=n("7560"),x=n("2b0e"),k=x["a"].extend({name:"transitionable",props:{mode:String,origin:String,transition:String}}),V=n("58df"),I=n("d9bd"),S=Object(V["a"])(B["a"],O["a"],k).extend({name:"v-alert",props:{border:{type:String,validator:function(t){return["top","right","bottom","left"].includes(t)}},closeLabel:{type:String,default:"$vuetify.close"},coloredBorder:Boolean,dense:Boolean,dismissible:Boolean,closeIcon:{type:String,default:"$cancel"},icon:{default:"",type:[Boolean,String],validator:function(t){return"string"===typeof t||!1===t}},outlined:Boolean,prominent:Boolean,text:Boolean,type:{type:String,validator:function(t){return["info","error","success","warning"].includes(t)}},value:{type:Boolean,default:!0}},computed:{__cachedBorder:function(){if(!this.border)return null;var t={staticClass:"v-alert__border",class:Object(w["a"])({},"v-alert__border--".concat(this.border),!0)};return this.coloredBorder&&(t=this.setBackgroundColor(this.computedColor,t),t.class["v-alert__border--has-color"]=!0),this.$createElement("div",t)},__cachedDismissible:function(){var t=this;if(!this.dismissible)return null;var e=this.iconColor;return this.$createElement($["a"],{staticClass:"v-alert__dismissible",props:{color:e,icon:!0,small:!0},attrs:{"aria-label":this.$vuetify.lang.t(this.closeLabel)},on:{click:function(){return t.isActive=!1}}},[this.$createElement(j["a"],{props:{color:e}},this.closeIcon)])},__cachedIcon:function(){return this.computedIcon?this.$createElement(j["a"],{staticClass:"v-alert__icon",props:{color:this.iconColor}},this.computedIcon):null},classes:function(){var t=Object(C["a"])(Object(C["a"])({},B["a"].options.computed.classes.call(this)),{},{"v-alert--border":Boolean(this.border),"v-alert--dense":this.dense,"v-alert--outlined":this.outlined,"v-alert--prominent":this.prominent,"v-alert--text":this.text});return this.border&&(t["v-alert--border-".concat(this.border)]=!0),t},computedColor:function(){return this.color||this.type},computedIcon:function(){return!1!==this.icon&&("string"===typeof this.icon&&this.icon?this.icon:!!["error","info","success","warning"].includes(this.type)&&"$".concat(this.type))},hasColoredIcon:function(){return this.hasText||Boolean(this.border)&&this.coloredBorder},hasText:function(){return this.text||this.outlined},iconColor:function(){return this.hasColoredIcon?this.computedColor:void 0},isDark:function(){return!(!this.type||this.coloredBorder||this.outlined)||E["a"].options.computed.isDark.call(this)}},created:function(){this.$attrs.hasOwnProperty("outline")&&Object(I["a"])("outline","outlined",this)},methods:{genWrapper:function(){var t=[this.$slots.prepend||this.__cachedIcon,this.genContent(),this.__cachedBorder,this.$slots.append,this.$scopedSlots.close?this.$scopedSlots.close({toggle:this.toggle}):this.__cachedDismissible],e={staticClass:"v-alert__wrapper"};return this.$createElement("div",e,t)},genContent:function(){return this.$createElement("div",{staticClass:"v-alert__content"},this.$slots.default)},genAlert:function(){var t={staticClass:"v-alert",attrs:{role:"alert"},on:this.listeners$,class:this.classes,style:this.styles,directives:[{name:"show",value:this.isActive}]};if(!this.coloredBorder){var e=this.hasText?this.setTextColor:this.setBackgroundColor;t=e(this.computedColor,t)}return this.$createElement("div",t,[this.genWrapper()])},toggle:function(){this.isActive=!this.isActive}},render:function(t){var e=this.genAlert();return this.transition?t("transition",{props:{name:this.transition,origin:this.origin,mode:this.mode}},[e]):e}}),T=n("8336"),A=n("b0af"),L=n("99d9"),D=n("62ad"),R=n("a523"),W=(n("4de4"),n("7db0"),n("4160"),n("07ac"),n("2532"),n("159b"),n("7e2b")),P=n("3206"),z=Object(V["a"])(W["a"],Object(P["b"])("form")).extend({name:"v-form",provide:function(){return{form:this}},inheritAttrs:!1,props:{disabled:Boolean,lazyValidation:Boolean,readonly:Boolean,value:Boolean},data:function(){return{inputs:[],watchers:[],errorBag:{}}},watch:{errorBag:{handler:function(t){var e=Object.values(t).includes(!0);this.$emit("input",!e)},deep:!0,immediate:!0}},methods:{watchInput:function(t){var e=this,n=function(t){return t.$watch("hasError",(function(n){e.$set(e.errorBag,t._uid,n)}),{immediate:!0})},r={_uid:t._uid,valid:function(){},shouldValidate:function(){}};return this.lazyValidation?r.shouldValidate=t.$watch("shouldValidate",(function(i){i&&(e.errorBag.hasOwnProperty(t._uid)||(r.valid=n(t)))})):r.valid=n(t),r},validate:function(){return 0===this.inputs.filter((function(t){return!t.validate(!0)})).length},reset:function(){this.inputs.forEach((function(t){return t.reset()})),this.resetErrorBag()},resetErrorBag:function(){var t=this;this.lazyValidation&&setTimeout((function(){t.errorBag={}}),0)},resetValidation:function(){this.inputs.forEach((function(t){return t.resetValidation()})),this.resetErrorBag()},register:function(t){this.inputs.push(t),this.watchers.push(this.watchInput(t))},unregister:function(t){var e=this.inputs.find((function(e){return e._uid===t._uid}));if(e){var n=this.watchers.find((function(t){return t._uid===e._uid}));n&&(n.valid(),n.shouldValidate()),this.watchers=this.watchers.filter((function(t){return t._uid!==e._uid})),this.inputs=this.inputs.filter((function(t){return t._uid!==e._uid})),this.$delete(this.errorBag,e._uid)}}},render:function(t){var e=this;return t("form",{staticClass:"v-form",attrs:Object(C["a"])({novalidate:!0},this.attrs$),on:{submit:function(t){return e.$emit("submit",t)}}},this.$slots.default)}}),q=n("0fd9"),F=n("8654"),H=Object(g["a"])(m,r,i,!1,null,null,null);e["default"]=H.exports;y()(H,{VAlert:S,VBtn:T["a"],VCard:A["a"],VCardActions:L["a"],VCol:D["a"],VContainer:R["a"],VForm:z,VRow:q["a"],VTextField:F["a"]})},afdd:function(t,e,n){"use strict";var r=n("8336");e["a"]=r["a"]}}]);
import numpy as np from flarestack import ResultsHandler, MinimisationHandler from flarestack.data.icecube import ps_v003_p02 from flarestack.shared import plot_output_dir, flux_to_k from flarestack.utils.prepare_catalogue import ps_catalogue_name from flarestack.icecube_utils.reference_sensitivity import ( reference_sensitivity, reference_discovery_potential, ) import matplotlib.pyplot as plt from flarestack import analyse, wait_cluster import logging logging.basicConfig(level=logging.INFO) # Initialise Injectors/LLHs injection_energy = { "energy_pdf_name": "power_law", "gamma": 2.0, } injection_time = { "time_pdf_name": "steady", } llh_time = { "time_pdf_name": "steady", } inj_kwargs = { "injection_energy_pdf": injection_energy, "injection_sig_time_pdf": injection_time, } llh_energy = injection_energy llh_kwargs = { "llh_name": "standard", "llh_energy_pdf": llh_energy, "llh_sig_time_pdf": llh_time, "llh_bkg_time_pdf": {"time_pdf_name": "steady"}, "negative_ns_bool": True, } name = "analyses/benchmarks/ps_sens_10yr" # sindecs = np.linspace(0.90, -0.90, 3) sindecs = np.linspace(0.90, -0.90, 19) # sindecs = np.linspace(0.5, -0.5, 3) # analyses = [] cluster = True job_ids = [] for sindec in sindecs: cat_path = ps_catalogue_name(sindec) subname = name + "/sindec=" + "{0:.2f}".format(sindec) + "/" scale = flux_to_k(reference_sensitivity(sindec)) * 3 mh_dict = { "name": subname, "mh_name": "fixed_weights", "dataset": ps_v003_p02, "catalogue": cat_path, "inj_dict": inj_kwargs, "llh_dict": llh_kwargs, "scale": scale, "n_trials": 5000, "n_steps": 15, } job_id = analyse( mh_dict, cluster=cluster, n_cpu=1 if cluster else 32, h_cpu="23:59:59", ram_per_core="8.0G", ) job_ids.append(job_id) analyses.append(mh_dict) wait_cluster(job_ids) sens = [] sens_err = [] disc_pots = [] for rh_dict in analyses: rh = ResultsHandler(rh_dict) sens.append(rh.sensitivity) sens_err.append(rh.sensitivity_err) disc_pots.append(rh.disc_potential) sens_err = np.array(sens_err).T # sens = reference_sensitivity(sindecs, sample="7yr") # disc_pots = reference_discovery_potential(sindecs, sample="7yr") # sens_err = 0.1*sens plot_range = np.linspace(-0.99, 0.99, 1000) plt.figure() ax1 = plt.subplot2grid((4, 1), (0, 0), colspan=3, rowspan=3) ax1.plot( sindecs, reference_sensitivity(sindecs, sample="10yr"), color="blue", label=r"10-year Point Source analysis", ) # ax1.plot(sindecs, reference_sensitivity(sindecs, sample="7yr"), color="green", # label=r"7-year Point Source analysis") # ax1.plot(sindecs, sens, color='orange', label="Flarestack") ax1.errorbar( sindecs, sens, yerr=sens_err, color="orange", label="Sensitivity", marker="o" ) ax1.plot( sindecs, reference_discovery_potential(sindecs, sample="10yr"), color="blue", linestyle="--", ) ax1.plot( sindecs, disc_pots, color="orange", linestyle="--", label="Discovery Potential" ) ax1.set_xlim(xmin=-1.0, xmax=1.0) # ax1.set_ylim(ymin=1.e-13, ymax=1.e-10) ax1.grid(True, which="both") ax1.semilogy(nonposy="clip") ax1.set_ylabel(r"Flux Strength [ GeV$^{-1}$ cm$^{-2}$ s$^{-1}$ ]", fontsize=12) ax2 = plt.subplot2grid((4, 1), (3, 0), colspan=3, rowspan=1, sharex=ax1) sens_ratios = np.array(sens) / reference_sensitivity(sindecs, sample="10yr") sens_ratio_errs = sens_err / reference_sensitivity(sindecs, sample="10yr") disc_ratios = np.array(disc_pots) / reference_discovery_potential( sindecs, sample="10yr" ) ax2.errorbar(sindecs, sens_ratios, yerr=sens_ratio_errs, color="red", marker="o") ax2.scatter(sindecs, disc_ratios, color="k") ax2.plot(sindecs, disc_ratios, color="k", linestyle="--") ax2.set_ylabel(r"ratio", fontsize=12) ax2.set_xlabel(r"sin($\delta$)", fontsize=12) plt.suptitle("Point Source Sensitivity (10 year)") # ax1.set_xlim(xmin=-1.0, xmax=1.0) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) ax1.legend(loc="upper right", fancybox=True, framealpha=1.0) savefile = plot_output_dir(name) + "/PS10yr.pdf" logging.info(f"Saving to {savefile}") plt.savefig(savefile) plt.close()
import re from model.contact import Contact def test_contacts_on_home_page(app,db): home_page_contacts,db_contacts = sorted(app.contact.get_contact_list(),key=Contact.id_or_max),sorted(db.get_contact_list(),key=Contact.id_or_max) assert len(home_page_contacts)==len(db_contacts) for index in range(0,len(db_contacts)): assert db_contacts[index].first_name == home_page_contacts[index].first_name assert db_contacts[index].last_name == home_page_contacts[index].last_name assert db_contacts[index].address == home_page_contacts[index].address assert merge_emails_like_on_home_page([db_contacts[index].email, db_contacts[index].email2, db_contacts[index].email3]) == home_page_contacts[index].all_emails_from_home_page assert merge_phones_like_on_home_page([db_contacts[index].home_number, db_contacts[index].mobile_number, db_contacts[index].work_number, db_contacts[index].phone2])== home_page_contacts[index].all_phones_from_home_page def merge_emails_like_on_home_page(list): return "\n".join(filter(lambda x: x != "", filter(lambda x: x is not None,list))) def merge_phones_like_on_home_page(list): return "\n".join(filter(lambda x: x != "", map(lambda x: re.sub("[ -()]","",x), filter(lambda x: x is not None,list))))
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SQLALCHEMY_DATABASE_URI = 'postgresql://__DB_USER__:__DB_PASSWORD__@__DB_HOST__:__DB_PORT__/__DB_NAME__' SQLALCHEMY_TRACK_MODIFICATIONS = False TWITTER_CONSUMER_KEY = '__TWITTER_CONSUMER_KEY__' TWITTER_CONSUMER_SECRET = '__TWITTER_CONSUMER_SECRET__' TWITTER_ACCESS_TOKEN_KEY = '__TWITTER_ACCESS_TOKEN_KEY__' TWITTER_ACCESS_TOKEN_SECRET = '__TWITTER_ACCESS_TOKEN_SECRET__'
import bibtexParse from 'bibtex-parse-js'; import bibString from '../static/bibliography.bib'; export function getBibtexEntries() { let bibliography = bibtexParse.toJSON(bibString); // filter out all bibtex entries except interactive article examples let examples = bibliography.filter(function (bibEntry) { return bibEntry.entryTags.howpublished === "web"; }); examples.forEach(citation => { // coerce tag string into array of strings citation.entryTags.tags = citation.entryTags.tags.split(',') // give examples with no journal string with space if (!citation.entryTags.journal) { citation.entryTags.journal = "Self published" } // publication/author format for table if (citation.entryTags.author) { let tempAuthor = citation.entryTags.author tempAuthor = tempAuthor.split(' and ') if (tempAuthor.length === 1) { citation.entryTags.author = tempAuthor } else { tempAuthor.forEach((author, i) => { author = author.split(',') tempAuthor[i] = author[1].trim() + ' ' + author[0].trim() }); citation.entryTags.author = tempAuthor.join(', ') } } }); return examples; }
import React from "react"; import { Link } from "react-router-dom"; import styles from "./NavItems.module.scss"; import { navItemsList } from "../../utilities/NavItemsList"; const NavItemsUI = ({ favJobs, isInDesktopNav, handleMenuClose }) => { return ( <ul className={`${styles.nav_items} ${ isInDesktopNav ? styles.nav_items_desktop : styles.nav_items_mobile }`} > {navItemsList.map((navItem) => ( <li key={navItem.id} className={styles.nav_item}> <Link onClick={handleMenuClose} to={navItem.link} className={`${styles.link} ${ navItem.label === "YOUR LIST" ? styles.your_list_item : "" }`} > {navItem.label} {navItem.label === "YOUR LIST" && favJobs.length > 0 && ( <span className={styles.fav_jobs_num}>{favJobs.length}</span> )} </Link> </li> ))} </ul> ); }; export default NavItemsUI;
(window.webpackJsonp=window.webpackJsonp||[]).push([[29],{"113":function(e,t,n){"use strict";var r=n(114);function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,e.exports=function(){function shim(e,t,n,o,c,s){if(s!==r){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function getShim(){return shim}shim.isRequired=shim;var e={"array":shim,"bool":shim,"func":shim,"number":shim,"object":shim,"string":shim,"symbol":shim,"any":shim,"arrayOf":getShim,"element":shim,"elementType":shim,"instanceOf":getShim,"node":shim,"objectOf":getShim,"oneOf":getShim,"oneOfType":getShim,"shape":getShim,"exact":getShim,"checkPropTypes":emptyFunctionWithReset,"resetWarningCache":emptyFunction};return e.PropTypes=e,e}},"114":function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},"115":function(e,t,n){var r=n(116);"string"==typeof r&&(r=[[e.i,r,""]]);var o={"sourceMap":!1,"insertAt":"top","hmr":!0,"transform":void 0,"insertInto":void 0};n(66)(r,o);r.locals&&(e.exports=r.locals)},"116":function(e,t,n){(e.exports=n(65)(!1)).push([e.i,".taro-text {\n -moz-user-select: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.taro-text__selectable {\n -moz-user-select: text;\n -webkit-user-select: text;\n -ms-user-select: text;\n user-select: text;\n}",""])},"209":function(e,t,n){"use strict";n.d(t,"a",function(){return m});var r,o,c=n(1),s=n(2),i=n(57),a=n.n(i),l=n(55),u=n.n(l),p=n(210),f=n(56),h=function(){function defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}();var m=(o=r=function(e){function AtIcon(){return function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,AtIcon),function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(AtIcon.__proto__||Object.getPrototypeOf(AtIcon)).apply(this,arguments))}return function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{"constructor":{"value":e,"enumerable":!1,"writable":!0,"configurable":!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(AtIcon,f["a"]),h(AtIcon,[{"key":"handleClick","value":function handleClick(){var e;(e=this.props).onClick.apply(e,arguments)}},{"key":"render","value":function render(){var e=this.props,t=e.customStyle,n=e.className,r=e.prefixClass,o=e.value,i=e.size,a=e.color,l={"fontSize":""+s.default.pxTransform(2*parseInt(i)),"color":a},f=o?r+"-"+o:"";return c.l.createElement(p.a,{"className":u()(r,f,n),"style":this.mergeStyle(l,t),"onClick":this.handleClick.bind(this)})}}]),AtIcon}(),r.defaultProps={"customStyle":"","className":"","prefixClass":"at-icon","value":"","color":"","size":24,"onClick":function onClick(){}},r.propTypes={"customStyle":a.a.oneOfType([a.a.object,a.a.string]),"className":a.a.oneOfType([a.a.array,a.a.string]),"prefixClass":a.a.string,"value":a.a.string,"color":a.a.string,"size":a.a.oneOfType([a.a.string,a.a.number]),"onClick":a.a.func},o)},"210":function(e,t,n){"use strict";n(62);var r=n(1),o=n(67),c=n(55),s=n.n(c),i=(n(115),Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}),a=function(){function defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}();var l=function(e){function Text(){return function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,Text),function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(Text.__proto__||Object.getPrototypeOf(Text)).apply(this,arguments))}return function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{"constructor":{"value":e,"enumerable":!1,"writable":!0,"configurable":!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(Text,r["l"].Component),a(Text,[{"key":"render","value":function render(){var e=this.props,t=e.className,n=e.selectable,c=void 0!==n&&n,a=s()("taro-text",{"taro-text__selectable":c},t);return r.l.createElement("span",i({},Object(o.a)(this.props,["selectable","className"]),{"className":a}),this.props.children)}}]),Text}();t.a=l},"344":function(e,t,n){"use strict";n.r(t);var r,o=n(1),c=n(2),s=n(333),i=n(209),a=n(16),l=n(75),u=n(76),p=(n(88),function(){function defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}()),f=function get(e,t,n){null===e&&(e=Function.prototype);var r=Object.getOwnPropertyDescriptor(e,t);if(void 0===r){var o=Object.getPrototypeOf(e);return null===o?void 0:get(o,t,n)}if("value"in r)return r.value;var c=r.get;return void 0!==c?c.call(n):void 0};t.default=Object(a.b)(function(e){return{"screen":e.screen}},function(e){return{"setScreen":function setScreen(t){e(Object(l.b)(t))}}})(r=function(e){function Acts(){return function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,Acts),function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(Acts.__proto__||Object.getPrototypeOf(Acts)).apply(this,arguments))}return function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{"constructor":{"value":e,"enumerable":!1,"writable":!0,"configurable":!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(Acts,c["default"].Component),p(Acts,[{"key":"redirectTo","value":function redirectTo(e){c.default.redirectTo({"url":e})}},{"key":"selectorIndexs","value":function selectorIndexs(e){this.props.screen.acts!==e&&this.props.setScreen({"update":!0,"acts":e}),c.default.navigateBack()}},{"key":"render","value":function render(){var e=this.props.screen.acts;return o.l.createElement(s.a,{"className":"jxh-app"},o.l.createElement(u.a,{"isActive":2,"onClick":this.redirectTo.bind(this)}),o.l.createElement(s.a,{"className":"screen-select","hoverClass":"screen-select-hover","onClick":this.selectorIndexs.bind(this,"")},o.l.createElement(s.a,{"className":"screen-select-border"},o.l.createElement(s.a,{"className":"screen-select-item"},"所有类型"),""===e&&o.l.createElement(s.a,{"className":"screen-select-checked"},o.l.createElement(i.a,{"value":"check","size":"20","color":"#6885CF"})))),o.l.createElement(s.a,{"className":"screen-select","hoverClass":"screen-select-hover","onClick":this.selectorIndexs.bind(this,1)},o.l.createElement(s.a,{"className":"screen-select-border"},o.l.createElement(s.a,{"className":"screen-select-item"},"购入"),1===e&&o.l.createElement(s.a,{"className":"screen-select-checked"},o.l.createElement(i.a,{"value":"check","size":"20","color":"#6885CF"})))),o.l.createElement(s.a,{"className":"screen-select","hoverClass":"screen-select-hover","onClick":this.selectorIndexs.bind(this,2)},o.l.createElement(s.a,{"className":"screen-select-border"},o.l.createElement(s.a,{"className":"screen-select-item"},"卖出"),2===e&&o.l.createElement(s.a,{"className":"screen-select-checked"},o.l.createElement(i.a,{"value":"check","size":"20","color":"#6885CF"})))))}},{"key":"componentDidMount","value":function componentDidMount(){f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidMount",this)&&f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidMount",this).call(this)}},{"key":"componentDidShow","value":function componentDidShow(){f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidShow",this)&&f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidShow",this).call(this)}},{"key":"componentDidHide","value":function componentDidHide(){f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidHide",this)&&f(Acts.prototype.__proto__||Object.getPrototypeOf(Acts.prototype),"componentDidHide",this).call(this)}}]),Acts}())||r},"56":function(e,t,n){"use strict";n.d(t,"a",function(){return l});var r,o,c=n(2),s=function(){function defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}(),i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};var a=function objectToString(e){if(e&&"object"===(void 0===e?"undefined":i(e))){var t="";return Object.keys(e).forEach(function(n){var r=n.replace(/([A-Z])/g,"-$1").toLowerCase();t+=r+":"+e[n]+";"}),t}return e&&"string"==typeof e?e:""},l=(o=r=function(e){function AtComponent(){return function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,AtComponent),function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(AtComponent.__proto__||Object.getPrototypeOf(AtComponent)).apply(this,arguments))}return function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{"constructor":{"value":e,"enumerable":!1,"writable":!0,"configurable":!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(AtComponent,c["default"].Component),s(AtComponent,[{"key":"mergeStyle","value":function mergeStyle(e,t){return e&&"object"===(void 0===e?"undefined":i(e))&&t&&"object"===(void 0===t?"undefined":i(t))?Object.assign({},e,t):a(e)+a(t)}}]),AtComponent}(),r.options={"addGlobalClass":!0},o)},"57":function(e,t,n){e.exports=n(113)()},"75":function(e,t,n){"use strict";n.d(t,"b",function(){return o}),n.d(t,"a",function(){return c});var r=n(11),o=function set(e){return{"type":r.b,"data":e}},c=function reset(){return{"type":r.a}}},"76":function(e,t,n){"use strict";var r,o=n(1),c=n(2),s=n(210),i=n(333),a=n(209),l=n(16),u=(n(77),function(){function defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}());t.a=Object(l.b)(function(e){return{"screen":e.screen,"coins":e.coins,"status":e.status}})(r=function(e){function Screen(){return function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,Screen),function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(Screen.__proto__||Object.getPrototypeOf(Screen)).apply(this,arguments))}return function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{"constructor":{"value":e,"enumerable":!1,"writable":!0,"configurable":!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(Screen,c["default"].Component),u(Screen,[{"key":"handleClick","value":function handleClick(e){if(this.props.onClick){var t="/pages/wallet/trades/screen/"+e;this.props.onClick(t)}}},{"key":"render","value":function render(){var e=["screen-item","screen-item","screen-item"];(this.props.isActive||0===this.props.isActive)&&(e[this.props.isActive]+=" screen-active");var t=this.props.screen,n=(t.time_mode,t.start_time),r=t.end_time,c=t.coin_id,l=t.acts,u=o.l.createElement(s.a,null,"本月");u=""!==n&&""!==r?o.l.createElement(i.a,{"className":"screen-item-date"},o.l.createElement(i.a,{"className":"screen-item-date-context"},o.l.createElement(s.a,null,n),o.l.createElement("br",null),o.l.createElement(s.a,null,r)),o.l.createElement(i.a,null,o.l.createElement(a.a,{"prefixClass":"jxh","value":"xiangxia","size":"16"}))):""!==n||""!==r?o.l.createElement(i.a,null,o.l.createElement(s.a,null,n||r),o.l.createElement(a.a,{"prefixClass":"jxh","value":"xiangxia","size":"16"})):o.l.createElement(i.a,null,o.l.createElement(s.a,{"className":""},"本月"),o.l.createElement(a.a,{"prefixClass":"jxh","value":"xiangxia","size":"16"}));var p=c&&this.props.coins[c]?this.props.coins[c].title:"所有币种",f=l&&this.props.status.trades[l]?this.props.status.trades[l].title:"所有类别";return o.l.createElement(i.a,{"className":"screen"},o.l.createElement(i.a,{"className":e[0],"onClick":this.handleClick.bind(this,"timer")},u),o.l.createElement(i.a,{"className":e[1],"onClick":this.handleClick.bind(this,"coins")},o.l.createElement(s.a,null,p),o.l.createElement(a.a,{"prefixClass":"jxh","value":"xiangxia","size":"16"})),o.l.createElement(i.a,{"className":e[2],"onClick":this.handleClick.bind(this,"acts")},o.l.createElement(s.a,null,f),o.l.createElement(a.a,{"prefixClass":"jxh","value":"xiangxia","size":"16"})))}}]),Screen}())||r},"77":function(e,t,n){},"88":function(e,t,n){}}]);
'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const path = require('path') const {closeWindow} = require('./window-helpers') const {expect} = chai chai.use(dirtyChai) const {remote} = require('electron') const {ipcMain, BrowserWindow} = remote describe('ipc main module', () => { const fixtures = path.join(__dirname, 'fixtures') let w = null afterEach(() => closeWindow(w).then(() => { w = null })) describe('ipc.sendSync', () => { afterEach(() => { ipcMain.removeAllListeners('send-sync-message') }) it('does not crash when reply is not sent and browser is destroyed', (done) => { w = new BrowserWindow({ show: false }) ipcMain.once('send-sync-message', (event) => { event.returnValue = null done() }) w.loadURL(`file://${path.join(fixtures, 'api', 'send-sync-message.html')}`) }) it('does not crash when reply is sent by multiple listeners', (done) => { w = new BrowserWindow({ show: false }) ipcMain.on('send-sync-message', (event) => { event.returnValue = null }) ipcMain.on('send-sync-message', (event) => { event.returnValue = null done() }) w.loadURL(`file://${path.join(fixtures, 'api', 'send-sync-message.html')}`) }) }) describe('remote listeners', () => { it('can be added and removed correctly', () => { w = new BrowserWindow({ show: false }) const listener = () => {} w.on('test', listener) expect(w.listenerCount('test')).to.equal(1) w.removeListener('test', listener) expect(w.listenerCount('test')).to.equal(0) }) }) it('throws an error when removing all the listeners', () => { ipcMain.on('test-event', () => {}) expect(ipcMain.listenerCount('test-event')).to.equal(1) expect(() => { ipcMain.removeAllListeners() }).to.throw(/Removing all listeners from ipcMain will make Electron internals stop working/) ipcMain.removeAllListeners('test-event') expect(ipcMain.listenerCount('test-event')).to.equal(0) }) describe('remote objects registry', () => { it('does not dereference until the render view is deleted (regression)', (done) => { w = new BrowserWindow({ show: false }) ipcMain.once('error-message', (event, message) => { const correctMsgStart = message.startsWith('Cannot call function \'getURL\' on missing remote object') expect(correctMsgStart).to.be.true() done() }) w.loadURL(`file://${path.join(fixtures, 'api', 'render-view-deleted.html')}`) }) }) })
// @flow import {symbolLayoutAttributes, collisionVertexAttributes, collisionBoxLayout, collisionCircleLayout, dynamicLayoutAttributes } from './symbol_attributes'; import {SymbolLayoutArray, SymbolDynamicLayoutArray, SymbolOpacityArray, CollisionBoxLayoutArray, CollisionCircleLayoutArray, CollisionVertexArray, PlacedSymbolArray, SymbolInstanceArray, GlyphOffsetArray, SymbolLineVertexArray } from '../array_types'; import Point from '@mapbox/point-geometry'; import SegmentVector from '../segment'; import {ProgramConfigurationSet} from '../program_configuration'; import {TriangleIndexArray, LineIndexArray} from '../index_array_type'; import transformText from '../../symbol/transform_text'; import mergeLines from '../../symbol/mergelines'; import {allowsVerticalWritingMode} from '../../util/script_detection'; import {WritingMode} from '../../symbol/shaping'; import loadGeometry from '../load_geometry'; import mvt from '@mapbox/vector-tile'; const vectorTileFeatureTypes = mvt.VectorTileFeature.types; import {verticalizedCharacterMap} from '../../util/verticalize_punctuation'; import Anchor from '../../symbol/anchor'; import {getSizeData} from '../../symbol/symbol_size'; import {MAX_PACKED_SIZE} from '../../symbol/symbol_layout'; import {register} from '../../util/web_worker_transfer'; import EvaluationParameters from '../../style/evaluation_parameters'; import Formatted from '../../style-spec/expression/types/formatted'; import ResolvedImage from '../../style-spec/expression/types/resolved_image'; import {plugin as globalRTLTextPlugin, getRTLTextPluginStatus} from '../../source/rtl_text_plugin'; import type { Bucket, BucketParameters, IndexedFeature, PopulateParameters } from '../bucket'; import type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types'; import type {StructArray, StructArrayMember} from '../../util/struct_array'; import SymbolStyleLayer from '../../style/style_layer/symbol_style_layer'; import type Context from '../../gl/context'; import type IndexBuffer from '../../gl/index_buffer'; import type VertexBuffer from '../../gl/vertex_buffer'; import type {SymbolQuad} from '../../symbol/quads'; import type {SizeData} from '../../symbol/symbol_size'; import type {FeatureStates} from '../../source/source_state'; import type {ImagePosition} from '../../render/image_atlas'; export type SingleCollisionBox = { x1: number; y1: number; x2: number; y2: number; anchorPointX: number; anchorPointY: number; }; export type CollisionArrays = { textBox?: SingleCollisionBox; verticalTextBox?: SingleCollisionBox; iconBox?: SingleCollisionBox; verticalIconBox?: SingleCollisionBox; textCircles?: Array<number>; textFeatureIndex?: number; verticalTextFeatureIndex?: number; iconFeatureIndex?: number; verticalIconFeatureIndex?: number; }; export type SymbolFeature = {| sortKey: number | void, text: Formatted | void, icon: ResolvedImage | void, index: number, sourceLayerIndex: number, geometry: Array<Array<Point>>, properties: Object, type: 'Point' | 'LineString' | 'Polygon', id?: any |}; // Opacity arrays are frequently updated but don't contain a lot of information, so we pack them // tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph // 7 bits are for the current opacity, and the lowest bit is the target opacity // actually defined in symbol_attributes.js // const placementOpacityAttributes = [ // { name: 'a_fade_opacity', components: 1, type: 'Uint32' } // ]; const shaderOpacityAttributes = [ {name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0} ]; function addVertex(array, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF: boolean, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) { const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0; const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0; array.emplaceBack( // a_pos_offset anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), // a_data tx, // x coordinate of symbol on glyph atlas texture ty, // y coordinate of symbol on glyph atlas texture (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256 ); } function addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number) { dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle); } export class SymbolBuffers { layoutVertexArray: SymbolLayoutArray; layoutVertexBuffer: VertexBuffer; indexArray: TriangleIndexArray; indexBuffer: IndexBuffer; programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>; segments: SegmentVector; dynamicLayoutVertexArray: SymbolDynamicLayoutArray; dynamicLayoutVertexBuffer: VertexBuffer; opacityVertexArray: SymbolOpacityArray; opacityVertexBuffer: VertexBuffer; collisionVertexArray: CollisionVertexArray; collisionVertexBuffer: VertexBuffer; placedSymbolArray: PlacedSymbolArray; constructor(programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>) { this.layoutVertexArray = new SymbolLayoutArray(); this.indexArray = new TriangleIndexArray(); this.programConfigurations = programConfigurations; this.segments = new SegmentVector(); this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(); this.opacityVertexArray = new SymbolOpacityArray(); this.placedSymbolArray = new PlacedSymbolArray(); } upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean) { if (upload) { this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members); this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer); this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true); this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true); // This is a performance hack so that we can write to opacityVertexArray with uint32s // even though the shaders read uint8s this.opacityVertexBuffer.itemSize = 1; } if (upload || update) { this.programConfigurations.upload(context); } } destroy() { if (!this.layoutVertexBuffer) return; this.layoutVertexBuffer.destroy(); this.indexBuffer.destroy(); this.programConfigurations.destroy(); this.segments.destroy(); this.dynamicLayoutVertexBuffer.destroy(); this.opacityVertexBuffer.destroy(); } } register('SymbolBuffers', SymbolBuffers); class CollisionBuffers { layoutVertexArray: StructArray; layoutAttributes: Array<StructArrayMember>; layoutVertexBuffer: VertexBuffer; indexArray: TriangleIndexArray | LineIndexArray; indexBuffer: IndexBuffer; segments: SegmentVector; collisionVertexArray: CollisionVertexArray; collisionVertexBuffer: VertexBuffer; constructor(LayoutArray: Class<StructArray>, layoutAttributes: Array<StructArrayMember>, IndexArray: Class<TriangleIndexArray | LineIndexArray>) { this.layoutVertexArray = new LayoutArray(); this.layoutAttributes = layoutAttributes; this.indexArray = new IndexArray(); this.segments = new SegmentVector(); this.collisionVertexArray = new CollisionVertexArray(); } upload(context: Context) { this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes); this.indexBuffer = context.createIndexBuffer(this.indexArray); this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true); } destroy() { if (!this.layoutVertexBuffer) return; this.layoutVertexBuffer.destroy(); this.indexBuffer.destroy(); this.segments.destroy(); this.collisionVertexBuffer.destroy(); } } register('CollisionBuffers', CollisionBuffers); /** * Unlike other buckets, which simply implement #addFeature with type-specific * logic for (essentially) triangulating feature geometries, SymbolBucket * requires specialized behavior: * * 1. WorkerTile#parse(), the logical owner of the bucket creation process, * calls SymbolBucket#populate(), which resolves text and icon tokens on * each feature, adds each glyphs and symbols needed to the passed-in * collections options.glyphDependencies and options.iconDependencies, and * stores the feature data for use in subsequent step (this.features). * * 2. WorkerTile asynchronously requests from the main thread all of the glyphs * and icons needed (by this bucket and any others). When glyphs and icons * have been received, the WorkerTile creates a CollisionIndex and invokes: * * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and * layout on a Symbol Bucket. This step populates: * `this.symbolInstances`: metadata on generated symbols * `this.collisionBoxArray`: collision data for use by foreground * `this.text`: SymbolBuffers for text symbols * `this.icons`: SymbolBuffers for icons * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes * `this.iconCollisionCircle`: Debug SymbolBuffers for icon collision circles * `this.textCollisionCircle`: Debug SymbolBuffers for text collision circles * The results are sent to the foreground for rendering * * 4. performSymbolPlacement(bucket, collisionIndex) is run on the foreground, * and uses the CollisionIndex along with current camera settings to determine * which symbols can actually show on the map. Collided symbols are hidden * using a dynamic "OpacityVertexArray". * * @private */ class SymbolBucket implements Bucket { static MAX_GLYPHS: number; static addDynamicAttributes: typeof addDynamicAttributes; collisionBoxArray: CollisionBoxArray; zoom: number; overscaling: number; layers: Array<SymbolStyleLayer>; layerIds: Array<string>; stateDependentLayers: Array<SymbolStyleLayer>; stateDependentLayerIds: Array<string>; index: number; sdfIcons: boolean; iconsInText: boolean; iconsNeedLinear: boolean; bucketInstanceId: number; justReloaded: boolean; hasPattern: boolean; textSizeData: SizeData; iconSizeData: SizeData; glyphOffsetArray: GlyphOffsetArray; lineVertexArray: SymbolLineVertexArray; features: Array<SymbolFeature>; symbolInstances: SymbolInstanceArray; collisionArrays: Array<CollisionArrays>; pixelRatio: number; tilePixelRatio: number; compareText: {[string]: Array<Point>}; fadeStartTime: number; sortFeaturesByKey: boolean; sortFeaturesByY: boolean; sortedAngle: number; featureSortOrder: Array<number>; text: SymbolBuffers; icon: SymbolBuffers; textCollisionBox: CollisionBuffers; iconCollisionBox: CollisionBuffers; textCollisionCircle: CollisionBuffers; iconCollisionCircle: CollisionBuffers; uploaded: boolean; sourceLayerIndex: number; sourceID: string; symbolInstanceIndexes: Array<number>; writingModes: Array<number>; allowVerticalPlacement: boolean; hasPaintOverrides: boolean; hasRTLText: boolean; constructor(options: BucketParameters<SymbolStyleLayer>) { this.collisionBoxArray = options.collisionBoxArray; this.zoom = options.zoom; this.overscaling = options.overscaling; this.layers = options.layers; this.layerIds = this.layers.map(layer => layer.id); this.index = options.index; this.pixelRatio = options.pixelRatio; this.sourceLayerIndex = options.sourceLayerIndex; this.hasPattern = false; this.hasPaintOverrides = false; this.hasRTLText = false; const layer = this.layers[0]; const unevaluatedLayoutValues = layer._unevaluatedLayout._values; this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']); this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']); const layout = this.layers[0].layout; const sortKey = layout.get('symbol-sort-key'); const zOrder = layout.get('symbol-z-order'); this.sortFeaturesByKey = zOrder !== 'viewport-y' && sortKey.constantOr(1) !== undefined; const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey); this.sortFeaturesByY = zOrderByViewportY && (layout.get('text-allow-overlap') || layout.get('icon-allow-overlap') || layout.get('text-ignore-placement') || layout.get('icon-ignore-placement')); if (layout.get('symbol-placement') === 'point') { this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]); } this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id); this.sourceID = options.sourceID; } createArrays() { const layout = this.layers[0].layout; this.hasPaintOverrides = SymbolStyleLayer.hasPaintOverrides(layout); this.text = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, property => /^text/.test(property))); this.icon = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, property => /^icon/.test(property))); this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray); this.textCollisionCircle = new CollisionBuffers(CollisionCircleLayoutArray, collisionCircleLayout.members, TriangleIndexArray); this.iconCollisionCircle = new CollisionBuffers(CollisionCircleLayoutArray, collisionCircleLayout.members, TriangleIndexArray); this.glyphOffsetArray = new GlyphOffsetArray(); this.lineVertexArray = new SymbolLineVertexArray(); this.symbolInstances = new SymbolInstanceArray(); } calculateGlyphDependencies(text: string, stack: {[number]: boolean}, textAlongLine: boolean, allowVerticalPlacement: boolean, doesAllowVerticalWritingMode: boolean) { for (let i = 0; i < text.length; i++) { stack[text.charCodeAt(i)] = true; if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) { const verticalChar = verticalizedCharacterMap[text.charAt(i)]; if (verticalChar) { stack[verticalChar.charCodeAt(0)] = true; } } } } populate(features: Array<IndexedFeature>, options: PopulateParameters) { const layer = this.layers[0]; const layout = layer.layout; const textFont = layout.get('text-font'); const textField = layout.get('text-field'); const iconImage = layout.get('icon-image'); const hasText = (textField.value.kind !== 'constant' || (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) || textField.value.value.toString().length > 0) && (textFont.value.kind !== 'constant' || textFont.value.value.length > 0); // we should always resolve the icon-image value if the property was defined in the style // this allows us to fire the styleimagemissing event if image evaluation returns null // the only way to distinguish between null returned from a coalesce statement with no valid images // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object const hasIcon = (iconImage.value.kind !== 'constant' || !!iconImage.value.value) && Object.keys(iconImage.parameters).length > 0; const symbolSortKey = layout.get('symbol-sort-key'); this.features = []; if (!hasText && !hasIcon) { return; } const icons = options.iconDependencies; const stacks = options.glyphDependencies; const availableImages = options.availableImages; const globalProperties = new EvaluationParameters(this.zoom); for (const {feature, id, index, sourceLayerIndex} of features) { if (!layer._featureFilter(globalProperties, feature)) { continue; } let text: Formatted | void; if (hasText) { // Expression evaluation will automatically coerce to Formatted // but plain string token evaluation skips that pathway so do the // conversion here. const resolvedTokens = layer.getValueAndResolveTokens('text-field', feature, availableImages); const formattedText = Formatted.factory(resolvedTokens); if (formattedText.containsRTLText()) { this.hasRTLText = true; } if ( !this.hasRTLText || // non-rtl text so can proceed safely getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping this.hasRTLText && globalRTLTextPlugin.isParsed() // Use the rtlText plugin to shape text ) { text = transformText(formattedText, layer, feature); } } let icon: ResolvedImage | void; if (hasIcon) { // Expression evaluation will automatically coerce to Image // but plain string token evaluation skips that pathway so do the // conversion here. const resolvedTokens = layer.getValueAndResolveTokens('icon-image', feature, availableImages); if (resolvedTokens instanceof ResolvedImage) { icon = resolvedTokens; } else { icon = ResolvedImage.fromString(resolvedTokens); } } if (!text && !icon) { continue; } const sortKey = this.sortFeaturesByKey ? symbolSortKey.evaluate(feature, {}) : undefined; const symbolFeature: SymbolFeature = { id, text, icon, index, sourceLayerIndex, geometry: loadGeometry(feature), properties: feature.properties, type: vectorTileFeatureTypes[feature.type], sortKey }; this.features.push(symbolFeature); if (icon) { icons[icon.name] = true; } if (text) { const fontStack = textFont.evaluate(feature, {}).join(','); const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point'; this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0; for (const section of text.sections) { if (!section.image) { const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString()); const sectionFont = section.fontStack || fontStack; const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {}; this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode); } else { // Add section image to the list of dependencies. icons[section.image.name] = true; } } } } if (layout.get('symbol-placement') === 'line') { // Merge adjacent lines with the same text to improve labelling. // It's better to place labels on one long line than on many short segments. this.features = mergeLines(this.features); } if (this.sortFeaturesByKey) { this.features.sort((a, b) => { // a.sortKey is always a number when sortFeaturesByKey is true return ((a.sortKey: any): number) - ((b.sortKey: any): number); }); } } update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[string]: ImagePosition}) { if (!this.stateDependentLayers.length) return; this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions); } isEmpty() { return this.symbolInstances.length === 0; } uploadPending() { return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload; } upload(context: Context) { if (!this.uploaded) { this.textCollisionBox.upload(context); this.iconCollisionBox.upload(context); this.textCollisionCircle.upload(context); this.iconCollisionCircle.upload(context); } this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload); this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload); this.uploaded = true; } destroy() { this.text.destroy(); this.icon.destroy(); this.textCollisionBox.destroy(); this.iconCollisionBox.destroy(); this.textCollisionCircle.destroy(); this.iconCollisionCircle.destroy(); } addToLineVertexArray(anchor: Anchor, line: any) { const lineStartIndex = this.lineVertexArray.length; if (anchor.segment !== undefined) { let sumForwardLength = anchor.dist(line[anchor.segment + 1]); let sumBackwardLength = anchor.dist(line[anchor.segment]); const vertices = {}; for (let i = anchor.segment + 1; i < line.length; i++) { vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength}; if (i < line.length - 1) { sumForwardLength += line[i + 1].dist(line[i]); } } for (let i = anchor.segment || 0; i >= 0; i--) { vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength}; if (i > 0) { sumBackwardLength += line[i - 1].dist(line[i]); } } for (let i = 0; i < line.length; i++) { const vertex = vertices[i]; this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor); } } return { lineStartIndex, lineLength: this.lineVertexArray.length - lineStartIndex }; } addSymbols(arrays: SymbolBuffers, quads: Array<SymbolQuad>, sizeVertex: any, lineOffset: [number, number], alongLine: boolean, feature: SymbolFeature, writingMode: any, labelAnchor: Anchor, lineStartIndex: number, lineLength: number, associatedIconIndex: number) { const indexArray = arrays.indexArray; const layoutVertexArray = arrays.layoutVertexArray; const dynamicLayoutVertexArray = arrays.dynamicLayoutVertexArray; const segment = arrays.segments.prepareSegment(4 * quads.length, arrays.layoutVertexArray, arrays.indexArray, feature.sortKey); const glyphOffsetArrayStart = this.glyphOffsetArray.length; const vertexStartIndex = segment.vertexLength; const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0; const addSymbol = (symbol: SymbolQuad) => { const tl = symbol.tl, tr = symbol.tr, bl = symbol.bl, br = symbol.br, tex = symbol.tex, pixelOffsetTL = symbol.pixelOffsetTL, pixelOffsetBR = symbol.pixelOffsetBR, mfsx = symbol.minFontScaleX, mfsy = symbol.minFontScaleY; const index = segment.vertexLength; const y = symbol.glyphOffset[1]; addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, symbol.isSDF, pixelOffsetTL.x, pixelOffsetTL.y, mfsx, mfsy); addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, symbol.isSDF, pixelOffsetBR.x, pixelOffsetTL.y, mfsx, mfsy); addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, symbol.isSDF, pixelOffsetTL.x, pixelOffsetBR.y, mfsx, mfsy); addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, symbol.isSDF, pixelOffsetBR.x, pixelOffsetBR.y, mfsx, mfsy); addDynamicAttributes(dynamicLayoutVertexArray, labelAnchor, angle); indexArray.emplaceBack(index, index + 1, index + 2); indexArray.emplaceBack(index + 1, index + 2, index + 3); segment.vertexLength += 4; segment.primitiveLength += 2; this.glyphOffsetArray.emplaceBack(symbol.glyphOffset[0]); }; if (feature.text && feature.text.sections) { const sections = feature.text.sections; if (this.hasPaintOverrides) { let currentSectionIndex; const populatePaintArrayForSection = (sectionIndex?: number, lastSection: boolean) => { if (currentSectionIndex !== undefined && (currentSectionIndex !== sectionIndex || lastSection)) { arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {}, sections[currentSectionIndex]); } currentSectionIndex = sectionIndex; }; for (const symbol of quads) { populatePaintArrayForSection(symbol.sectionIndex, false); addSymbol(symbol); } // Populate paint arrays for the last section. populatePaintArrayForSection(currentSectionIndex, true); } else { for (const symbol of quads) { addSymbol(symbol); } arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {}, sections[0]); } } else { for (const symbol of quads) { addSymbol(symbol); } arrays.programConfigurations.populatePaintArrays(arrays.layoutVertexArray.length, feature, feature.index, {}); } arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, (labelAnchor.segment: any), sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed 0, (false: any), // The crossTileID is only filled/used on the foreground for dynamic text anchors 0, associatedIconIndex ); } _addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point) { collisionVertexArray.emplaceBack(0, 0); return layoutVertexArray.emplaceBack( // pos point.x, point.y, // a_anchor_pos anchorX, anchorY, // extrude Math.round(extrude.x), Math.round(extrude.y)); } addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance, isCircle: boolean) { const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray); const index = segment.vertexLength; const layoutVertexArray = arrays.layoutVertexArray; const collisionVertexArray = arrays.collisionVertexArray; const anchorX = symbolInstance.anchorX; const anchorY = symbolInstance.anchorY; this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1)); this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1)); this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2)); this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y2)); segment.vertexLength += 4; if (isCircle) { const indexArray: TriangleIndexArray = (arrays.indexArray: any); indexArray.emplaceBack(index, index + 1, index + 2); indexArray.emplaceBack(index, index + 2, index + 3); segment.primitiveLength += 2; } else { const indexArray: LineIndexArray = (arrays.indexArray: any); indexArray.emplaceBack(index, index + 1); indexArray.emplaceBack(index + 1, index + 2); indexArray.emplaceBack(index + 2, index + 3); indexArray.emplaceBack(index + 3, index); segment.primitiveLength += 4; } } addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean) { for (let b = startIndex; b < endIndex; b++) { const box: CollisionBox = (this.collisionBoxArray.get(b): any); const x1 = box.x1; const y1 = box.y1; const x2 = box.x2; const y2 = box.y2; // If the radius > 0, this collision box is actually a circle // The data we add to the buffers is exactly the same, but we'll render with a different shader. const isCircle = box.radius > 0; this.addCollisionDebugVertices(x1, y1, x2, y2, isCircle ? (isText ? this.textCollisionCircle : this.iconCollisionCircle) : (isText ? this.textCollisionBox : this.iconCollisionBox), box.anchorPoint, symbolInstance, isCircle); } } generateCollisionDebugBuffers() { for (let i = 0; i < this.symbolInstances.length; i++) { const symbolInstance = this.symbolInstances.get(i); this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true); this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true); this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false); this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false); } } // These flat arrays are meant to be quicker to iterate over than the source // CollisionBoxArray _deserializeCollisionBoxesForSymbol(collisionBoxArray: CollisionBoxArray, textStartIndex: number, textEndIndex: number, verticalTextStartIndex: number, verticalTextEndIndex: number, iconStartIndex: number, iconEndIndex: number, verticalIconStartIndex: number, verticalIconEndIndex: number): CollisionArrays { const collisionArrays = {}; for (let k = textStartIndex; k < textEndIndex; k++) { const box: CollisionBox = (collisionBoxArray.get(k): any); if (box.radius === 0) { collisionArrays.textBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY}; collisionArrays.textFeatureIndex = box.featureIndex; break; // Only one box allowed per instance } else { if (!collisionArrays.textCircles) { collisionArrays.textCircles = []; collisionArrays.textFeatureIndex = box.featureIndex; } const used = 1; // May be updated at collision detection time collisionArrays.textCircles.push(box.anchorPointX, box.anchorPointY, box.radius, box.signedDistanceFromAnchor, used); } } for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) { const box: CollisionBox = (collisionBoxArray.get(k): any); if (box.radius === 0) { collisionArrays.verticalTextBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY}; collisionArrays.verticalTextFeatureIndex = box.featureIndex; break; // Only one box allowed per instance } } for (let k = iconStartIndex; k < iconEndIndex; k++) { // An icon can only have one box now, so this indexing is a bit vestigial... const box: CollisionBox = (collisionBoxArray.get(k): any); if (box.radius === 0) { collisionArrays.iconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY}; collisionArrays.iconFeatureIndex = box.featureIndex; break; // Only one box allowed per instance } } for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) { // An icon can only have one box now, so this indexing is a bit vestigial... const box: CollisionBox = (collisionBoxArray.get(k): any); if (box.radius === 0) { collisionArrays.verticalIconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY}; collisionArrays.verticalIconFeatureIndex = box.featureIndex; break; // Only one box allowed per instance } } return collisionArrays; } deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray) { this.collisionArrays = []; for (let i = 0; i < this.symbolInstances.length; i++) { const symbolInstance = this.symbolInstances.get(i); this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol( collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex )); } } hasTextData() { return this.text.segments.get().length > 0; } hasIconData() { return this.icon.segments.get().length > 0; } hasTextCollisionBoxData() { return this.textCollisionBox.segments.get().length > 0; } hasIconCollisionBoxData() { return this.iconCollisionBox.segments.get().length > 0; } hasTextCollisionCircleData() { return this.textCollisionCircle.segments.get().length > 0; } hasIconCollisionCircleData() { return this.iconCollisionCircle.segments.get().length > 0; } addIndicesForPlacedTextSymbol(placedTextSymbolIndex: number) { const placedSymbol = this.text.placedSymbolArray.get(placedTextSymbolIndex); const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4; for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) { this.text.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); this.text.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); } } addIndicesForPlacedIconSymbol(placedIconSymbolIndex: number) { const placedIcon = this.icon.placedSymbolArray.get(placedIconSymbolIndex); if (placedIcon.numGlyphs) { const vertexIndex = placedIcon.vertexStartIndex; this.icon.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2); this.icon.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3); } } getSortedSymbolIndexes(angle: number) { if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) { return this.symbolInstanceIndexes; } const sin = Math.sin(angle); const cos = Math.cos(angle); const rotatedYs = []; const featureIndexes = []; const result = []; for (let i = 0; i < this.symbolInstances.length; ++i) { result.push(i); const symbolInstance = this.symbolInstances.get(i); rotatedYs.push(Math.round(sin * symbolInstance.anchorX + cos * symbolInstance.anchorY) | 0); featureIndexes.push(symbolInstance.featureIndex); } result.sort((aIndex, bIndex) => { return (rotatedYs[aIndex] - rotatedYs[bIndex]) || (featureIndexes[bIndex] - featureIndexes[aIndex]); }); return result; } sortFeatures(angle: number) { if (!this.sortFeaturesByY) return; if (this.sortedAngle === angle) return; // The current approach to sorting doesn't sort across segments so don't try. // Sorting within segments separately seemed not to be worth the complexity. if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return; // If the symbols are allowed to overlap sort them by their vertical screen position. // The index array buffer is rewritten to reference the (unchanged) vertices in the // sorted order. // To avoid sorting the actual symbolInstance array we sort an array of indexes. this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle); this.sortedAngle = angle; this.text.indexArray.clear(); this.icon.indexArray.clear(); this.featureSortOrder = []; for (const i of this.symbolInstanceIndexes) { const symbolInstance = this.symbolInstances.get(i); this.featureSortOrder.push(symbolInstance.featureIndex); [ symbolInstance.rightJustifiedTextSymbolIndex, symbolInstance.centerJustifiedTextSymbolIndex, symbolInstance.leftJustifiedTextSymbolIndex ].forEach((index, i, array) => { // Only add a given index the first time it shows up, // to avoid duplicate opacity entries when multiple justifications // share the same glyphs. if (index >= 0 && array.indexOf(index) === i) { this.addIndicesForPlacedTextSymbol(index); } }); if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) { this.addIndicesForPlacedTextSymbol(symbolInstance.verticalPlacedTextSymbolIndex); } if (symbolInstance.placedIconSymbolIndex >= 0) { this.addIndicesForPlacedIconSymbol(symbolInstance.placedIconSymbolIndex); } if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) { this.addIndicesForPlacedIconSymbol(symbolInstance.verticalPlacedIconSymbolIndex); } } if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray); if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray); } } register('SymbolBucket', SymbolBucket, { omit: ['layers', 'collisionBoxArray', 'features', 'compareText'] }); // this constant is based on the size of StructArray indexes used in a symbol // bucket--namely, glyphOffsetArrayStart // eg the max valid UInt16 is 65,535 // See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation // lineStartIndex and textBoxStartIndex could potentially be concerns // but we expect there to be many fewer boxes/lines than glyphs SymbolBucket.MAX_GLYPHS = 65535; SymbolBucket.addDynamicAttributes = addDynamicAttributes; export default SymbolBucket; export {addDynamicAttributes};
const fs = require("fs"); const child_process = require("child_process"); let chunklostTool = require("C:\\work\\Git_work\\NodeGFS\\Master\\metadata\\tool\\chunklostTool.js"); //////////////////////////////////////////////////////////////////////////////// function reload(){ delete require.cache[require.resolve("C:\\work\\Git_work\\NodeGFS\\Master\\metadata\\tool\\chunklostTool.js")] chunklostTool = require("C:\\work\\Git_work\\NodeGFS\\Master\\metadata\\tool\\chunklostTool.js"); } async function forkServer(forkFile, startParam){ var child = child_process.fork(forkFile); return new Promise( (resolve, reject) => { child.on("message", (result) => { if("onload" == result.state){ child.send(startParam); } else if("started" == result.state){ resolve(child); } else{ } }); }); } //////////////////////////////////////////////////////////////////////////////// // get list which will be repaired, early is in top exports.getList = function(){ // START reload(); // run var chunklostData = {"aabbccdd":[1599701518196,1603841772044],"eeffgghh":[1603842910809,0],"ooxxkkmm":[1599701518196,0]}; var timestamp = 1606443851845; var result = chunklostTool.getList(chunklostData, timestamp); return result; // END }; // set time stamp exports.setTime = function(){ // START reload(); // run var chunklostData = {"aabbccdd":[1599701518196,0],"eeffgghh":[1603842910809,0],"ooxxkkmm":[1599701518196,0]}; var chunkNameList = ["aabbccdd", "eeffgghh"] var timestamp = 1601131150047; var result = chunklostTool.setTime(chunklostData, chunkNameList, timestamp); return result; // END }; // add chunk is lost exports.add = function(){ // START reload(); // run var chunklostData = {}; var chunkNameList = ["aabbccdd"] var timestamp = 1601130794448; var result = chunklostTool.add(chunklostData, chunkNameList, timestamp); return result; // END }; // clear chunk whick is repaired or expired exports._clear = function(){ // START reload(); // run var chunklostData = {"aabbccdd":[1599701518196,1603841772044],"eeffgghh":[1603842910809,0],"ooxxkkmm":[1599701518196,0]}; var timestamp = 1603843484074; var result = chunklostTool._clear(chunklostData, timestamp); return result; // END };
webpackJsonp([1],{"+Z9X":function(e,s){},"4ww8":function(e,s){},NHnr:function(e,s,r){"use strict";Object.defineProperty(s,"__esModule",{value:!0});var i=r("7+uW"),t=r("woOf"),o=r.n(t),n={name:"resizer-comp",props:["splitTo","resizerColor","resizerBorderColor","resizerThickness","resizerBorderThickness"],data:function(){return{isMouseOver:!1}},computed:{resizerTotalThickness:function(){return this.resizerThickness+2*this.resizerBorderThickness},margin:function(){return this.resizerBorderThickness+Math.floor(this.resizerThickness/2)},rBorder:function(){return"rows"===this.splitTo?{border1:"top",border2:"bottom"}:{border1:"left",border2:"right"}},resStyle:function(){var e={};return e["background-color"]=this.resizerColor,"rows"===this.splitTo?(e.height=this.resizerTotalThickness+"px",e.margin="-"+this.margin+"px 0",e.padding="0 "+this.resizerBorderThickness+"px"):(e.width=this.resizerTotalThickness+"px",e.margin="0 -"+this.margin+"px",e.padding=this.resizerBorderThickness+"px 0"),this.isMouseOver?e["border-"+this.rBorder.border1]=e["border-"+this.rBorder.border2]=this.resizerBorderColor+" solid "+this.resizerBorderThickness+"px":e["border-"+this.rBorder.border1]=e["border-"+this.rBorder.border2]="transparent solid "+this.resizerBorderThickness+"px",e}}},l={render:function(){var e=this,s=e.$createElement;return(e._self._c||s)("span",{staticClass:"Resizer",style:e.resStyle,on:{mouseover:function(s){e.isMouseOver=!0},mouseout:function(s){e.isMouseOver=!1}}})},staticRenderFns:[]};var a={render:function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"Pane"},[this._t("default",[this._v("Content")])],2)},staticRenderFns:[]};function c(e,s){if(e.selection)e.selection.empty();else try{s.getSelection().removeAllRanges()}catch(e){}}var d={name:"pane-rs",components:{"resizer-comp":r("VU/8")(n,l,!1,function(e){r("+Z9X")},"data-v-5c23195e",null).exports,"pane-comp":r("VU/8")({name:"pane-comp",data:function(){return{}}},a,!1,function(e){r("4ww8")},"data-v-6df9e7fc",null).exports},props:{allowResize:{type:Boolean,default:!1},splitTo:{type:String,default:"columns"},primary:{type:String,default:"first"},size:{type:Number,default:16},units:{type:String,default:"pixels"},minSize:{type:Number,default:16},maxSize:{type:Number,default:0},step:{type:Number,default:0},resizerThickness:{type:Number,default:2},resizerColor:{type:String,default:"#AAA"},resizerBorderColor:{type:String,default:"rgba(0,0,0, 0.15)"},resizerBorderThickness:{type:Number,default:3}},data:function(){return{active:!1,position:0,localSize:this.size}},watch:{size:function(e,s){this.localSize=e}},computed:{classObject:function(){return{columns:"columns"===this.splitTo,rows:"rows"===this.splitTo}},iStyleFirst:function(){var e={flex:1,position:"relative",outline:"none"};if("first"===this.primary){e.flex="0 0 auto";var s="pixels"===this.units?"px":"%";"columns"===this.splitTo?e.width=this.localSize+s:e.height=this.localSize+s}else e.flex="1 1 0%";return e},iStyleSecond:function(){var e={flex:1,position:"relative",outline:"none"};if("second"===this.primary){e.flex="0 0 auto";var s="pixels"===this.units?"px":"%";"columns"===this.splitTo?e.width=this.localSize+s:e.height=this.localSize+s}else e.flex="1 1 0%";return e}},methods:{round2Fixed:function(e){var s=+e;return isNaN(s)?NaN:+((s=Math.round(+(s.toString()+"e2"))).toString()+"e-2")},onMouseDown:function(e){if(this.allowResize){var s=o()({},e,{touches:[{clientX:e.clientX,clientY:e.clientY}]});this.onTouchStart(s)}},onTouchStart:function(e){if(this.allowResize){c(document,window);var s="columns"===this.splitTo?e.touches[0].clientX:e.touches[0].clientY;"function"==typeof this.onDragStarted&&onDragStarted(),this.active=!0,this.position=s}},onMouseMove:function(e){if(this.allowResize){var s=o()({},e,{touches:[{clientX:e.clientX,clientY:e.clientY}]});this.onTouchMove(s)}},onTouchMove:function(e){var s=this.$data,r=s.active,i=s.position,t=this.$props,o=t.maxSize,n=t.minSize,l=(t.step,t.allowResize),a=t.splitTo,d=t.primary;if(l&&r){c(document,window);var u="first"===d,h=u?"pane1":"pane2";if(h){var p=this.$refs[h].$vnode.elm;if(p.getBoundingClientRect){var v="columns"===a?e.touches[0].clientX:e.touches[0].clientY,z="columns"===a?p.getBoundingClientRect().width:p.getBoundingClientRect().height,f="columns"===a?this.$refs[h].$parent.$vnode.elm.getBoundingClientRect().width:this.$refs[h].$parent.$vnode.elm.getBoundingClientRect().height,m=i-v,_=u?m:-m,T="percents"===this.units?this.round2Fixed(100*(z-_)/f):z-_,g=i-m;if(this.step){if(Math.abs(m)<this.step)return;m=~~(m/this.step)*this.step}n&&T<n&&(T=n),o&&T>o&&(T=o),this.localSize=T,this.position=g}}}},onMouseUp:function(){var e={allowResize:this.allowResize,onDragFinished:this.onDragFinished},s=e.allowResize,r=e.onDragFinished,i={active:this.active,draggedSize:this.draggedSize};s&&i.active&&("function"==typeof r&&r(i.draggedSize),this.$emit("update:size",this.localSize),console.log("Resizing to: ",this.localSize),this.active=!1)}}},u={render:function(){var e=this,s=e.$createElement,r=e._self._c||s;return r("div",{staticClass:"pane-rs root",class:e.classObject,on:{mousemove:e.onMouseMove,mouseup:e.onMouseUp}},[r("pane-comp",{ref:"pane1",class:{column:"columns"===e.splitTo,row:"rows"===e.splitTo},style:e.iStyleFirst},[e._t("firstPane")],2),e._v(" "),e.allowResize?r("resizer-comp",{class:{rows:"rows"===e.splitTo,columns:"columns"===e.splitTo},attrs:{splitTo:e.splitTo,resizerColor:e.resizerColor,resizerBorderColor:e.resizerBorderColor,resizerThickness:e.resizerThickness,resizerBorderThickness:e.resizerBorderThickness},nativeOn:{mousedown:function(s){return e.onMouseDown(s)}}}):e._e(),e._v(" "),r("pane-comp",{ref:"pane2",class:{column:"columns"===e.splitTo,row:"rows"===e.splitTo},style:e.iStyleSecond},[e._t("secondPane")],2)],1)},staticRenderFns:[]};var h={name:"HelloWorld",components:{"rs-panes":r("VU/8")(d,u,!1,function(e){r("k5BX")},"data-v-aa33c8fe",null).exports},data:function(){return{msg:"Welcome to Your Vue.js App",localSize:250,localResizerColor:"#DEF",localResizerBorderColor:"rgba(0,0,0,.2)",localResizerThickness:2,localBorderThickness:2}},methods:{setSize:function(){this.localSize=Math.ceil(500*Math.random())},setResizerWidth:function(){this.localResizerThickness=20*Math.random()},setResizerBorderWidth:function(){this.localBorderThickness=20*Math.random()}}},p={render:function(){var e=this,s=e.$createElement,r=e._self._c||s;return r("div",{staticClass:"hello"},[r("rs-panes",{attrs:{"split-to":"columns","allow-resize":!1,size:250}},[r("div",{staticClass:"hello menu",attrs:{slot:"firstPane"},slot:"firstPane"},[r("div",{staticClass:"title"},[r("h2",[e._v("Vue-resize-split-panel")]),e._v(" "),r("i",[e._v("in level1.firstPane")])]),e._v(" "),r("div",[r("label",{attrs:{for:"rSize"}},[e._v("Dynamic size: "+e._s(e.localSize)+"px")]),e._v(" "),r("button",{attrs:{id:"rSize"},on:{click:e.setSize}},[e._v("New size")])]),e._v(" "),r("div",[r("label",{attrs:{for:"ResizerWidth"}},[e._v("Resizer thickness: "+e._s(e.localResizerThickness)+"px")]),e._v(" "),r("input",{directives:[{name:"model",rawName:"v-model",value:e.localResizerThickness,expression:"localResizerThickness"}],attrs:{id:"ResizerWidth",type:"range",min:"1",max:"15",step:"1"},domProps:{value:e.localResizerThickness},on:{__r:function(s){e.localResizerThickness=s.target.value}}})]),e._v(" "),r("div",[r("label",{attrs:{for:"ResizerColor"}},[e._v("Resizer color: "+e._s(e.localResizerColor))]),e._v(" "),r("input",{directives:[{name:"model",rawName:"v-model",value:e.localResizerColor,expression:"localResizerColor"}],attrs:{id:"ResizerColor",type:"color"},domProps:{value:e.localResizerColor},on:{input:function(s){s.target.composing||(e.localResizerColor=s.target.value)}}}),e._v(" "),r("br"),e._v(" "),r("small",[e._v("This is html color picker so transparency is not available.")])]),e._v(" "),r("div",[r("label",{attrs:{for:"BorderWidth"}},[e._v("Resizer border width: "+e._s(e.localBorderThickness)+"px")]),e._v(" "),r("input",{directives:[{name:"model",rawName:"v-model",value:e.localBorderThickness,expression:"localBorderThickness"}],attrs:{id:"BorderWidth",type:"range",min:"0",max:"10",step:"1"},domProps:{value:e.localBorderThickness},on:{__r:function(s){e.localBorderThickness=s.target.value}}}),e._v(" "),r("br"),e._v(" "),r("small",[e._v("Mouse over resizer to see the border")])]),e._v(" "),r("div",[r("label",{attrs:{for:"BorderColor"}},[e._v("Resizer color: "+e._s(e.localResizerBorderColor))]),e._v(" "),r("input",{directives:[{name:"model",rawName:"v-model",value:e.localResizerBorderColor,expression:"localResizerBorderColor"}],attrs:{id:"BorderColor",type:"color"},domProps:{value:e.localResizerBorderColor},on:{input:function(s){s.target.composing||(e.localResizerBorderColor=s.target.value)}}}),e._v(" "),r("br"),e._v(" "),r("small",[e._v("This is html color picker so transparency is not available.")])])]),e._v(" "),r("div",{attrs:{slot:"secondPane"},slot:"secondPane"},[r("rs-panes",{attrs:{"split-to":"columns","allow-resize":!0,size:+e.localSize,resizerColor:e.localResizerColor,resizerBorderColor:e.localResizerBorderColor,resizerThickness:+e.localResizerThickness,resizerBorderThickness:+e.localBorderThickness},on:{"update:size":function(s){e.localSize=s}}},[r("div",{attrs:{slot:"firstPane"},slot:"firstPane"},[r("rs-panes",{attrs:{"split-to":"rows","allow-resize":!0,size:450,resizerColor:e.localResizerColor,resizerBorderColor:e.localResizerBorderColor,resizerThickness:+e.localResizerThickness,resizerBorderThickness:+e.localBorderThickness}},[r("div",{attrs:{slot:"firstPane"},slot:"firstPane"},[r("div",{staticClass:"paneContent"},[r("h3",[e._v(" Panes can be nested as deep as you want!")]),e._v(" "),r("p",[e._v(" This entire page is made out of "),r("b",[e._v("ResizeSplitPane")]),e._v(".")]),e._v(" "),r("p",[e._v(" Menu is in "),r("b",[e._v("level1.firsPane")]),e._v(" and resizing is disabled!")]),e._v(" "),r("h4",[e._v("level1.secondPane > level2.firstPane > level3.firstPane")])])]),e._v(" "),r("div",{attrs:{slot:"secondPane"},slot:"secondPane"},[r("div",{staticClass:"paneContent"},[r("h3",[e._v(" Each ResizeSplitPane has his own settings.")]),e._v(" "),r("p",[e._v(" Or they can share the same data!")]),e._v(" "),r("h4",[e._v("level1.secondPane > level2.firstPane > level3.secondPane")])])])])],1),e._v(" "),r("div",{attrs:{slot:"secondPane"},slot:"secondPane"},[r("div",{staticClass:"paneContent"},[r("div",{staticClass:"paneContent"},[r("h3",[e._v("Links:")]),e._v(" "),r("p",[r("a",{attrs:{href:"https://github.com/raven78/vue-resize-split-pane",target:"_blank"}},[e._v("GitHub repo")])]),e._v(" "),r("p",[r("a",{attrs:{href:"https://www.npmjs.com/package/vue-resize-split-pane",target:"_blank"}},[e._v("Node module")])]),e._v(" "),r("h4",[e._v("level1.secondPane > level2.secondPane")])])])])])],1)])],1)},staticRenderFns:[]};var v={name:"App",components:{HelloWorld:r("VU/8")(h,p,!1,function(e){r("VhIf")},"data-v-633aa52c",null).exports}},z={render:function(){var e=this.$createElement,s=this._self._c||e;return s("div",{attrs:{id:"app"}},[s("HelloWorld")],1)},staticRenderFns:[]};var f=r("VU/8")(v,z,!1,function(e){r("W96P")},null,null).exports;i.a.config.productionTip=!1,new i.a({el:"#app",components:{App:f},template:"<App/>"})},VhIf:function(e,s){},W96P:function(e,s){},k5BX:function(e,s){}},["NHnr"]); //# sourceMappingURL=app.528bb2bb9511b7fa244f.js.map
import { message } from 'antd'; import { createAction } from 'redux-actions'; import http from '../../../../http/index'; import { MENU_LIST_SEARCH, MENU_LIST_SEARCH_FAILED, MENU_LIST_SEARCH_SUCCESS, MENU_ITEM_SELECTED } from './constants'; // 查询菜单列表 const menuListSearch = createAction(MENU_LIST_SEARCH); const menuListSearchSuccess = createAction(MENU_LIST_SEARCH_SUCCESS); const menuListSearchFailed = createAction(MENU_LIST_SEARCH_FAILED); export function onMenuListSearch(params) { return (dispatch) => { dispatch(menuListSearch()); http.get('/menu/list', { params }) .then((response) => { message.info('查询成功'); dispatch(menuListSearchSuccess(response.data.data)); }) .catch((error) => { message.error('查询失败'); dispatch(menuListSearchFailed(error)); }); }; } // 选中菜单列表项 const menuItemSelected = createAction(MENU_ITEM_SELECTED); export const onMenuItemSelected = (key, keyPath) => { return (dispatch) => { dispatch(menuItemSelected(key, keyPath)); }; };
// need express to interact with the front end const express = require('express'); // need path for filename paths const path = require('path'); // need fs to read and write to files const fs = require('fs'); // creating an 'express' server const app = express(); // Sets an Initial port for listeners const PORT = process.env.PORT || 2700; // Initialize activeNote let activeNote = {}; // Set up body parsing, static, and route middleware app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, 'public'))); // routes // api call response for all the notes, and sends the results to the browser as an array of object app.get('/api/notes', (err, res) => { try { // reads the notes from json file activeNote = fs.readFileSync('db/db.json', 'utf8'); console.log('hi!'); // parse it so activeNote is an array of objects activeNote = JSON.parse(activeNote); // error handling } catch (err) { console.log('\n error (in app.get.catch):'); console.log(err); } // send objects to the browser res.json(activeNote); }); // writes the new note to the json file app.post('/api/notes', (req, res) => { try { // reads the json file activeNote = fs.readFileSync('./db/db.json', 'utf8'); console.log(activeNote); // parse the data to get an array of objects activeNote = JSON.parse(activeNote); // Set new notes id req.body.id = activeNote.length; // add the new note to the array of note objects activeNote.push(req.body); // req.body - user input // make it string(stringify)so you can write it to the file activeNote = JSON.stringify(activeNote); // writes the new note to file fs.writeFile('./db/db.json', activeNote, 'utf8', (err) => { // error handling if (err) throw err; }); // changeit back to an array of objects & send it back to the browser(client) res.json(JSON.parse(activeNote)); // error Handling } catch (err) { throw err; console.error(err); } }); // Delete a note app.delete('/api/notes/:id', (req, res) => { try { // reads the json file activeNote = fs.readFileSync('./db/db.json', 'utf8'); // parse the data to get an array of the objects activeNote = JSON.parse(activeNote); // delete the old note from the array on note objects activeNote = activeNote.filter((note) => { return note.id != req.params.id; }); // make it string(stringify)so you can write it to the file activeNote = JSON.stringify(activeNote); // write the new notes to the file fs.writeFile('./db/db.json', activeNote, 'utf8', (err) => { // error handling if (err) throw err; }); // change it back to an array of objects & send it back to the browser (client) res.send(JSON.parse(activeNote)); // error handling } catch (err) { throw err; console.log(err); } }); // HTML GET Requests // Web page when the Get started button is clicked app.get('/notes', (req, res) => { res.sendFile(path.join(__dirname, 'public/notes.html')); }); // If no matching route is found default to home app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public/index.html')); }); app.get('/api/notes', (req, res) => { return res.sendFile(path.json(__dirname, 'db/db.json')); }); // Start the server on the port app.listen(PORT, () => { console.log('App Listening on: http://localhost:' + PORT); });
__author__ = 'Faustin W. Carter' from .logfile_tools import *
/** * MUI CSS/JS utilities module * @module lib/util */ 'use strict'; var config = require('../config'), jqLite = require('./jqLite'), nodeInsertedCallbacks = [], scrollLock = 0, scrollLockCls = 'mui-body--scroll-lock', scrollLockPos, _supportsPointerEvents; /** * Logging function */ function logFn() { var win = window; if (config.debug && typeof win.console !== "undefined") { try { win.console.log.apply(win.console, arguments); } catch (a) { var e = Array.prototype.slice.call(arguments); win.console.log(e.join("\n")); } } } /** * Load CSS text in new stylesheet * @param {string} cssText - The css text. */ function loadStyleFn(cssText) { var doc = document, head; // copied from jQuery head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement; var e = doc.createElement('style'); e.type = 'text/css'; if (e.styleSheet) e.styleSheet.cssText = cssText; else e.appendChild(doc.createTextNode(cssText)); // add to document head.insertBefore(e, head.firstChild); return e; } /** * Raise an error * @param {string} msg - The error message. */ function raiseErrorFn(msg, useConsole) { if (useConsole) { if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg); } else { throw new Error('MUI: ' + msg); } } /** * Register callbacks on muiNodeInserted event * @param {function} callbackFn - The callback function. */ function onNodeInsertedFn(callbackFn) { nodeInsertedCallbacks.push(callbackFn); // initalize listeners if (nodeInsertedCallbacks._initialized === undefined) { var doc = document, events = 'animationstart mozAnimationStart webkitAnimationStart'; jqLite.on(doc, events, animationHandlerFn); nodeInsertedCallbacks._initialized = true; } } /** * Execute muiNodeInserted callbacks * @param {Event} ev - The DOM event. */ function animationHandlerFn(ev) { // check animation name if (ev.animationName !== 'mui-node-inserted') return; var el = ev.target; // iterate through callbacks for (var i=nodeInsertedCallbacks.length - 1; i >= 0; i--) { nodeInsertedCallbacks[i](el); } } /** * Convert Classname object, with class as key and true/false as value, to an * class string. * @param {Object} classes The classes * @return {String} class string */ function classNamesFn(classes) { var cs = ''; for (var i in classes) { cs += (classes[i]) ? i + ' ' : ''; } return cs.trim(); } /** * Check if client supports pointer events. */ function supportsPointerEventsFn() { // check cache if (_supportsPointerEvents !== undefined) return _supportsPointerEvents; var element = document.createElement('x'); element.style.cssText = 'pointer-events:auto'; _supportsPointerEvents = (element.style.pointerEvents === 'auto'); return _supportsPointerEvents; } /** * Create callback closure. * @param {Object} instance - The object instance. * @param {String} funcName - The name of the callback function. */ function callbackFn(instance, funcName) { return function() {instance[funcName].apply(instance, arguments);}; } /** * Dispatch event. * @param {Element} element - The DOM element. * @param {String} eventType - The event type. * @param {Boolean} bubbles=true - If true, event bubbles. * @param {Boolean} cancelable=true = If true, event is cancelable * @param {Object} [data] - Data to add to event object */ function dispatchEventFn(element, eventType, bubbles, cancelable, data) { var ev = document.createEvent('HTMLEvents'), bubbles = (bubbles !== undefined) ? bubbles : true, cancelable = (cancelable !== undefined) ? cancelable : true, k; ev.initEvent(eventType, bubbles, cancelable); // add data to event object if (data) for (k in data) ev[k] = data[k]; // dispatch if (element) element.dispatchEvent(ev); return ev; } /** * Turn on window scroll lock. */ function enableScrollLockFn() { // increment counter scrollLock += 1; // add lock if (scrollLock === 1) { var win = window, doc = document; scrollLockPos = {left: jqLite.scrollLeft(win), top: jqLite.scrollTop(win)}; jqLite.addClass(doc.body, scrollLockCls); win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * Turn off window scroll lock. * @param {Boolean} resetPos - Reset scroll position to original value. */ function disableScrollLockFn(resetPos) { // ignore if (scrollLock === 0) return; // decrement counter scrollLock -= 1; // remove lock if (scrollLock === 0) { var win = window, doc = document; jqLite.removeClass(doc.body, scrollLockCls); if (resetPos) win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * requestAnimationFrame polyfilled * @param {Function} callback - The callback function */ function requestAnimationFrameFn(callback) { var fn = window.requestAnimationFrame; if (fn) fn(callback); else setTimeout(callback, 0); } /** * Define the module API */ module.exports = { /** Create callback closures */ callback: callbackFn, /** Classnames object to string */ classNames: classNamesFn, /** Disable scroll lock */ disableScrollLock: disableScrollLockFn, /** Dispatch event */ dispatchEvent: dispatchEventFn, /** Enable scroll lock */ enableScrollLock: enableScrollLockFn, /** Log messages to the console when debug is turned on */ log: logFn, /** Load CSS text as new stylesheet */ loadStyle: loadStyleFn, /** Register muiNodeInserted handler */ onNodeInserted: onNodeInsertedFn, /** Raise MUI error */ raiseError: raiseErrorFn, /** Request animation frame */ requestAnimationFrame: requestAnimationFrameFn, /** Support Pointer Events check */ supportsPointerEvents: supportsPointerEventsFn };
let [milliseconds, seconds, minutes, hours] = [0, 0, 0, 0]; let timerRef = document.querySelector('.timerDisplay'); let currentInterval = null; document.getElementById('startTimer').addEventListener('click', () => { if (currentInterval !== null) { clearInterval(currentInterval); } currentInterval = setInterval(displayTimer, 10); }); document.getElementById('pauseTimer').addEventListener('click', () => { clearInterval(currentInterval); }); document.getElementById('resetTimer').addEventListener('click', () => { clearInterval(currentInterval); [milliseconds, seconds, minutes, hours] = [0, 0, 0, 0]; timerRef.innerHTML = '00 : 00 : 00 : 000 '; }); function displayTimer() { milliseconds += 10; if (milliseconds == 1000) { milliseconds = 0; seconds++; if (seconds == 60) { seconds = 0; minutes++; if (minutes == 60) { minutes = 0; hours++; } } } let h = hours < 10 ? "0" + hours : hours; let m = minutes < 10 ? "0" + minutes : minutes; let s = seconds < 10 ? "0" + seconds : seconds; let ms = milliseconds < 10 ? "00" + milliseconds : milliseconds < 100 ? "0" + milliseconds : milliseconds; timerRef.innerHTML = ` ${h} : ${m} : ${s} : ${ms}`; }
"""API endpoints for managing process resource.""" from http import HTTPStatus from flask import g, jsonify, request from flask_restx import Namespace, Resource, cors from ..exceptions import BusinessException from ..services import ProcessService from ..utils.auth import auth from ..utils.util import cors_preflight from ..schemas.process import ProcessMessageSchema API = Namespace('Process', description='Process') @cors_preflight('GET,OPTIONS') @API.route('/<string:process_key>/task/<string:task_key>/state', methods=['GET', 'OPTIONS']) class ProcessStateResource(Resource): """Resource for managing state.""" @staticmethod @cors.crossdomain(origin='*') @auth.require def get(process_key, task_key): """Get states by process and task key.""" try: return jsonify(ProcessService.get_states(process_key, task_key, request.headers["Authorization"])), HTTPStatus.OK except BusinessException as err: return err.error, err.status_code @cors_preflight('GET,OPTIONS') @API.route('', methods=['GET', 'OPTIONS']) class ProcessResource(Resource): """Resource for managing process.""" @staticmethod @cors.crossdomain(origin='*') @auth.require def get(): """Get all process.""" try: return jsonify({ 'process': ProcessService.get_all_processes(request.headers["Authorization"]) }), HTTPStatus.OK except BusinessException as err: return err.error, err.status_code # API for getting process diagram xml -for displaying bpmn diagram in UI @cors_preflight('GET,OPTIONS') @API.route('/<string:process_key>/xml', methods=['GET', 'OPTIONS']) class ProcessDefinitionResource(Resource): """Resource for managing process details.""" @staticmethod @cors.crossdomain(origin='*') def get(process_key): """Get process detailsXML.""" try: return ProcessService.get_process_definition_xml(process_key,request.headers["Authorization"]), HTTPStatus.OK except BusinessException as err: return err.error, err.status_code @cors_preflight('POST,OPTIONS') @API.route('/event', methods=['POST', 'OPTIONS']) class ProcessEventResource(Resource): """Resource for managing state.""" @staticmethod @cors.crossdomain(origin='*') @auth.require def post(): message_json = request.get_json() message_schema = ProcessMessageSchema() dict_data = message_schema.load(message_json) """Get states by process and task key.""" try: return jsonify(ProcessService.post_message(dict_data, request.headers["Authorization"])), HTTPStatus.OK except BusinessException as err: return err.error, err.status_code @cors_preflight('GET,OPTIONS') @API.route('/process-instance/<string:process_InstanceId>/activity-instances', methods=['GET', 'OPTIONS']) class ProcessInstanceResource(Resource): """Get Process Activity Instances.""" @staticmethod @cors.crossdomain(origin='*') @auth.require def get(process_InstanceId): """Get states by process and task key.""" try: return ProcessService.get_process_activity_instances(process_InstanceId,request.headers["Authorization"]), HTTPStatus.OK except BusinessException as err: return err.error, err.status_code # @cors_preflight('GET,OPTIONS') # @API.route('/<int:process_key>', methods=['GET', 'OPTIONS']) # class ProcessDetailsResource(Resource): # """Resource for managing process details.""" # @staticmethod # @cors.crossdomain(origin='*') # def get(process_key): # """Get process details.""" # try: # return ProcessService.get_process(process_key), HTTPStatus.OK # except BusinessException as err: # return err.error, err.status_code # @cors_preflight('GET,OPTIONS') # @API.route('/<int:process_key>/action', methods=['GET', 'OPTIONS']) # class ProcessActionsResource(Resource): # """Resource for managing process ations.""" # @staticmethod # @cors.crossdomain(origin='*') # def get(process_key): # """Get process action details.""" # try: # return ProcessService.get_process_action(process_key), HTTPStatus.OK # except BusinessException as err: # return err.error, err.status_code
import React from 'react'; import {Dialog} from "primereact/dialog"; import {Button} from "primereact/button"; export const Confirm = (props) => { function click(status) { props.click(status) } return ( <Dialog header={props.header} visible={true} style={{width: '50vw'}} footer={ <div> <Button label="დიახ" icon="pi pi-check" onClick={()=>click('yes')} /> <Button label="არა" icon="pi pi-times" onClick={()=>click('no')} className="p-button-secondary" /> </div> } onHide={props.onHide} maximizable> {props.text} </Dialog> ) };
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, }, "css-loader" ] }, { test: /favicon\.ico$/, use: { loader: 'url-loader', query: { limit: 1, name: '[name].[ext]', }, }, } ] }, plugins: [ new HtmlWebpackPlugin({ template: __dirname + "/src/public/index.html", inject: 'body' }), new MiniCssExtractPlugin({ filename: `components/[name].css` }) ] };
import DashboardLog from './DashboardLog.vue'; export default DashboardLog;
# SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries # # SPDX-License-Identifier: MIT import threading import time import board import busio from adafruit_lsm6ds import LSM6DSOX from adafruit_lis3mdl import LIS3MDL SAMPLE_SIZE = 500 class KeyListener: """Object for listening for input in a separate thread""" def __init__(self): self._input_key = None self._listener_thread = None def _key_listener(self): while True: self._input_key = input() def start(self): """Start Listening""" if self._listener_thread is None: self._listener_thread = threading.Thread( target=self._key_listener, daemon=True ) if not self._listener_thread.is_alive(): self._listener_thread.start() def stop(self): """Stop Listening""" if self._listener_thread is not None and self._listener_thread.is_alive(): self._listener_thread.join() @property def pressed(self): "Return whether enter was pressed since last checked" "" result = False if self._input_key is not None: self._input_key = None result = True return result def main(): # pylint: disable=too-many-locals, too-many-statements i2c = busio.I2C(board.SCL, board.SDA) gyro_accel = LSM6DSOX(i2c) magnetometer = LIS3MDL(i2c) key_listener = KeyListener() key_listener.start() ############################ # Magnetometer Calibration # ############################ print("Magnetometer Calibration") print("Start moving the board in all directions") print("When the magnetic Hard Offset values stop") print("changing, press ENTER to go to the next step") print("Press ENTER to continue...") while not key_listener.pressed: pass mag_x, mag_y, mag_z = magnetometer.magnetic min_x = max_x = mag_x min_y = max_y = mag_y min_z = max_z = mag_z while not key_listener.pressed: mag_x, mag_y, mag_z = magnetometer.magnetic print( "Magnetometer: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} uT".format( mag_x, mag_y, mag_z ) ) min_x = min(min_x, mag_x) min_y = min(min_y, mag_y) min_z = min(min_z, mag_z) max_x = max(max_x, mag_x) max_y = max(max_y, mag_y) max_z = max(max_z, mag_z) offset_x = (max_x + min_x) / 2 offset_y = (max_y + min_y) / 2 offset_z = (max_z + min_z) / 2 field_x = (max_x - min_x) / 2 field_y = (max_y - min_y) / 2 field_z = (max_z - min_z) / 2 print( "Hard Offset: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} uT".format( offset_x, offset_y, offset_z ) ) print( "Field: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} uT".format( field_x, field_y, field_z ) ) print("") time.sleep(0.01) mag_calibration = (offset_x, offset_y, offset_z) print( "Final Magnetometer Calibration: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} uT".format( offset_x, offset_y, offset_z ) ) ######################### # Gyroscope Calibration # ######################### gyro_x, gyro_y, gyro_z = gyro_accel.gyro min_x = max_x = gyro_x min_y = max_y = gyro_y min_z = max_z = gyro_z print("") print("") print("Gyro Calibration") print("Place your gyro on a FLAT stable surface.") print("Press ENTER to continue...") while not key_listener.pressed: pass for _ in range(SAMPLE_SIZE): gyro_x, gyro_y, gyro_z = gyro_accel.gyro print( "Gyroscope: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} rad/s".format( gyro_x, gyro_y, gyro_z ) ) min_x = min(min_x, gyro_x) min_y = min(min_y, gyro_y) min_z = min(min_z, gyro_z) max_x = max(max_x, gyro_x) max_y = max(max_y, gyro_y) max_z = max(max_z, gyro_z) offset_x = (max_x + min_x) / 2 offset_y = (max_y + min_y) / 2 offset_z = (max_z + min_z) / 2 noise_x = max_x - min_x noise_y = max_y - min_y noise_z = max_z - min_z print( "Zero Rate Offset: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} rad/s".format( offset_x, offset_y, offset_z ) ) print( "Rad/s Noise: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} rad/s".format( noise_x, noise_y, noise_z ) ) print("") gyro_calibration = (offset_x, offset_y, offset_z) print( "Final Zero Rate Offset: X: {0:8.2f}, Y:{1:8.2f}, Z:{2:8.2f} rad/s".format( offset_x, offset_y, offset_z ) ) print("") print("------------------------------------------------------------------------") print("Final Magnetometer Calibration Values: ", mag_calibration) print("Final Gyro Calibration Values: ", gyro_calibration) if __name__ == "__main__": main()
import Phaser from 'phaser'; export default class Asteroid extends Phaser.Physics.Arcade.Sprite { constructor(scene, x, y) { super(scene, x, y, 'asteroid'); this.speed = Phaser.Math.GetSpeed(150, 1); this.orbiting = false; this.direction = 0; this.factor = 1; this.startingPoint = [0, 600]; this.loc = 0; } isOrbiting() { return this.orbiting; } launch(shipX, shipY) { this.orbiting = true; this.setActive(true); this.setVisible(true); const xOrigin = Phaser.Math.RND.between(0, 800); const yOrigin = this.startingPoint[Math.floor(Math.random() * 2)]; this.loc = yOrigin; this.setPosition(xOrigin, yOrigin); if (shipY > xOrigin) { const m = (shipY - yOrigin) / (shipX - xOrigin); this.direction = Math.atan(m); } else { this.factor = -1; const m = (shipY - yOrigin) / (xOrigin - shipX); this.direction = Math.atan(m); } this.angleRotation = Phaser.Math.RND.between(0.2, 0.9); } update(time, delta) { this.x += this.factor * Math.cos(this.direction) * this.speed * delta; if (this.loc === 600) { this.y += -(this.speed * Math.floor(Math.random() * 10)); } else { this.y += (this.speed * Math.floor(Math.random() * 10)); } this.angle += this.angleRotation; if (this.x < -50 || this.y < -50 || this.x > 800 || this.y > 600) { this.setActive(false); this.setVisible(false); this.destroy(); } } }
'use strict' /* global describe it beforeEach afterEach context */ const fs = require('fs') const path = require('path') const { PassThrough } = require('stream') const { EventEmitter, once } = require('events') const { constants: { signals } } = require('os') const ChildProcess = require('child_process') const proxyquire = require('proxyquire') const tmp = require('tmp') const sinon = require('sinon') const { expect } = require('chai') const unwrap = require('../unwrap') const db = { user: 'jeff', password: 'pass', database: 'mydb', port: 5432, host: 'localhost', hostname: 'localhost' } const bastionDb = { user: 'jeff', password: 'pass', database: 'mydb', port: 5432, bastionHost: 'bastion-host', bastionKey: 'super-private-key', host: 'localhost', hostname: 'localhost' } const NOW_OUTPUT = ` now ------------------------------- 2020-12-16 09:54:01.916894-08 (1 row) ` describe('psql', () => { let fakePsqlProcess, fakeTunnel, tunnelStub let sandbox let mockSpawn let psql, bastion beforeEach(() => { sandbox = sinon.createSandbox() tunnelStub = sandbox.stub().callsFake((_config, callback) => { fakeTunnel = new TunnelStub() callback(null, fakeTunnel) }) mockSpawn = createSpawnMocker(sandbox) bastion = proxyquire('../../lib/bastion', { 'tunnel-ssh': tunnelStub }) psql = proxyquire('../../lib/psql', { './bastion': bastion }) fakePsqlProcess = new FakeChildProcess() sandbox.stub(Math, 'random').callsFake(() => 0) }) afterEach(async () => { await fakePsqlProcess.teardown() fakeTunnel = fakePsqlProcess = undefined sandbox.restore() }) async function ensureFinished (promise) { try { return await promise } finally { if (fakeTunnel) { if (!fakeTunnel.exited) { throw new Error('tunnel was not closed') } } if (!fakePsqlProcess.exited) { throw new Error('psql process did not close') } } } describe('exec', () => { it('runs psql', async () => { const expectedEnv = Object.freeze({ PGAPPNAME: 'psql non-interactive', PGSSLMODE: 'prefer', PGUSER: 'jeff', PGPASSWORD: 'pass', PGDATABASE: 'mydb', PGPORT: 5432, PGHOST: 'localhost' }) const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'], env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.exec(db, 'SELECT NOW();') await fakePsqlProcess.waitForStart() mock.verify() fakePsqlProcess.stdout.write(NOW_OUTPUT) await fakePsqlProcess.simulateExit(0) const output = await ensureFinished(promise) expect(output, 'to equal', NOW_OUTPUT) }) it('runs psql with supplied args', async () => { const expectedEnv = Object.freeze({ PGAPPNAME: 'psql non-interactive', PGSSLMODE: 'prefer', PGUSER: 'jeff', PGPASSWORD: 'pass', PGDATABASE: 'mydb', PGPORT: 5432, PGHOST: 'localhost' }) const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require', '-t', '-q'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'], env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.exec(db, 'SELECT NOW();', ['-t', '-q']) await fakePsqlProcess.waitForStart() mock.verify() fakePsqlProcess.stdout.write(NOW_OUTPUT) await fakePsqlProcess.simulateExit(0) const output = await ensureFinished(promise) expect(output, 'to equal', NOW_OUTPUT) }) it('runs psql and throws an error if psql exits with exit code > 0', async () => { const expectedEnv = Object.freeze({ PGAPPNAME: 'psql non-interactive', PGSSLMODE: 'prefer', PGUSER: 'jeff', PGPASSWORD: 'pass', PGDATABASE: 'mydb', PGPORT: 5432, PGHOST: 'localhost' }) const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'], env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.exec(db, 'SELECT NOW();') await fakePsqlProcess.waitForStart() mock.verify() try { expect(fakePsqlProcess.exited).to.equal(false) await fakePsqlProcess.simulateExit(1) await ensureFinished(promise) throw new Error('psql.exec should have thrown') } catch (err) { expect(err.message).to.equal('psql exited with code 1') } }) describe('private databases (not shield)', () => { it('opens an SSH tunnel and runs psql for bastion databases', async () => { const tunnelConf = { username: 'bastion', host: 'bastion-host', privateKey: 'super-private-key', dstHost: 'localhost', dstPort: 5432, localHost: '127.0.0.1', localPort: 49152 } const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require'], sinon.match.any ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.exec(bastionDb, 'SELECT NOW();') await fakePsqlProcess.waitForStart() mock.verify() expect(tunnelStub.withArgs(tunnelConf).calledOnce).to.equal(true) await fakePsqlProcess.simulateExit(0) await ensureFinished(promise) }) it('closes the tunnel manually if psql exits and the tunnel does not close on its own', async () => { const tunnelConf = { username: 'bastion', host: 'bastion-host', privateKey: 'super-private-key', dstHost: 'localhost', dstPort: 5432, localHost: '127.0.0.1', localPort: 49152 } const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require'], sinon.match.any ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.exec(bastionDb, 'SELECT NOW();') await fakePsqlProcess.waitForStart() mock.verify() expect(tunnelStub.withArgs(tunnelConf).calledOnce).to.equal(true) expect(fakeTunnel.exited).to.equal(false) await fakePsqlProcess.simulateExit(0) await ensureFinished(promise) expect(fakeTunnel.exited).to.equal(true) }) it('closes psql manually if the tunnel exits and psql does not close on its own', async () => { const tunnelConf = { username: 'bastion', host: 'bastion-host', privateKey: 'super-private-key', dstHost: 'localhost', dstPort: 5432, localHost: '127.0.0.1', localPort: 49152 } const mock = mockSpawn( 'psql', ['-c', 'SELECT NOW();', '--set', 'sslmode=require'], sinon.match.any ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const execPromise = psql.exec(bastionDb, 'SELECT NOW();') await fakePsqlProcess.waitForStart() mock.verify() expect(tunnelStub.withArgs(tunnelConf).calledOnce).to.equal(true) expect(fakePsqlProcess.exited).to.equal(false) fakeTunnel.close() await ensureFinished(execPromise) expect(fakePsqlProcess.exited).to.equal(true) }) }) }) describe('execFile', () => { it('runs psql with file as input', async () => { const expectedEnv = Object.freeze({ PGAPPNAME: 'psql non-interactive', PGSSLMODE: 'prefer', PGUSER: 'jeff', PGPASSWORD: 'pass', PGDATABASE: 'mydb', PGPORT: 5432, PGHOST: 'localhost' }) const mock = mockSpawn( 'psql', ['-f', 'test.sql', '--set', 'sslmode=require'], { stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8', env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.execFile(db, 'test.sql') await fakePsqlProcess.waitForStart() mock.verify() await fakePsqlProcess.simulateExit(0) await ensureFinished(promise) }) it('opens an SSH tunnel and runs psql for bastion databases', async () => { const tunnelConf = { username: 'bastion', host: 'bastion-host', privateKey: 'super-private-key', dstHost: 'localhost', dstPort: 5432, localHost: '127.0.0.1', localPort: 49152 } const mock = mockSpawn( 'psql', ['-f', 'test.sql', '--set', 'sslmode=require'], { stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8', env: sinon.match.object } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.execFile(bastionDb, 'test.sql') await fakePsqlProcess.waitForStart() mock.verify() expect(tunnelStub.withArgs(tunnelConf).calledOnce).to.equal(true) await fakePsqlProcess.simulateExit(0) await ensureFinished(promise) }) }) describe('psqlInteractive', () => { const db = { attachment: { app: { name: 'sleepy-hollow-9876' }, name: 'DATABASE' } } context('when HEROKU_PSQL_HISTORY is set', () => { let historyPath function mockHerokuPSQLHistory (path) { process.env.HEROKU_PSQL_HISTORY = path } before(function () { tmp.setGracefulCleanup() }) afterEach(() => { delete process.env.HEROKU_PSQL_HISTORY }) context('when HEROKU_PSQL_HISTORY is a valid directory path', () => { beforeEach(() => { historyPath = tmp.dirSync().name mockHerokuPSQLHistory(historyPath) }) afterEach(() => { fs.rmdirSync(historyPath) }) it('is the directory path to per-app history files', async () => { const expectedArgs = [ '--set', 'PROMPT1=sleepy-hollow-9876::DATABASE%R%# ', '--set', 'PROMPT2=sleepy-hollow-9876::DATABASE%R%# ', '--set', `HISTFILE=${historyPath}/sleepy-hollow-9876`, '--set', 'sslmode=require' ] const expectedEnv = Object.freeze({ PGAPPNAME: 'psql interactive', PGSSLMODE: 'prefer' }) const mock = mockSpawn( 'psql', expectedArgs, { stdio: 'inherit', env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.interactive(db) await fakePsqlProcess.waitForStart() await fakePsqlProcess.simulateExit(0) mock.verify() const output = await ensureFinished(promise) // psql interactive doesn't pipe output to the process // ensure promise returned resolves with a promise anyway expect(output, 'to equal', '') }) }) context('when HEROKU_PSQL_HISTORY is a valid file path', () => { beforeEach(function () { historyPath = tmp.fileSync().name mockHerokuPSQLHistory(historyPath) }) afterEach(() => { fs.unlinkSync(historyPath) }) it('is the path to the history file', async () => { const expectedEnv = Object.freeze({ PGAPPNAME: 'psql interactive', PGSSLMODE: 'prefer' }) const expectedArgs = [ '--set', 'PROMPT1=sleepy-hollow-9876::DATABASE%R%# ', '--set', 'PROMPT2=sleepy-hollow-9876::DATABASE%R%# ', '--set', `HISTFILE=${process.env.HEROKU_PSQL_HISTORY}`, '--set', 'sslmode=require' ] const mock = mockSpawn( 'psql', expectedArgs, { stdio: 'inherit', env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.interactive(db) await fakePsqlProcess.waitForStart() await fakePsqlProcess.simulateExit(0) mock.verify() const output = await ensureFinished(promise) // psql interactive doesn't pipe output to the process // ensure promise returned resolves with a promise anyway expect(output, 'to equal', '') }) }) context('when HEROKU_PSQL_HISTORY is an invalid path', async () => { it('issues a warning', async () => { const invalidPath = path.join('/', 'path', 'to', 'history') mockHerokuPSQLHistory(invalidPath) const cli = require('heroku-cli-util') cli.mockConsole() const expectedEnv = Object.freeze({ PGAPPNAME: 'psql interactive', PGSSLMODE: 'prefer' }) const expectedArgs = [ '--set', 'PROMPT1=sleepy-hollow-9876::DATABASE%R%# ', '--set', 'PROMPT2=sleepy-hollow-9876::DATABASE%R%# ', '--set', 'sslmode=require' ] const mock = mockSpawn( 'psql', expectedArgs, { stdio: 'inherit', env: expectedEnv } ) mock.callsFake(() => { fakePsqlProcess.start() return fakePsqlProcess }) const promise = psql.interactive(db) await fakePsqlProcess.waitForStart() await fakePsqlProcess.simulateExit(0) mock.verify() const expectedMessage = `HEROKU_PSQL_HISTORY is set but is not a valid path (${invalidPath})\n` await ensureFinished(promise) expect(unwrap(cli.stderr)).to.equal(expectedMessage) }) }) }) }) }) function isSinonMatcher (value) { return typeof value === 'object' && value !== null && typeof value.test === 'function' } // create a sinon matcher that only asserts on ENV values we expect. // we don't want to leak other ENV variables to the console in CI. // it also makes the test output easier by not listing all the environment variables available in process.env function matchEnv (expectedEnv) { const matcher = (actualEnv) => { const reducedActualEnv = Object.entries(expectedEnv).reduce((memo, [key, value]) => { if (key in actualEnv) { memo[key] = value } return memo }, {}) sinon.match(expectedEnv).test(reducedActualEnv) return true } return sinon.match(matcher, 'env contains expected keys and values') } class FakeChildProcess extends EventEmitter { constructor (...args) { super(...args) this.ready = false this.exited = false this.killed = false this.stdout = new PassThrough() } async waitForStart () { if (!this.ready) { await once(this, 'ready') } } start () { this.ready = true this.emit('ready') } simulateExit (code) { if (!this.exited) { return new Promise((resolve) => { this.exited = true this.stdout.end() process.nextTick(() => { try { this.emit('close', code) } finally { resolve() } }) }) } } kill (signal) { this.killed = true this._killedWithSignal = signal const killedWithCode = signals[signal] this.simulateExit(killedWithCode) } get killedWithSignal () { return this._killedWithSignal } async teardown () { await this.simulateExit(0) this.removeAllListeners() } } class TunnelStub extends EventEmitter { constructor (...args) { super(...args) this.exited = false } close () { this.exited = true process.nextTick(() => { this.emit('close') }) } } function createSpawnMocker (sandbox) { return function mockSpawn (commandName, expectedArgs, expectedOptions) { const spawnMock = sandbox.mock(ChildProcess) const { env: expectedEnv } = expectedOptions let optionsMatchers if (isSinonMatcher(expectedOptions)) { optionsMatchers = expectedOptions } else { optionsMatchers = Object.entries(expectedOptions).reduce((memo, [key, value]) => { let matcher if (key === 'env') { matcher = matchEnv(expectedEnv) } else { matcher = value } memo[key] = matcher return memo }, {}) } return spawnMock .expects('spawn') .withArgs( commandName, sinon.match.array.deepEquals(expectedArgs), sinon.match(optionsMatchers) ) } }
# -*- coding: utf-8 -*- from ..akad.ttypes import ApplicationType import re class Config(object): LINE_HOST_DOMAIN = 'https://gd2.line.naver.jp' LINE_OBS_DOMAIN = 'https://obs-sg.line-apps.com' LINE_TIMELINE_API = 'https://gd2.line.naver.jp/mh/api' LINE_TIMELINE_MH = 'https://gd2.line.naver.jp/mh' LINE_LOGIN_QUERY_PATH = '/api/v4p/rs' LINE_AUTH_QUERY_PATH = '/api/v4/TalkService.do' LINE_API_QUERY_PATH_FIR = '/S4' LINE_POLL_QUERY_PATH_FIR = '/P4' LINE_CALL_QUERY_PATH = '/V4' LINE_CERTIFICATE_PATH = '/Q' LINE_CHAN_QUERY_PATH = '/CH4' LINE_SQUARE_QUERY_PATH = '/SQS1' LINE_SHOP_QUERY_PATH = '/SHOP4' CHANNEL_ID = { 'LINE_TIMELINE': '1341209850', 'LINE_WEBTOON': '1401600689', 'LINE_TODAY': '1518712866', 'LINE_STORE': '1376922440', 'LINE_MUSIC': '1381425814', 'LINE_SERVICES': '1459630796' } APP_TYPE = ApplicationType._VALUES_TO_NAMES[368] APP_VER = '8.4.1' CARRIER = '51089, 1-0' SYSTEM_NAME = 'HelloWorld' SYSTEM_VER = '8.22.17' IP_ADDR = '8.8.8.8' EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+") def __init__(self): self.APP_NAME = '%s\t%s\t%s\t%s' % (self.APP_TYPE, self.APP_VER, self.SYSTEM_NAME, self.SYSTEM_VER) self.USER_AGENT = 'Line/%s' % self.APP_VER
from collections import defaultdict class Status: '''When looping through objects and doing operations to them, this is a useful object to keep track of what happens and summarise the numbers at the end.''' def __init__(self, obj_type_str=None): self.obj_type_str = obj_type_str self.pkg_status = defaultdict(list) # reason: [pkgs] def record(self, status_category, pkg_name, do_print=True): self.pkg_status[status_category].append(pkg_name) if do_print: print '%s: %s' % (pkg_name, status_category) def __str__(self): status = '\nStatus' if self.obj_type_str: status += ' of: %s' % self.obj_type_str status += '\n' status += '\n'.join([ \ '%s: %i (e.g. %s)' % (category, len(pkg_names), sorted(pkg_names)[0]) \ for (category, pkg_names) in self.pkg_status.items()]) status += '\nTotal: %i\n' % sum([len(pkg_names) for pkg_names in self.pkg_status.values()]) return status
import { Router } from 'express'; import * as RecipeController from '../controllers/recipe.controller'; import { isAuthenticated, getUserFromToken } from '../util/authMiddleware' import { getSession } from '../util/dbUtils'; const router = new Router(); router.route('/recipes/search/').get(getUserFromToken, RecipeController.searchRecipes); router.route('/recipes/:cuid').get(getUserFromToken, RecipeController.getRecipe); router.route('/recipes').post(isAuthenticated, RecipeController.addRecipe); router.route('/recipes').put(isAuthenticated, RecipeController.updateRecipe); router.route('/recipes').delete(isAuthenticated, RecipeController.deleteRecipe); export default router;
import cv2 from crust_slices import get_crust_masks from stat_tracker import StatTracker def process_highlights( save_information, start_epoxy_mask, highlights, tube_circle, precision, thickness, thresh, epox_thresh, ker, ): """ Classifies the highlights around the tube as either epoxy or not. To do so, it looks in a small pizza-crust slice outwards from the highlight, and checks how much is epoxy and highlight vs nothingness. Currently, epox_thresh is set to 0, so it's really only checking that there isn't too much void in the crust slice. :param bool save_information: whether the stat tracker should record information for this slice :param img start_epoxy_mask: Input of epoxy mask. :param img highlights: Mask of the image highlights, to be classified. :param tuple tube_circle: Contains information about the bounding circle for the tube. :param int precision: How many pizza crust slices to use. :param int thickness: How thick the crusts should be for the interpolation. If this is too high, you may need to lower thresholds. Too low and you might have holes in the final image for sections with thick highlights. :param float thresh: Overall threshold for how much of the stuff in the crust slice must be either epoxy or highlights to classify the slice as epoxy. Too high, and you may miss on actual epoxy. Too low and you might get false positives. :param float epox_thresh: Threshold for how much epoxy must be in crust slice to characterize highlight as epoxy. Often 0 works fine, as the reflections seem to be more extreme around the tube when there's epoxy. :param ker: Kernel for closing small holes at end of analysis. :return: """ assert isinstance(precision, int), "precision must be int" assert isinstance(thickness, int), "thickness must be int" assert 0 <= thresh <= 1, "thresh must be between 0 and 1" assert 0 <= epox_thresh <= 1, "epox_thresh must be between 0 and 1" result = start_epoxy_mask.copy() masks = get_crust_masks(start_epoxy_mask.shape, tube_circle, precision, thickness) for i in range(len(masks)): crust = masks[i] tot = cv2.countNonZero(crust) epoxy_crust = cv2.bitwise_and(start_epoxy_mask, crust) highlight_crust = cv2.bitwise_and(highlights, crust) prop_epoxy_crust = cv2.countNonZero(epoxy_crust) / tot prop_highlight_crust = cv2.countNonZero(highlight_crust) / tot is_epoxy = ( prop_epoxy_crust + prop_highlight_crust >= thresh and prop_epoxy_crust >= epox_thresh ) if is_epoxy: result = cv2.bitwise_or( result, cv2.bitwise_or(epoxy_crust, highlight_crust) ) if save_information: StatTracker.get_instance().update_coverage(i, is_epoxy) result = cv2.morphologyEx( result, cv2.MORPH_CLOSE, ker ) # Closure to remove little holes return result
from transformers import pipeline def hf_distilbert_model_question_answering(): model_name = "distilbert-base-uncased-distilled-squad" model = pipeline('question-answering', model=model_name, tokenizer=model_name) return model
/** * Active item. */ AFRAME.registerComponent('active-item', { dependencies: ['material'], schema: { active: {default: false}, opacity: {default: 1.0} }, init: function () { this.defaultOpacity = this.el.getAttribute('material').opacity; this.materialObj = {opacity: this.data.opacity}; }, update: function () { var el = this.el; if (this.data.active) { el.setAttribute('material', this.materialObj); el.object3D.visible = true; } else { el.setAttribute('material', 'opacity', this.defaultOpacity); if (el.components.animation__mouseleave) { setTimeout(() => { el.emit('mouseleave', null, false); }); } } } }); AFRAME.registerComponent('active-text-color', { dependencies: ['text'], schema: { active: {default: false}, color: {default: '#333'} }, init: function () { this.defaultColor = this.el.getAttribute('text').color; }, update: function () { var el = this.el; if (this.data.active) { el.setAttribute('text', 'color', this.data.color); } else { el.setAttribute('text', 'color', this.defaultColor); } } });
Ti.Media.defaultAudioSessionMode = Ti.Media.AUDIO_SESSION_MODE_PLAYBACK; var episodioWin = Titanium.UI.createWindow({ title:titulo2[indicador], backgroundImage:'/icons/fondodescargas.png', barColor:'black', width:'100%', height:'100%' }); var vistaCabeza2 = Ti.UI.createView({ top:0, left:0, width:'100%', height:90, backgroundColor:'black' }); var border2 = Ti.UI.createView({ height:2, backgroundColor:'white', bottom:0 }); vistaCabeza2.add(border2); var coverCabeza2 = Titanium.UI.createImageView({ image:foto2[indicador], width:80, height:80, left:4, top:5 }); vistaCabeza2.add(coverCabeza2); var titCabeza2 = Titanium.UI.createLabel({ text:'Titulo episodio', font:{fontSize:16,fontWeight:'bold'}, width:235, textAlign:'left', top:8, color:'660000', left:87, height:20 }); vistaCabeza2.add(titCabeza2); var titleCabeza2 = Titanium.UI.createLabel({ text:titulo3[indicador2], font:{fontSize:16}, width:235, textAlign:'left', top:32, color:'white', left:87, height:40 }); vistaCabeza2.add(titleCabeza2); episodioWin.add(vistaCabeza2); var infobg2 = Titanium.UI.createView({ top:110, width:'100%', height:200, backgroundColor:'black', opacity:0.7 }); episodioWin.add(infobg2); var info2 = Titanium.UI.createView({ width:'100%', height:200, backgroundColor:'transparent' }); var webdes = Titanium.UI.createWebView({ top:5, width:'100%', height:200, html: "<html><body style='color:white;font-size:18px;width:100%;'><div style='width:100%;overflow: hidden;'>" + descripcion3[indicador2] + "</div></body></html>", backgroundColor:'transparent', enableZoomControls:'false' }); info2.add(webdes); infobg2.add(info2); episodioWin.add(infobg2); /** var podcast3 sonido abajo indicador2*/ var play2 = Ti.UI.createButton({ width:100, height:100, bottom:0, left:30, backgroundSelectedImage:'/icons/playb.png', backgroundImage:'/icons/play.png' }); play2.addEventListener('click',function(e){ // When paused, playing returns false. // If both are false, playback is stopped. if (audioPlayer2.playing ) { audioPlayer2.pause(); play2.setBackgroundImage('/icons/play.png'); play2.setBackgroundSelectedImage('/icons/playb.png'); } else { audioPlayer2.start(); play2.setBackgroundImage('/icons/pause.png'); play2.setBackgroundSelectedImage('/icons/pauseb.png'); } }); var stop2 = Ti.UI.createButton({ right:30, bottom:0, width:100, height:100, backgroundSelectedImage:'/icons/stopb.png', backgroundImage:'/icons/stop.png' }); stop2.addEventListener('click',function(e){ audioPlayer2.stop(); play2.setBackgroundImage('/icons/play.png'); play2.setBackgroundSelectedImage('/icons/playb.png'); }); episodioWin.add(play2); episodioWin.add(stop2); // allowBackground: true on Android allows the // player to keep playing when the app is in the // background. var audioPlayer2 = Ti.Media.createAudioPlayer({ url: podcast3[indicador2], allowBackground: true }); episodioWin.open();
# Copyright 2019-2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application()
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { genKey } from 'draft-js'; import escapeRegExp from 'lodash/escapeRegExp'; import Entry from './Entry/Entry'; import addMention from '../modifiers/addMention'; import decodeOffsetKey from '../utils/decodeOffsetKey'; import getSearchText from '../utils/getSearchText'; import defaultEntryComponent from './Entry/defaultEntryComponent'; export class MentionSuggestions extends Component { static propTypes = { open: PropTypes.bool.isRequired, onOpenChange: PropTypes.func.isRequired, entityMutability: PropTypes.oneOf(['SEGMENTED', 'IMMUTABLE', 'MUTABLE']), entryComponent: PropTypes.func, onAddMention: PropTypes.func, suggestions: PropTypes.array.isRequired, }; state = { focusedOptionIndex: 0, }; constructor(props) { super(props); this.key = genKey(); this.props.callbacks.onChange = this.onEditorStateChange; } componentDidUpdate(prevProps) { if (this.popover) { // In case the list shrinks there should be still an option focused. // Note: this might run multiple times and deduct 1 until the condition is // not fullfilled anymore. const size = this.props.suggestions.length; if (size > 0 && this.state.focusedOptionIndex >= size) { this.setState({ focusedOptionIndex: size - 1, }); } // Note: this is a simple protection for the error when componentDidUpdate // try to get new getPortalClientRect, but the key already was deleted by // previous action. (right now, it only can happened when set the mention // trigger to be multi-characters which not supported anyway!) if (!this.props.store.getAllSearches().has(this.activeOffsetKey)) { return; } const decoratorRect = this.props.store.getPortalClientRect( this.activeOffsetKey ); const newStyles = this.props.positionSuggestions({ decoratorRect, prevProps, props: this.props, popover: this.popover, }); Object.keys(newStyles).forEach(key => { this.popover.style[key] = newStyles[key]; }); } } componentWillUnmount() { this.props.callbacks.onChange = undefined; } onEditorStateChange = editorState => { const searches = this.props.store.getAllSearches(); // if no search portal is active there is no need to show the popover if (searches.size === 0) { return editorState; } const removeList = () => { this.props.store.resetEscapedSearch(); this.closeDropdown(); return editorState; }; // get the current selection const selection = editorState.getSelection(); const anchorKey = selection.getAnchorKey(); const anchorOffset = selection.getAnchorOffset(); // the list should not be visible if a range is selected or the editor has no focus if (!selection.isCollapsed() || !selection.getHasFocus()) return removeList(); // identify the start & end positon of each search-text const offsetDetails = searches.map(offsetKey => decodeOffsetKey(offsetKey)); // a leave can be empty when it is removed due e.g. using backspace // do not check leaves, use full decorated portal text const leaves = offsetDetails .filter(({ blockKey }) => blockKey === anchorKey) .map(({ blockKey, decoratorKey }) => editorState.getBlockTree(blockKey).getIn([decoratorKey]) ); // if all leaves are undefined the popover should be removed if (leaves.every(leave => leave === undefined)) { return removeList(); } // Checks that the cursor is after the @ character but still somewhere in // the word (search term). Setting it to allow the cursor to be left of // the @ causes troubles due selection confusion. const plainText = editorState.getCurrentContent().getPlainText(); const selectionIsInsideWord = leaves .filter(leave => leave !== undefined) .map( ({ start, end }) => (start === 0 && anchorOffset === this.props.mentionTrigger.length && plainText.charAt(anchorOffset) !== this.props.mentionTrigger && new RegExp( String.raw({ raw: `${escapeRegExp(this.props.mentionTrigger)}` }), 'g' ).test(plainText) && anchorOffset <= end) || // @ is the first character (anchorOffset > start + this.props.mentionTrigger.length && anchorOffset <= end) // @ is in the text or at the end ); if (selectionIsInsideWord.every(isInside => isInside === false)) return removeList(); const lastActiveOffsetKey = this.activeOffsetKey; this.activeOffsetKey = selectionIsInsideWord .filter(value => value === true) .keySeq() .first(); this.onSearchChange( editorState, selection, this.activeOffsetKey, lastActiveOffsetKey ); // make sure the escaped search is reseted in the cursor since the user // already switched to another mention search if (!this.props.store.isEscaped(this.activeOffsetKey)) { this.props.store.resetEscapedSearch(); } // If none of the above triggered to close the window, it's safe to assume // the dropdown should be open. This is useful when a user focuses on another // input field and then comes back: the dropdown will show again. if ( !this.props.open && !this.props.store.isEscaped(this.activeOffsetKey) && this.props.suggestions.length > 0 ) { this.openDropdown(); } // makes sure the focused index is reseted every time a new selection opens // or the selection was moved to another mention search if ( this.lastSelectionIsInsideWord === undefined || !selectionIsInsideWord.equals(this.lastSelectionIsInsideWord) ) { this.setState({ focusedOptionIndex: 0, }); } this.lastSelectionIsInsideWord = selectionIsInsideWord; return editorState; }; onSearchChange = ( editorState, selection, activeOffsetKey, lastActiveOffsetKey ) => { const { matchingString: searchValue } = getSearchText( editorState, selection, this.props.mentionTrigger ); if ( this.lastSearchValue !== searchValue || activeOffsetKey !== lastActiveOffsetKey ) { this.lastSearchValue = searchValue; this.props.onSearchChange({ value: searchValue }); } }; onDownArrow = keyboardEvent => { keyboardEvent.preventDefault(); const newIndex = this.state.focusedOptionIndex + 1; this.onMentionFocus( newIndex >= this.props.suggestions.length ? 0 : newIndex ); }; onTab = keyboardEvent => { keyboardEvent.preventDefault(); this.commitSelection(); }; onUpArrow = keyboardEvent => { keyboardEvent.preventDefault(); if (this.props.suggestions.length > 0) { const newIndex = this.state.focusedOptionIndex - 1; this.onMentionFocus( newIndex < 0 ? this.props.suggestions.length - 1 : newIndex ); } }; onEscape = keyboardEvent => { keyboardEvent.preventDefault(); const activeOffsetKey = this.lastSelectionIsInsideWord .filter(value => value === true) .keySeq() .first(); this.props.store.escapeSearch(activeOffsetKey); this.closeDropdown(); // to force a re-render of the outer component to change the aria props this.props.store.setEditorState(this.props.store.getEditorState()); }; onMentionSelect = mention => { // Note: This can happen in case a user typed @xxx (invalid mention) and // then hit Enter. Then the mention will be undefined. if (!mention) { return; } if (this.props.onAddMention) { this.props.onAddMention(mention); } this.closeDropdown(); const newEditorState = addMention( this.props.store.getEditorState(), mention, this.props.mentionPrefix, this.props.mentionTrigger, this.props.entityMutability ); this.props.store.setEditorState(newEditorState); }; onMentionFocus = index => { const descendant = `mention-option-${this.key}-${index}`; this.props.ariaProps.ariaActiveDescendantID = descendant; this.setState({ focusedOptionIndex: index, }); // to force a re-render of the outer component to change the aria props this.props.store.setEditorState(this.props.store.getEditorState()); }; commitSelection = () => { if (!this.props.store.getIsOpened()) { return 'not-handled'; } this.onMentionSelect(this.props.suggestions[this.state.focusedOptionIndex]); return 'handled'; }; openDropdown = () => { // This is a really nasty way of attaching & releasing the key related functions. // It assumes that the keyFunctions object will not loose its reference and // by this we can replace inner parameters spread over different modules. // This better be some registering & unregistering logic. PRs are welcome :) this.props.callbacks.handleReturn = this.commitSelection; this.props.callbacks.keyBindingFn = keyboardEvent => { // arrow down if (keyboardEvent.keyCode === 40) { this.onDownArrow(keyboardEvent); } // arrow up if (keyboardEvent.keyCode === 38) { this.onUpArrow(keyboardEvent); } // escape if (keyboardEvent.keyCode === 27) { this.onEscape(keyboardEvent); } // tab if (keyboardEvent.keyCode === 9) { this.onTab(keyboardEvent); } }; const descendant = `mention-option-${this.key}-${this.state.focusedOptionIndex}`; this.props.ariaProps.ariaActiveDescendantID = descendant; this.props.ariaProps.ariaOwneeID = `mentions-list-${this.key}`; this.props.ariaProps.ariaHasPopup = 'true'; this.props.ariaProps.ariaExpanded = true; this.props.onOpenChange(true); }; closeDropdown = () => { // make sure none of these callbacks are triggered this.props.callbacks.handleReturn = undefined; this.props.callbacks.keyBindingFn = undefined; this.props.ariaProps.ariaHasPopup = 'false'; this.props.ariaProps.ariaExpanded = false; this.props.ariaProps.ariaActiveDescendantID = undefined; this.props.ariaProps.ariaOwneeID = undefined; this.props.onOpenChange(false); }; render() { if (!this.props.open) { return null; } const { entryComponent, popoverComponent = <div />, onOpenChange, // eslint-disable-line no-unused-vars onAddMention, // eslint-disable-line no-unused-vars, no-shadow onSearchChange, // eslint-disable-line no-unused-vars, no-shadow suggestions, // eslint-disable-line no-unused-vars ariaProps, // eslint-disable-line no-unused-vars callbacks, // eslint-disable-line no-unused-vars theme = {}, store, // eslint-disable-line no-unused-vars entityMutability, // eslint-disable-line no-unused-vars positionSuggestions, // eslint-disable-line no-unused-vars mentionTrigger, // eslint-disable-line no-unused-vars mentionPrefix, // eslint-disable-line no-unused-vars ...elementProps } = this.props; return React.cloneElement( popoverComponent, { ...elementProps, className: theme.mentionSuggestions, role: 'listbox', id: `mentions-list-${this.key}`, ref: element => { this.popover = element; }, }, this.props.suggestions.map((mention, index) => ( <Entry key={mention.id != null ? mention.id : mention.name} onMentionSelect={this.onMentionSelect} onMentionFocus={this.onMentionFocus} isFocused={this.state.focusedOptionIndex === index} mention={mention} index={index} id={`mention-option-${this.key}-${index}`} theme={theme} searchValue={this.lastSearchValue} entryComponent={entryComponent || defaultEntryComponent} /> )) ); } } export default MentionSuggestions;
var searchData= [ ['ambient_5fintensity',['ambient_intensity',['../classmingfx_1_1_default_shader_1_1_light_properties.html#a226c173b193459af291687dd45280fbb',1,'mingfx::DefaultShader::LightProperties']]], ['ambient_5freflectance',['ambient_reflectance',['../classmingfx_1_1_default_shader_1_1_material_properties.html#ad4db9a1b0636db84f57f022c51ce7657',1,'mingfx::DefaultShader::MaterialProperties']]] ];
class NotificationsFeature extends Feature { init() { Notification.requestPermission().then(function(result) { Vowsh.onReady(function() { if(result !== 'granted') { $('.chat-lines').append('<div class="msg-chat msg-info"><span class="text" style="color: crimson">Notifications are enabled in Vowsh settings, but you haven\'t granted permission yet.</span></div>'); } }); }); } onMessage(message) { if(message.is('.msg-highlight') && document.visibilityState != 'visible') { var mention = new Notification(message.data('username') + ' mentioned you'); mention.onclick = function() { window.focus(); mention.close(); }; document.addEventListener('visibilitychange', function() { if(document.visibilityState == 'visible') { mention.close(); } }); } } }
import request from '@/utils/request' // 登录 export function login(param) { return request({ url: 'api/manage/valid/login', method: 'post', data: param }) } //登出 export function logout(param) { return request({ url: 'api/manage/valid/logout', method: 'post', data: param }) } //获取用户信息 export function getUserInfo(param) { return request({ url: 'api/manage/user/get', method: 'get', data: param }) }
# coding: utf-8 from __future__ import absolute_import, unicode_literals from django.utils.safestring import mark_safe from django_tables2.utils import AttributeDict import warnings from .base import Column, library @library.register class CheckBoxColumn(Column): """ A subclass of `.Column` that renders as a checkbox form input. This column allows a user to *select* a set of rows. The selection information can then be used to apply some operation (e.g. "delete") onto the set of objects that correspond to the selected rows. The value that is extracted from the :term:`table data` for this column is used as the value for the checkbox, i.e. ``<input type="checkbox" value="..." />`` This class implements some sensible defaults: - HTML input's ``name`` attribute is the :term:`column name` (can override via *attrs* argument). - *orderable* defaults to `False`. .. note:: You'd expect that you could select multiple checkboxes in the rendered table and then *do something* with that. This functionality isn't implemented. If you want something to actually happen, you'll need to implement that yourself. In addition to *attrs* keys supported by `.Column`, the following are available: - *input* -- ``<input>`` elements in both ``<td>`` and ``<th>``. - *th__input* -- Replaces *input* attrs in header cells. - *td__input* -- Replaces *input* attrs in body cells. """ def __init__(self, attrs=None, **extra): # For backwards compatibility, passing in a normal dict effectively # should assign attributes to the `<input>` tag. valid = set(("input", "th__input", "td__input", "th", "td", "cell")) if attrs and not set(attrs) & set(valid): # if none of the keys in attrs are actually valid, assume it's some # old code that should be be interpreted as {"td__input": ...} warnings.warn('attrs keys must be one of %s, interpreting as {"td__input": %s}' % (', '.join(valid), attrs), DeprecationWarning) attrs = {"td__input": attrs} # This is done for backwards compatible too, there used to be a # ``header_attrs`` argument, but this has been deprecated. We'll # maintain it for a while by translating it into ``head.checkbox``. if "header_attrs" in extra: warnings.warn('header_attrs argument is deprecated, ' 'use attrs={"th__input": ...} instead', DeprecationWarning) attrs.setdefault('th__input', {}).update(extra.pop('header_attrs')) kwargs = {'orderable': False, 'attrs': attrs} kwargs.update(extra) super(CheckBoxColumn, self).__init__(**kwargs) @property def header(self): default = {'type': 'checkbox'} general = self.attrs.get('input') specific = self.attrs.get('th__input') attrs = AttributeDict(default, **(specific or general or {})) return mark_safe('<input %s/>' % attrs.as_html()) def render(self, value, bound_column): # pylint: disable=W0221 default = { 'type': 'checkbox', 'name': bound_column.name, 'value': value } general = self.attrs.get('input') specific = self.attrs.get('td__input') attrs = AttributeDict(default, **(specific or general or {})) return mark_safe('<input %s/>' % attrs.as_html())
//@flow import React, { Component } from 'react' import styled from 'styled-components/native' import { Text, Tooltip } from '@morpheus-ui/core' import bgGraphic from '../../../assets/images/onboard-background.png' import bgIDGraphic from '../../../assets/images/identity-onboard-background.png' import bgWalletGraphic from '../../../assets/images/wallet-onboard-background.png' type Props = { children: any, title: string, description?: string, id?: boolean, wallet?: boolean, tooltipContent?: ?any, step?: 1 | 2 | 3, } const Container = styled.View` flex: 1; ` const TitleContainer = styled.View` margin-bottom: ${props => props.theme.spacing * 4}; ` const BgGraphicContainer = styled.View` position: fixed; right: 0; bottom: 0; width: 348; height: 575; ` const Content = styled.View` max-width: 400; margin-left: 100; ` const FormContainer = styled.View` justify-content: center; flex-direction: column; flex: 1; ` const BgImage = styled.Image` flex: 1; ` const Steps = styled.View` flex-direction: row; margin: 0 0 50px 90px; ` const StepIndicator = styled.Text` border-top-width: 1px; border-top-color: #d3d3d3; border-top-style: solid; width: 45px; font-size: 11px; margin: 0 5px; color: transparent; text-align: center; padding: 5px; ${props => props.selected && `color: #1F3464; border-top-color: #1F3464;`} ` const DescriptionContainer = styled.View` flex-direction: row; align-items: center; ` export default class OnboardContainerView extends Component<Props> { render() { const description = this.props.description ? ( <DescriptionContainer> <Text variant="regular" size={16}> {this.props.description} </Text> {this.props.tooltipContent && ( <Tooltip>{this.props.tooltipContent}</Tooltip> )} </DescriptionContainer> ) : null return ( <Container> <FormContainer> <Content> <TitleContainer> <Text variant="h1">{this.props.title}</Text> {description} </TitleContainer> {this.props.children} </Content> </FormContainer> {this.props.step && ( <Steps> {/*eslint-disable react-native/no-raw-text */} <StepIndicator selected={this.props.step === 1}>1</StepIndicator> <StepIndicator selected={this.props.step === 2}>2</StepIndicator> <StepIndicator selected={this.props.step === 3}>3</StepIndicator> {/*eslint-enable react-native/no-raw-text */} </Steps> )} <BgGraphicContainer> <BgImage source={ this.props.id ? bgIDGraphic : this.props.wallet ? bgWalletGraphic : bgGraphic } resizeMode="contain" /> </BgGraphicContainer> </Container> ) } }
!function(e){"use strict";var t=function(){};t.prototype.init=function(){e('input[name="dates"]').daterangepicker({alwaysShowCalendars:!0}),e(".open_picker").show(),e('input[name="daterange"]').daterangepicker({opens:"left"},function(t,a,e){console.log("A new date selection was made: "+t.format("YYYY-MM-DD")+" to "+a.format("YYYY-MM-DD"))}),e('input[name="datetimes"]').daterangepicker({timePicker:!0,startDate:moment().startOf("hour"),endDate:moment().startOf("hour").add(32,"hour"),locale:{format:"M/DD hh:mm A"}}),e('input[name="birthday"]').daterangepicker({singleDatePicker:!0,showDropdowns:!0,minYear:1901,maxYear:parseInt(moment().format("YYYY"),10)},function(t,a,e){var n=moment().diff(t,"years");alert("You are "+n+" years old!")});var t=moment().subtract(29,"days"),a=moment();e("#reportrange").daterangepicker({startDate:t,endDate:a,ranges:{Today:[moment(),moment()],Yesterday:[moment().subtract(1,"days"),moment().subtract(1,"days")],"Last 7 Days":[moment().subtract(6,"days"),moment()],"Last 30 Days":[moment().subtract(29,"days"),moment()],"This Month":[moment().startOf("month"),moment().endOf("month")],"Last Month":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]}},function(t,a){e("#reportrange span").html(t.format("MMMM D, YYYY")+" - "+a.format("MMMM D, YYYY"))}),e(".select2").select2({width:"100%"}),e("#b_color-default, #b_color_rgb, #b_color_hsl").colorpicker(),e("#mdate").bootstrapMaterialDatePicker({weekStart:0,time:!1}),e("#timepicker").bootstrapMaterialDatePicker({format:"HH:mm",time:!0,date:!1}),e("#date-format").bootstrapMaterialDatePicker({format:"dddd DD MMMM YYYY - HH:mm"}),e("#min-date").bootstrapMaterialDatePicker({format:"DD/MM/YYYY HH:mm",minDate:new Date}),e("#date-end").bootstrapMaterialDatePicker({weekStart:0,format:"DD/MM/YYYY HH:mm"}),e("#date-start").bootstrapMaterialDatePicker({weekStart:0,format:"DD/MM/YYYY HH:mm",shortTime:!0}).on("change",function(t,a){e("#date-end").bootstrapMaterialDatePicker("setMinDate",a)}),e("input#defaultconfig").maxlength({warningClass:"badge badge-info",limitReachedClass:"badge badge-warning"}),e("input#thresholdconfig").maxlength({threshold:20,warningClass:"badge badge-info",limitReachedClass:"badge badge-warning"}),e("input#moreoptions").maxlength({alwaysShow:!0,warningClass:"badge badge-success",limitReachedClass:"badge badge-danger"}),e("input#alloptions").maxlength({alwaysShow:!0,warningClass:"badge badge-success",limitReachedClass:"badge badge-danger",separator:" out of ",preText:"You typed ",postText:" chars available.",validate:!0}),e("textarea#textarea").maxlength({alwaysShow:!0,warningClass:"badge badge-info",limitReachedClass:"badge badge-warning"}),e("input#placement").maxlength({alwaysShow:!0,placement:"top-left",warningClass:"badge badge-info",limitReachedClass:"badge badge-warning"}),e(".vertical-spin").TouchSpin({verticalbuttons:!0,verticalupclass:"ion-plus-round",verticaldownclass:"ion-minus-round",buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo1']").TouchSpin({min:0,max:100,step:.1,decimals:2,boostat:5,maxboostedstep:10,postfix:"%",buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo2']").TouchSpin({min:-1e9,max:1e9,stepinterval:50,maxboostedstep:1e7,prefix:"$",buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo3']").TouchSpin({buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo3_21']").TouchSpin({initval:40,buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo3_22']").TouchSpin({initval:40,buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo5']").TouchSpin({prefix:"pre",postfix:"post",buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"}),e("input[name='demo0']").TouchSpin({buttondown_class:"btn btn-gradient-primary",buttonup_class:"btn btn-gradient-primary"})},e.AdvancedForm=new t,e.AdvancedForm.Constructor=t}(window.jQuery),function(t){"use strict";window.jQuery.AdvancedForm.init()}();
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const ReactComponent = props => (react_1.default.createElement("svg", Object.assign({ viewBox: "0 0 24 24", width: "1em", height: "1em" }, props), react_1.default.createElement("path", { fill: "none", d: "M24 0H0v24h24V0z" }), react_1.default.createElement("path", { d: "M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58s4.1-.78 5.66-2.34c3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z" }))); exports.default = ReactComponent;
'use strict'; function readAll(obj) { if(Array.isArray(obj)) { return obj; } if(typeof(obj) === 'object') { return Object.fromEntries([...Object.entries(obj)].map(([k, v])=> [k, readAll(v)])); } return obj; } const {defineRegisters} = require('./defineRegisters'); module.exports.NVMe = class NVMe { constructor(options={/*Driver, PCIeDev*/}) { Object.assign(this, options); const bar01 = options.PCIeDev.Bar01.buffer; const {registers, registerBuffers, subregisters} = defineRegisters({srcBuf: bar01}); const submission = []; const completion = []; { const cached_DSTRD = subregisters.CAP.DSTRD; const queueBuf = bar01.slice(0x1000); for(let y = 0n; y < 65536n; y++) { const submission_offset = (2n * y) * cached_DSTRD; const completion_offset = submission_offset + cached_DSTRD; if(submission_offset + cached_DSTRD * 2n > queueBuf.byteLength) { break; } submission[y] = new Uint32Array(queueBuf, Number(submission_offset), 1); completion[y] = new Uint32Array(queueBuf, Number(completion_offset), 1); } } console.log(submission); Object.freeze(submission); Object.freeze(completion); Object.defineProperties(this, { registers: {value: registers, enumerable: true}, registerBuffers: { value: registerBuffers, enumerable: true}, subregisters: {value: subregisters, enumerable: true}, submission: {value: submission, enumerable: true}, completion: {value: completion, enumerable: true}, }); Object.freeze(this); console.log(readAll(registers)); console.log(readAll(subregisters)); } };
#!/usr/bin/env python import rospy import os import scipy.misc import numpy as np os.environ["CUDA_VISIBLE_DEVICES"]="2" from model_training import WGAN from yaml import load, Loader import tensorflow as tf flags = None def init(): global flags rospy.init_node('train_underwater_camera_model', anonymous=True) # load configuration config_filename = rospy.get_param('~config_filename') config = load(file(config_filename, 'r'), Loader=Loader) flags = tf.app.flags flags.DEFINE_integer("epoch", 25, "Epoch to train [25]") flags.DEFINE_float("learning_rate", 0.0002, "Learning rate of for adam [0.0002]") flags.DEFINE_float("beta1", 0.5, "Momentum term of adam [0.5]") flags.DEFINE_float("train_size", np.inf, "The size of train images [np.inf]") flags.DEFINE_integer("batch_size", 64, "The size of batch images [64]") flags.DEFINE_integer("input_height", 480, "The size of image to use (will be center cropped). [108]") flags.DEFINE_integer("input_width", 640, "The size of image to use (will be center cropped). If None, same value as input_height [None]") flags.DEFINE_integer("input_water_height", 1024, "The size of image to use (will be center cropped). [108]") flags.DEFINE_integer("input_water_width", 1360, "The size of image to use (will be center cropped). If None, same value as input_height [None]") flags.DEFINE_integer("output_height", 48, "The size of the output images to produce [64]") flags.DEFINE_integer("output_width", 64, "The size of the output images to produce. If None, same value as output_height [None]") flags.DEFINE_integer("c_dim", 3, "Dimension of image color. [3]") flags.DEFINE_float("max_depth", 1.5, "Dimension of image color. [3.0]") flags.DEFINE_string("water_dataset", config['water_dataset'], "The name of dataset [celebA, mnist, lsun]") flags.DEFINE_string("air_dataset",config['rgb_dataset'],"The name of dataset with air images") flags.DEFINE_string("depth_dataset",config['depth_dataset'],"The name of dataset with depth images") flags.DEFINE_string("input_fname_pattern", "*.png", "Glob pattern of filename of input images [*]") flags.DEFINE_string("checkpoint_dir", config['model_directory'], "Directory name to save the models [model]") flags.DEFINE_string("results_dir", "results", "Directory name to save the checkpoints [results]") flags.DEFINE_string("sample_dir", "samples", "Directory name to save the image samples [samples]") flags.DEFINE_boolean("is_train", True, "True for training, False for testing [False]") flags.DEFINE_boolean("is_crop", True, "True for training, False for testing [False]") flags.DEFINE_boolean("visualize", False, "True for visualizing, False for nothing [False]") flags.DEFINE_integer("num_samples",64, "True for visualizing, False for nothing [4000]") flags.DEFINE_integer("save_epoch",10, "The size of the output images to produce. If None, same value as output_height [None]") flags = flags.FLAGS if flags.input_width is None: flags.input_width = flags.input_height if flags.output_width is None: flags.output_width = flags.output_height if not os.path.exists(flags.checkpoint_dir): os.makedirs(flags.checkpoint_dir) def main(_): global flags run_config = tf.ConfigProto() run_config.gpu_options.allow_growth=True with tf.Session(config=run_config) as sess: wgan = WGAN( sess, input_width=flags.input_width, input_height=flags.input_height, input_water_width=flags.input_water_width, input_water_height=flags.input_water_height, output_width=flags.output_width, output_height=flags.output_height, batch_size=flags.batch_size, c_dim=flags.c_dim, max_depth = flags.max_depth, save_epoch=flags.save_epoch, water_dataset_name=flags.water_dataset, air_dataset_name = flags.air_dataset, depth_dataset_name = flags.depth_dataset, input_fname_pattern=flags.input_fname_pattern, is_crop=flags.is_crop, checkpoint_dir=flags.checkpoint_dir, results_dir = flags.results_dir, sample_dir=flags.sample_dir, num_samples = flags.num_samples) if flags.is_train: print('TRAINING') wgan.train(flags) else: print('TESTING') if not wgan.load(flags.checkpoint_dir): raise Exception("[!] Train a model first, then run test mode") wgan.test(flags) rospy.spin() if __name__ == '__main__': init() tf.app.run()
/* Copyright (c) 2018 Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ // @flow import {thumbWidth} from './constants'; export function startThumbIcon(backgroundColor: string, thumbColor: string) { return `<svg width="20" height="32" viewBox="0 0 20 32" fill="none" xmlns="http://www.w3.org/2000/svg"><g filter="url(#filter0_d)"><path d="M4 7C4 4.79086 5.79086 3 8 3H15C15.5523 3 16 3.44772 16 4V26C16 26.5523 15.5523 27 15 27H8C5.79086 27 4 25.2091 4 23V7Z" fill="${backgroundColor}"/></g><rect x="9" y="11" width="2" height="8" rx="1" fill="${thumbColor}"/><defs><filter id="filter0_d" x="0" y="0" width="20" height="32" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dy="1"/><feGaussianBlur stdDeviation="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.12 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter></defs></svg>`; } export function endThumbIcon(backgroundColor: string, thumbColor: string) { return `<svg width="20" height="32" viewBox="0 0 20 32" fill="none" xmlns="http://www.w3.org/2000/svg"><g filter="url(#filter0_d)"><path d="M4 4C4 3.44772 4.44772 3 5 3H12C14.2091 3 16 4.79086 16 7V23C16 25.2091 14.2091 27 12 27H5C4.44772 27 4 26.5523 4 26V4Z" fill="${backgroundColor}"/></g><rect x="9" y="11" width="2" height="8" rx="1" fill="${thumbColor}"/><defs><filter id="filter0_d" x="0" y="0" width="20" height="32" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dy="1"/><feGaussianBlur stdDeviation="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.12 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter></defs></svg>`; } export function singleThumbIcon(backgroundColor: string, thumbColor: string) { return `<svg width="32" height="32" viewBox="0 0 ${thumbWidth} 32" fill="none" xmlns="http://www.w3.org/2000/svg"><g filter="url(#filter0_d)"><rect x="4" y="3" width="24" height="24" rx="4" fill="${backgroundColor}"/><rect width="2" height="8" x="15" y="11" rx="1" fill="${thumbColor}"/></g><defs><filter id="filter0_d" x="0" y="0" width="32" height="32" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset dy="1"/><feGaussianBlur stdDeviation="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.32 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter></defs></svg>`; }
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, './coverage/ng-http'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
import random from math import * import time import sympy as sym from PIL import Image import pyttsx3 # have to install this and pypiwin32 import matplotlib.pyplot as plt import matplotlib import numpy as np from sympy import * from IPython.display import display, Math, Latex from threading import Timer from colorama import Fore, Back, Style, init import cv2 #def story(): def speak(text): eng.say(text) eng.runandwait() def basic(): print(Back.BLACK + Fore.RED + 'This will include questions that are to be solved using Vedic Maths in a given time limit') print(Fore.RED+Back.BLACK+'These will help you develop your speed of calculation') speak('This will include questions that are to be solved using Vedic Maths in a given time limit and they will help you develop your speed of calculation') print(Fore.BLUE + Back.BLACK+'You will have 60 seconds to attempt each question') speak('You will have 60 seconds to attempt each question') while True: time.sleep(1) print(Fore.GREEN + Back.BLACK + """1 --> Double Digit Multiplication 2 --> Multiplication of a two-digit number by 11 3--> Finding square of double digit numbers ending with 5 4 --> Go Back""") speak('Type one of the following options. 1 Double Digit Multiplication; 2 Multiplication by number of the form 11; 3 Go Back') print(Fore.GREEN + Back.BLACK + "1 --> Double Digit Multiplication; 2 --> Multiplication of a two-digit number by 11... ; 3 --> Go Back") speak('Type one of the following options. 1 Double Digit Multiplication; 2 Multiplication by number of the form 11; 3 Go Back') print( Fore.GREEN + Back.BLACK +"Choose one of the following options.") choice = int(input()) if choice== 1: dd() if choice== 2: elev() if choice==3: sqr5() if choice== 4: break def dd(): print(Back.BLACK +'Do you know about various tricks which are given by Vedic Maths?') speak('Do you know about various tricks which are given by Vedic Maths?') print(Fore.RED + Back.BLACK + """ We are going to learn about one of the basic rules of vedic maths.""" + Fore.BLUE + Back.BLACK + """ This involves multiplication of two digit numbers. Say you have any two digit numbers : ab and cd, where a is in tenth place of number "ab" and b is in ones place, similarly for "cd". So the trick is to take the ones digit of both numbers and multiply it (i.e. b x d) and write the ones digit of their product as the ones digit of a new number. And carry forward the tens place digit. """ ) print(Fore.GREEN + """ Now take the product of "a" and "d" and add it to the product of "b" and "c" (i.e. a x d + b x c). Now you need to add the tens place digit of the number obtained on multiplying "b" and "d". now take the ones place digit of the number obtained and put it in the tens place of the number and carry forward the tens place digit. Now multiply a and c (i.e. a x c) and add the tens place digit that was obtained in the previous step, now write the obtained number in the hundreds place of the new number. The number that you have now obtained is the product of ab and cd.) """) speak("We are going to learn about one of the basic rules of vedic maths.") speak("This involves multiplication of two digit numbers.") speak("Say you have any two digit numbers : ab and cd, where a is in tenth place of number 'ab' and b is in ones place, similarly for 'cd'.") speak("So the trick is to take the ones digit of both numbers and multiply it (i.e. b x d) and write the ones digit of their product as the ones digit of a new number.") speak("And carry forward the tens place digit.") speak("Now take the product of 'a' and 'd' and add it to the product of 'b' and 'c'") speak("Now you need to add the tens place digit of the number obtained on multiplying 'b' and 'd'.") speak("now take the ones place digit of the number obtained and put it in the tens place of the number and carry forward the tens place digit.") speak("Now multiply a and c and add the tens place digit that was obtained in the previous step, now write the obtained number in the hundreds place of the new number.") speak("The number that you have now obtained is the product of a b and c d.") time.sleep(1) print() scr = 0 while True: for i1 in range(4): no1 = floor(random.uniform(10, 99)) no2 = floor(random.uniform(10, 99)) print( Style.DIM +'Find the product when',no1,'is multiplied by',no2) speak('Find the product on multiplication of: ') speak(no1) speak('and') speak(no2) speak("Enter the answer . If you don't know just press enter") right_answer = no1 * no2 #t= Timer(60, time_up) #x is amount of allowed time in seconds then execute the provided function #t.start() #start the timerx = np.linspace(-2,2,100) ans = input('Enter the answer, if you dont know it just press enter: ') if ans == str(right_answer): #t.cancel() scr += 1 print( Fore.GREEN +'Well Done! Your answer is correct') speak('Well Done! Your answer is correct') elif ans == "": #t.cancel() print(Back.BLACK + "The correct answer is {}".format(right_answer)) speak("The correct answer is {}".format(right_answer)) elif ans != str(right_answer): #t.cancel() print(Back.BLACK + 'Sorry, incorrect answer') speak('Sorry, incorrect answer') print(Back.BLACK + 'The correct answer is {}'.format(no1 * no2)) speak('The correct answer is {}'.format(no1 * no2)) print() break print("You got {} questions right out of 4".format(scr)) perc = ((int(scr)/4)*100) if perc >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc)) print("We know that you can score better."+ Fore.RED +"You should try again") def had(): print(Fore.RED + Back.BLACK + ''' Welcome to the Everyday Maths Module. Here we will learn how some basic mathematical concepts can be used in our daily life. We all make use of distances and heights in daily life. For example: Measuring the height of our shadows, Measuring distances between 2 points and much more. Its not practically possible to measure large distances. So, we make use of " Trigonometry " for such purposes. Also, trigonometry is majorly used in aviation. It helps in determining distances covered,heghts achieved by plane when it took off at a certain angle. Trigonometric ratios are ratios of different sides of a right angled triangle. A right angled triangle has perpendicular(P),base(B) and hypotenuse(H). Let us call the angle opposite perpendicular A. So,we call the ratio between P/B as tanA B/P as cotA P/H as sinA B/H as cosA These are some basic ratios that we use in solving height and distance measurement questions. We try to analyse daily life situations and try to apply these concepts there. ''' ) lhd = {"A street light pole stands between two parallel roads. The height of the pole is 10m. From the top of the tower, the angles of depression of the roads are 45° and 30°. Find the distance between the roads.":27.32, "A tree of height 24 cm stands in my vicinity. On a stormy night, the tree broke and fell in such a way that the upper part remained attached to the stem, forming an angle of 30° with the ground. Find the height from where it broke.":8, "The shadow formed by a man on a sunny day is 1/3 times the actual height. Find the sun's angle of elevation?":60, "The actual height of a man is 6 feet but due to the position of Sun he casts a shadow of 4 feet. He is standing next to an electricity tower and notices that it casts a shadow of 36 feet. Find the height of the electricity tower.":54, } for i in range(4): hd1 = list(lhd.keys())[i] print(Fore.RED + Back.BLACK + "This is your question 👇", hd1, sep='\n') print("Please enter answer without the units") anshd = input("Enter the answer: ") lmfao = anshd.replace(' ', '').lower() try: if float(lmfao) == float(list(lhd.values())[i]) : print("You got the correct answer!") except: if lmfao.find('pi') != -1 or lmfao.find('Pi') != -1: if lmfao.find('/') != -1 : jjj = float(lmfao[lmfao.find('/')+1:lmfao.find('/')+2]) sos = 180/jjj else: sosiph = float(lmfao.lower().replace('pi','')) sos = sosiph*180 if sos == float(list(lhd.values())[i]): print("You got the correct answer!") elif lmfao == '': print('You did not enter anything.') else: print("Your answer is incorrect.", "Better luck next time.", sep='\n') i+=1 if i == 4 : break print() time.sleep(1) def ci(): print(''' Let's learn about compound interest another mathematical concept used in our daily life. When we deposit some money (P) for some time(t) at some rate of interest(R), provided that it is compounded at periodic intervals of time this ,means that after every interval the principal of the next interval is the amount(A) at the previous interval.Thus , it gets compounded after intervals. Therefore, the formula for ''' ) listi = ["Mr. Narendra", "Reliance Industries", "Laksh"] for i in range(4): rnnr = random.randint(1,4) if rnnr == 1: n=1 nmx='yearly' t = 3 if rnnr == 2: n=2 nmx="halfyearly" t = 2 if rnnr == 3: n=4 nmx = "quarterly" t = 1 lii = random.choice(listi) r = random.randint(5,16) p = random.choice(list(range(10000, 60000, 10000))) a = lambda p,r,n,t : p*(1+r/n)**(n*t) print("{} invests ₹{} for a period of {} years. Find the total amount if it is compounded {} at a rate of {}".format(lii,p,t,nmx,r)) time.sleep(1) answerpls = float(input("Enter your answer : ₹ ")) if answerpls == round(float(a(p,r,n,t)),2): print("Well Done!") print("You got the correct answer.") else: print("Uh-Oh, Incorrect answer."); print("The correct answer is {}".format(round(float(a(p,r,n,t))),2)) print() time.sleep(1) def elev(): print(Back.BLACK +'Do you know about various tricks which are given by Vedic Maths?') speak('Do you know about various tricks which are given by Vedic Maths?') print( Fore.RED + Back.BLACK +""" We will learn about the a trick to ease our calculations when we multiply any 2-digit number by 11. When we multiply a 2-digit number for example-43 by 11,using the trick the answer comes out to be 473. Let us see how, The tens digit(4) of the multiplicant is placed at hundreds place of the product and ones digit (3) of the multiplicant is placed at the ones place of product.The sum of the digits of multiplicant is placed at tens place in the product. Let's take another case our numbers are 67 and 11, Here, we will proceed with same steps, the answer will be 737. But as we proceed with the 2nd step,the sum of multiplicants (6+7) is 13.So, we put the ones digit(3) at tens place and tens digit(1) will be added to the hundreds digit of the answer(6+1)37. """) speak('''We will learn about the a trick to ease our calculations when we multiply any 2-digit number by 11. When we multiply a 2-digit number for example-43 by 11,using the trick the answer comes out to be 473. Let us see how, The tens digit(4) of the multiplicant is placed at hundreds place of the product and ones digit (3) of the multiplicant is placed at the ones place of product.The sum of the digits of multiplicant is placed at tens place in the product. Let's take another case our numbers are 67 and 11, Here, we will proceed with same steps, the answer will be 737. But as we proceed with the 2nd step,the sum of multiplicants (6+7) is 13.So, we put the ones digit(3) at tens place and tens digit(1) will be added to the hundreds digit of the answer(6+1)37.''') time.sleep(4) speak('Let\'s Practice') print( Fore.GREEN +"Let's Practice") time.sleep(2) scr1 = 0 while True: for ii in range(4): no3 = floor(random.uniform(11, 100)) lol = int(input('Enter how many digits of 1 you want in the multiplier: ')) r = '1'*lol print( Back.BLACK + Fore.MAGENTA + 'Find the product when', no3,'is multiplied by', int(r)) speak('Find the product when') speak(no3) speak('is multiplied by', int(r)) speak('Enter the answer. If you dont know just press enter: ') ans = input("Enter the answer. If you dont know just press enter:") # t = Timer(60, time_up) # x is amount of allowed time in seconds then execute the provided function # t.start() #start the timer rgtans = no3 * int(r) if ans == str(rgtans): # t.cancel() scr1 += 1 print( Back.BLACK + 'Well Done! Your answer is correct') speak('Well Done! Your answer is correct') elif ans == "": print( Back.BLACK + "The correct answer is {}".format(rgtans)) speak("The correct answer is {}".format(rgtans)) elif ans != str(rgtans) : # t.cancel() print( Fore.RED +'Your answer is incorrect') speak('Your answer is incorrect') print( Fore.GREEN + 'The correct answer is', rgtans) speak('The correct answer is') speak(rgtans) print() break print("You got {} questions right out of 4".format(scr1)) perc1 = ((int(scr1)/4)*100) if perc1 >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc1)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc1)) print("We know that you can score better."+ Fore.RED +"You should try again") def sqr5(): print(Back.BLACK +'Do you know about various tricks which are given by Vedic Maths?') eng.say('Do you know about various tricks which are given by Vedic Maths?') eng.runAndWait() print(Fore.RED + Back.BLACK + """ We are going to learn about one of the basic rules of vedic maths.""" + Fore.BLUE + Back.BLACK + """ This involves easily finding squares of 2 digit numbers ending with digit 5 . STEP-1 As we all know square of any number ending with 5 must have 25 as digits on it's tens and ones places respectively. STEP-2 Multiply the tens digit of the number with its successor and write down the number obtained in front of 25. You got the square of the number.""" ) print(Fore.GREEN + """ Example - Let the number be 65. So, at tens and ones digit we put 25. Next we multiply 6 X (6+1) 6 X 7= 42 So, square of 65 comes out to be 4225.""") eng.say("We are going to learn about one of the basic rules of vedic maths.") eng.runAndWait() eng.say("This involves easily finding squares of 2 digit numbers ending with digit 5 .") eng.say("STEP-1 As we all know square of any number ending with 5 must have 25 as digits on it's tens and ones places respectively.") eng.runAndWait() eng.say("STEP-2 Multiply the tens digit of the number with its successor and write down the number obtained in front of 25.You got the square of the number.") eng.runAndWait() eng.say("Example") eng.runAndWait() eng.say("Let the number be 65.So, at tens and ones digit we put 25.") eng.runAndWait() eng.say("Next we multiply 6 X (6+1) 6 X 7= 42") eng.runAndWait() eng.say("So, square of 65 comes out to be 4225.") eng.runAndWait() time.sleep(1) print() scr = 0 while True: for i1 in range(4): no1 = floor(randrange(15,96,10 )) print( Style.DIM +'Find the square of',no1) eng.say('Find the square of ') eng.runAndWait() eng.say(no1) eng.runAndWait() eng.say("Enter the answer . If you don't know just press enter") eng.runAndWait() right_answer = no1 **2 #t= Timer(60, time_up) #x is amount of allowed time in seconds then execute the provided function #t.start() #start the timerx = np.linspace(-2,2,100) ans = input('Enter the answer, if you dont know it just press enter: ') if ans == str(right_answer): #t.cancel() scr += 1 print( Fore.GREEN +'Well Done! Your answer is correct') eng.say('Well Done! Your answer is correct') eng.runAndWait() elif ans == "": #t.cancel() print(Back.BLACK + "The correct answer is {}".format(right_answer)) eng.say("The correct answer is {}".format(right_answer)) eng.runAndWait() elif ans != str(right_answer): #t.cancel() print(Back.BLACK + 'Sorry, incorrect answer') eng.say('Sorry, incorrect answer') eng.runAndWait() print(Back.BLACK + 'The correct answer is {}'.format(no1**2)) eng.say('The correct answer is {}'.format(no1 **2)) eng.runAndWait() print() break print("You got {} questions right out of 4".format(scr)) perc = ((int(scr)/4)*100) if perc >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc)) print("We know that you can score better."+ Fore.RED +"You should try again") # def linear(): # print(Fore.RED + 'These questions will test your basic knowledge of Linear Equations') # print(Fore.RED + 'A linear equation of the form ax + by + c will be given') # eng.say('These questions will test your basic knowledge of Linear Equations. A linear equation of the form ax + by + c will be given') # eng.runAndWait() # print(Style.DIM + 'You have to find the value of x only') # eng.say('You have to find the value of x only') # eng.runAndWait() # time.sleep(2) # scr2 = 0 # while True: # for i in range(4): # num1 = floor(random.uniform(-10, 10)) # num2 = floor(random.uniform(-10, 10)) # con = floor(random.uniform(-10, 10)) # var = floor(random.uniform(-10, 10)) # sym.init_printing() # x,y = sym.symbols('x,y') # a = sym.Eq(num1*x + num2*y + con,0) # b = sym.Eq((num1+var)*x + num2*var*y + (con/var),0) # d = {} # d = sym.solve([a,b],(x,y)) # print( Style.DIM + 'equation 1 is', num1,x, '+', num2,y, '+', con, '=', '0') # eng.say('equation 1 is') # eng.runAndWait() # eng.say(num1) # eng.runAndWait() # eng.say('x plus') # eng.runAndWait() # eng.say(num2) # eng.runAndWait() # eng.say('y plus') # eng.runAndWait() # eng.say(con) # eng.runAndWait() # eng.say('equal to zero') # eng.runAndWait() # print( Back.BLACK + 'equation 2 is', (num1+var),x, '+', (num2*var)+y, '+', con/var, '=', '0') # print( Fore.CYAN + 'Enter the value of x') # #display(Math(r'nudef cg(): # print( Back.BLACK + 'These questions will test your basic knowledge of Coordinate Geometry more specifically the section formula') # print( Back.BLACK + 'The coordinates of the two end points and the ratio with which the line is internally divided will be given') # print( Back.BLACK + 'You have to find the coordinates of the point which divides the line internally in the given ratio') # scr3 = 0 # while True: # for i2 in range(4): # x1 = floor(random.uniform(-10, 10)) # x2 = floor(random.uniform(-10, 10)) # y1 = floor(random.uniform(-10, 10)) # y2 = floor(random.uniform(-10, 10)) # m = floor(random.uniform(-10, 10)) # n = floor(random.uniform(-10, 10)) # lmb = lambda x1,x2,m,n : (x1*n + x2*m)/m+n # lmb1 = lambda y1,y2,m,n : (y1*n + y2*m)/m+n # print(Fore.CYAN + 'coordinates of point1 are', '(',x1,',',y1,')') # print( Fore.CYAN + 'coordinates of point2 are', '(',x2,',',y2,')') # print( Back.BLACK +'The line is internally divided in a ratio of m:n where m = {} and n = {}'.format(m,n)) # x3 = int(input('Enter the x coordinate of point ')) # y3 = int(input('Enter the y coordinate of point ')) # kaw = floor(lmb(x1,x2,m,n)) # koo = floor(lmb1(y1,y2,m,n)) # t= Timer(120, time_up) #x is amount of allowed time in seconds then execute the provided function # t.start() #start the timer # if x3 == kaw and y3 == koo: # t.cancel() # scr3 += 1 # print( Fore.GREEN + 'Good Job! Your answer is correct') # eng.say('Good Job! Your answer is correct') # eng.runAndWait() # else : # t.cancel() # print( Style.DIM + 'Your answer is incorrect') # eng.say('Your answer is incorrect') # eng.runAndWait() # print( Fore.YELLOW + 'The correct answer is, x coordinate = {} and y coordinate = {}'.format(kaw, koo)) # eng.say('The correct answer is, x coordinate = {} and y coordinate = {}'.format(kaw, koo)) # eng.runAndWait() # print() # time.sleep(5) # break # print('You got {} questions right out of 4'.format(scr3)) # perc3 = int((scr3)/4)*100 # if perc3 >= 75: # print("Which means you scored" + Fore.CYAN + {} + "percentage".format(perc3)) # print(Fore.GREEN + "WOW !! Nice Score") # else: # print("You have scored {} percentage".format(perc3)) # print("We know that you can score better."+ Fore.RED +"You should try again") # m1 x + num2 y + con = 0')) # # num1,x, '+', num2,y, '+', con, '=', '0') # eng.say('equation 2 is') # eng.runAndWait() # eng.say(num1+var) # eng.runAndWait() # eng.say('x plus') # eng.runAndWait() # eng.say(num2*var) # eng.runAndWait() # eng.say('y plus') # eng.runAndWait() # eng.say(con/var) # eng.runAndWait() # eng.say('equal to zero') # eng.runAndWait() # eng.say("Enter the value of x. If you don't know the answer press space") # eng.runAndWait() # inp = int(input()) # k = floor(d[x]) # #t= Timer(120, time_up) #x is amount of allowed time in seconds then execute the provided function # #t.start() #start the timer # if inp == k: # #t.cancel() # scr2 += 1 # eng.say('Enter the value of x and wait for 2 minutes') # eng.runAndWait() # print( Fore.GREEN +'Good Job! Your answer is correct') # elif inp == "": # print(Fore.MAGENTA+"The correct answer is {}".format(k)) # eng.say("The correct answer is {}".format(k)) # eng.runAndWait() # else : # #t.cancel() # print( Fore.RED + 'Your answer is incorrect') # eng.say('Your answer is incorrect') # eng.runAndWait() # print( Back.BLACK + 'The correct answer is', k) # eng.say('The correct answer is' + str(floor(d[x]))) # eng.runAndWait() # eng.say(floor(d[x])) # eng.runAndWait() # print() # time.sleep(2) # break # print('You got {} questions right out of 4'.format(scr2)) # perc2 = int((scr2)/4)*100 # if perc2 >= 75: # print("Which means you scored" + Fore.CYAN + {} + "percentage".format(perc2)) # print(Fore.GREEN + "WOW !! Nice Score") # else: # print("You have scored {} percentage".format(perc2)) # print("We know that you can score better."+ Fore.RED +"You should try again") def cg(): print("Do you know about the method to calculate the coordinates of any point dividing a line in a particular ratio?") speak("Do you know about the method to calculate the coordinates of any point dividing a line in a particular ratio?") time.sleep(2) print("""Consider a line with the coordinates of the end points as (x1, y1) and (x2, y2), which is divided in a ratio m:n by a point (x3, y3). Now there is a formula known as the section formula :- x3 = (m*x2 + n*x1)/(m + n), similarly in order to find y3 just replace "x" with "y". """) speak("""Consider a line with the coordinates of the end points as (x1, y1) and (x2, y2), which is divided in a ratio m:n by a point (x3, y3). Now there is a formula known as the section formula :- x3 = (m*x2 + n*x1)/(m + n), similarly in order to find y3 just replace "x" with "y". """) print(Back.BLACK + "These questions will test your basic knowledge of Coordinate Geometry more specifically the section formula") print(Back.BLACK + "The coordinates of the two end points and the ratio with which the line is internally divided will be given") print(Back.BLACK + "You have to find the coordinates of the point which divides the line internally in the given ratio") speak('These questions will test your basic knowledge of Coordinate Geometry more specifically the section formula. The coordinates of the two end points and the ratio with which the line is internally divided will be given. You have to find the coordinates of the point which divides the line internally in the given ratio') scr3 = 0 while True: for i2 in range(4): x1 = floor(random.uniform(-10, 10)) x2 = floor(random.uniform(-10, 10)) y1 = floor(random.uniform(-10, 10)) y2 = floor(random.uniform(-10, 10)) m = floor(random.uniform(-10, 10)) n = floor(random.uniform(-10, 10)) lmb = lambda x1,x2,m,n : (x1*n + x2*m)/m+n lmb1 = lambda y1,y2,m,n : (y1*n + y2*m)/m+n print(Fore.CYAN + "coordinates of point1 are", "(",x1,",",y1,")") print( Fore.CYAN + "coordinates of point2 are", "(",x2,",",y2,")") print( Back.BLACK +"The line is internally divided in a ratio of m:n where m = {} and n = {}".format(m,n)) x3 = int(input('Enter the x coordinate of point ')) y3 = int(input('Enter the y coordinate of point ')) kaw = floor(lmb(x1,x2,m,n)) koo = floor(lmb1(y1,y2,m,n)) t= Timer(120, time_up) #x is amount of allowed time in seconds then execute the provided function t.start() #start the timer if x3 == kaw and y3 == koo: t.cancel() scr3 += 1 print( Fore.GREEN + 'Good Job! Your answer is correct') speak('Good Job! Your answer is correct') else : t.cancel() print( Style.DIM + 'Your answer is incorrect') speak('Your answer is incorrect') print( Fore.YELLOW + 'The correct answer is, x coordinate = {} and y coordinate = {}'.format(kaw, koo)) speak('The correct answer is, x coordinate = {} and y coordinate = {}'.format(kaw, koo)) print() time.sleep(1) break print("You got {} questions right out of 4".format(scr3)) perc3 = ((int(scr3)/4)*100) if perc3 >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc3)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc3)) print("We know that you can score better."+ Fore.RED +"You should try again") def mod(): print(Fore.YELLOW + 'There will be a total of 4 questions') print(Fore.YELLOW + 'You will have 2 minutes to solve each question, after the time ends the answer will be displayed.') print(Back.BLACK + 'While answering the question enter the closest integer value') print() while True: print(Fore.YELLOW + 'Choose one of the following options.') print(Fore.RED + '''1 --> Linear Equations 2 --> Coordinate Geometry (section formula) 3 --> Visualise Equations 4 --> Go Back''') c1 = int(input()) if c1 == 1: into() #; linear() if c1 == 2: cg() if c1 == 3: visualise_eqn1() visualise_eqn2() if c1 == 4: break def calculus(): print( Back.BLACK + 'These questions will test your basic knowledge of differentiation') print( Style.DIM + 'A function will be given, you will have to find the derivative of that function') scr4 = 0 while True: for i5 in range(4): coeff1 = floor(random.uniform(-3, 3)) coeff2 = floor(random.uniform(-3, 3)) coeff3 = floor(random.uniform(-3, 3)) x = symbols('x') init_printing(use_unicode=True) expression = coeff1*exp(coeff2*x**coeff1)*sin(coeff3*x**coeff2)+cos(x) l =[] l.append(diff(expression)) l.append(coeff1*diff(expression)+coeff1) l.append(diff(expression)/coeff2+coeff3) op1 = random.choice(l) l.remove(op1) op2 = random.choice(l) l.remove(op2) op3 = random.choice(l) print( Back.BLACK + "Find the derivative of f(x) =" ,expression) speak("Find the derivative of f(x) =" ,expression) print( Fore.CYAN + "Choose the correct option. If you don't know just press enter") print(Back.BLACK +'1 -->', op1) print(Back.BLACK +'2 -->', op2) print(Back.BLACK +'3 -->', op3) speak("Choose the correct option. If you don't know just press enter") print(Back.BLACK +'1 -->', op1, '; 2 -->', op2, '; 3 -->', op3) speak("Choose the correct option. If you don't know just press enter") it = input() if it == "1": annn = op1 elif it == "": print("The correct option is".format(diff(expression))) elif it == "2": annn = op2 elif it == "3": annn = op3 #t = Timer(150, time_up) #x is amount of allowed time in seconds then execute the provided function #t.start() if annn == diff(expression): # t.cancel() scr4 += 1 print('Good Job! your answer is correct') speak('Good Job! your answer is correct') else: # t.cancel() print('Sorry, incorrect answer') print("The correct answer is", diff(expression)) speak('Sorry, incorrect answer') print() time.sleep(1) break print("You got {} questions right out of 4".format(scr4)) perc4 = ((int(scr4)/4)*100) if perc4 >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc4)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc4)) print("We know that you can score better."+ Fore.RED +"You should try again") def quad(): print("""A quadratic equation is an algebraic equation which can be rearranged in the following standard form: ax^2 + bx + c. The solution to such equations can be easily found by using Shri Dharacharya's formula, which goes, x = (-b + sqrt(b^2 - 4ac))/(2a) and x = (-b - sqrt(b^2 - 4ac))/(2a).""") print() time.sleep(1) print(Style.DIM + 'These questions will test your basic knowledge of Quadratic Equations') print(Back.BLACK + Fore.RED + 'An Equations of the form ax^2 + bx + c = 0 will be given') print( Back.BLACK +'You have to find the value of x and input it in the closest possible integer') scr5 = 0 while True: for i3 in range(4): a1 = floor(random.uniform(-10, 10)) b1 = floor(random.uniform(-10, 10)) co = floor(random.uniform(-10, 10)) v = floor(random.uniform(-10, 10)) sym.init_printing() x = sym.symbols('x') rr = sym.Eq(a1*(x**2) + b1*x + co,0) dict = {} dict = sym.solve([rr],(x)) print( Back.BLACK + 'equation is', a1,'x^2', '+', '('+str(b1)+')','x', '+', '('+str(co)+')', '=', '0') answer = str(input("Enter the value of x, if i(iota) is coming in the solution then write it as 'I'. If you don't know just press enter : ")) hehe = floor(dict[0][0]) huh = floor(dict[1][0]) #t = Timer(5, time_up) #t.start() if answer == str(hehe) or answer == str(huh): # t.cancel() scr5 += 1 print( Back.BLACK + 'Good Job! Your answer is correct') if answer == "": # t.cancel() print("The correct answer is", hehe, "or", huh) else: # t.cancel() print(Back.BLACK + 'Your answer is incorrect') print("The correct answer is", hehe, "or", huh) print() time.sleep(2) break print("You got {} questions right out of 4".format(scr5)) perc5 = ((int(scr5)/4)*100) if perc5 >= 75: print("Which means you scored" + Fore.CYAN + " {} %".format(perc5)) print(Fore.GREEN + "WOW !! Nice Score") else: print("You have scored {} percentage".format(perc5)) print("We know that you can score better."+ Fore.RED +"You should try again") def adv(): print('There will be a total of 4 questions') print('You will have 2 minutes and 30 seconds to answer each question') print('While answering the question enter the closest integer value') while True: print(Back.BLACK + 'Choose one of the following options') print( Fore.RED + '''1 --> Calculus 2 --> Quadratic Equations 3 --> Go Back''') # 2 --> Quadratic Equations; c2 = int(input()) if c2 == 1: calculus() if c2 == 2: quad() elif c2 == 3: break def evd(): print('There will be a total of 4 questions') while True : print(Back.BLACK + 'Choose one of the following options') print("""1 --> Heights and Distances 2 --> Compound Interest 3 --> Go Back""") cwfl = int(input()) if cwfl == 1: had() if cwfl == 2: ci() if cwfl == 3: break def into(): speak("Do you know what an algebric equation is ") intro_ques = input("Do you know what an algebric equation is (yes/no): ") if intro_ques == "yes": print( Style.DIM + "Ok then lets directly move to visualsing linear equations") visualise_eqn1() if intro_ques == "no": print( Fore.GREEN+ "well its basically just a simple equation with variables") speak("well its basically just a simple equation with variables") speak("Do you know what variables are") intro_ques1 = input("Do you know what variables are (yes/no): ") if intro_ques1 == "no": print( Back.BLACK + """ In simple terms variables is something whose value can change(or vary). Let me explain you this in simpler terms for example Ram has 5 apples. Now if he will never eat those apples the quantity of those apples will never change Those apples are 5 and will remain 5 untill someone eats them. So here we have a constant 5 But now Shyam comes and he says that he has "some" apples now how can we define that "some" we don't have any definate to put in the place of "some" so "some" is a variable quantity it can be 2,3,4,5.... anything. """) speak("In simple terms variables is something whose value can't change.") speak("""Let me explain you this in simpler terms for example Ram has 5 apples. Now if he will never eat those apples the quantity of those apples will never change Those apples are 5 and will remain 5 untill someone eats them. So here we have a constant 5 But now Shyam comes and he says that he has "some" apples now how can we define that "some" we don't have any definate to put in the place of "some". So "some" is a variable quantity it can be 2,3,4,5.... anything. """ ) print( Back.BLACK + """Now if we ask ourself,how we can we identify variables, well just ask yourself, can we define that particular value? if yes then it's a constant else a variable""") speak("Now if we ask ourself,how we can we identify variables, well just ask yourself, can we define that particular value? if yes then it's a constant else a variable") print(Fore.CYAN + "Lets move to ") speak("Lets move to") print("examples of linear equations. :") speak("examples of linear equations. ") ln_examples = cv2.imread('Types-of-linear-equation.png',1) not_ln_examples = cv2.imread('not-linear-equations.png',1) cv2.imshow("Types-of-linear-equation",ln_examples) k = cv2.waitKey(33) print("These are the examples of types of linear equation. The window will automatically after 6 seconds ") speak("These are the examples of types of linear equation. The window will close automatically after 6 seconds") time.sleep(6) cv2.destroyWindow("Types-of-linear-equation") cv2.imshow("Not linear equations",not_ln_examples) k = cv2.waitKey(33) print("They are not linear equation. The window will close automatically after 6 seconds") speak("They are not linear equation. The window will close automatically after 6 seconds") time.sleep(6) cv2.destroyWindow("Not linear equations") # examples to be added using image or anything def img(): graph_table = cv2.imread("table.png",1) cv2.imshow("How to get coordinates of linear equation",graph_table) k = cv2.waitKey(33) print("This table explains, how we have to find coordinates. The window will close automatically after 6 seconds") speak("This table explains, how we have to find coordinates. The window will close automatically after 6 seconds") time.sleep(6) cv2.destroyWindow("How to get coordinates of linear equation") def visualise_eqn1(): print( Back.BLACK + "Lets say if we want a graph of y = 2x+3. How to make that ?") speak("Lets say if we want a graph of y = 2x+3. How to make that ?") print( Fore.YELLOW + """ we basically see variation in x with respect to y. This means that we put y = 2x+3 and we will put random value to x like 1,2,3,4 .... and will see what is the value of y. When y becomes 0 we say that the equation satisfies and we have a zero for that equation. """) speak("we basically see variation in x with respect to y. This means that we put y = 2x+3 and we will put random value to x like 1,2,3,4 .... and will see what is the value of y. When y becomes 0 we say that the equation satisfies and we have a zero for that equation.") img() print("So we plot using these points/coordinates we found i.e. (0,3), (1,5), (2,7) and (3,9). We join these points and we get the graph of the equation") speak("So we plot using these points/coordinates we found that is 0 comma 3 1 comma 5 2 comma 7 and 3 comma 9 . We join these points to get the graph of the equation") def visualise_eqn2(): x = np.linspace(-2,2,100) # the function, which is y = x^3 here y = 2*x+3 roots =[] x1 = 0 y1 = 2*x1+3 x2 = -3/2 y2 = 0 # setting the axes at the centre fig = plt.figure(figsize=(12,7)) ax = plt.gca() ax.spines['top'].set_color('none') ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') # explain linear equations with graph more plt.plot(x,y,'purple') plt.plot(x1,y1,marker="o") plt.plot(x2,y2,marker="o") plt.grid() plt.savefig("GRAPH.jpeg") time.sleep(2) print("If you don't see a graph pop out please check the folder for a file named GRAPH.png") eng.say("If you don't see a graph pop out please check the folder for a file named GRAPH.png") eng.runAndWait() print(Fore.RED + """ The orange dot represents the zero of the linear equation here the value of whole equation becomes 0 the blue dot just represents the point where the line intersects with Y axis. After you have viewed the program please close it to move forward""") # explain how to find zeros theoretically speak("The orange dot represents the zero of the linear equation here the value of whole equation becomes 0 the blue dot just represents the point where the line intersects with Y axis.After you have viewed the program please close it to move forward") img = cv2.imread("GRAPH.jpeg",1) cv2.imshow("GRAPH.jpeg",img) print("This is how the graph will look like. The window will close automatically after 6 seconds") speak("This is how the graph will look like. The window will close automatically after 6 seconds") k = cv2.waitKey(33) time.sleep(6) cv2.destroyWindow("GRAPH.jpeg") # eng.say("Do you want to plot a of your own equation:") # eng.runAndWait() # user_input() # def user_input(): # this is how you do recusrsion babyyyy # inp1 = input("Do you want to plot a of your own equation(yes/no): ") # if inp1 == "": # user_input() # if inp1 == "yes": # print( Back.BLACK + """ # Write your equation using following rules or the application will not work and may crash # **Rules** # Use * for multiplication example 4x = 4*x and (4)(3) = 4*3 # Use ** for exponent example if you want to represent x² = x**2 ; for 2x² = 2*x**2 # use / for divisiond # use + for addition and - for subtraction # Write equation in one variable using only 'x' # Do not use equal to sign, just write LHS part of that equation. # """) # cahnge colour for last 2 . To highlight them # eng.say("Write your equation using following rules or the application will not work and may crash") # eng.runAndWait() # eng.say("Rules") # eng.runAndWait() # eng.say("Use astericks for multiplication") # eng.runAndWait() # eng.say("use slash for division") # eng.runAndWait() # eng.say("use plus for addition and minus for subtraction") # eng.runAndWait() # eng.say("Write equation in one variable using only 'x'") # eng.runAndWait() # eng.say("Do not use equal to sign, just write LHS part of that equation.") # eng.runAndWait() # x = np.linspace(-2,2,100) # Y = input("enter your equation here using above rules: ") # plt.plot(x,Y,color="Brown",title="Your Equation's plot") # plt.grid() # plt.show(block=True) # plt.savefig("Your-Graph.png") # your_graph = Image.open("Your-Graph.png") # your_graph.show() # print("If you don't see a graph pop out please check the folder for a file named GRAPH.png") # eng.say("If you don't see a graph pop out please check the folder for a file named GRAPH.png") # eng.runAndWait() # if inp1 == "no": # pass def time_up(): answer= None option2 = "You failed to answer within the given time limit" #what to do if the player does not enter an answer within the allowed time option1 = 'You failed to input an answer within the time limit' optimize = 'You took too long to answer the time is over' arr = [option1, option2, optimize] r = random.choice(arr) print(r) speak(r) def welcome(): print(Fore.CYAN+Back.BLACK+ """ ██╗ ██╗███████╗██╗ ██████╗ ██████╗ ███╗ ███╗███████╗ ██║ ██║██╔════╝██║ ██╔════╝██╔═══██╗████╗ ████║██╔════╝ ██║ █╗ ██║█████╗ ██║ ██║ ██║ ██║██╔████╔██║█████╗ ██║███╗██║██╔══╝ ██║ ██║ ██║ ██║██║╚██╔╝██║██╔══╝ ╚███╔███╔╝███████╗███████╗╚██████╗╚██████╔╝██║ ╚═╝ ██║███████╗ ╚══╝╚══╝ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ """ ) def game_over(): print(Fore.CYAN + Back.BLACK + """ ▄██████▄ ▄████████ ▄▄▄▄███▄▄▄▄ ▄████████ ▄██████▄ ▄█ █▄ ▄████████ ▄████████ ███ ███ ███ ███ ▄██▀▀▀███▀▀▀██▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ███ █▀ ███ ███ ▄███ ███ ███ ███ ███ ███ ▄███▄▄▄ ███ ███ ███ ███ ▄███▄▄▄ ▄███▄▄▄▄██▀ ▀▀███ ████▄ ▀███████████ ███ ███ ███ ▀▀███▀▀▀ ███ ███ ███ ███ ▀▀███▀▀▀ ▀▀███▀▀▀▀▀ ███ ███ ███ ███ ███ ███ ███ ███ █▄ ███ ███ ███ ███ ███ █▄ ▀███████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ████████▀ ███ █▀ ▀█ ███ █▀ ██████████ ▀██████▀ ▀██████▀ ██████████ ███ ███ ███ ███ """ ) def main(): while True: print(Fore.YELLOW + "Choose one of the following options.") print(Fore.RED + '''1 --> Basic Level (VEDIC MATHS) 2 --> Moderate Level(6TH -8TH STANDARD) 3 --> Advance Level(9TH TO 12TH STANDARD) 4 --> Everyday Mathematics 5 --> End Game''') c = int(input()) if c == 1: basic() if c == 2: mod() if c == 3: adv() if c == 4 : # scr+scr1+scr2+scr3+scr4+scr5 is not working so removed evd() if c == 5 print( Fore.RED + 'You have successfully exited the game.') speak("exit") break if __name__ == '__main__': # text to speech engine init() eng = pyttsx3.init() # not making a function volume = eng.getProperty('volume') # volume print(Fore.RED + "Your current volume level is:" + str(volume)) vol_inp = float(input("We recommend you to set volume to max. Max volume is 1 and minimum is 0 you can choose either of them or you can choose between them using decimal: ")) eng.setProperty('volume', vol_inp) # max volume is 1.0 eng.setProperty('rate',132) welcome() main() game_over()
// Compiled by ClojureScript 1.8.51 {} goog.provide('cljs.tools.reader'); goog.require('cljs.core'); goog.require('cljs.tools.reader.impl.commons'); goog.require('goog.string'); goog.require('goog.array'); goog.require('cljs.tools.reader.reader_types'); goog.require('goog.string.StringBuffer'); goog.require('cljs.tools.reader.impl.utils'); goog.require('clojure.string'); cljs.tools.reader.macro_terminating_QMARK_ = (function cljs$tools$reader$macro_terminating_QMARK_(ch){ var G__15479 = ch; switch (G__15479) { case "\"": case ";": case "@": case "^": case "`": case "~": case "(": case ")": case "[": case "]": case "{": case "}": case "\\": return true; break; default: return false; } }); cljs.tools.reader.sb = (new goog.string.StringBuffer()); /** * Read in a single logical token from the reader */ cljs.tools.reader.read_token = (function cljs$tools$reader$read_token(rdr,initch){ if((initch == null)){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading"); } else { cljs.tools.reader.sb.clear(); var ch = initch; while(true){ if((cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch)) || (cljs.tools.reader.macro_terminating_QMARK_.call(null,ch)) || ((ch == null))){ if((ch == null)){ } else { cljs.tools.reader.reader_types.unread.call(null,rdr,ch); } return cljs.tools.reader.sb.toString(); } else { cljs.tools.reader.sb.append(ch); var G__15481 = cljs.tools.reader.reader_types.read_char.call(null,rdr); ch = G__15481; continue; } break; } } }); cljs.tools.reader.read_dispatch = (function cljs$tools$reader$read_dispatch(rdr,_,opts,pending_forms){ var temp__4655__auto__ = cljs.tools.reader.reader_types.read_char.call(null,rdr); if(cljs.core.truth_(temp__4655__auto__)){ var ch = temp__4655__auto__; var temp__4655__auto____$1 = cljs.tools.reader.dispatch_macros.call(null,ch); if(cljs.core.truth_(temp__4655__auto____$1)){ var dm = temp__4655__auto____$1; return dm.call(null,rdr,ch,opts,pending_forms); } else { return cljs.tools.reader.read_tagged.call(null,(function (){var G__15483 = rdr; cljs.tools.reader.reader_types.unread.call(null,G__15483,ch); return G__15483; })(),ch,opts,pending_forms); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading character"); } }); cljs.tools.reader.read_unmatched_delimiter = (function cljs$tools$reader$read_unmatched_delimiter(rdr,ch,opts,pending_forms){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Unmatched delimiter ",ch); }); cljs.tools.reader.read_regex = (function cljs$tools$reader$read_regex(rdr,ch,opts,pending_forms){ var sb = (new goog.string.StringBuffer()); var ch__$1 = cljs.tools.reader.reader_types.read_char.call(null,rdr); while(true){ if(("\"" === ch__$1)){ return cljs.core.re_pattern.call(null,[cljs.core.str(sb)].join('')); } else { if((ch__$1 == null)){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading regex"); } else { sb.append(ch__$1); if(("\\" === ch__$1)){ var ch_15484__$2 = cljs.tools.reader.reader_types.read_char.call(null,rdr); if((ch_15484__$2 == null)){ cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading regex"); } else { } sb.append(ch_15484__$2); } else { } var G__15485 = cljs.tools.reader.reader_types.read_char.call(null,rdr); ch__$1 = G__15485; continue; } } break; } }); cljs.tools.reader.char_code = (function cljs$tools$reader$char_code(ch,base){ var code = parseInt(ch,base); if(cljs.core.truth_(isNaN(code))){ return (-1); } else { return code; } }); cljs.tools.reader.read_unicode_char = (function cljs$tools$reader$read_unicode_char(var_args){ var args15486 = []; var len__7157__auto___15489 = arguments.length; var i__7158__auto___15490 = (0); while(true){ if((i__7158__auto___15490 < len__7157__auto___15489)){ args15486.push((arguments[i__7158__auto___15490])); var G__15491 = (i__7158__auto___15490 + (1)); i__7158__auto___15490 = G__15491; continue; } else { } break; } var G__15488 = args15486.length; switch (G__15488) { case 4: return cljs.tools.reader.read_unicode_char.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; case 5: return cljs.tools.reader.read_unicode_char.cljs$core$IFn$_invoke$arity$5((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args15486.length)].join(''))); } }); cljs.tools.reader.read_unicode_char.cljs$core$IFn$_invoke$arity$4 = (function (token,offset,length,base){ var l = (offset + length); if((cljs.core.count.call(null,token) === l)){ } else { throw cljs.core.ex_info.call(null,[cljs.core.str("Invalid unicode character: \\"),cljs.core.str(token)].join(''),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-argument","illegal-argument",-1845493170)], null)); } var i = offset; var uc = (0); while(true){ if((i === l)){ return String.fromCharCode(uc); } else { var d = cljs.tools.reader.char_code.call(null,cljs.core.nth.call(null,token,i),base); if((d === (-1))){ throw cljs.core.ex_info.call(null,[cljs.core.str("Invalid digit: "),cljs.core.str(cljs.core.nth.call(null,token,i))].join(''),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-argument","illegal-argument",-1845493170)], null)); } else { var G__15493 = (i + (1)); var G__15494 = (d + (uc * base)); i = G__15493; uc = G__15494; continue; } } break; } }); cljs.tools.reader.read_unicode_char.cljs$core$IFn$_invoke$arity$5 = (function (rdr,initch,base,length,exact_QMARK_){ var i = (1); var uc = cljs.tools.reader.char_code.call(null,initch,base); while(true){ if((uc === (-1))){ throw cljs.core.ex_info.call(null,[cljs.core.str("Invalid digit: "),cljs.core.str(initch)].join(''),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-argument","illegal-argument",-1845493170)], null)); } else { if(!((i === length))){ var ch = cljs.tools.reader.reader_types.peek_char.call(null,rdr); if(cljs.core.truth_((function (){var or__6087__auto__ = cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch); if(or__6087__auto__){ return or__6087__auto__; } else { var or__6087__auto____$1 = cljs.tools.reader.macros.call(null,ch); if(cljs.core.truth_(or__6087__auto____$1)){ return or__6087__auto____$1; } else { return (ch == null); } } })())){ if(cljs.core.truth_(exact_QMARK_)){ throw cljs.core.ex_info.call(null,[cljs.core.str("Invalid character length: "),cljs.core.str(i),cljs.core.str(", should be: "),cljs.core.str(length)].join(''),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-argument","illegal-argument",-1845493170)], null)); } else { return String.fromCharCode(uc); } } else { var d = cljs.tools.reader.char_code.call(null,ch,base); cljs.tools.reader.reader_types.read_char.call(null,rdr); if((d === (-1))){ throw cljs.core.ex_info.call(null,[cljs.core.str("Invalid digit: "),cljs.core.str(ch)].join(''),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-argument","illegal-argument",-1845493170)], null)); } else { var G__15495 = (i + (1)); var G__15496 = (d + (uc * base)); i = G__15495; uc = G__15496; continue; } } } else { return String.fromCharCode(uc); } } break; } }); cljs.tools.reader.read_unicode_char.cljs$lang$maxFixedArity = 5; cljs.tools.reader.upper_limit = "\uD7FF".charCodeAt((0)); cljs.tools.reader.lower_limit = "\uE000".charCodeAt((0)); cljs.tools.reader.valid_octal_QMARK_ = (function cljs$tools$reader$valid_octal_QMARK_(token,base){ return (parseInt(token,base) <= (255)); }); /** * Read in a character literal */ cljs.tools.reader.read_char_STAR_ = (function cljs$tools$reader$read_char_STAR_(rdr,backslash,opts,pending_forms){ var ch = cljs.tools.reader.reader_types.read_char.call(null,rdr); if(!((ch == null))){ var token = (((cljs.tools.reader.macro_terminating_QMARK_.call(null,ch)) || (cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch)))?[cljs.core.str(ch)].join(''):cljs.tools.reader.read_token.call(null,rdr,ch)); var token_len = token.length; if(((1) === token_len)){ return token.charAt((0)); } else { if(cljs.core._EQ_.call(null,token,"newline")){ return "\n"; } else { if(cljs.core._EQ_.call(null,token,"space")){ return " "; } else { if(cljs.core._EQ_.call(null,token,"tab")){ return "\t"; } else { if(cljs.core._EQ_.call(null,token,"backspace")){ return "\b"; } else { if(cljs.core._EQ_.call(null,token,"formfeed")){ return "\f"; } else { if(cljs.core._EQ_.call(null,token,"return")){ return "\r"; } else { if(cljs.core.truth_(goog.string.startsWith(token,"u"))){ var c = cljs.tools.reader.read_unicode_char.call(null,token,(1),(4),(16)); var ic = c.charCodeAt((0)); if(((ic > cljs.tools.reader.upper_limit)) && ((ic < cljs.tools.reader.lower_limit))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Invalid character constant: \\u",c); } else { return c; } } else { if(cljs.core.truth_(goog.string.startsWith(token,"o"))){ var len = (token_len - (1)); if((len > (3))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Invalid octal escape sequence length: ",len); } else { var offset = (1); var base = (8); var uc = cljs.tools.reader.read_unicode_char.call(null,token,offset,len,base); if(cljs.core.not.call(null,cljs.tools.reader.valid_octal_QMARK_.call(null,cljs.core.subs.call(null,token,offset),base))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Octal escape sequence must be in range [0, 377]"); } else { return uc; } } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Unsupported character: \\",token); } } } } } } } } } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading character"); } }); cljs.tools.reader.starting_line_col_info = (function cljs$tools$reader$starting_line_col_info(rdr){ if(cljs.core.truth_(cljs.tools.reader.reader_types.indexing_reader_QMARK_.call(null,rdr))){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.tools.reader.reader_types.get_line_number.call(null,rdr),((cljs.tools.reader.reader_types.get_column_number.call(null,rdr) - (1)) | (0))], null); } else { return null; } }); cljs.tools.reader.ending_line_col_info = (function cljs$tools$reader$ending_line_col_info(rdr){ if(cljs.core.truth_(cljs.tools.reader.reader_types.indexing_reader_QMARK_.call(null,rdr))){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.tools.reader.reader_types.get_line_number.call(null,rdr),cljs.tools.reader.reader_types.get_column_number.call(null,rdr)], null); } else { return null; } }); if(typeof cljs.tools.reader.READ_EOF !== 'undefined'){ } else { cljs.tools.reader.READ_EOF = (new Object()); } if(typeof cljs.tools.reader.READ_FINISHED !== 'undefined'){ } else { cljs.tools.reader.READ_FINISHED = (new Object()); } cljs.tools.reader._STAR_read_delim_STAR_ = false; cljs.tools.reader.read_delimited_internal = (function cljs$tools$reader$read_delimited_internal(delim,rdr,opts,pending_forms){ var vec__15498 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var start_line = cljs.core.nth.call(null,vec__15498,(0),null); var start_column = cljs.core.nth.call(null,vec__15498,(1),null); var delim__$1 = cljs.tools.reader.impl.utils.char$.call(null,delim); var a = cljs.core.transient$.call(null,cljs.core.PersistentVector.EMPTY); while(true){ var form = cljs.tools.reader.read_STAR_.call(null,rdr,false,cljs.tools.reader.READ_EOF,delim__$1,opts,pending_forms); if((form === cljs.tools.reader.READ_FINISHED)){ return cljs.core.persistent_BANG_.call(null,a); } else { if((form === cljs.tools.reader.READ_EOF)){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading",(cljs.core.truth_(start_line)?[cljs.core.str(", starting at line "),cljs.core.str(start_line),cljs.core.str(" and column "),cljs.core.str(start_column)].join(''):null)); } else { var G__15499 = cljs.core.conj_BANG_.call(null,a,form); a = G__15499; continue; } } break; } }); /** * Reads and returns a collection ended with delim */ cljs.tools.reader.read_delimited = (function cljs$tools$reader$read_delimited(delim,rdr,opts,pending_forms){ var _STAR_read_delim_STAR_15501 = cljs.tools.reader._STAR_read_delim_STAR_; cljs.tools.reader._STAR_read_delim_STAR_ = true; try{return cljs.tools.reader.read_delimited_internal.call(null,delim,rdr,opts,pending_forms); }finally {cljs.tools.reader._STAR_read_delim_STAR_ = _STAR_read_delim_STAR_15501; }}); /** * Read in a list, including its location if the reader is an indexing reader */ cljs.tools.reader.read_list = (function cljs$tools$reader$read_list(rdr,_,opts,pending_forms){ var vec__15504 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var start_line = cljs.core.nth.call(null,vec__15504,(0),null); var start_column = cljs.core.nth.call(null,vec__15504,(1),null); var the_list = cljs.tools.reader.read_delimited.call(null,")",rdr,opts,pending_forms); var vec__15505 = cljs.tools.reader.ending_line_col_info.call(null,rdr); var end_line = cljs.core.nth.call(null,vec__15505,(0),null); var end_column = cljs.core.nth.call(null,vec__15505,(1),null); return cljs.core.with_meta.call(null,((cljs.core.empty_QMARK_.call(null,the_list))?cljs.core.List.EMPTY:cljs.core.apply.call(null,cljs.core.list,the_list)),(cljs.core.truth_(start_line)?cljs.core.merge.call(null,(function (){var temp__4657__auto__ = cljs.tools.reader.reader_types.get_file_name.call(null,rdr); if(cljs.core.truth_(temp__4657__auto__)){ var file = temp__4657__auto__; return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"file","file",-1269645878),file], null); } else { return null; } })(),new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"line","line",212345235),start_line,new cljs.core.Keyword(null,"column","column",2078222095),start_column,new cljs.core.Keyword(null,"end-line","end-line",1837326455),end_line,new cljs.core.Keyword(null,"end-column","end-column",1425389514),end_column], null)):null)); }); /** * Read in a vector, including its location if the reader is an indexing reader */ cljs.tools.reader.read_vector = (function cljs$tools$reader$read_vector(rdr,_,opts,pending_forms){ var vec__15508 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var start_line = cljs.core.nth.call(null,vec__15508,(0),null); var start_column = cljs.core.nth.call(null,vec__15508,(1),null); var the_vector = cljs.tools.reader.read_delimited.call(null,"]",rdr,opts,pending_forms); var vec__15509 = cljs.tools.reader.ending_line_col_info.call(null,rdr); var end_line = cljs.core.nth.call(null,vec__15509,(0),null); var end_column = cljs.core.nth.call(null,vec__15509,(1),null); return cljs.core.with_meta.call(null,the_vector,(cljs.core.truth_(start_line)?cljs.core.merge.call(null,(function (){var temp__4657__auto__ = cljs.tools.reader.reader_types.get_file_name.call(null,rdr); if(cljs.core.truth_(temp__4657__auto__)){ var file = temp__4657__auto__; return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"file","file",-1269645878),file], null); } else { return null; } })(),new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"line","line",212345235),start_line,new cljs.core.Keyword(null,"column","column",2078222095),start_column,new cljs.core.Keyword(null,"end-line","end-line",1837326455),end_line,new cljs.core.Keyword(null,"end-column","end-column",1425389514),end_column], null)):null)); }); cljs.tools.reader.duplicate_keys_error = (function cljs$tools$reader$duplicate_keys_error(msg,coll){ var duplicates = (function cljs$tools$reader$duplicate_keys_error_$_duplicates(seq){ var iter__6867__auto__ = (function cljs$tools$reader$duplicate_keys_error_$_duplicates_$_iter__15566(s__15567){ return (new cljs.core.LazySeq(null,(function (){ var s__15567__$1 = s__15567; while(true){ var temp__4657__auto__ = cljs.core.seq.call(null,s__15567__$1); if(temp__4657__auto__){ var s__15567__$2 = temp__4657__auto__; if(cljs.core.chunked_seq_QMARK_.call(null,s__15567__$2)){ var c__6865__auto__ = cljs.core.chunk_first.call(null,s__15567__$2); var size__6866__auto__ = cljs.core.count.call(null,c__6865__auto__); var b__15569 = cljs.core.chunk_buffer.call(null,size__6866__auto__); if((function (){var i__15568 = (0); while(true){ if((i__15568 < size__6866__auto__)){ var vec__15572 = cljs.core._nth.call(null,c__6865__auto__,i__15568); var id = cljs.core.nth.call(null,vec__15572,(0),null); var freq = cljs.core.nth.call(null,vec__15572,(1),null); if((freq > (1))){ cljs.core.chunk_append.call(null,b__15569,id); var G__15574 = (i__15568 + (1)); i__15568 = G__15574; continue; } else { var G__15575 = (i__15568 + (1)); i__15568 = G__15575; continue; } } else { return true; } break; } })()){ return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__15569),cljs$tools$reader$duplicate_keys_error_$_duplicates_$_iter__15566.call(null,cljs.core.chunk_rest.call(null,s__15567__$2))); } else { return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__15569),null); } } else { var vec__15573 = cljs.core.first.call(null,s__15567__$2); var id = cljs.core.nth.call(null,vec__15573,(0),null); var freq = cljs.core.nth.call(null,vec__15573,(1),null); if((freq > (1))){ return cljs.core.cons.call(null,id,cljs$tools$reader$duplicate_keys_error_$_duplicates_$_iter__15566.call(null,cljs.core.rest.call(null,s__15567__$2))); } else { var G__15576 = cljs.core.rest.call(null,s__15567__$2); s__15567__$1 = G__15576; continue; } } } else { return null; } break; } }),null,null)); }); return iter__6867__auto__.call(null,cljs.core.frequencies.call(null,seq)); }); var dups = duplicates.call(null,coll); return cljs.core.apply.call(null,cljs.core.str,msg,(((cljs.core.count.call(null,dups) > (1)))?"s":null),": ",cljs.core.interpose.call(null,", ",dups)); }); /** * Read in a map, including its location if the reader is an indexing reader */ cljs.tools.reader.read_map = (function cljs$tools$reader$read_map(rdr,_,opts,pending_forms){ var vec__15579 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var start_line = cljs.core.nth.call(null,vec__15579,(0),null); var start_column = cljs.core.nth.call(null,vec__15579,(1),null); var the_map = cljs.tools.reader.read_delimited.call(null,"}",rdr,opts,pending_forms); var map_count = cljs.core.count.call(null,the_map); var ks = cljs.core.take_nth.call(null,(2),the_map); var key_set = cljs.core.set.call(null,ks); var vec__15580 = cljs.tools.reader.ending_line_col_info.call(null,rdr); var end_line = cljs.core.nth.call(null,vec__15580,(0),null); var end_column = cljs.core.nth.call(null,vec__15580,(1),null); if(cljs.core.odd_QMARK_.call(null,map_count)){ cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Map literal must contain an even number of forms"); } else { } if(cljs.core._EQ_.call(null,cljs.core.count.call(null,key_set),cljs.core.count.call(null,ks))){ } else { cljs.tools.reader.reader_types.reader_error.call(null,rdr,cljs.tools.reader.duplicate_keys_error.call(null,"Map literal contains duplicate key",ks)); } return cljs.core.with_meta.call(null,(((map_count === (0)))?cljs.core.PersistentArrayMap.EMPTY:cljs.core.apply.call(null,cljs.core.hash_map,cljs.core.to_array.call(null,the_map))),(cljs.core.truth_(start_line)?cljs.core.merge.call(null,(function (){var temp__4657__auto__ = cljs.tools.reader.reader_types.get_file_name.call(null,rdr); if(cljs.core.truth_(temp__4657__auto__)){ var file = temp__4657__auto__; return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"file","file",-1269645878),file], null); } else { return null; } })(),new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"line","line",212345235),start_line,new cljs.core.Keyword(null,"column","column",2078222095),start_column,new cljs.core.Keyword(null,"end-line","end-line",1837326455),end_line,new cljs.core.Keyword(null,"end-column","end-column",1425389514),end_column], null)):null)); }); cljs.tools.reader.read_number = (function cljs$tools$reader$read_number(rdr,initch){ var sb = (function (){var G__15583 = (new goog.string.StringBuffer()); G__15583.append(initch); return G__15583; })(); var ch = cljs.tools.reader.reader_types.read_char.call(null,rdr); while(true){ if(cljs.core.truth_((function (){var or__6087__auto__ = cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch); if(or__6087__auto__){ return or__6087__auto__; } else { var or__6087__auto____$1 = cljs.tools.reader.macros.call(null,ch); if(cljs.core.truth_(or__6087__auto____$1)){ return or__6087__auto____$1; } else { return (ch == null); } } })())){ var s = [cljs.core.str(sb)].join(''); cljs.tools.reader.reader_types.unread.call(null,rdr,ch); var or__6087__auto__ = cljs.tools.reader.impl.commons.match_number.call(null,s); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Invalid number format [",s,"]"); } } else { var G__15585 = (function (){var G__15584 = sb; G__15584.append(ch); return G__15584; })(); var G__15586 = cljs.tools.reader.reader_types.read_char.call(null,rdr); sb = G__15585; ch = G__15586; continue; } break; } }); cljs.tools.reader.escape_char = (function cljs$tools$reader$escape_char(sb,rdr){ var ch = cljs.tools.reader.reader_types.read_char.call(null,rdr); var G__15588 = ch; switch (G__15588) { case "t": return "\t"; break; case "r": return "\r"; break; case "n": return "\n"; break; case "\\": return "\\"; break; case "\"": return "\""; break; case "b": return "\b"; break; case "f": return "\f"; break; case "u": var ch__$1 = cljs.tools.reader.reader_types.read_char.call(null,rdr); if(((-1) === parseInt((ch__$1 | (0)),(16)))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Invalid unicode escape: \\u",ch__$1); } else { return cljs.tools.reader.read_unicode_char.call(null,rdr,ch__$1,(16),(4),true); } break; default: if(cljs.tools.reader.impl.utils.numeric_QMARK_.call(null,ch)){ var ch__$1 = cljs.tools.reader.read_unicode_char.call(null,rdr,ch,(8),(3),false); if(((ch__$1 | (0)) > (223))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Octal escape sequence must be in range [0, 377]"); } else { return ch__$1; } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Unsupported escape character: \\",ch); } } }); cljs.tools.reader.read_string_STAR_ = (function cljs$tools$reader$read_string_STAR_(reader,_,opts,pending_forms){ var sb = (new goog.string.StringBuffer()); var ch = cljs.tools.reader.reader_types.read_char.call(null,reader); while(true){ if((ch == null)){ return cljs.tools.reader.reader_types.reader_error.call(null,reader,"EOF while reading string"); } else { var G__15593 = ch; switch (G__15593) { case "\\": var G__15597 = (function (){var G__15594 = sb; G__15594.append(cljs.tools.reader.escape_char.call(null,sb,reader)); return G__15594; })(); var G__15598 = cljs.tools.reader.reader_types.read_char.call(null,reader); sb = G__15597; ch = G__15598; continue; break; case "\"": return [cljs.core.str(sb)].join(''); break; default: var G__15599 = (function (){var G__15595 = sb; G__15595.append(ch); return G__15595; })(); var G__15600 = cljs.tools.reader.reader_types.read_char.call(null,reader); sb = G__15599; ch = G__15600; continue; } } break; } }); cljs.tools.reader.loc_info = (function cljs$tools$reader$loc_info(rdr,line,column){ if((line == null)){ return null; } else { var file = cljs.tools.reader.reader_types.get_file_name.call(null,rdr); var filem = (((file == null))?null:new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"file","file",-1269645878),file], null)); var vec__15602 = cljs.tools.reader.ending_line_col_info.call(null,rdr); var end_line = cljs.core.nth.call(null,vec__15602,(0),null); var end_column = cljs.core.nth.call(null,vec__15602,(1),null); var lcm = new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"line","line",212345235),line,new cljs.core.Keyword(null,"column","column",2078222095),column,new cljs.core.Keyword(null,"end-line","end-line",1837326455),end_line,new cljs.core.Keyword(null,"end-column","end-column",1425389514),end_column], null); return cljs.core.merge.call(null,filem,lcm); } }); cljs.tools.reader.read_symbol = (function cljs$tools$reader$read_symbol(rdr,initch){ var vec__15605 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var line = cljs.core.nth.call(null,vec__15605,(0),null); var column = cljs.core.nth.call(null,vec__15605,(1),null); var token = cljs.tools.reader.read_token.call(null,rdr,initch); if((token == null)){ return null; } else { var G__15606 = token; switch (G__15606) { case "nil": return null; break; case "true": return true; break; case "false": return false; break; case "/": return new cljs.core.Symbol(null,"/","/",-1371932971,null); break; case "NaN": return Number.NaN; break; case "-Infinity": return Number.NEGATIVE_INFINITY; break; case "Infinity": case "+Infinity": return Number.POSITIVE_INFINITY; break; default: var p = cljs.tools.reader.impl.commons.parse_symbol.call(null,token); if(!((p == null))){ var sym = cljs.core.symbol.call(null,cljs.core._nth.call(null,p,(0)),cljs.core._nth.call(null,p,(1))); return cljs.core._with_meta.call(null,sym,cljs.tools.reader.loc_info.call(null,rdr,line,column)); } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Invalid token: ",token); } } } }); /** * Map from ns alias to ns, if non-nil, it will be used to resolve read-time * ns aliases. * * Defaults to nil */ cljs.tools.reader._STAR_alias_map_STAR_ = null; cljs.tools.reader.resolve_ns = (function cljs$tools$reader$resolve_ns(sym){ var or__6087__auto__ = cljs.core.get.call(null,cljs.tools.reader._STAR_alias_map_STAR_,sym); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { var temp__4657__auto__ = cljs.core.find_ns.call(null,sym); if(cljs.core.truth_(temp__4657__auto__)){ var ns = temp__4657__auto__; return cljs.core.symbol.call(null,cljs.core.ns_name.call(null,ns)); } else { return null; } } }); cljs.tools.reader.read_keyword = (function cljs$tools$reader$read_keyword(reader,initch,opts,pending_forms){ var ch = cljs.tools.reader.reader_types.read_char.call(null,reader); if(!(cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch))){ var token = cljs.tools.reader.read_token.call(null,reader,ch); var s = cljs.tools.reader.impl.commons.parse_symbol.call(null,token); if(!((s == null))){ var ns = cljs.core._nth.call(null,s,(0)); var name = cljs.core._nth.call(null,s,(1)); if((":" === token.charAt((0)))){ if(!((ns == null))){ var ns__$1 = cljs.tools.reader.resolve_ns.call(null,cljs.core.symbol.call(null,cljs.core.subs.call(null,ns,(1)))); if(!((ns__$1 == null))){ return cljs.core.keyword.call(null,[cljs.core.str(ns__$1)].join(''),name); } else { return cljs.tools.reader.reader_types.reader_error.call(null,reader,"Invalid token: :",token); } } else { return cljs.core.keyword.call(null,[cljs.core.str(cljs.core._STAR_ns_STAR_)].join(''),cljs.core.subs.call(null,name,(1))); } } else { return cljs.core.keyword.call(null,ns,name); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,reader,"Invalid token: :",token); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,reader,"Invalid token: :"); } }); /** * Returns a function which wraps a reader in a call to sym */ cljs.tools.reader.wrapping_reader = (function cljs$tools$reader$wrapping_reader(sym){ return (function (rdr,_,opts,pending_forms){ var x__6921__auto__ = sym; return cljs.core._conj.call(null,(function (){var x__6921__auto____$1 = cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto____$1); })(),x__6921__auto__); }); }); /** * Read metadata and return the following object with the metadata applied */ cljs.tools.reader.read_meta = (function cljs$tools$reader$read_meta(rdr,_,opts,pending_forms){ if((cljs.tools.reader.reader_types.source_logging_reader_QMARK_.call(null,rdr)) && (!(cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,cljs.tools.reader.reader_types.peek_char.call(null,rdr))))){ return cljs.tools.reader.reader_types.log_source_STAR_.call(null,rdr,(function (){ var vec__15614 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var line = cljs.core.nth.call(null,vec__15614,(0),null); var column = cljs.core.nth.call(null,vec__15614,(1),null); var m = cljs.tools.reader.impl.utils.desugar_meta.call(null,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); if(cljs.core.map_QMARK_.call(null,m)){ } else { cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Metadata must be Symbol, Keyword, String or Map"); } var o = cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms); if(((!((o == null)))?((((o.cljs$lang$protocol_mask$partition0$ & (131072))) || (o.cljs$core$IMeta$))?true:false):false)){ var m__$1 = (cljs.core.truth_((function (){var and__6075__auto__ = line; if(cljs.core.truth_(and__6075__auto__)){ return cljs.core.seq_QMARK_.call(null,o); } else { return and__6075__auto__; } })())?cljs.core.assoc.call(null,m,new cljs.core.Keyword(null,"line","line",212345235),line,new cljs.core.Keyword(null,"column","column",2078222095),column):m); if(((!((o == null)))?((((o.cljs$lang$protocol_mask$partition0$ & (262144))) || (o.cljs$core$IWithMeta$))?true:false):false)){ return cljs.core.with_meta.call(null,o,cljs.core.merge.call(null,cljs.core.meta.call(null,o),m__$1)); } else { return cljs.core.reset_meta_BANG_.call(null,o,m__$1); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Metadata can only be applied to IMetas"); } })); } else { var vec__15617 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var line = cljs.core.nth.call(null,vec__15617,(0),null); var column = cljs.core.nth.call(null,vec__15617,(1),null); var m = cljs.tools.reader.impl.utils.desugar_meta.call(null,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); if(cljs.core.map_QMARK_.call(null,m)){ } else { cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Metadata must be Symbol, Keyword, String or Map"); } var o = cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms); if(((!((o == null)))?((((o.cljs$lang$protocol_mask$partition0$ & (131072))) || (o.cljs$core$IMeta$))?true:false):false)){ var m__$1 = (cljs.core.truth_((function (){var and__6075__auto__ = line; if(cljs.core.truth_(and__6075__auto__)){ return cljs.core.seq_QMARK_.call(null,o); } else { return and__6075__auto__; } })())?cljs.core.assoc.call(null,m,new cljs.core.Keyword(null,"line","line",212345235),line,new cljs.core.Keyword(null,"column","column",2078222095),column):m); if(((!((o == null)))?((((o.cljs$lang$protocol_mask$partition0$ & (262144))) || (o.cljs$core$IWithMeta$))?true:false):false)){ return cljs.core.with_meta.call(null,o,cljs.core.merge.call(null,cljs.core.meta.call(null,o),m__$1)); } else { return cljs.core.reset_meta_BANG_.call(null,o,m__$1); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Metadata can only be applied to IMetas"); } } }); cljs.tools.reader.read_set = (function cljs$tools$reader$read_set(rdr,_,opts,pending_forms){ var vec__15622 = cljs.tools.reader.starting_line_col_info.call(null,rdr); var start_line = cljs.core.nth.call(null,vec__15622,(0),null); var start_column = cljs.core.nth.call(null,vec__15622,(1),null); var start_column__$1 = (cljs.core.truth_(start_column)?((start_column - (1)) | (0)):null); var coll = cljs.tools.reader.read_delimited.call(null,"}",rdr,opts,pending_forms); var the_set = cljs.core.set.call(null,coll); var vec__15623 = cljs.tools.reader.ending_line_col_info.call(null,rdr); var end_line = cljs.core.nth.call(null,vec__15623,(0),null); var end_column = cljs.core.nth.call(null,vec__15623,(1),null); if(cljs.core._EQ_.call(null,cljs.core.count.call(null,coll),cljs.core.count.call(null,the_set))){ } else { cljs.tools.reader.reader_types.reader_error.call(null,rdr,cljs.tools.reader.duplicate_keys_error.call(null,"Set literal contains duplicate key",coll)); } return cljs.core.with_meta.call(null,the_set,(cljs.core.truth_(start_line)?cljs.core.merge.call(null,(function (){var temp__4657__auto__ = cljs.tools.reader.reader_types.get_file_name.call(null,rdr); if(cljs.core.truth_(temp__4657__auto__)){ var file = temp__4657__auto__; return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"file","file",-1269645878),file], null); } else { return null; } })(),new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"line","line",212345235),start_line,new cljs.core.Keyword(null,"column","column",2078222095),start_column__$1,new cljs.core.Keyword(null,"end-line","end-line",1837326455),end_line,new cljs.core.Keyword(null,"end-column","end-column",1425389514),end_column], null)):null)); }); /** * Read and discard the first object from rdr */ cljs.tools.reader.read_discard = (function cljs$tools$reader$read_discard(rdr,_,opts,pending_forms){ var G__15625 = rdr; cljs.tools.reader.read_STAR_.call(null,G__15625,true,null,opts,pending_forms); return G__15625; }); cljs.tools.reader.RESERVED_FEATURES = new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"else","else",-1508377146),null,new cljs.core.Keyword(null,"none","none",1333468478),null], null), null); cljs.tools.reader.has_feature_QMARK_ = (function cljs$tools$reader$has_feature_QMARK_(rdr,feature,opts){ if((feature instanceof cljs.core.Keyword)){ return (cljs.core._EQ_.call(null,new cljs.core.Keyword(null,"default","default",-1987822328),feature)) || (cljs.core.contains_QMARK_.call(null,cljs.core.get.call(null,opts,new cljs.core.Keyword(null,"features","features",-1146962336)),feature)); } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,[cljs.core.str("Feature should be a keyword: "),cljs.core.str(feature)].join('')); } }); cljs.tools.reader.check_eof_error = (function cljs$tools$reader$check_eof_error(form,rdr,first_line){ if((form === cljs.tools.reader.READ_EOF)){ if((first_line < (0))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading"); } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading, starting at line ",first_line); } } else { return null; } }); cljs.tools.reader.check_reserved_features = (function cljs$tools$reader$check_reserved_features(rdr,form){ if(cljs.core.truth_(cljs.core.get.call(null,cljs.tools.reader.RESERVED_FEATURES,form))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,[cljs.core.str("Feature name "),cljs.core.str(form),cljs.core.str(" is reserved")].join('')); } else { return null; } }); cljs.tools.reader.check_invalid_read_cond = (function cljs$tools$reader$check_invalid_read_cond(form,rdr,first_line){ if((form === cljs.tools.reader.READ_FINISHED)){ if((first_line < (0))){ return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"read-cond requires an even number of forms"); } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,[cljs.core.str("read-cond starting on line "),cljs.core.str(first_line),cljs.core.str(" requires an even number of forms")].join('')); } } else { return null; } }); /** * Read next form and suppress. Return nil or READ_FINISHED. */ cljs.tools.reader.read_suppress = (function cljs$tools$reader$read_suppress(first_line,rdr,opts,pending_forms){ var _STAR_suppress_read_STAR_15627 = cljs.tools.reader._STAR_suppress_read_STAR_; cljs.tools.reader._STAR_suppress_read_STAR_ = true; try{var form = cljs.tools.reader.read_STAR_.call(null,rdr,false,cljs.tools.reader.READ_EOF,")",opts,pending_forms); cljs.tools.reader.check_eof_error.call(null,form,rdr,first_line); if((form === cljs.tools.reader.READ_FINISHED)){ return cljs.tools.reader.READ_FINISHED; } else { return null; } }finally {cljs.tools.reader._STAR_suppress_read_STAR_ = _STAR_suppress_read_STAR_15627; }}); if(typeof cljs.tools.reader.NO_MATCH !== 'undefined'){ } else { cljs.tools.reader.NO_MATCH = (new Object()); } /** * Read next feature. If matched, read next form and return. * Otherwise, read and skip next form, returning READ_FINISHED or nil. */ cljs.tools.reader.match_feature = (function cljs$tools$reader$match_feature(first_line,rdr,opts,pending_forms){ var feature = cljs.tools.reader.read_STAR_.call(null,rdr,false,cljs.tools.reader.READ_EOF,")",opts,pending_forms); cljs.tools.reader.check_eof_error.call(null,feature,rdr,first_line); if(cljs.core._EQ_.call(null,feature,cljs.tools.reader.READ_FINISHED)){ return cljs.tools.reader.READ_FINISHED; } else { cljs.tools.reader.check_reserved_features.call(null,rdr,feature); if(cljs.core.truth_(cljs.tools.reader.has_feature_QMARK_.call(null,rdr,feature,opts))){ var G__15629 = cljs.tools.reader.read_STAR_.call(null,rdr,false,cljs.tools.reader.READ_EOF,")",opts,pending_forms); cljs.tools.reader.check_eof_error.call(null,G__15629,rdr,first_line); cljs.tools.reader.check_invalid_read_cond.call(null,G__15629,rdr,first_line); return G__15629; } else { var or__6087__auto__ = cljs.tools.reader.read_suppress.call(null,first_line,rdr,opts,pending_forms); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { return cljs.tools.reader.NO_MATCH; } } } }); cljs.tools.reader.read_cond_delimited = (function cljs$tools$reader$read_cond_delimited(rdr,splicing,opts,pending_forms){ var first_line = (cljs.core.truth_(cljs.tools.reader.reader_types.indexing_reader_QMARK_.call(null,rdr))?cljs.tools.reader.reader_types.get_line_number.call(null,rdr):(-1)); var result = (function (){var matched = cljs.tools.reader.NO_MATCH; var finished = null; while(true){ if((matched === cljs.tools.reader.NO_MATCH)){ var match = cljs.tools.reader.match_feature.call(null,first_line,rdr,opts,pending_forms); if((match === cljs.tools.reader.READ_FINISHED)){ return cljs.tools.reader.READ_FINISHED; } else { var G__15632 = match; var G__15633 = null; matched = G__15632; finished = G__15633; continue; } } else { if(!((finished === cljs.tools.reader.READ_FINISHED))){ var G__15634 = matched; var G__15635 = cljs.tools.reader.read_suppress.call(null,first_line,rdr,opts,pending_forms); matched = G__15634; finished = G__15635; continue; } else { return matched; } } break; } })(); if((result === cljs.tools.reader.READ_FINISHED)){ return rdr; } else { if(cljs.core.truth_(splicing)){ if(((!((result == null)))?((((result.cljs$lang$protocol_mask$partition0$ & (16777216))) || (result.cljs$core$ISequential$))?true:false):false)){ goog.array.insertArrayAt(pending_forms,cljs.core.to_array.call(null,result),(0)); return rdr; } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Spliced form list in read-cond-splicing must implement java.util.List."); } } else { return result; } } }); cljs.tools.reader.read_cond = (function cljs$tools$reader$read_cond(rdr,_,opts,pending_forms){ if(cljs.core.not.call(null,(function (){var and__6075__auto__ = opts; if(cljs.core.truth_(and__6075__auto__)){ return new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"preserve","preserve",1276846509),null,new cljs.core.Keyword(null,"allow","allow",-1857325745),null], null), null).call(null,new cljs.core.Keyword(null,"read-cond","read-cond",1056899244).cljs$core$IFn$_invoke$arity$1(opts)); } else { return and__6075__auto__; } })())){ throw cljs.core.ex_info.call(null,"Conditional read not allowed",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"runtime-exception","runtime-exception",-1495664514)], null)); } else { } var temp__4655__auto__ = cljs.tools.reader.reader_types.read_char.call(null,rdr); if(cljs.core.truth_(temp__4655__auto__)){ var ch = temp__4655__auto__; var splicing = cljs.core._EQ_.call(null,ch,"@"); var ch__$1 = ((splicing)?cljs.tools.reader.reader_types.read_char.call(null,rdr):ch); if(splicing){ if(cljs.core.truth_(cljs.tools.reader._STAR_read_delim_STAR_)){ } else { cljs.tools.reader.reader_types.reader_error.call(null,rdr,"cond-splice not in list"); } } else { } var temp__4655__auto____$1 = ((cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch__$1))?cljs.tools.reader.impl.commons.read_past.call(null,cljs.tools.reader.impl.utils.whitespace_QMARK_,rdr):ch__$1); if(cljs.core.truth_(temp__4655__auto____$1)){ var ch__$2 = temp__4655__auto____$1; if(cljs.core.not_EQ_.call(null,ch__$2,"(")){ throw cljs.core.ex_info.call(null,"read-cond body must be a list",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"runtime-exception","runtime-exception",-1495664514)], null)); } else { var _STAR_suppress_read_STAR_15637 = cljs.tools.reader._STAR_suppress_read_STAR_; cljs.tools.reader._STAR_suppress_read_STAR_ = (function (){var or__6087__auto__ = cljs.tools.reader._STAR_suppress_read_STAR_; if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { return cljs.core._EQ_.call(null,new cljs.core.Keyword(null,"preserve","preserve",1276846509),new cljs.core.Keyword(null,"read-cond","read-cond",1056899244).cljs$core$IFn$_invoke$arity$1(opts)); } })(); try{if(cljs.core.truth_(cljs.tools.reader._STAR_suppress_read_STAR_)){ return cljs.tools.reader.impl.utils.reader_conditional.call(null,cljs.tools.reader.read_list.call(null,rdr,ch__$2,opts,pending_forms),splicing); } else { return cljs.tools.reader.read_cond_delimited.call(null,rdr,splicing,opts,pending_forms); } }finally {cljs.tools.reader._STAR_suppress_read_STAR_ = _STAR_suppress_read_STAR_15637; }} } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading character"); } } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"EOF while reading character"); } }); cljs.tools.reader.arg_env = null; /** * Get a symbol for an anonymous ?argument? */ cljs.tools.reader.garg = (function cljs$tools$reader$garg(n){ return cljs.core.symbol.call(null,[cljs.core.str(((((-1) === n))?"rest":[cljs.core.str("p"),cljs.core.str(n)].join(''))),cljs.core.str("__"),cljs.core.str(cljs.tools.reader.impl.utils.next_id.call(null)),cljs.core.str("#")].join('')); }); cljs.tools.reader.read_fn = (function cljs$tools$reader$read_fn(rdr,_,opts,pending_forms){ if(cljs.core.truth_(cljs.tools.reader.arg_env)){ throw cljs.core.ex_info.call(null,"Nested #()s are not allowed",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-state","illegal-state",-1519851182)], null)); } else { } var arg_env15640 = cljs.tools.reader.arg_env; cljs.tools.reader.arg_env = cljs.core.sorted_map.call(null); try{var form = cljs.tools.reader.read_STAR_.call(null,(function (){var G__15641 = rdr; cljs.tools.reader.reader_types.unread.call(null,G__15641,"("); return G__15641; })(),true,null,opts,pending_forms); var rargs = cljs.core.rseq.call(null,cljs.tools.reader.arg_env); var args = ((rargs)?(function (){var higharg = cljs.core.key.call(null,cljs.core.first.call(null,rargs)); var args = (function (){var i = (1); var args = cljs.core.transient$.call(null,cljs.core.PersistentVector.EMPTY); while(true){ if((i > higharg)){ return cljs.core.persistent_BANG_.call(null,args); } else { var G__15642 = (i + (1)); var G__15643 = cljs.core.conj_BANG_.call(null,args,(function (){var or__6087__auto__ = cljs.core.get.call(null,cljs.tools.reader.arg_env,i); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { return cljs.tools.reader.garg.call(null,i); } })()); i = G__15642; args = G__15643; continue; } break; } })(); var args__$1 = (cljs.core.truth_(cljs.tools.reader.arg_env.call(null,(-1)))?cljs.core.conj.call(null,args,new cljs.core.Symbol(null,"&","&",-2144855648,null),cljs.tools.reader.arg_env.call(null,(-1))):args); return args__$1; })():cljs.core.PersistentVector.EMPTY); return cljs.core._conj.call(null,(function (){var x__6921__auto__ = args; return cljs.core._conj.call(null,(function (){var x__6921__auto____$1 = form; return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto____$1); })(),x__6921__auto__); })(),new cljs.core.Symbol(null,"fn*","fn*",-752876845,null)); }finally {cljs.tools.reader.arg_env = arg_env15640; }}); /** * Registers an argument to the arg-env */ cljs.tools.reader.register_arg = (function cljs$tools$reader$register_arg(n){ if(cljs.core.truth_(cljs.tools.reader.arg_env)){ var temp__4655__auto__ = cljs.tools.reader.arg_env.call(null,n); if(cljs.core.truth_(temp__4655__auto__)){ var ret = temp__4655__auto__; return ret; } else { var g = cljs.tools.reader.garg.call(null,n); cljs.tools.reader.arg_env = cljs.core.assoc.call(null,cljs.tools.reader.arg_env,n,g); return g; } } else { throw cljs.core.ex_info.call(null,"Arg literal not in #()",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-state","illegal-state",-1519851182)], null)); } }); cljs.tools.reader.read_arg = (function cljs$tools$reader$read_arg(rdr,pct,opts,pending_forms){ if((cljs.tools.reader.arg_env == null)){ return cljs.tools.reader.read_symbol.call(null,rdr,pct); } else { var ch = cljs.tools.reader.reader_types.peek_char.call(null,rdr); if((cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch)) || (cljs.tools.reader.macro_terminating_QMARK_.call(null,ch)) || ((ch == null))){ return cljs.tools.reader.register_arg.call(null,(1)); } else { if(cljs.core._EQ_.call(null,ch,"&")){ cljs.tools.reader.reader_types.read_char.call(null,rdr); return cljs.tools.reader.register_arg.call(null,(-1)); } else { var n = cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms); if(!(cljs.core.integer_QMARK_.call(null,n))){ throw cljs.core.ex_info.call(null,"Arg literal must be %, %& or %integer",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-state","illegal-state",-1519851182)], null)); } else { return cljs.tools.reader.register_arg.call(null,n); } } } } }); cljs.tools.reader.gensym_env = null; cljs.tools.reader.read_unquote = (function cljs$tools$reader$read_unquote(rdr,comma,opts,pending_forms){ var temp__4655__auto__ = cljs.tools.reader.reader_types.peek_char.call(null,rdr); if(cljs.core.truth_(temp__4655__auto__)){ var ch = temp__4655__auto__; if(cljs.core._EQ_.call(null,"@",ch)){ return cljs.tools.reader.wrapping_reader.call(null,new cljs.core.Symbol("clojure.core","unquote-splicing","clojure.core/unquote-splicing",-552003150,null)).call(null,(function (){var G__15645 = rdr; cljs.tools.reader.reader_types.read_char.call(null,G__15645); return G__15645; })(),"@",opts,pending_forms); } else { return cljs.tools.reader.wrapping_reader.call(null,new cljs.core.Symbol("clojure.core","unquote","clojure.core/unquote",843087510,null)).call(null,rdr,"~",opts,pending_forms); } } else { return null; } }); cljs.tools.reader.unquote_splicing_QMARK_ = (function cljs$tools$reader$unquote_splicing_QMARK_(form){ return (cljs.core.seq_QMARK_.call(null,form)) && (cljs.core._EQ_.call(null,cljs.core.first.call(null,form),new cljs.core.Symbol("clojure.core","unquote-splicing","clojure.core/unquote-splicing",-552003150,null))); }); cljs.tools.reader.unquote_QMARK_ = (function cljs$tools$reader$unquote_QMARK_(form){ return (cljs.core.seq_QMARK_.call(null,form)) && (cljs.core._EQ_.call(null,cljs.core.first.call(null,form),new cljs.core.Symbol("clojure.core","unquote","clojure.core/unquote",843087510,null))); }); /** * Expand a list by resolving its syntax quotes and unquotes */ cljs.tools.reader.expand_list = (function cljs$tools$reader$expand_list(s){ var s__$1 = cljs.core.seq.call(null,s); var r = cljs.core.transient$.call(null,cljs.core.PersistentVector.EMPTY); while(true){ if(s__$1){ var item = cljs.core.first.call(null,s__$1); var ret = cljs.core.conj_BANG_.call(null,r,(cljs.core.truth_(cljs.tools.reader.unquote_QMARK_.call(null,item))?cljs.core._conj.call(null,(function (){var x__6921__auto__ = cljs.core.second.call(null,item); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol("clojure.core","list","clojure.core/list",-1119203325,null)):(cljs.core.truth_(cljs.tools.reader.unquote_splicing_QMARK_.call(null,item))?cljs.core.second.call(null,item):cljs.core._conj.call(null,(function (){var x__6921__auto__ = cljs.tools.reader.syntax_quote_STAR_.call(null,item); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol("clojure.core","list","clojure.core/list",-1119203325,null)) ))); var G__15646 = cljs.core.next.call(null,s__$1); var G__15647 = ret; s__$1 = G__15646; r = G__15647; continue; } else { return cljs.core.seq.call(null,cljs.core.persistent_BANG_.call(null,r)); } break; } }); /** * Flatten a map into a seq of alternate keys and values */ cljs.tools.reader.flatten_map = (function cljs$tools$reader$flatten_map(form){ var s = cljs.core.seq.call(null,form); var key_vals = cljs.core.transient$.call(null,cljs.core.PersistentVector.EMPTY); while(true){ if(s){ var e = cljs.core.first.call(null,s); var G__15648 = cljs.core.next.call(null,s); var G__15649 = cljs.core.conj_BANG_.call(null,cljs.core.conj_BANG_.call(null,key_vals,cljs.core.key.call(null,e)),cljs.core.val.call(null,e)); s = G__15648; key_vals = G__15649; continue; } else { return cljs.core.seq.call(null,cljs.core.persistent_BANG_.call(null,key_vals)); } break; } }); cljs.tools.reader.register_gensym = (function cljs$tools$reader$register_gensym(sym){ if(cljs.core.not.call(null,cljs.tools.reader.gensym_env)){ throw cljs.core.ex_info.call(null,"Gensym literal not in syntax-quote",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-state","illegal-state",-1519851182)], null)); } else { } var or__6087__auto__ = cljs.core.get.call(null,cljs.tools.reader.gensym_env,sym); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { var gs = cljs.core.symbol.call(null,[cljs.core.str(cljs.core.subs.call(null,cljs.core.name.call(null,sym),(0),(cljs.core.count.call(null,cljs.core.name.call(null,sym)) - (1)))),cljs.core.str("__"),cljs.core.str(cljs.tools.reader.impl.utils.next_id.call(null)),cljs.core.str("__auto__")].join('')); cljs.tools.reader.gensym_env = cljs.core.assoc.call(null,cljs.tools.reader.gensym_env,sym,gs); return gs; } }); cljs.tools.reader.add_meta = (function cljs$tools$reader$add_meta(form,ret){ if((function (){var and__6075__auto__ = ((!((form == null)))?((((form.cljs$lang$protocol_mask$partition0$ & (262144))) || (form.cljs$core$IWithMeta$))?true:false):false); if(and__6075__auto__){ return cljs.core.seq.call(null,cljs.core.dissoc.call(null,cljs.core.meta.call(null,form),new cljs.core.Keyword(null,"line","line",212345235),new cljs.core.Keyword(null,"column","column",2078222095),new cljs.core.Keyword(null,"end-line","end-line",1837326455),new cljs.core.Keyword(null,"end-column","end-column",1425389514),new cljs.core.Keyword(null,"file","file",-1269645878),new cljs.core.Keyword(null,"source","source",-433931539))); } else { return and__6075__auto__; } })()){ return cljs.core._conj.call(null,(function (){var x__6921__auto__ = ret; return cljs.core._conj.call(null,(function (){var x__6921__auto____$1 = cljs.tools.reader.syntax_quote_STAR_.call(null,cljs.core.meta.call(null,form)); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto____$1); })(),x__6921__auto__); })(),new cljs.core.Symbol("cljs.core","with-meta","cljs.core/with-meta",749126446,null)); } else { return ret; } }); cljs.tools.reader.syntax_quote_coll = (function cljs$tools$reader$syntax_quote_coll(type,coll){ var res = cljs.core._conj.call(null,(function (){var x__6921__auto__ = cljs.core.cons.call(null,new cljs.core.Symbol("cljs.core","concat","cljs.core/concat",-1133584918,null),cljs.tools.reader.expand_list.call(null,coll)); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol("cljs.core","sequence","cljs.core/sequence",1908459032,null)); if(cljs.core.truth_(type)){ return cljs.core._conj.call(null,(function (){var x__6921__auto__ = type; return cljs.core._conj.call(null,(function (){var x__6921__auto____$1 = res; return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto____$1); })(),x__6921__auto__); })(),new cljs.core.Symbol("cljs.core","apply","cljs.core/apply",1757277831,null)); } else { return res; } }); /** * Decide which map type to use, array-map if less than 16 elements */ cljs.tools.reader.map_func = (function cljs$tools$reader$map_func(coll){ if((cljs.core.count.call(null,coll) >= (16))){ return new cljs.core.Symbol("cljs.core","hash-map","cljs.core/hash-map",303385767,null); } else { return new cljs.core.Symbol("cljs.core","array-map","cljs.core/array-map",-1519210683,null); } }); cljs.tools.reader.bool_QMARK_ = (function cljs$tools$reader$bool_QMARK_(x){ return ((x instanceof Boolean)) || (x === true) || (x === false); }); /** * Resolve a symbol s into its fully qualified namespace version */ cljs.tools.reader.resolve_symbol = (function cljs$tools$reader$resolve_symbol(s){ throw cljs.core.ex_info.call(null,"resolve-symbol is not implemented",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"sym","sym",-1444860305),s], null)); }); cljs.tools.reader.syntax_quote_STAR_ = (function cljs$tools$reader$syntax_quote_STAR_(form){ return cljs.tools.reader.add_meta.call(null,form,((cljs.core.special_symbol_QMARK_.call(null,form))?cljs.core._conj.call(null,(function (){var x__6921__auto__ = form; return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol(null,"quote","quote",1377916282,null)):(((form instanceof cljs.core.Symbol))?cljs.core._conj.call(null,(function (){var x__6921__auto__ = (cljs.core.truth_((function (){var and__6075__auto__ = cljs.core.not.call(null,cljs.core.namespace.call(null,form)); if(and__6075__auto__){ return goog.string.endsWith(cljs.core.name.call(null,form),"#"); } else { return and__6075__auto__; } })())?cljs.tools.reader.register_gensym.call(null,form):cljs.tools.reader.resolve_symbol.call(null,form)); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol(null,"quote","quote",1377916282,null)):(cljs.core.truth_(cljs.tools.reader.unquote_QMARK_.call(null,form))?cljs.core.second.call(null,form):(cljs.core.truth_(cljs.tools.reader.unquote_splicing_QMARK_.call(null,form))?(function(){throw cljs.core.ex_info.call(null,"unquote-splice not in list",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"illegal-state","illegal-state",-1519851182)], null))})():((cljs.core.coll_QMARK_.call(null,form))?((((!((form == null)))?((((form.cljs$lang$protocol_mask$partition0$ & (67108864))) || (form.cljs$core$IRecord$))?true:false):false))?form:((cljs.core.map_QMARK_.call(null,form))?cljs.tools.reader.syntax_quote_coll.call(null,cljs.tools.reader.map_func.call(null,form),cljs.tools.reader.flatten_map.call(null,form)):((cljs.core.vector_QMARK_.call(null,form))?cljs.core._conj.call(null,(function (){var x__6921__auto__ = cljs.tools.reader.syntax_quote_coll.call(null,null,form); return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol("cljs.core","vec","cljs.core/vec",307622519,null)):((cljs.core.set_QMARK_.call(null,form))?cljs.tools.reader.syntax_quote_coll.call(null,new cljs.core.Symbol("cljs.core","hash-set","cljs.core/hash-set",1130426749,null),form):(((cljs.core.seq_QMARK_.call(null,form)) || (cljs.core.list_QMARK_.call(null,form)))?(function (){var seq = cljs.core.seq.call(null,form); if(seq){ return cljs.tools.reader.syntax_quote_coll.call(null,null,seq); } else { return cljs.core.list(new cljs.core.Symbol("cljs.core","list","cljs.core/list",-1331406371,null)); } })():(function(){throw cljs.core.ex_info.call(null,"Unknown Collection type",new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"unsupported-operation","unsupported-operation",1890540953)], null))})() ))))):(cljs.core.truth_((function (){var or__6087__auto__ = (form instanceof cljs.core.Keyword); if(or__6087__auto__){ return or__6087__auto__; } else { var or__6087__auto____$1 = typeof form === 'number'; if(or__6087__auto____$1){ return or__6087__auto____$1; } else { var or__6087__auto____$2 = typeof form === 'string'; if(or__6087__auto____$2){ return or__6087__auto____$2; } else { var or__6087__auto____$3 = (form == null); if(or__6087__auto____$3){ return or__6087__auto____$3; } else { var or__6087__auto____$4 = cljs.tools.reader.bool_QMARK_.call(null,form); if(cljs.core.truth_(or__6087__auto____$4)){ return or__6087__auto____$4; } else { return (form instanceof RegExp); } } } } } })())?form:cljs.core._conj.call(null,(function (){var x__6921__auto__ = form; return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__6921__auto__); })(),new cljs.core.Symbol(null,"quote","quote",1377916282,null)) ))))))); }); cljs.tools.reader.read_syntax_quote = (function cljs$tools$reader$read_syntax_quote(rdr,backquote,opts,pending_forms){ var gensym_env15657 = cljs.tools.reader.gensym_env; cljs.tools.reader.gensym_env = cljs.core.PersistentArrayMap.EMPTY; try{return cljs.tools.reader.syntax_quote_STAR_.call(null,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); }finally {cljs.tools.reader.gensym_env = gensym_env15657; }}); cljs.tools.reader.macros = (function cljs$tools$reader$macros(ch){ var G__15659 = ch; switch (G__15659) { case "\"": return cljs.tools.reader.read_string_STAR_; break; case ":": return cljs.tools.reader.read_keyword; break; case ";": return cljs.tools.reader.impl.commons.read_comment; break; case "'": return cljs.tools.reader.wrapping_reader.call(null,new cljs.core.Symbol(null,"quote","quote",1377916282,null)); break; case "@": return cljs.tools.reader.wrapping_reader.call(null,new cljs.core.Symbol("clojure.core","deref","clojure.core/deref",188719157,null)); break; case "^": return cljs.tools.reader.read_meta; break; case "`": return cljs.tools.reader.read_syntax_quote; break; case "~": return cljs.tools.reader.read_unquote; break; case "(": return cljs.tools.reader.read_list; break; case ")": return cljs.tools.reader.read_unmatched_delimiter; break; case "[": return cljs.tools.reader.read_vector; break; case "]": return cljs.tools.reader.read_unmatched_delimiter; break; case "{": return cljs.tools.reader.read_map; break; case "}": return cljs.tools.reader.read_unmatched_delimiter; break; case "\\": return cljs.tools.reader.read_char_STAR_; break; case "%": return cljs.tools.reader.read_arg; break; case "#": return cljs.tools.reader.read_dispatch; break; default: return null; } }); cljs.tools.reader.dispatch_macros = (function cljs$tools$reader$dispatch_macros(ch){ var G__15662 = ch; switch (G__15662) { case "^": return cljs.tools.reader.read_meta; break; case "'": return cljs.tools.reader.wrapping_reader.call(null,new cljs.core.Symbol(null,"var","var",870848730,null)); break; case "(": return cljs.tools.reader.read_fn; break; case "{": return cljs.tools.reader.read_set; break; case "<": return cljs.tools.reader.impl.commons.throwing_reader.call(null,"Unreadable form"); break; case "=": return cljs.tools.reader.impl.commons.throwing_reader.call(null,"read-eval not supported"); break; case "\"": return cljs.tools.reader.read_regex; break; case "!": return cljs.tools.reader.impl.commons.read_comment; break; case "_": return cljs.tools.reader.read_discard; break; case "?": return cljs.tools.reader.read_cond; break; default: return null; } }); cljs.tools.reader.read_tagged = (function cljs$tools$reader$read_tagged(rdr,initch,opts,pending_forms){ var tag = cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms); if(!((tag instanceof cljs.core.Symbol))){ cljs.tools.reader.reader_types.reader_error.call(null,rdr,"Reader tag must be a symbol"); } else { } if(cljs.core.truth_(cljs.tools.reader._STAR_suppress_read_STAR_)){ return cljs.core.tagged_literal.call(null,tag,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); } else { var temp__4655__auto__ = (function (){var or__6087__auto__ = cljs.tools.reader._STAR_data_readers_STAR_.call(null,tag); if(cljs.core.truth_(or__6087__auto__)){ return or__6087__auto__; } else { return cljs.tools.reader.default_data_readers.call(null,tag); } })(); if(cljs.core.truth_(temp__4655__auto__)){ var f = temp__4655__auto__; return f.call(null,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); } else { var temp__4655__auto____$1 = cljs.tools.reader._STAR_default_data_reader_fn_STAR_; if(cljs.core.truth_(temp__4655__auto____$1)){ var f = temp__4655__auto____$1; return f.call(null,tag,cljs.tools.reader.read_STAR_.call(null,rdr,true,null,opts,pending_forms)); } else { return cljs.tools.reader.reader_types.reader_error.call(null,rdr,"No reader function for tag ",cljs.core.name.call(null,tag)); } } } }); /** * Map from reader tag symbols to data reader Vars. * Reader tags without namespace qualifiers are reserved for Clojure. * This light version of tools.reader has no implementation for default * reader tags such as #inst and #uuid. */ cljs.tools.reader._STAR_data_readers_STAR_ = cljs.core.PersistentArrayMap.EMPTY; /** * When no data reader is found for a tag and *default-data-reader-fn* * is non-nil, it will be called with two arguments, the tag and the value. * If *default-data-reader-fn* is nil (the default value), an exception * will be thrown for the unknown tag. */ cljs.tools.reader._STAR_default_data_reader_fn_STAR_ = null; cljs.tools.reader._STAR_suppress_read_STAR_ = false; /** * Default map of data reader functions provided by Clojure. * May be overridden by binding *data-readers* */ cljs.tools.reader.default_data_readers = cljs.core.PersistentArrayMap.EMPTY; cljs.tools.reader.read_STAR__internal = (function cljs$tools$reader$read_STAR__internal(reader,eof_error_QMARK_,sentinel,return_on,opts,pending_forms){ while(true){ if((cljs.tools.reader.reader_types.source_logging_reader_QMARK_.call(null,reader)) && (!(cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,cljs.tools.reader.reader_types.peek_char.call(null,reader))))){ return cljs.tools.reader.reader_types.log_source_STAR_.call(null,reader,(function (){ while(true){ if(!(goog.array.isEmpty(pending_forms))){ var form = (pending_forms[(0)]); goog.array.removeAt(pending_forms,(0)); return form; } else { var ch = cljs.tools.reader.reader_types.read_char.call(null,reader); if(cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch)){ continue; } else { if((ch == null)){ if(eof_error_QMARK_){ return cljs.tools.reader.reader_types.reader_error.call(null,reader,"EOF"); } else { return sentinel; } } else { if((ch === return_on)){ return cljs.tools.reader.READ_FINISHED; } else { if(cljs.tools.reader.impl.commons.number_literal_QMARK_.call(null,reader,ch)){ return cljs.tools.reader.read_number.call(null,reader,ch); } else { var f = cljs.tools.reader.macros.call(null,ch); if(!((f == null))){ var res = f.call(null,reader,ch,opts,pending_forms); if((res === reader)){ continue; } else { return res; } } else { return cljs.tools.reader.read_symbol.call(null,reader,ch); } } } } } } break; } })); } else { if(!(goog.array.isEmpty(pending_forms))){ var form = (pending_forms[(0)]); goog.array.removeAt(pending_forms,(0)); return form; } else { var ch = cljs.tools.reader.reader_types.read_char.call(null,reader); if(cljs.tools.reader.impl.utils.whitespace_QMARK_.call(null,ch)){ continue; } else { if((ch == null)){ if(eof_error_QMARK_){ return cljs.tools.reader.reader_types.reader_error.call(null,reader,"EOF"); } else { return sentinel; } } else { if((ch === return_on)){ return cljs.tools.reader.READ_FINISHED; } else { if(cljs.tools.reader.impl.commons.number_literal_QMARK_.call(null,reader,ch)){ return cljs.tools.reader.read_number.call(null,reader,ch); } else { var f = cljs.tools.reader.macros.call(null,ch); if(!((f == null))){ var res = f.call(null,reader,ch,opts,pending_forms); if((res === reader)){ continue; } else { return res; } } else { return cljs.tools.reader.read_symbol.call(null,reader,ch); } } } } } } } break; } }); cljs.tools.reader.read_STAR_ = (function cljs$tools$reader$read_STAR_(var_args){ var args15664 = []; var len__7157__auto___15668 = arguments.length; var i__7158__auto___15669 = (0); while(true){ if((i__7158__auto___15669 < len__7157__auto___15668)){ args15664.push((arguments[i__7158__auto___15669])); var G__15670 = (i__7158__auto___15669 + (1)); i__7158__auto___15669 = G__15670; continue; } else { } break; } var G__15666 = args15664.length; switch (G__15666) { case 5: return cljs.tools.reader.read_STAR_.cljs$core$IFn$_invoke$arity$5((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)])); break; case 6: return cljs.tools.reader.read_STAR_.cljs$core$IFn$_invoke$arity$6((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]),(arguments[(4)]),(arguments[(5)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args15664.length)].join(''))); } }); cljs.tools.reader.read_STAR_.cljs$core$IFn$_invoke$arity$5 = (function (reader,eof_error_QMARK_,sentinel,opts,pending_forms){ return cljs.tools.reader.read_STAR_.call(null,reader,eof_error_QMARK_,sentinel,null,opts,pending_forms); }); cljs.tools.reader.read_STAR_.cljs$core$IFn$_invoke$arity$6 = (function (reader,eof_error_QMARK_,sentinel,return_on,opts,pending_forms){ try{return cljs.tools.reader.read_STAR__internal.call(null,reader,eof_error_QMARK_,sentinel,return_on,opts,pending_forms); }catch (e15667){if((e15667 instanceof Error)){ var e = e15667; if(cljs.tools.reader.impl.utils.ex_info_QMARK_.call(null,e)){ var d = cljs.core.ex_data.call(null,e); if(cljs.core._EQ_.call(null,new cljs.core.Keyword(null,"reader-exception","reader-exception",-1938323098),new cljs.core.Keyword(null,"type","type",1174270348).cljs$core$IFn$_invoke$arity$1(d))){ throw e; } else { throw cljs.core.ex_info.call(null,e.message,cljs.core.merge.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"reader-exception","reader-exception",-1938323098)], null),d,(cljs.core.truth_(cljs.tools.reader.reader_types.indexing_reader_QMARK_.call(null,reader))?new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"line","line",212345235),cljs.tools.reader.reader_types.get_line_number.call(null,reader),new cljs.core.Keyword(null,"column","column",2078222095),cljs.tools.reader.reader_types.get_column_number.call(null,reader),new cljs.core.Keyword(null,"file","file",-1269645878),cljs.tools.reader.reader_types.get_file_name.call(null,reader)], null):null)),e); } } else { throw cljs.core.ex_info.call(null,e.message,cljs.core.merge.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"type","type",1174270348),new cljs.core.Keyword(null,"reader-exception","reader-exception",-1938323098)], null),(cljs.core.truth_(cljs.tools.reader.reader_types.indexing_reader_QMARK_.call(null,reader))?new cljs.core.PersistentArrayMap(null, 3, [new cljs.core.Keyword(null,"line","line",212345235),cljs.tools.reader.reader_types.get_line_number.call(null,reader),new cljs.core.Keyword(null,"column","column",2078222095),cljs.tools.reader.reader_types.get_column_number.call(null,reader),new cljs.core.Keyword(null,"file","file",-1269645878),cljs.tools.reader.reader_types.get_file_name.call(null,reader)], null):null)),e); } } else { throw e15667; } }}); cljs.tools.reader.read_STAR_.cljs$lang$maxFixedArity = 6; /** * Reads the first object from an IPushbackReader or a java.io.PushbackReader. * Returns the object read. If EOF, throws if eof-error? is true. * Otherwise returns sentinel. If no stream is providen, *in* will be used. * * Opts is a persistent map with valid keys: * :read-cond - :allow to process reader conditionals, or * :preserve to keep all branches * :features - persistent set of feature keywords for reader conditionals * :eof - on eof, return value unless :eofthrow, then throw. * if not specified, will throw * * To read data structures only, use clojure.tools.reader.edn/read * * Note that the function signature of clojure.tools.reader/read and * clojure.tools.reader.edn/read is not the same for eof-handling */ cljs.tools.reader.read = (function cljs$tools$reader$read(var_args){ var args15672 = []; var len__7157__auto___15678 = arguments.length; var i__7158__auto___15679 = (0); while(true){ if((i__7158__auto___15679 < len__7157__auto___15678)){ args15672.push((arguments[i__7158__auto___15679])); var G__15680 = (i__7158__auto___15679 + (1)); i__7158__auto___15679 = G__15680; continue; } else { } break; } var G__15674 = args15672.length; switch (G__15674) { case 1: return cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args15672.length)].join(''))); } }); cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$1 = (function (reader){ return cljs.tools.reader.read.call(null,reader,true,null); }); cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$2 = (function (p__15675,reader){ var map__15676 = p__15675; var map__15676__$1 = ((((!((map__15676 == null)))?((((map__15676.cljs$lang$protocol_mask$partition0$ & (64))) || (map__15676.cljs$core$ISeq$))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__15676):map__15676); var opts = map__15676__$1; var eof = cljs.core.get.call(null,map__15676__$1,new cljs.core.Keyword(null,"eof","eof",-489063237),new cljs.core.Keyword(null,"eofthrow","eofthrow",-334166531)); return cljs.tools.reader.read_STAR_.call(null,reader,cljs.core._EQ_.call(null,eof,new cljs.core.Keyword(null,"eofthrow","eofthrow",-334166531)),eof,null,opts,cljs.core.to_array.call(null,cljs.core.PersistentVector.EMPTY)); }); cljs.tools.reader.read.cljs$core$IFn$_invoke$arity$3 = (function (reader,eof_error_QMARK_,sentinel){ return cljs.tools.reader.read_STAR_.call(null,reader,eof_error_QMARK_,sentinel,null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.to_array.call(null,cljs.core.PersistentVector.EMPTY)); }); cljs.tools.reader.read.cljs$lang$maxFixedArity = 3; /** * Reads one object from the string s. * Returns nil when s is nil or empty. * * To read data structures only, use clojure.tools.reader.edn/read-string * * Note that the function signature of clojure.tools.reader/read-string and * clojure.tools.reader.edn/read-string is not the same for eof-handling */ cljs.tools.reader.read_string = (function cljs$tools$reader$read_string(var_args){ var args15682 = []; var len__7157__auto___15685 = arguments.length; var i__7158__auto___15686 = (0); while(true){ if((i__7158__auto___15686 < len__7157__auto___15685)){ args15682.push((arguments[i__7158__auto___15686])); var G__15687 = (i__7158__auto___15686 + (1)); i__7158__auto___15686 = G__15687; continue; } else { } break; } var G__15684 = args15682.length; switch (G__15684) { case 1: return cljs.tools.reader.read_string.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return cljs.tools.reader.read_string.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args15682.length)].join(''))); } }); cljs.tools.reader.read_string.cljs$core$IFn$_invoke$arity$1 = (function (s){ return cljs.tools.reader.read_string.call(null,cljs.core.PersistentArrayMap.EMPTY,s); }); cljs.tools.reader.read_string.cljs$core$IFn$_invoke$arity$2 = (function (opts,s){ if(cljs.core.truth_((function (){var and__6075__auto__ = s; if(cljs.core.truth_(and__6075__auto__)){ return !((s === "")); } else { return and__6075__auto__; } })())){ return cljs.tools.reader.read.call(null,opts,cljs.tools.reader.reader_types.string_push_back_reader.call(null,s)); } else { return null; } }); cljs.tools.reader.read_string.cljs$lang$maxFixedArity = 2;
from trafpy.benchmarker.versions.benchmark_v001.distribution_generator import DistributionGenerator if __name__ == '__main__': distgen = DistributionGenerator(load_prev_dists=True) plots, dists, rand_vars = distgen.plot_benchmark_dists(benchmarks=['uniform', 'university'])
'use strict' var StaticAnalysisRunner = require('remix-analyzer').CodeAnalysis var yo = require('yo-yo') var $ = require('jquery') var remixLib = require('remix-lib') var utils = remixLib.util var css = require('./styles/staticAnalysisView-styles') var globlalRegistry = require('../../global/registry') var EventManager = require('../../lib/events') function staticAnalysisView (localRegistry) { var self = this this.event = new EventManager() this.view = null this.runner = new StaticAnalysisRunner() this.modulesView = this.renderModules() this.lastCompilationResult = null this.lastCompilationSource = null self._components = {} self._components.registry = localRegistry || globlalRegistry // dependencies self._deps = { pluginManager: self._components.registry.get('pluginmanager').api, renderer: self._components.registry.get('renderer').api, offsetToLineColumnConverter: self._components.registry.get('offsettolinecolumnconverter').api } self._deps.pluginManager.event.register('sendCompilationResult', (file, source, languageVersion, data) => { self.lastCompilationResult = null self.lastCompilationSource = null $('#staticanalysisresult').empty() if (languageVersion.indexOf('soljson') !== 0) return self.lastCompilationResult = data self.lastCompilationSource = source if (self.view.querySelector('#autorunstaticanalysis').checked) { self.run() } }) } staticAnalysisView.prototype.render = function () { var self = this var view = yo` <div class="${css.analysis}"> <div class="${css.buttons}"> <div class="${css.buttonsInner}"> <button class="${css.buttonRun} btn btn-sm btn-primary" onclick="${function () { self.run() }}" >Run</button> <label class="${css.label}" for="autorunstaticanalysis"> <input id="autorunstaticanalysis" type="checkbox" style="vertical-align:bottom" checked="true" > Auto run </label> <label class="${css.label}" for="checkAllEntries"> <input id="checkAllEntries" type="checkbox" onclick="${function (event) { self.checkAll(event) }}" style="vertical-align:bottom" checked="true" > Check/Uncheck all </label> </div> </div> <div id="staticanalysismodules" class="list-group list-group-flush ${css.container}"> ${this.modulesView} </div> <div class="${css.resultTitle} mx-2"><h6>Results:</h6></div> <div class="${css.result} m-2" id='staticanalysisresult'></div> </div> ` if (!this.view) { this.view = view } return view } staticAnalysisView.prototype.selectedModules = function () { if (!this.view) { return [] } var selected = this.view.querySelectorAll('[name="staticanalysismodule"]:checked') var toRun = [] for (var i = 0; i < selected.length; i++) { toRun.push(selected[i].attributes['index'].value) } return toRun } staticAnalysisView.prototype.run = function () { if (!this.view) { return } var selected = this.selectedModules() var warningContainer = $('#staticanalysisresult') warningContainer.empty() var self = this if (this.lastCompilationResult && selected.length) { var warningCount = 0 this.runner.run(this.lastCompilationResult, selected, function (results) { results.map(function (result, i) { result.report.map(function (item, i) { var location = '' if (item.location !== undefined) { var split = item.location.split(':') var file = split[2] location = { start: parseInt(split[0]), length: parseInt(split[1]) } location = self._deps.offsetToLineColumnConverter.offsetToLineColumn(location, parseInt(file), self.lastCompilationSource.sources, self.lastCompilationResult.sources) location = Object.keys(self.lastCompilationResult.contracts)[file] + ':' + (location.start.line + 1) + ':' + (location.start.column + 1) + ':' } warningCount++ var msg = yo`<span>${location} ${item.warning} ${item.more ? yo`<span><br><a href="${item.more}" target="blank">more</a></span>` : yo`<span></span>`}</span>` self._deps.renderer.error(msg, warningContainer, {type: 'staticAnalysisWarning alert alert-warning', useSpan: true}) }) }) self.event.trigger('staticAnaysisWarning', [warningCount]) }) } else { if (selected.length) { warningContainer.html('No compiled AST available') } self.event.trigger('staticAnaysisWarning', [-1]) } } staticAnalysisView.prototype.checkModule = function (event) { let selected = this.view.querySelectorAll('[name="staticanalysismodule"]:checked') let checkAll = this.view.querySelector('[id="checkAllEntries"]') if (event.target.checked) { checkAll.checked = true } else if (!selected.length) { checkAll.checked = false } } staticAnalysisView.prototype.checkAll = function (event) { if (!this.view) { return } // checks/unchecks all var checkBoxes = this.view.querySelectorAll('[name="staticanalysismodule"]') checkBoxes.forEach((checkbox) => { checkbox.checked = event.target.checked }) } staticAnalysisView.prototype.renderModules = function () { var self = this var groupedModules = utils.groupBy(preProcessModules(self.runner.modules()), 'categoryId') return Object.keys(groupedModules).map((categoryId, i) => { var category = groupedModules[categoryId] var entriesDom = category.map((item, i) => { return yo` <label class="${css.label}"> <input id="staticanalysismodule_${categoryId}_${i}" type="checkbox" class="staticAnalysisItem" name="staticanalysismodule" index=${item._index} checked="true" style="vertical-align:bottom" onclick="${function (event) { self.checkModule(event) }}" > ${item.name} ${item.description} </label> ` }) return yo`<div class="${css.analysisModulesContainer} list-group-item py-1"> <label class="${css.label}"><b>${category[0].categoryDisplayName}</b></label> ${entriesDom} </div>` }) } module.exports = staticAnalysisView function preProcessModules (arr) { return arr.map((item, i) => { item['_index'] = i item.categoryDisplayName = item.category.displayName item.categoryId = item.category.id return item }) }
// lightweight is an optional argument that will try to draw the graph as fast as possible var resetSize = { x:0, y:0, s:1 }; function XTraceDAG(attachPoint, reports, /*optional*/ params) { var cancerType = attachPoint.id.substr(8); //GETS CANCER TYPE var dag = this; // Get the necessary parameters var lightweight = params.lightweight ? true : false; // Twiddle the attach point a little bit var rootSVG = d3.select(attachPoint).append("svg").attr("width", "100%").attr("height", "100%"); var graphSVG = rootSVG.append("svg").attr("width", "100%").attr("height", "100%").attr("class", "graph-attach").attr("id", "graph-attach"); graphSVG.node().oncontextmenu = function(d) { return false; }; var minimapSVG = rootSVG.append("svg").attr("class", "minimap-attach"); var listSVG = rootSVG.append("svg").attr("class", "history-attach"); // Create the graph and history representations var graph = createGraphFromReports(reports, params); var history = DirectedAcyclicGraphHistory(); // Create the chart instances var DAG = DirectedAcyclicGraph(attachPoint).animate(!lightweight); var DAGMinimap = DirectedAcyclicGraphMinimap(DAG).width("19.5%").height("19.5%").x("80%").y("80%"); var DAGHistory = List().width("15%").height("99%").x("0.5%").y("0.5%"); var DAGTooltip = DirectedAcyclicGraphTooltip(); var DAGContextMenu = DirectedAcyclicGraphContextMenu(graph, graphSVG); // Attach the panzoom behavior var refreshViewport = function() { var t = zoom.translate(); var scale = zoom.scale(); graphSVG.select(".graph").attr("transform","translate("+t[0]+","+t[1]+") scale("+scale+")"); minimapSVG.select('.viewfinder').attr("x", -t[0]/scale).attr("y", -t[1]/scale).attr("width", attachPoint.offsetWidth/scale).attr("height", attachPoint.offsetHeight/scale); if (!lightweight) graphSVG.selectAll(".node text").attr("opacity", 3*scale-0.3); } var zoom = MinimapZoom().scaleExtent([0.001, 2.0]).on("zoom", refreshViewport); zoom.call(this, rootSVG, minimapSVG); // A function that resets the viewport by zooming all the way out var resetViewport = function() { var curbbox = graphSVG.node().getBBox(); var bbox = { x: curbbox.x, y: curbbox.y, width: curbbox.width+50, height: curbbox.height+50}; scale = Math.min(attachPoint.offsetWidth/bbox.width, attachPoint.offsetHeight/bbox.height); w = attachPoint.offsetWidth/scale; h = attachPoint.offsetHeight/scale; tx = ((w - bbox.width)/2 - bbox.x + 25)*scale; ty = ((h - bbox.height)/2 - bbox.y + 25)*scale; zoom.translate([tx, ty]).scale(scale); refreshViewport(); resetSize.x = tx; resetSize.y = ty; resetSize.s = scale; } // Attaches a context menu to any selected graph nodess function attachContextMenus() { DAGContextMenu.call(graphSVG.node(), graphSVG.selectAll(".node")); DAGContextMenu.on("open", function() { DAGTooltip.hide(); // }).on("close", function() { // if (!lightweight) { // graphSVG.selectAll(".node").classed("preview", false); // graphSVG.selectAll(".edge").classed("preview", false); // } }).on("hidenodes", function(nodes, selectionname) { var item = history.addSelection(nodes, selectionname); if (!lightweight) graphSVG.classed("hovering", false); listSVG.datum(history).call(DAGHistory); // Find the point to animate the hidden nodes to var bbox = DAGHistory.bbox().call(DAGHistory.select.call(listSVG.node(), item), item); var transform = zoom.getTransform(bbox); DAG.removenode(function(d) { if (lightweight) { d3.select(this).remove(); } else { d3.select(this).classed("visible", false).transition().duration(800).attr("transform", transform).remove(); } }); dag.draw(); // Refresh selected edges var selected = {}; graphSVG.selectAll(".node.selected").data().forEach(function(d) { selected[d.id]=true; }); graphSVG.selectAll(".edge").classed("selected", function(d) { return selected[d.source.id] && selected[d.target.id]; }); }).on("hovernodes", function(nodes) { if (!lightweight) { graphSVG.selectAll(".node").classed("preview", function(d) { return nodes.indexOf(d)!=-1; }) var previewed = {}; graphSVG.selectAll(".node.preview").data().forEach(function(d) { previewed[d.id]=true; }); graphSVG.selectAll(".edge").classed("preview", function(d) { return previewed[d.source.id] && previewed[d.target.id]; }); } }).on("selectnodes", function(nodes) { var selected = {}; nodes.forEach(function(d) { selected[d.id]=true; }); graphSVG.selectAll(".node").classed("selected", function(d) { var selectme = selected[d.id]; if (d3.event.ctrlKey) selectme = selectme || d3.select(this).classed("selected"); return selectme; }) graphSVG.selectAll(".edge").classed("selected", function(d) { var selectme = selected[d.source.id] && selected[d.target.id]; if (d3.event.ctrlKey) selectme = selectme || d3.select(this).classed("selected"); return selectme; }); attachContextMenus(); DAGTooltip.hide(); }); //TODO: ADD MENU ITEM FOR GOING TO THE GO WEBSITE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } // Detaches any bound context menus function detachContextMenus() { $(".graph .node").unbind("contextmenu"); } // A function that attaches mouse-click events to nodes to enable node selection function setupEvents(){ var nodes = graphSVG.selectAll(".node"); var edges = graphSVG.selectAll(".edge"); var items = listSVG.selectAll(".item"); // Set up node selection events var select = Selectable().getrange(function(a, b) { var path = getNodesBetween(a, b).concat(getNodesBetween(b, a)); return nodes.data(path, DAG.nodeid()); }).on("select", function() { var selected = {}; graphSVG.selectAll(".node.selected").data().forEach(function(d) { selected[d.id]=true; }); edges.classed("selected", function(d) { return selected[d.source.id] && selected[d.target.id]; }); attachContextMenus(); DAGTooltip.hide(); }); select(nodes); if (!lightweight) { nodes.on("mouseover", function(d) { graphSVG.classed("hovering", true); highlightPath(d); }).on("mouseout", function(d){ graphSVG.classed("hovering", false); edges.classed("hovered", false).classed("immediate", false); nodes.classed("hovered", false).classed("immediate", false); }); } // When a list item is clicked, it will be removed from the history and added to the graph // So we override the DAG node transition behaviour so that the new nodes animate from the click position items.on("click", function(d, i) { // Remove the item from the history and redraw the history history.remove(d); listSVG.datum(history).call(DAGHistory); // Now update the location that the new elements of the graph will enter from var transform = zoom.getTransform(DAGHistory.bbox().call(this, d)); DAG.newnodetransition(function(d) { if (DAG.animate()) { d3.select(this).attr("transform", transform).transition().duration(800).attr("transform", DAG.nodeTranslate); } else { d3.select(this).attr("transform", transform).attr("transform", DAG.nodeTranslate); } }) // Redraw the graph and such dag.draw(); }) function highlightPath(center) { var path = getEntirePathLinks(center); var pathnodes = {}; var pathlinks = {}; path.forEach(function(p) { pathnodes[p.source.id] = true; pathnodes[p.target.id] = true; pathlinks[p.source.id+p.target.id] = true; }); edges.classed("hovered", function(d) { return pathlinks[d.source.id+d.target.id]; }) nodes.classed("hovered", function(d) { return pathnodes[d.id]; }); var immediatenodes = {}; var immediatelinks = {}; immediatenodes[center.id] = true; center.getVisibleParents().forEach(function(p) { immediatenodes[p.id] = true; immediatelinks[p.id+center.id] = true; }) center.getVisibleChildren().forEach(function(p) { immediatenodes[p.id] = true; immediatelinks[center.id+p.id] = true; }) edges.classed("immediate", function(d) { return immediatelinks[d.source.id+d.target.id]; }) nodes.classed("immediate", function(d) { return immediatenodes[d.id]; }) } } // The main draw function this.draw = function() { DAGTooltip.hide(); // Hide any tooltips console.log("draw begin") var begin = (new Date()).getTime(); var start = (new Date()).getTime(); graphSVG.datum(graph).call(DAG); // Draw a DAG at the graph attach console.log("draw graph", new Date().getTime() - start); start = (new Date()).getTime(); minimapSVG.datum(graphSVG.node()).call(DAGMinimap); // Draw a Minimap at the minimap attach console.log("draw minimap", new Date().getTime() - start); start = (new Date()).getTime(); graphSVG.selectAll(".node").call(DAGTooltip); // Attach tooltips console.log("draw tooltips", new Date().getTime() - start); start = (new Date()).getTime(); setupEvents(); // Set up the node selection events console.log("draw events", new Date().getTime() - start); start = (new Date()).getTime(); refreshViewport(); // Update the viewport settings console.log("draw viewport", new Date().getTime() - start); start = (new Date()).getTime(); attachContextMenus(); console.log("draw contextmenus", new Date().getTime() - start); console.log("draw complete, total time=", new Date().getTime() - begin); } //Call the draw function this.draw(); // Start with the graph all the way zoomed out resetViewport(); // Save important variables this.attachPoint = attachPoint; this.reports = reports; this.DAG = DAG this.DAGMinimap = DAGMinimap; this.DAGHistory = DAGHistory; this.DAGTooltip = DAGTooltip; this.DAGContextMenu = DAGContextMenu; this.graph = graph; this.resetViewport = resetViewport; this.history = history; // Add a play button // console.log("appending play button"); // var playbutton = rootSVG.append("svg").attr("x", "10").attr("y", "5").append("text").attr("text-anchor", "left").append("tspan").attr("x", 0).attr("dy", "1em").text("Click To Play").on("click", // function(d) { // animate(); // }); var animate = function() { var startTime = new Date().getTime(); // Find the min and max times var max = 0; var min = Infinity; graphSVG.selectAll(".node").each(function(d) { var time = parseFloat(d.report["Timestamp"]); if (time < min) { min = time; } if (time > max) { max = time; } }) var playDuration = 10000; var update = function() { var elapsed = new Date().getTime() - startTime var threshold = (elapsed * (max - min) / playDuration) + min; graphSVG.selectAll(".node").attr("display", function(d) { d.animation_hiding = parseFloat(d.report["Timestamp"]) < threshold ? null : true; return d.animation_hiding ? "none" : ""; }); graphSVG.selectAll(".edge").attr("display", function(d) { return (d.source.animation_hiding || d.target.animation_hiding) ? "none" : ""; }) if (elapsed < playDuration) { window.setTimeout(update, 10); } } update(); } }
let hasLoaded=false;let initTemplate="";let mainUrl="https://latex.ppizarror.com/stats/";$(function(){printAboutInfo();generateFooter();writeTableHeader();initializeChartjsPlugins();try{let $mainsection=$("#mainSelector");for(let $i=0;$i<Object.keys(stat).length;$i+=1){if(stat[Object.keys(stat)[$i]].available){$mainsection.append($("<option>",{value:Object.keys(stat)[$i],text:stat[Object.keys(stat)[$i]].name}))}}$mainsection.on("change",function(){loadTemplate($mainsection.val())});$($mainsection).find("option[value='none']").attr("disabled","disabled")}catch(a){throwErrorID(errorID.errorretrievetemplatelist,a);return}finally{}initTemplate=$.urlParam("template");let $found;if(initTemplate!=null){$found=false;for(let $i=0;$i<Object.keys(stat).length;$i+=1){if(stat[Object.keys(stat)[$i]].tag===initTemplate&&stat[Object.keys(stat)[$i]].available){$("#mainSelector").val(Object.keys(stat)[$i]);setTimeout(function(){loadTemplate(Object.keys(stat)[$i])},timeProcessOnGETurl);$found=true;break}}if(!$found){throwErrorID(errorID.badtemplateid,"");return}}let $lockScrollUpClass=false;let $lockScrollDownClass=false;$(window).scroll(function(){let $tabledata=$("#tableData");if($(window).scrollTop()>pxScrollDownToFixTable){$lockScrollDownClass=false;if(!$lockScrollUpClass&&$(window).height()>=$tabledata.height()){$tabledata.removeClass("nonFixedTableData");$tabledata.addClass("fixedTableData");$lockScrollUpClass=true}}else{$lockScrollUpClass=false;if(!$lockScrollDownClass){$tabledata.addClass("nonFixedTableData");$tabledata.removeClass("fixedTableData");$lockScrollDownClass=true}}});$(window).resize(function(){let $tabledata=$("#tableData");$lockScrollDownClass=false;$lockScrollUpClass=false;if($(window).height()<$tabledata.height()){$tabledata.addClass("nonFixedTableData");$tabledata.removeClass("fixedTableData")}else{if($(window).scrollTop()>pxScrollDownToFixTable){$tabledata.removeClass("nonFixedTableData");$tabledata.addClass("fixedTableData")}}})});
const User = require("../models/user.model"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); exports.signIn = async (req, res) => { const { email, password } = req.body; const userWithEmail = await User.findOne({ where: { email } }).catch( (err) => { console.log("Error: ", err); } ); if (!userWithEmail){ return res .status(400) .json({ message: "Email or password does not match!" }); } const validatePassword = await bcrypt.compare(password, userWithEmail.password) if (!validatePassword){ return res .status(400) .json({ message: "Email or password does not match!" }); } const jwtToken = jwt.sign( { id: userWithEmail.id, email: userWithEmail.email }, process.env.JWT_SECRET ); res.json({ message: `Welcome Back ${userWithEmail.username} !!!`, token: jwtToken }); }
import { post } from "highline/api/v2_client" export const save = (email, leadSource) => { return post("/user_leads", { email, lead_source: leadSource, }) }
// @include org.kohsuke.stapler.codemirror.lib.codemirror // @include org.kohsuke.stapler.codemirror.mode.xml.xml // @include org.kohsuke.stapler.codemirror.mode.javascript.javascript // @include org.kohsuke.stapler.codemirror.mode.css.css CodeMirror.defineMode("htmlmixed", function(config) { var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); var jsMode = CodeMirror.getMode(config, "javascript"); var cssMode = CodeMirror.getMode(config, "css"); function html(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (/(?:^|\s)tag(?:\s|$)/.test(style) && stream.current() == ">" && state.htmlState.context) { if (/^script$/i.test(state.htmlState.context.tagName)) { state.token = javascript; state.localState = jsMode.startState(htmlMode.indent(state.htmlState, "")); } else if (/^style$/i.test(state.htmlState.context.tagName)) { state.token = css; state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); } } return style; } function maybeBackup(stream, pat, style) { var cur = stream.current(); var close = cur.search(pat), m; if (close > -1) stream.backUp(cur.length - close); else if (m = cur.match(/<\/?$/)) { stream.backUp(cur.length); if (!stream.match(pat, false)) stream.match(cur[0]); } return style; } function javascript(stream, state) { if (stream.match(/^<\/\s*script\s*>/i, false)) { state.token = html; state.localState = null; return html(stream, state); } return maybeBackup(stream, /<\/\s*script\s*>/, jsMode.token(stream, state.localState)); } function css(stream, state) { if (stream.match(/^<\/\s*style\s*>/i, false)) { state.token = html; state.localState = null; return html(stream, state); } return maybeBackup(stream, /<\/\s*style\s*>/, cssMode.token(stream, state.localState)); } return { startState: function() { var state = htmlMode.startState(); return {token: html, localState: null, mode: "html", htmlState: state}; }, copyState: function(state) { if (state.localState) var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState); return {token: state.token, localState: local, mode: state.mode, htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; }, token: function(stream, state) { return state.token(stream, state); }, indent: function(state, textAfter) { if (state.token == html || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter); else if (state.token == javascript) return jsMode.indent(state.localState, textAfter); else return cssMode.indent(state.localState, textAfter); }, electricChars: "/{}:", innerMode: function(state) { var mode = state.token == html ? htmlMode : state.token == javascript ? jsMode : cssMode; return {state: state.localState || state.htmlState, mode: mode}; } }; }, "xml", "javascript", "css"); CodeMirror.defineMIME("text/html", "htmlmixed");
""" Django settings for DjangoWebProject1 project. Based on 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import posixpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fbf8bb71-3800-4df2-8524-872d1fbadd8f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['mm-djangowebproject1.azurewebsites.net'] # Application references # https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-INSTALLED_APPS INSTALLED_APPS = [ 'app', # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # Middleware framework # https://docs.djangoproject.com/en/2.1/topics/http/middleware/ MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DjangoWebProject1.urls' # Template configuration # https://docs.djangoproject.com/en/2.1/topics/templates/ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'DjangoWebProject1.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
define(['knockout', 'text!./exhibition-view.html', 'app', 'magnific-popup', 'slick'], function (ko, template, app, magnificPopup, slick) { ko.bindingHandlers.backgroundImage = { update: function (element, valueAccessor, allBindingsAccessor, viewModel, context) { ko.bindingHandlers.style.update(element, function () { return { backgroundImage: "url('" + viewModel.backgroundImgWithUrl() + "')" }; }); } }; function Record(data) { var self = this; self.recordId = ""; self.title = ""; self.description = ""; self.thumb = ""; self.fullres = ko.observable(""); self.view_url = ""; self.source = ""; self.creator = ""; self.provider = ""; self.rights = ""; self.url = ""; self.externalId = ""; self.isLoaded = ko.observable(false); self.load = function (options) { var admindata = options.administrative; var descdata = options.descriptiveData; var media = options.media; var provenance = options.provenance; var usage = options.usage; if (descdata) { self.title = findByLang(descdata.label); self.description = findByLang(descdata.description); self.rights = findResOrLit(descdata.metadataRights); if (options.withCreator != null) { self.creator = options.withCreatorInfo.username; } } self.dbId = options.dbId; if (provenance) { self.view_url = findProvenanceValues(provenance, "source_uri"); self.dataProvider = findProvenanceValues(provenance, "dataProvider"); self.provider = findProvenanceValues(provenance, "provider"); self.source = findProvenanceValues(provenance, "source"); } self.externalId = admindata.externalid; if (usage) { self.likes = usage.likes; self.collected = usage.collected; self.collectedIn = usage.collectedIn; } self.thumb = media[0] != null && media[0].Thumbnail != null && media[0].Thumbnail.url != "null" ? media[0].Thumbnail.url : "img/content/thumb-empty.png"; //self.fullres = media[0] != null && media[0].Original != null && media[0].Original.url != "null" ? media[0].Original.url : null, if(media[0] != null && media[0].Original != null && media[0].Original.url != "null"){ self.fullres(media[0].Original.url); } self.isLoaded = ko.observable(false); if(self.fullres()==null || self.fullres().length==0){ self.fullres(self.thumb); } }; if (data != undefined) self.load(data); } function EViewModel(params) { document.body.setAttribute("data-page", "exhibition"); $("div[role='main']").toggleClass("homepage", false); var self = this; var $container = $(".grid"); self.route = params.route; var counter = 1; self.exhName = ko.observable(''); //self.access = ko.observable([]); self.id = ko.observable(params.id); self.owner = ko.observable(''); self.ownerId = ko.observable(-1); self.entryCount = ko.observable(0); self.exhItems = ko.observableArray(); self.desc = ko.observable(''); self.loading = ko.observable(false); self.showCarousel = ko.observable(false); self.backgroundImgWithUrl = ko.observable(''); self.initCarousel = function () { WITHApp.initCarousel(); WITHApp.initExpandExhibitionText(); WITHApp.initImageZoom(); }; self.revealItems = function (data) { for (var i in data) { var result = data[i]; var record = new Record(result); record.annotation = ''; if (result.contextData !== undefined && result.contextData !== null && result.contextData.body != undefined && result.contextData.body != null && ! $.isEmptyObject(result.contextData.body)) { record.annotation = result.contextData.body.text.default; record.videoUrl = result.contextData.body.videoUrl; // for (var j in result.contextData) { // if (result.contextData[j].target.collectionId == self.id() && result.contextData[j].target.position == i) { // record.annotation = result.contextData[j].body.text.default; // record.videoUrl = result.contextData[j].body.videoUrl; // } // } } var styleId = self.exhItems().length % 5 || 0; var styleIdMapping = { 0: 1, 1: 1, 2: 2, 3: 2, 4: 3 }; styleId = styleIdMapping[styleId]; record.css = 'item style' + styleId; //0, 1, 2, 3, 4 -> 2 x style1, 2 x style2 , 1 x style3 self.exhItems().push(record); } console.log(self.exhItems()[0]); self.exhItems.valueHasMutated(); setTimeout(function () { self.initCarousel(); }, 1000); }; self.loadExhibition = function (id) { self.loading(true); $.ajax({ "url": "/collection/" + self.id(), "method": "get", "contentType": "application/json", "success": function (data) { /*if user not logged in and not public redirect*/ if (data.administrative.access.isPublic == false) { if (isLogged() == false) { window.location = '#home'; $.smkAlert({ text: 'This exhibition is private', type: 'danger', permanent: true }); return; } } var adminData = data.administrative; var descData = data.descriptiveData; self.exhName(findByLang(data.descriptiveData.label)); self.desc(findByLang(data.descriptiveData.description)); self.owner(data.withCreatorInfo.username); self.ownerId(data.administrative.withCreator); self.entryCount(data.administrative.entryCount); var backgroundImg = data.descriptiveData.backgroundImg; //self.access(adminData.access); if (self.entryCount() && self.entryCount() > 0) { $.ajax({ "url": "/collection/" + self.id() + "/list?count="+self.entryCount()+"&start=0", "method": "get", "contentType": "application/json", "success": function (data) { var items = self.revealItems(data.records); if (backgroundImg == null || backgroundImg.Original ==null || backgroundImg.Original.withUrl == null || backgroundImg.Original.withUrl == "") { self.backgroundImgWithUrl(self.exhItems()[0].fullres()); } else { if (backgroundImg.Original.withUrl.indexOf("/media") == 0) { self.backgroundImgWithUrl(window.location.origin + backgroundImg.Original.withUrl); } else { self.backgroundImgWithUrl(self.backgroundImg.Original.withUrl); } } self.loading(false); }, "error": function (result) { self.loading(false); $.smkAlert({ text: 'An error has occured', type: 'danger', permanent: true }); } }); } self.showCarousel(true); self.loading(false); }, error: function (xhr, textStatus, errorThrown) { self.loading(false); $.smkAlert({ text: 'An error has occured', type: 'danger', permanent: true }); } }); }; self.loadExhibition(); self.loadNext = function () { self.moreItems(); }; self.moreItems = function () { if (self.loading === true) { setTimeout(self.moreItems(), 300); } if (self.loading() === false) { self.loading(true); var offset = self.exhItems().length; $.ajax({ "url": "/collection/" + self.id() + "/list?count=10&start=" + offset, "method": "get", "contentType": "application/json", "success": function (data) { self.revealItems(data.records); self.loading(false); }, "error": function (result) { self.loading(false); } }); } }; } return { viewModel: EViewModel, template: template }; });
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.post('/api/open', function(req, res, next){ console.log(req.body) res.json({'drawer': req.body.drawer}) }) router.get('/api/test/open', function(req, res){ res.json("Test") }) module.exports = router;
//>>built require({cache:{"url:dojox/grid/resources/Expando.html":'\x3cdiv class\x3d"dojoxGridExpando"\n\t\x3e\x3cdiv class\x3d"dojoxGridExpandoNode" dojoAttachEvent\x3d"onclick:onToggle"\n\t\t\x3e\x3cdiv class\x3d"dojoxGridExpandoNodeInner" dojoAttachPoint\x3d"expandoInner"\x3e\x3c/div\n\t\x3e\x3c/div\n\x3e\x3c/div\x3e\n'}}); define("dojox/grid/_TreeView","dijit/registry ../main dojo/_base/declare dojo/_base/array dojo/_base/lang dojo/_base/event dojo/dom-attr dojo/dom-class dojo/dom-style dojo/dom-construct dojo/query dojo/parser dojo/text!./resources/Expando.html dijit/_Widget dijit/_TemplatedMixin ./_View ./_Builder ./util".split(" "),function(s,C,l,w,x,E,h,f,D,F,g,G,q,H,I,J,K,L){l("dojox.grid._Expando",[H,I],{open:!1,toggleClass:"",itemId:"",cellIdx:-1,view:null,rowNode:null,rowIdx:-1,expandoCell:null,level:0,templateString:q, _toggleRows:function(a,c){if(a&&this.rowNode)if(g("table.dojoxGridRowTableNeedsRowUpdate").length)this._initialized&&this.view.grid.updateRow(this.rowIdx);else{var b=this;if(this.view.grid.treeModel){var e=this._tableRow?h.get(this._tableRow,"dojoxTreeGridPath"):"";e&&g('tr[dojoxTreeGridPath^\x3d"'+e+'/"]',this.rowNode).forEach(function(b){var d=g(".dojoxGridExpando",b)[0];d&&d.parentNode&&d.parentNode.parentNode&&!f.contains(d.parentNode.parentNode,"dojoxGridNoChildren")&&(d=s.byNode(d))&&d._toggleRows(a, d.open&&c);b.style.display=c?"":"none"})}else g("tr."+a,this.rowNode).forEach(function(a){if(f.contains(a,"dojoxGridExpandoRow")){var d=g(".dojoxGridExpando",a)[0];if(d){var e=s.byNode(d),r=e?e.toggleClass:d.getAttribute("toggleClass"),d=e?e.open:b.expandoCell.getOpenState(d.getAttribute("itemId"));b._toggleRows(r,d&&c)}}a.style.display=c?"":"none"})}},setOpen:function(a){a&&f.contains(this.domNode,"dojoxGridExpandoLoading")&&(a=!1);var c=this.view.grid,b=c.store,e=c.treeModel,t=this;if(c._by_idx[this.rowIdx])if(e&& !this._loadedChildren)if(a){var d=c.getItem(h.get(this._tableRow,"dojoxTreeGridPath"));d?(this.expandoInner.innerHTML="o",f.add(this.domNode,"dojoxGridExpandoLoading"),e.getChildren(d,function(b){t._loadedChildren=!0;t._setOpen(a)})):this._setOpen(a)}else this._setOpen(a);else!e&&b?a?(e=c._by_idx[this.rowIdx])&&!b.isItemLoaded(e.item)?(this.expandoInner.innerHTML="o",f.add(this.domNode,"dojoxGridExpandoLoading"),b.loadItem({item:e.item,onItem:x.hitch(this,function(e){var d=b.getIdentity(e);c._by_idty[d]= c._by_idx[this.rowIdx]={idty:d,item:e};this._setOpen(a)})})):this._setOpen(a):this._setOpen(a):this._setOpen(a)},_setOpen:function(a){if(a&&this._tableRow&&f.contains(this._tableRow,"dojoxGridNoChildren"))this._setOpen(!1);else{this.expandoInner.innerHTML=a?"-":"+";f.remove(this.domNode,"dojoxGridExpandoLoading");f.toggle(this.domNode,"dojoxGridExpandoOpened",a);if(this._tableRow){f.toggle(this._tableRow,"dojoxGridRowCollapsed",!a);var c=h.get(this._tableRow,"dojoxTreeGridBaseClasses"),b="",b=a?x.trim((" "+ c+" ").replace(" dojoxGridRowCollapsed "," ")):0>(" "+c+" ").indexOf(" dojoxGridRowCollapsed ")?c+(c?" ":"")+"dojoxGridRowCollapsed":c;h.set(this._tableRow,"dojoxTreeGridBaseClasses",b)}c=this.open!==a;this.open=a;this.expandoCell&&this.itemId&&(this.expandoCell.openStates[this.itemId]=a);var b=this.view,e=b.grid;this.toggleClass&&c&&(!this._tableRow||!this._tableRow.style.display)&&this._toggleRows(this.toggleClass,a);b&&(this._initialized&&0<=this.rowIdx)&&(e.rowHeightChanged(this.rowIdx),e.postresize(), b.hasVScrollbar(!0));this._initialized=!0}},onToggle:function(a){this.setOpen(!this.open);E.stop(a)},setRowNode:function(a,c,b){if(0>this.cellIdx||!this.itemId)return!1;this._initialized=!1;this.view=b;this.rowNode=c;this.rowIdx=a;this.expandoCell=b.structure.cells[0][this.cellIdx];if((a=this.domNode)&&a.parentNode&&a.parentNode.parentNode)this._tableRow=a.parentNode.parentNode;this.open=this.expandoCell.getOpenState(this.itemId);b.grid.treeModel&&(D.set(this.domNode,"marginLeft",18*this.level+"px"), this.domNode.parentNode&&D.set(this.domNode.parentNode,"backgroundPosition",18*this.level+3+"px"));this.setOpen(this.open);return!0}});q=l("dojox.grid._TreeContentBuilder",K._ContentBuilder,{generateHtml:function(a,c){var b=this.getTableArray(),e=this.view,t=e.structure.cells[0],d=this.grid.getItem(c),m=this.grid,r=this.grid.store;L.fire(this.view,"onBeforeRow",[c,[t]]);var B=function(a,c,d,f,g,h){if(h){var y=b.length;f=f||[];var l=f.join("|"),z=f[f.length-1],k=z+(d?" dojoxGridSummaryRow":"");m.treeModel&& (c&&!m.treeModel.mayHaveChildren(c))&&(k+=" dojoxGridNoChildren");b.push('\x3ctr style\x3d"" class\x3d"'+k+'" dojoxTreeGridPath\x3d"'+g.join("/")+'" dojoxTreeGridBaseClasses\x3d"'+k+'"\x3e');for(var q=a+1,k=null,u=0,n;n=t[u];u++){var A=n.markup,s=n.customClasses=[],x=n.customStyles=[];A[5]=n.formatAtLevel(g,c,a,d,z,s);A[1]=s.join(" ");A[3]=x.join(";");b.push.apply(b,A);!k&&(n.level===q&&n.parentCell)&&(k=n.parentCell)}b.push("\x3c/tr\x3e");c&&(r&&r.isItem(c))&&(u=r.getIdentity(c),"undefined"==typeof m._by_idty_paths[u]&& (m._by_idty_paths[u]=g.join("/")));var v,p=g.concat([]);m.treeModel&&c?m.treeModel.mayHaveChildren(c)&&(d=e.structure.cells[0][m.expandoCell||0],v=d.getOpenState(c)&&h,d=new C.grid.TreePath(g.join("/"),m),d=d.children(!0)||[],w.forEach(d,function(a,b){var d=l.split("|");d.push(d[d.length-1]+"-"+b);p.push(b);B(q,a,!1,d,p,v);p.pop()})):c&&k&&!d?(d=e.structure.cells[0][k.level],v=d.getOpenState(c)&&h,r.hasAttribute(c,k.field)?(h=l.split("|"),h.pop(),d=new C.grid.TreePath(g.join("/"),m),d=d.children(!0)|| [],d.length?(b[y]='\x3ctr class\x3d"'+h.join(" ")+' dojoxGridExpandoRow" dojoxTreeGridPath\x3d"'+g.join("/")+'"\x3e',w.forEach(d,function(a,b){var d=l.split("|");d.push(d[d.length-1]+"-"+b);p.push(b);B(q,a,!1,d,p,v);p.pop()}),p.push(d.length),B(a,c,!0,f,p,v)):b[y]='\x3ctr class\x3d"'+z+' dojoxGridNoChildren" dojoxTreeGridPath\x3d"'+g.join("/")+'"\x3e'):r.isItemLoaded(c)?b[y]='\x3ctr class\x3d"'+z+' dojoxGridNoChildren" dojoxTreeGridPath\x3d"'+g.join("/")+'"\x3e':b[0]=b[0].replace("dojoxGridRowTable", "dojoxGridRowTable dojoxGridRowTableNeedsRowUpdate")):c&&(!d&&1<f.length)&&(b[y]='\x3ctr class\x3d"'+f[f.length-2]+'" dojoxTreeGridPath\x3d"'+g.join("/")+'"\x3e')}else-1==b[0].indexOf("dojoxGridRowTableNeedsRowUpdate")&&(b[0]=b[0].replace("dojoxGridRowTable","dojoxGridRowTable dojoxGridRowTableNeedsRowUpdate"))};B(0,d,!1,["dojoxGridRowToggle-"+c],[c],!0);b.push("\x3c/table\x3e");return b.join("")},findTarget:function(a,c){for(var b=a;b&&b!=this.domNode&&!(b.tagName&&"tr"==b.tagName.toLowerCase());)b= b.parentNode;return b!=this.domNode?b:null},getCellNode:function(a,c){var b=g("td[idx\x3d'"+c+"']",a)[0];if(b&&b.parentNode&&!f.contains(b.parentNode,"dojoxGridSummaryRow"))return b},decorateEvent:function(a){a.rowNode=this.findRowTarget(a.target);if(!a.rowNode)return!1;a.rowIndex=h.get(a.rowNode,"dojoxTreeGridPath");this.baseDecorateEvent(a);a.cell=this.grid.getCell(a.cellIndex);return!0}});return l("dojox.grid._TreeView",J,{_contentBuilderClass:q,_onDndDrop:function(a,c,b){this.grid&&this.grid.aggregator&& this.grid.aggregator.clearSubtotalCache();this.inherited(arguments)},postCreate:function(){this.inherited(arguments);this.connect(this.grid,"_cleanupExpandoCache","_cleanupExpandoCache")},_cleanupExpandoCache:function(a,c,b){if(-1!=a)if(w.forEach(this.grid.layout.cells,function(a){"undefined"!=typeof a.openStates&&c in a.openStates&&delete a.openStates[c]}),"string"==typeof a&&-1<a.indexOf("/")){var e=new C.grid.TreePath(a,this.grid);for(a=e.parent();a;)e=a,a=e.parent();if(e=e.item())if(e=this.grid.store.getIdentity(e), "undefined"!=typeof this._expandos[e]){for(var f in this._expandos[e])(a=this._expandos[e][f])&&a.destroy(),delete this._expandos[e][f];delete this._expandos[e]}}else{for(f in this._expandos)if("undefined"!=typeof this._expandos[f])for(e in this._expandos[f])(a=this._expandos[f][e])&&a.destroy();this._expandos={}}},postMixInProperties:function(){this.inherited(arguments);this._expandos={}},onBeforeRow:function(a,c){var b=this.grid;b._by_idx&&(b._by_idx[a]&&b._by_idx[a].idty)&&(b=b._by_idx[a].idty, this._expandos[b]=this._expandos[b]||{});this.inherited(arguments)},onAfterRow:function(a,c,b){w.forEach(g("span.dojoxGridExpando",b),function(d){if(d&&d.parentNode){var c=d.getAttribute("toggleClass"),e,f,g=this.grid;g._by_idx&&(g._by_idx[a]&&g._by_idx[a].idty)&&(e=g._by_idx[a].idty,f=this._expandos[e][c]);f?(F.place(f.domNode,d,"replace"),f.itemId=d.getAttribute("itemId"),f.cellIdx=parseInt(d.getAttribute("cellIdx"),10),isNaN(f.cellIdx)&&(f.cellIdx=-1)):e&&(f=G.parse(d.parentNode)[0],this._expandos[e][c]= f);f&&!f.setRowNode(a,b,this)&&f.domNode.parentNode.removeChild(f.domNode)}},this);var e=!1,l=this;g("tr[dojoxTreeGridPath]",b).forEach(function(a){f.toggle(a,"dojoxGridSubRowAlt",e);h.set(a,"dojoxTreeGridBaseClasses",a.className);e=!e;l.grid.rows.styleRowNode(h.get(a,"dojoxTreeGridPath"),a)});this.inherited(arguments)},updateRowStyles:function(a){var c=g("tr[dojoxTreeGridPath\x3d'"+a+"']",this.domNode);c.length&&this.styleRowNode(a,c[0])},getCellNode:function(a,c){var b=g("tr[dojoxTreeGridPath\x3d'"+ a+"']",this.domNode)[0];if(b)return this.content.getCellNode(b,c)},destroy:function(){this._cleanupExpandoCache();this.inherited(arguments)}})});
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class BttSpiderPipeline(object): def process_item(self, item, spider): return item
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest import numpy as np from op_test import OpTest, convert_float_to_uint16 import paddle import paddle.fluid as fluid import paddle.fluid.core as core def p_norm(x, axis, porder, keepdims=False, reduce_all=False): r = [] if axis is None or reduce_all: x = x.flatten() if porder == np.inf: r = np.amax(np.abs(x), keepdims=keepdims) elif porder == -np.inf: r = np.amin(np.abs(x), keepdims=keepdims) else: r = np.linalg.norm(x, ord=porder, keepdims=keepdims) elif isinstance(axis, list or tuple) and len(axis) == 2: if porder == np.inf: axis = tuple(axis) r = np.amax(np.abs(x), axis=axis, keepdims=keepdims) elif porder == -np.inf: axis = tuple(axis) r = np.amin(np.abs(x), axis=axis, keepdims=keepdims) elif porder == 0: axis = tuple(axis) r = x.astype(bool) r = np.sum(r, axis, keepdims=keepdims) elif porder == 1: axis = tuple(axis) r = np.sum(np.abs(x), axis, keepdims=keepdims) else: axis = tuple(axis) xp = np.power(np.abs(x), porder) s = np.sum(xp, axis=axis, keepdims=keepdims) r = np.power(s, 1.0 / porder) else: if isinstance(axis, list): axis = tuple(axis) r = np.linalg.norm(x, ord=porder, axis=axis, keepdims=keepdims) r = r.astype(x.dtype) return r def frobenius_norm(x, axis=None, keepdims=False): if isinstance(axis, list): axis = tuple(axis) if axis is None: x = x.reshape(1, x.size) r = np.linalg.norm( x, ord='fro', axis=axis, keepdims=keepdims).astype(x.dtype) return r class TestFrobeniusNormOp(OpTest): def setUp(self): self.op_type = "frobenius_norm" self.init_test_case() x = (np.random.random(self.shape) + 1.0).astype(self.dtype) norm = frobenius_norm(x, self.axis, self.keepdim) self.reduce_all = (len(self.axis) == len(self.shape)) self.inputs = {'X': x} self.attrs = { 'dim': list(self.axis), 'keep_dim': self.keepdim, 'reduce_all': self.reduce_all } self.outputs = {'Out': norm} def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(['X'], 'Out') def init_test_case(self): self.shape = [2, 3, 4, 5] self.axis = (1, 2) self.keepdim = False self.dtype = "float64" class TestFrobeniusNormOp2(TestFrobeniusNormOp): def init_test_case(self): self.shape = [5, 5, 5] self.axis = (0, 1) self.keepdim = True self.dtype = "float32" def test_check_grad(self): self.check_grad(['X'], 'Out') class TestPnormOp(OpTest): def setUp(self): self.op_type = "p_norm" self.init_test_case() x = (np.random.random(self.shape) + 0.5).astype(self.dtype) norm = p_norm(x, self.axis, self.porder, self.keepdim, self.asvector) self.inputs = {'X': x} self.attrs = { 'epsilon': self.epsilon, 'axis': self.axis, 'keepdim': self.keepdim, 'porder': float(self.porder), 'asvector': self.asvector } self.outputs = {'Out': norm} self.gradient = self.calc_gradient() def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(['X'], 'Out') def init_test_case(self): self.shape = [2, 3, 4, 5] self.axis = 1 self.epsilon = 1e-12 self.porder = 2.0 self.keepdim = False self.dtype = "float64" self.asvector = False def calc_gradient(self): self.attrs = { 'epsilon': self.epsilon, 'axis': self.axis, 'keepdim': self.keepdim, 'porder': float(self.porder), 'asvector': self.asvector } x = self.inputs["X"] porder = self.attrs["porder"] axis = self.attrs["axis"] asvector = self.attrs["asvector"] x_dtype = x.dtype x = x.astype(np.float32) if x.dtype == np.float16 else x if porder == 0: grad = np.zeros(x.shape).astype(x.dtype) elif porder in [float("inf"), float("-inf")]: norm = p_norm( x, axis=axis, porder=porder, keepdims=True, reduce_all=asvector) x_abs = np.abs(x) grad = np.sign(x) grad[x_abs != norm] = 0.0 else: norm = p_norm( x, axis=axis, porder=porder, keepdims=True, reduce_all=asvector) grad = np.power(norm, 1 - porder) * np.power( np.abs(x), porder - 1) * np.sign(x) numel = 1 for s in x.shape: numel *= s divisor = numel if asvector else x.shape[axis] numel /= divisor return [grad.astype(x_dtype) * 1 / numel] class TestPnormOp2(TestPnormOp): def init_test_case(self): self.shape = [3, 20, 3] self.axis = 2 self.epsilon = 1e-12 self.porder = 2.0 self.keepdim = True self.dtype = "float32" self.asvector = False def test_check_grad(self): self.check_grad(['X'], 'Out') class TestPnormOp3(TestPnormOp): def init_test_case(self): self.shape = [3, 20, 3] self.axis = 2 self.epsilon = 1e-12 self.porder = np.inf self.keepdim = True self.dtype = "float32" self.asvector = False def test_check_grad(self): self.check_grad(['X'], 'Out', user_defined_grads=self.gradient) class TestPnormOp4(TestPnormOp): def init_test_case(self): self.shape = [3, 20, 3] self.axis = 2 self.epsilon = 1e-12 self.porder = -np.inf self.keepdim = True self.dtype = "float32" self.asvector = False def test_check_grad(self): self.check_grad(['X'], 'Out', user_defined_grads=self.gradient) class TestPnormOp5(TestPnormOp): def init_test_case(self): self.shape = [3, 20, 3] self.axis = 2 self.epsilon = 1e-12 self.porder = 0 self.keepdim = True self.dtype = "float32" self.asvector = False def test_check_grad(self): self.check_grad(['X'], 'Out', user_defined_grads=self.gradient) class TestPnormOp6(TestPnormOp): def init_test_case(self): self.shape = [3, 20, 3] self.axis = -1 self.epsilon = 1e-12 self.porder = 2 self.keepdim = False self.dtype = "float32" self.asvector = True def test_check_grad(self): self.check_grad(['X'], 'Out', user_defined_grads=self.gradient) @unittest.skipIf(not core.is_compiled_with_cuda(), "core is not compiled with CUDA") class TestPnormOpFP16(TestPnormOp): def init_test_case(self): self.shape = [2, 3, 4, 5] self.axis = 1 self.epsilon = 1e-12 self.porder = 2.0 self.keepdim = False self.dtype = "float16" self.asvector = False def test_check_output(self): place = core.CUDAPlace(0) if core.is_float16_supported(place): self.check_output_with_place(place, atol=1e-3) def test_check_grad(self): place = core.CUDAPlace(0) if core.is_float16_supported(place): self.check_grad_with_place( place, ['X'], 'Out', user_defined_grads=self.gradient) @unittest.skipIf(not core.is_compiled_with_cuda(), "core is not compiled with CUDA") class TestPnormOpFP161(TestPnormOpFP16): def init_test_case(self): self.shape = [2, 3, 4, 5] self.axis = -1 self.epsilon = 1e-12 self.porder = 2.0 self.keepdim = False self.dtype = "float16" self.asvector = True @unittest.skipIf(not core.is_compiled_with_cuda(), "core is not compiled with CUDA") class TestPnormBF16Op(OpTest): def setUp(self): self.op_type = "p_norm" self.init_test_case() self.x = (np.random.random(self.shape) + 0.5).astype(np.float32) self.norm = p_norm(self.x, self.axis, self.porder, self.keepdim, self.asvector) self.gradient = self.calc_gradient() self.inputs = {'X': convert_float_to_uint16(self.x)} self.attrs = { 'epsilon': self.epsilon, 'axis': self.axis, 'keepdim': self.keepdim, 'porder': float(self.porder), 'asvector': self.asvector } self.outputs = {'Out': convert_float_to_uint16(self.norm)} def test_check_output(self): place = core.CUDAPlace(0) self.check_output_with_place(place, atol=1e-3) def test_check_grad(self): place = core.CUDAPlace(0) self.check_grad_with_place( place, ['X'], 'Out', user_defined_grads=self.gradient) def init_test_case(self): self.shape = [2, 3, 4, 5] self.axis = 1 self.epsilon = 1e-12 self.porder = 2.0 self.keepdim = False self.dtype = np.uint16 self.asvector = False def calc_gradient(self): self.attrs = { 'epsilon': self.epsilon, 'axis': self.axis, 'keepdim': self.keepdim, 'porder': float(self.porder), 'asvector': self.asvector } x = self.x porder = self.attrs["porder"] axis = self.attrs["axis"] asvector = self.attrs["asvector"] x_dtype = x.dtype x = x.astype(np.float32) if x.dtype == np.float16 else x if porder == 0: grad = np.zeros(x.shape).astype(x.dtype) elif porder in [float("inf"), float("-inf")]: norm = p_norm( x, axis=axis, porder=porder, keepdims=True, reduce_all=asvector) x_abs = np.abs(x) grad = np.sign(x) grad[x_abs != norm] = 0.0 else: norm = p_norm( x, axis=axis, porder=porder, keepdims=True, reduce_all=asvector) grad = np.power(norm, 1 - porder) * np.power( np.abs(x), porder - 1) * np.sign(x) numel = 1 for s in x.shape: numel *= s divisor = numel if asvector else x.shape[axis] numel /= divisor return [grad.astype(x_dtype) * 1 / numel] def run_fro(self, p, axis, shape_x, dtype, keep_dim, check_dim=False): with fluid.program_guard(fluid.Program()): data = fluid.data(name="X", shape=shape_x, dtype=dtype) out = paddle.norm(x=data, p=p, axis=axis, keepdim=keep_dim) place = fluid.CPUPlace() exe = fluid.Executor(place) np_input = (np.random.rand(*shape_x) + 1.0).astype(dtype) expected_result = frobenius_norm(np_input, axis=axis, keepdims=keep_dim) result, = exe.run(feed={"X": np_input}, fetch_list=[out]) self.assertEqual((np.abs(result - expected_result) < 1e-6).all(), True) if keep_dim and check_dim: self.assertEqual( (np.abs(np.array(result.shape) - np.array(expected_result.shape)) < 1e-6).all(), True) def run_pnorm(self, p, axis, shape_x, dtype, keep_dim, check_dim=False): with fluid.program_guard(fluid.Program()): data = fluid.data(name="X", shape=shape_x, dtype=dtype) out = paddle.norm(x=data, p=p, axis=axis, keepdim=keep_dim) place = fluid.CPUPlace() exe = fluid.Executor(place) np_input = (np.random.rand(*shape_x) + 1.0).astype(dtype) expected_result = p_norm( np_input, porder=p, axis=axis, keepdims=keep_dim).astype(dtype) result, = exe.run(feed={"X": np_input}, fetch_list=[out]) self.assertEqual((np.abs(result - expected_result) < 1e-6).all(), True) if keep_dim and check_dim: self.assertEqual( (np.abs(np.array(result.shape) - np.array(expected_result.shape)) < 1e-6).all(), True) def run_graph(self, p, axis, shape_x, dtype): paddle.disable_static() shape = [2, 3, 4] np_input = np.arange(24).astype('float32') - 12 np_input = np_input.reshape(shape) x = paddle.to_tensor(np_input) #[[[-12. -11. -10. -9.] [ -8. -7. -6. -5.] [ -4. -3. -2. -1.]] # [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]]] out_pnorm = paddle.norm(x, p=2, axis=-1) # compute frobenius norm along last two dimensions. out_fro = paddle.norm(x, p='fro') out_fro = paddle.norm(x, p='fro', axis=0) out_fro = paddle.norm(x, p='fro', axis=[0, 1]) # compute 2-order norm along [0,1] dimension. out_pnorm = paddle.norm(x, p=2, axis=[0, 1]) out_pnorm = paddle.norm(x, p=2) #out_pnorm = [17.43559577 16.91153453 16.73320053 16.91153453] # compute inf-order norm out_pnorm = paddle.norm(x, p=np.inf) #out_pnorm = [12.] out_pnorm = paddle.norm(x, p=np.inf, axis=0) #out_pnorm = [[0. 1. 2. 3.] [4. 5. 6. 5.] [4. 3. 2. 1.]] # compute -inf-order norm out_pnorm = paddle.norm(x, p=-np.inf) #out_pnorm = [0.] out_pnorm = paddle.norm(x, p=-np.inf, axis=0) # out_fro = [17.43559577 16.91153453 16.73320053 16.91153453] paddle.enable_static() class API_NormTest(unittest.TestCase): def test_basic(self): keep_dims = {False, True} for keep in keep_dims: run_fro( self, p='fro', axis=None, shape_x=[2, 3, 4], dtype="float32", keep_dim=keep) run_fro( self, p='fro', axis=[0, 1], shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=2, axis=None, shape_x=[3, 4], dtype="float32", keep_dim=keep) run_pnorm( self, p=2, axis=1, shape_x=[3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=np.inf, axis=0, shape_x=[2, 3, 4], dtype="float32", keep_dim=keep, check_dim=True) run_pnorm( self, p=np.inf, axis=None, shape_x=[2, 3, 4], dtype="float32", keep_dim=keep) run_pnorm( self, p=-np.inf, axis=0, shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=-np.inf, axis=None, shape_x=[2, 3, 4], dtype="float64", keep_dim=keep) run_pnorm( self, p=0, axis=1, shape_x=[3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=1, axis=1, shape_x=[3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=0, axis=None, shape_x=[3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=2, axis=[0, 1], shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=2, axis=-1, shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=1, axis=[0, 1], shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=np.inf, axis=[0, 1], shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) run_pnorm( self, p=-np.inf, axis=[0, 1], shape_x=[2, 3, 4], dtype="float64", keep_dim=keep, check_dim=True) def test_dygraph(self): run_graph(self, p='fro', axis=None, shape_x=[2, 3, 4], dtype="float32") def test_name(self): with fluid.program_guard(fluid.Program()): x = fluid.data(name="x", shape=[10, 10], dtype="float32") y_1 = paddle.norm(x, p='fro', name='frobenius_name') y_2 = paddle.norm(x, p=2, name='pnorm_name') self.assertEqual(('frobenius_name' in y_1.name), True) self.assertEqual(('pnorm_name' in y_2.name), True) def test_errors(self): with fluid.program_guard(fluid.Program(), fluid.Program()): def err_dtype(p, shape_x, xdtype, out=None): data = fluid.data(shape=shape_x, dtype=xdtype) paddle.norm(data, p=p, out=out) self.assertRaises(TypeError, err_dtype, "fro", [2, 2], "int64") self.assertRaises(ValueError, paddle.norm, "inf", [2], "int64") out = fluid.data(name="out", shape=[1], dtype="int64") self.assertRaises(TypeError, err_dtype, "fro", [2, 2], "float64", out) self.assertRaises(TypeError, err_dtype, 2, [10], "int64") self.assertRaises(TypeError, err_dtype, 2, [10], "float64", out) data = fluid.data(name="data_2d", shape=[2, 2], dtype="float64") self.assertRaises(ValueError, paddle.norm, data, p="unsupport norm") self.assertRaises(ValueError, paddle.norm, data, p=[1]) self.assertRaises(ValueError, paddle.norm, data, p=[1], axis=-1) self.assertRaises(ValueError, paddle.norm, 0, [1, 0], "float64") data = fluid.data(name="data_3d", shape=[2, 2, 2], dtype="float64") self.assertRaises( ValueError, paddle.norm, data, p='unspport', axis=[-3, -2, -1]) if __name__ == '__main__': unittest.main()
from django import template from math import log10, floor register = template.Library() @register.filter def sigfigs(value, count): ''' Returns the passed value as a float with <count> sigfigs. ''' # round_to_n = lambda x, n: # round(x, -int(floor(log10(x))) + (n - 1)) if value == 0: return 0 return round(value, -int(floor(log10(abs(value)))) + (count - 1))
# coding: utf-8 # Copyright © 2014-2020 VMware, Inc. All Rights Reserved. ################################################################################ import ipaddress import itertools from datetime import datetime from urllib.parse import urlparse, urljoin from stix2patterns.v21.grammars.STIXPatternListener import STIXPatternListener from stix2patterns.v21.pattern import Pattern class IOCPatternParser(object): def __init__(self, ioc_type_edr): self.edr_ioc_type = ioc_type_edr @property def key(self): return self.edr_ioc_type def parse(self, raw_value): raise NotImplementedError("must implement parse() in subclasses") class IPV4Parser(IOCPatternParser): def __init__(self): super().__init__("ipv4") def parse(self, raw_value): ioc_value_trimmed = raw_value.strip("'") if "/32" in ioc_value_trimmed: return ioc_value_trimmed[:-3] if "/" not in ioc_value_trimmed: return ioc_value_trimmed network = ipaddress.IPv4Network(ioc_value_trimmed, strict=False) hosts = (format(host) for host in itertools.islice(network.hosts(), 256)) return hosts class IPV6Parser(IOCPatternParser): def __init__(self): super().__init__("ipv6") def parse(self, raw_value): ioc_value_trimmed = raw_value.strip("'") if "/128" in ioc_value_trimmed: return ioc_value_trimmed[:-4] if "/" not in ioc_value_trimmed: return ioc_value_trimmed network = ipaddress.IPv6Network(ioc_value_trimmed, strict=False) hosts = (format(host) for host in itertools.islice(network.hosts(), 256)) return hosts class URLParser(IOCPatternParser): def __init__(self): super().__init__("dns") def parse(self, raw_value): ioc_value_trimmed = raw_value.strip("'") return urlparse(ioc_value_trimmed).netloc class DomainParser(IOCPatternParser): def __init__(self): super().__init__("dns") def parse(self, raw_value): return raw_value.strip("'") class MD5Parser(IOCPatternParser): def __init__(self): super().__init__("md5") def parse(self, raw_value): return raw_value.strip("'") class SHA256Parser(IOCPatternParser): def __init__(self): super().__init__("sha256") def parse(self, raw_value): return raw_value.strip("'") class ObjectPathToIOCParserMap(object): hash_parsers = {"file:hashes.'SHA-256'": SHA256Parser(), "artifact:hashes.'SHA-256'": SHA256Parser(), "artifact:hashes.'MD5'": MD5Parser(), "file:hashes.'MD5'": MD5Parser()} address_parsers = {"ipv4-addr:value": IPV4Parser(), "ipv6-addr:value": IPV6Parser()} domain_parsers = { 'url:value': URLParser(), 'domain-name:value': DomainParser()} DEFAULT_IOC_TYPES = ['address', 'hash', 'domain'] DEFAULT_ALL_PARSERS = {} DEFAULT_ALL_PARSERS.update(hash_parsers) DEFAULT_ALL_PARSERS.update(address_parsers) DEFAULT_ALL_PARSERS.update(domain_parsers) @staticmethod def get_parsers_for_ioc_types(ioc_types=None): if not ioc_types: return ObjectPathToIOCParserMap.DEFAULT_ALL_PARSERS parsers = {} if 'hash' in ioc_types: parsers.update(ObjectPathToIOCParserMap.hash_parsers) if 'domain' in ioc_types: parsers.update(ObjectPathToIOCParserMap.domain_parsers) if 'address' in ioc_types: parsers.update(ObjectPathToIOCParserMap.address_parsers) return parsers def __init__(self, ioc_types=None): self._parsers = ObjectPathToIOCParserMap.get_parsers_for_ioc_types(ioc_types) def __getitem__(self, item): return self._parsers.get(item, None) def __contains__(self, item): return self[item] is not None class STIXPatternParser(STIXPatternListener): def __init__(self, supported_ioc_types=None): self._indicators = {} self._ioc_map = ObjectPathToIOCParserMap(supported_ioc_types) def enterPattern(self, ctx): self._indicators = {} def enterPropTestEqual(self, ctx): parts = [child.getText() for child in ctx.getChildren()] if parts and len(parts) == 3: current_ioc_key = parts[0] parser = self._ioc_map[current_ioc_key] if parser: parsed_iocs = parser.parse(parts[2]) self._add_ioc(parser.key, parsed_iocs) def _add_ioc(self, key, value): if key in self._indicators: self._add_existing(key, value) else: self._add_new(key, value) def _add_existing(self, key, value): if isinstance(value, str): self._indicators[key].add(value) else: self._indicators[key].update(value) def _add_new(self, key, value): if isinstance(value, str): self._indicators[key] = {value} else: self._indicators[key] = set(value) @property def iocs(self): return self._indicators # [{'created': '2014-05-08T09:00:00.000Z', 'id': 'indicator--cd981c25-8042-4166-8945-51178443bdac', # 'indicator_types': ['file-hash-watchlist'], 'modified': '2014-05-08T09:00:00.000Z', # 'name': 'File hash for Poison Ivy variant', # 'pattern': "[file:hashes.'SHA-256' = 'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c']", # 'pattern_type': 'stix', 'spec_version': '2.1', 'type': 'indicator', 'valid_from': '2014-05-08T09:00:00.000000Z'}, class STIXIndicator(object): _TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ" _TIMESTAMP_FORMAT_FRAC = "%Y-%m-%dT%H:%M:%S.%fZ" @staticmethod def strptime(string_timestamp): if "." in string_timestamp: return datetime.strptime(string_timestamp, STIXIndicator._TIMESTAMP_FORMAT_FRAC) else: return datetime.strptime(string_timestamp, STIXIndicator._TIMESTAMP_FORMAT) def __init__(self, obj, collection_url, default_score=100, pattern_parser=None): self._id = obj['id'] self._description = obj.get("description", "") self._created = STIXIndicator.strptime(obj["created"]) self._pattern = Pattern(obj["pattern"]) self._name = obj.get('name', None) or obj.get('description', None) or self.id self.score = default_score self.url = urljoin(collection_url, f"objects/{self.id}") self._report = None self.stix_patern_parser = pattern_parser if pattern_parser else STIXPatternParser() @property def report(self): if not self._report: self._report = self._create_threat_report() return self._report @property def name(self): return self._name @property def id(self): return self._id @property def description(self): return self._description @property def created(self): return self._created @property def pattern(self): return self._pattern def _create_threat_report(self): """ { "timestamp": 1380773388, "iocs": { "ipv4": [ "100.2.142.8" ] }, "link": "https://www.dan.me.uk/tornodes", "id": "TOR-Node-100.2.142.8", "title": "As of Wed Oct 2 20:09:48 2013 GMT, 100.2.142.8 has been a TOR exit for 26 days, 0:44:42. Contact: Adam Langley <[email protected]>", "score": 50 }, """ self.pattern.walk(self.stix_patern_parser) report = {"timestamp": int(self.created.timestamp()), "id": self.id, "title": self.name, "iocs": self.stix_patern_parser.iocs, "score": self.score, "link": self.url} return report if self.stix_patern_parser.iocs else None
(window.webpackJsonp=window.webpackJsonp||[]).push([[59],{73:function(e,t,r){e.exports=function(){"use strict";return[{locale:"dua",pluralRuleFunction:function(e,t){return"other"},fields:{year:{displayName:"mbú",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}},"year-short":{displayName:"mbú",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}},month:{displayName:"mɔ́di",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},"month-short":{displayName:"mɔ́di",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},day:{displayName:"búnyá",relative:{0:"wɛ́ŋgɛ̄",1:"kíɛlɛ","-1":"kíɛlɛ nítómb́í"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},"day-short":{displayName:"búnyá",relative:{0:"wɛ́ŋgɛ̄",1:"kíɛlɛ","-1":"kíɛlɛ nítómb́í"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},hour:{displayName:"ŋgandɛ",relative:{0:"this hour"},relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},"hour-short":{displayName:"ŋgandɛ",relative:{0:"this hour"},relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},minute:{displayName:"ndɔkɔ",relative:{0:"this minute"},relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},"minute-short":{displayName:"ndɔkɔ",relative:{0:"this minute"},relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},second:{displayName:"píndí",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},"second-short":{displayName:"píndí",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}}}}]}()}}]); //# sourceMappingURL=59.m.f84c7cba.chunk.js.map
import time from abc import ABCMeta, abstractmethod from typing import List, Union from bxcommon.connections.connection_state import ConnectionState from bxcommon.connections.connection_type import ConnectionType from bxcommon.messages.abstract_block_message import AbstractBlockMessage from bxcommon.messages.abstract_message import AbstractMessage from bxcommon.utils.object_hash import Sha256Hash from bxcommon.utils.stats.block_stat_event_type import BlockStatEventType from bxcommon.utils.stats.block_statistics_service import block_stats from bxcommon.utils.stats.transaction_stat_event_type import TransactionStatEventType from bxcommon.utils.stats.transaction_statistics_service import tx_stats from bxgateway import gateway_constants from bxgateway.connections.abstract_gateway_blockchain_connection import AbstractGatewayBlockchainConnection from bxgateway.utils.stats.gateway_transaction_stats_service import gateway_transaction_stats_service from bxutils import logging logger = logging.get_logger(__name__) class AbstractBlockchainConnectionProtocol: __metaclass__ = ABCMeta connection: AbstractGatewayBlockchainConnection def __init__( self, connection: AbstractGatewayBlockchainConnection, block_cleanup_poll_interval_s: int = gateway_constants.BLOCK_CLEANUP_NODE_BLOCK_LIST_POLL_INTERVAL_S): self.block_cleanup_poll_interval_s = block_cleanup_poll_interval_s self.connection = connection def msg_tx(self, msg): """ Handle a TX message by broadcasting to the entire network """ bx_tx_messages = self.connection.node.message_converter.tx_to_bx_txs(msg, self.connection.network_num) for (bx_tx_message, tx_hash, tx_bytes) in bx_tx_messages: if self.connection.node.get_tx_service().has_transaction_contents(tx_hash): tx_stats.add_tx_by_hash_event(tx_hash, TransactionStatEventType.TX_RECEIVED_FROM_BLOCKCHAIN_NODE_IGNORE_SEEN, self.connection.network_num, peer=self.connection.peer_desc) gateway_transaction_stats_service.log_duplicate_transaction_from_blockchain() continue tx_stats.add_tx_by_hash_event(tx_hash, TransactionStatEventType.TX_RECEIVED_FROM_BLOCKCHAIN_NODE, self.connection.network_num, peer=self.connection.peer_desc) gateway_transaction_stats_service.log_transaction_from_blockchain(tx_hash) # All connections outside of this one is a bloXroute server broadcast_peers = self.connection.node.broadcast(bx_tx_message, self.connection, connection_types=[ConnectionType.RELAY_TRANSACTION]) tx_stats.add_tx_by_hash_event(tx_hash, TransactionStatEventType.TX_SENT_FROM_GATEWAY_TO_PEERS, self.connection.network_num, peers=map(lambda conn: (conn.peer_desc, conn.CONNECTION_TYPE), broadcast_peers)) self._set_transaction_contents(tx_hash, tx_bytes) def msg_block(self, msg: AbstractBlockMessage): """ Handle a block message. Sends to node for encryption, then broadcasts. """ block_hash = msg.block_hash() node = self.connection.node node.block_cleanup_service.on_new_block_received(block_hash, msg.prev_block_hash()) block_stats.add_block_event_by_block_hash(block_hash, BlockStatEventType.BLOCK_RECEIVED_FROM_BLOCKCHAIN_NODE, network_num=self.connection.network_num, more_info="Protocol: {}, Network: {}".format( node.opts.blockchain_protocol, node.opts.blockchain_network, msg.extra_stats_data() ) ) if block_hash in self.connection.node.blocks_seen.contents: node.on_block_seen_by_blockchain_node(block_hash) block_stats.add_block_event_by_block_hash(block_hash, BlockStatEventType.BLOCK_RECEIVED_FROM_BLOCKCHAIN_NODE_IGNORE_SEEN, network_num=self.connection.network_num) self.connection.log_trace("Have seen block {0} before. Ignoring.", block_hash) return if not self.is_valid_block_timestamp(msg): return node.track_block_from_node_handling_started(block_hash) node.on_block_seen_by_blockchain_node(block_hash) node.block_processing_service.queue_block_for_processing(msg, self.connection) return def msg_proxy_request(self, msg): """ Handle a chainstate request message. """ self.connection.node.send_msg_to_remote_node(msg) def msg_proxy_response(self, msg): """ Handle a chainstate response message. """ self.connection.node.send_msg_to_node(msg) def is_valid_block_timestamp(self, msg: AbstractBlockMessage) -> bool: max_time_offset = self.connection.node.opts.blockchain_block_interval * self.connection.node.opts.blockchain_ignore_block_interval_count if time.time() - msg.timestamp() >= max_time_offset: self.connection.log_trace("Received block {} more than {} seconds after it was created ({}). Ignoring.", msg.block_hash(), max_time_offset, msg.timestamp()) return False return True def _request_blocks_confirmation(self): if self.connection.state & ConnectionState.MARK_FOR_CLOSE: return None node = self.connection.node last_confirmed_block = node.block_cleanup_service.last_confirmed_block tracked_blocks = node.get_tx_service().get_oldest_tracked_block(node.network.block_confirmations_count) if last_confirmed_block is not None and len(tracked_blocks) <= node.network.block_confirmations_count + \ gateway_constants.BLOCK_CLEANUP_REQUEST_EXPECTED_ADDITIONAL_TRACKED_BLOCKS: hashes = [last_confirmed_block] hashes.extend(tracked_blocks) else: hashes = tracked_blocks if hashes: msg = self._build_get_blocks_message_for_block_confirmation(hashes) self.connection.enqueue_msg(msg) self.connection.log_debug("Sending block confirmation request. Last confirmed block: {}, hashes: {}", last_confirmed_block, hashes) return self.block_cleanup_poll_interval_s @abstractmethod def _build_get_blocks_message_for_block_confirmation(self, hashes: List[Sha256Hash]) -> AbstractMessage: pass @abstractmethod def _set_transaction_contents(self, tx_hash: Sha256Hash, tx_content: Union[memoryview, bytearray]) -> None: """ set the transaction contents in the connection transaction service. since some buffers needs to be copied while others should not, this handler was added. avoid calling transaction_service.set_transactions_contents directly from this class or its siblings. :param tx_hash: the transaction hash :param tx_content: the transaction contents buffer """ pass
var prob__EMC__e__pi__plotMacro_8C = [ [ "fillHist", "da/dcb/prob__EMC__e__pi__plotMacro_8C.html#a2b62a1f11a78e48c8a5351c53b91668d", null ], [ "histToPNG", "da/dcb/prob__EMC__e__pi__plotMacro_8C.html#a5e71560188a1e4fbca63bb75ffaad2bc", null ], [ "loadTree", "da/dcb/prob__EMC__e__pi__plotMacro_8C.html#a1b9fe5d594a7180b3e826c2005400855", null ], [ "prob_EMC_e_pi_plotMacro", "da/dcb/prob__EMC__e__pi__plotMacro_8C.html#a02dd2d9382be48b62211c37a508d4fb6", null ] ];
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["WSH"] = factory(); else root["WSH"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 150); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.3' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(74); /***/ }), /* 2 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(41)('wks'); var uid = __webpack_require__(26); var Symbol = __webpack_require__(2).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(2); var core = __webpack_require__(0); var ctx = __webpack_require__(13); var hide = __webpack_require__(11); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && key in exports) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(76), __esModule: true }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(5); var IE8_DOM_DEFINE = __webpack_require__(55); var toPrimitive = __webpack_require__(37); var dP = Object.defineProperty; exports.f = __webpack_require__(9) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(16)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _promise = __webpack_require__(6); var _promise2 = _interopRequireDefault(_promise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (fn) { return function () { var gen = fn.apply(this, arguments); return new _promise2.default(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return _promise2.default.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(7); var createDesc = __webpack_require__(17); module.exports = __webpack_require__(9) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 12 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(24); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(80); var defined = __webpack_require__(35); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(102), __esModule: true }; /***/ }), /* 16 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 17 */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 18 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 19 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(98), __esModule: true }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(95), __esModule: true }; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__(77)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(54)(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /* 23 */ /***/ (function(module, exports) { module.exports = true; /***/ }), /* 24 */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(57); var enumBugKeys = __webpack_require__(42); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 26 */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(7).f; var has = __webpack_require__(12); var TAG = __webpack_require__(3)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(35); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(109); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(111); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(104), __esModule: true }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(107), __esModule: true }; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _defineProperty = __webpack_require__(21); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /***/ }), /* 34 */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /* 35 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); var document = __webpack_require__(2).document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(8); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(5); var dPs = __webpack_require__(79); var enumBugKeys = __webpack_require__(42); var IE_PROTO = __webpack_require__(40)('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(36)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__(58).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(34); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(41)('keys'); var uid = __webpack_require__(26); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(2); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); module.exports = function (key) { return store[key] || (store[key] = {}); }; /***/ }), /* 42 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(83); var global = __webpack_require__(2); var hide = __webpack_require__(11); var Iterators = __webpack_require__(18); var TO_STRING_TAG = __webpack_require__(3)('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(60); var ITERATOR = __webpack_require__(3)('iterator'); var Iterators = __webpack_require__(18); module.exports = __webpack_require__(0).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) var aFunction = __webpack_require__(24); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /* 46 */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(3); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(2); var core = __webpack_require__(0); var LIBRARY = __webpack_require__(23); var wksExt = __webpack_require__(47); var defineProperty = __webpack_require__(7).f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; /***/ }), /* 49 */, /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeof2 = __webpack_require__(29); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _setPrototypeOf = __webpack_require__(30); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = __webpack_require__(31); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(29); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _toConsumableArray2 = __webpack_require__(153); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Base = function () { function Base() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _classCallCheck3.default)(this, Base); this.debug = !!config.debug; this.eventHandlers = {}; } (0, _createClass3.default)(Base, [{ key: "_log", value: function _log() { var _console; this.debug && (_console = console).log.apply(_console, arguments); } }, { key: "_trigger", value: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(event) { var _eventHandlers; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", this.eventHandlers[event] && (_eventHandlers = this.eventHandlers)[event].apply(_eventHandlers, (0, _toConsumableArray3.default)(args))); case 1: case "end": return _context.stop(); } } }, _callee, this); })); function _trigger(_x2) { return _ref.apply(this, arguments); } return _trigger; }() }, { key: "on", value: function on(event, fn) { this.eventHandlers[event] = fn; } }]); return Base; }(); exports.default = Base; /***/ }), /* 53 */ /***/ (function(module, exports) { /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(23); var $export = __webpack_require__(4); var redefine = __webpack_require__(56); var hide = __webpack_require__(11); var has = __webpack_require__(12); var Iterators = __webpack_require__(18); var $iterCreate = __webpack_require__(78); var setToStringTag = __webpack_require__(27); var getPrototypeOf = __webpack_require__(59); var ITERATOR = __webpack_require__(3)('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = (!BUGGY && $native) || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(9) && !__webpack_require__(16)(function () { return Object.defineProperty(__webpack_require__(36)('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(11); /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(12); var toIObject = __webpack_require__(14); var arrayIndexOf = __webpack_require__(81)(false); var IE_PROTO = __webpack_require__(40)('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__(2).document; module.exports = document && document.documentElement; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(12); var toObject = __webpack_require__(28); var IE_PROTO = __webpack_require__(40)('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(19); var TAG = __webpack_require__(3)('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(5); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(18); var ITERATOR = __webpack_require__(3)('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(5); var aFunction = __webpack_require__(24); var SPECIES = __webpack_require__(3)('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(13); var invoke = __webpack_require__(89); var html = __webpack_require__(58); var cel = __webpack_require__(36); var global = __webpack_require__(2); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function () { var id = +this; // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function (event) { run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (__webpack_require__(19)(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function (id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in cel('script')) { defer = function (id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /* 65 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(5); var isObject = __webpack_require__(8); var newPromiseCapability = __webpack_require__(45); module.exports = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(3)('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(97), __esModule: true }; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(100), __esModule: true }; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(4); var core = __webpack_require__(0); var fails = __webpack_require__(16); module.exports = function (KEY, exec) { var fn = (core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(46); var createDesc = __webpack_require__(17); var toIObject = __webpack_require__(14); var toPrimitive = __webpack_require__(37); var has = __webpack_require__(12); var IE8_DOM_DEFINE = __webpack_require__(55); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(9) ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /* 72 */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(57); var hiddenKeys = __webpack_require__(42).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This method of obtaining a reference to the global object needs to be // kept identical to the way it is obtained in runtime.js var g = (function() { return this })() || Function("return this")(); // Use `getOwnPropertyNames` because not all browsers support calling // `hasOwnProperty` on the global `self` object in a worker. See #183. var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; // Save the old regeneratorRuntime in case it needs to be restored later. var oldRuntime = hadRuntime && g.regeneratorRuntime; // Force reevalutation of runtime.js. g.regeneratorRuntime = undefined; module.exports = __webpack_require__(75); if (hadRuntime) { // Restore the original runtime. g.regeneratorRuntime = oldRuntime; } else { // Remove the global property added by runtime.js. try { delete g.regeneratorRuntime; } catch(e) { g.regeneratorRuntime = undefined; } } /***/ }), /* 75 */ /***/ (function(module, exports) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ !(function(global) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. runtime.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return Promise.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { if (delegate.iterator.return) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; })( // In sloppy mode, unbound `this` refers to the global object, fallback to // Function constructor if we're in global strict mode. That is sadly a form // of indirect eval which violates Content Security Policy. (function() { return this })() || Function("return this")() ); /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(53); __webpack_require__(22); __webpack_require__(43); __webpack_require__(86); __webpack_require__(93); __webpack_require__(94); module.exports = __webpack_require__(0).Promise; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(34); var defined = __webpack_require__(35); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__(38); var descriptor = __webpack_require__(17); var setToStringTag = __webpack_require__(27); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(11)(IteratorPrototype, __webpack_require__(3)('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(7); var anObject = __webpack_require__(5); var getKeys = __webpack_require__(25); module.exports = __webpack_require__(9) ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(19); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(14); var toLength = __webpack_require__(39); var toAbsoluteIndex = __webpack_require__(82); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(34); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__(84); var step = __webpack_require__(85); var Iterators = __webpack_require__(18); var toIObject = __webpack_require__(14); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(54)(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /* 84 */ /***/ (function(module, exports) { module.exports = function () { /* empty */ }; /***/ }), /* 85 */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(23); var global = __webpack_require__(2); var ctx = __webpack_require__(13); var classof = __webpack_require__(60); var $export = __webpack_require__(4); var isObject = __webpack_require__(8); var aFunction = __webpack_require__(24); var anInstance = __webpack_require__(87); var forOf = __webpack_require__(88); var speciesConstructor = __webpack_require__(63); var task = __webpack_require__(64).set; var microtask = __webpack_require__(90)(); var newPromiseCapabilityModule = __webpack_require__(45); var perform = __webpack_require__(65); var promiseResolve = __webpack_require__(66); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__webpack_require__(3)('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); if (domain) domain.exit(); } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(91)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __webpack_require__(27)($Promise, PROMISE); __webpack_require__(92)(PROMISE); Wrapper = __webpack_require__(0)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(67)(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /* 87 */ /***/ (function(module, exports) { module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(13); var call = __webpack_require__(61); var isArrayIter = __webpack_require__(62); var anObject = __webpack_require__(5); var toLength = __webpack_require__(39); var getIterFn = __webpack_require__(44); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /* 89 */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(2); var macrotask = __webpack_require__(64).set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __webpack_require__(19)(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function () { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify(); else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (isNode) { notify = function () { process.nextTick(flush); }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 } else if (Observer && !(global.navigator && global.navigator.standalone)) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { var promise = Promise.resolve(); notify = function () { promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var hide = __webpack_require__(11); module.exports = function (target, src, safe) { for (var key in src) { if (safe && target[key]) target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(2); var core = __webpack_require__(0); var dP = __webpack_require__(7); var DESCRIPTORS = __webpack_require__(9); var SPECIES = __webpack_require__(3)('species'); module.exports = function (KEY) { var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-finally var $export = __webpack_require__(4); var core = __webpack_require__(0); var global = __webpack_require__(2); var speciesConstructor = __webpack_require__(63); var promiseResolve = __webpack_require__(66); $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then( isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally ); } }); /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-try var $export = __webpack_require__(4); var newPromiseCapability = __webpack_require__(45); var perform = __webpack_require__(65); $export($export.S, 'Promise', { 'try': function (callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(96); var $Object = __webpack_require__(0).Object; module.exports = function defineProperty(it, key, desc) { return $Object.defineProperty(it, key, desc); }; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(4); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(9), 'Object', { defineProperty: __webpack_require__(7).f }); /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__(0); var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); module.exports = function stringify(it) { // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(43); __webpack_require__(22); module.exports = __webpack_require__(99); /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(5); var get = __webpack_require__(44); module.exports = __webpack_require__(0).getIterator = function (it) { var iterFn = get(it); if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(101); module.exports = __webpack_require__(0).Object.keys; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(28); var $keys = __webpack_require__(25); __webpack_require__(70)('keys', function () { return function keys(it) { return $keys(toObject(it)); }; }); /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(103); module.exports = __webpack_require__(0).Object.getPrototypeOf; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(28); var $getPrototypeOf = __webpack_require__(59); __webpack_require__(70)('getPrototypeOf', function () { return function getPrototypeOf(it) { return $getPrototypeOf(toObject(it)); }; }); /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(105); module.exports = __webpack_require__(0).Object.setPrototypeOf; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(4); $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(106).set }); /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(8); var anObject = __webpack_require__(5); var check = function (O, proto) { anObject(O); if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function (test, buggy, set) { try { set = __webpack_require__(13)(Function.call, __webpack_require__(71).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch (e) { buggy = true; } return function setPrototypeOf(O, proto) { check(O, proto); if (buggy) O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(108); var $Object = __webpack_require__(0).Object; module.exports = function create(P, D) { return $Object.create(P, D); }; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(4); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: __webpack_require__(38) }); /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(110), __esModule: true }; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(22); __webpack_require__(43); module.exports = __webpack_require__(47).f('iterator'); /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(112), __esModule: true }; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(113); __webpack_require__(53); __webpack_require__(118); __webpack_require__(119); module.exports = __webpack_require__(0).Symbol; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // ECMAScript 6 symbols shim var global = __webpack_require__(2); var has = __webpack_require__(12); var DESCRIPTORS = __webpack_require__(9); var $export = __webpack_require__(4); var redefine = __webpack_require__(56); var META = __webpack_require__(114).KEY; var $fails = __webpack_require__(16); var shared = __webpack_require__(41); var setToStringTag = __webpack_require__(27); var uid = __webpack_require__(26); var wks = __webpack_require__(3); var wksExt = __webpack_require__(47); var wksDefine = __webpack_require__(48); var enumKeys = __webpack_require__(115); var isArray = __webpack_require__(116); var anObject = __webpack_require__(5); var isObject = __webpack_require__(8); var toIObject = __webpack_require__(14); var toPrimitive = __webpack_require__(37); var createDesc = __webpack_require__(17); var _create = __webpack_require__(38); var gOPNExt = __webpack_require__(117); var $GOPD = __webpack_require__(71); var $DP = __webpack_require__(7); var $keys = __webpack_require__(25); var gOPD = $GOPD.f; var dP = $DP.f; var gOPN = gOPNExt.f; var $Symbol = global.Symbol; var $JSON = global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE = 'prototype'; var HIDDEN = wks('_hidden'); var TO_PRIMITIVE = wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = shared('symbol-registry'); var AllSymbols = shared('symbols'); var OPSymbols = shared('op-symbols'); var ObjectProto = Object[PROTOTYPE]; var USE_NATIVE = typeof $Symbol == 'function'; var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function () { return _create(dP({}, 'a', { get: function () { return dP(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP(it, key, D); if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); } : dP; var wrap = function (tag) { var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if (has(AllSymbols, key)) { if (!D.enumerable) { if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _create(D, { enumerable: createDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P) { anObject(it); var keys = enumKeys(P = toIObject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = toPrimitive(key, true)); if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = toIObject(it); key = toPrimitive(key, true); if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; var D = gOPD(it, key); if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN(toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString() { return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(73).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(46).f = $propertyIsEnumerable; __webpack_require__(72).f = $getOwnPropertySymbols; if (DESCRIPTORS && !__webpack_require__(23)) { redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function (name) { return wrap(wks(name)); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(11)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(26)('meta'); var isObject = __webpack_require__(8); var has = __webpack_require__(12); var setDesc = __webpack_require__(7).f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(16)(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(25); var gOPS = __webpack_require__(72); var pIE = __webpack_require__(46); module.exports = function (it) { var result = getKeys(it); var getSymbols = gOPS.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = pIE.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(19); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(14); var gOPN = __webpack_require__(73).f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(48)('asyncIterator'); /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(48)('observable'); /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(121), __esModule: true }; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(22); __webpack_require__(122); module.exports = __webpack_require__(0).Array.from; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ctx = __webpack_require__(13); var $export = __webpack_require__(4); var toObject = __webpack_require__(28); var call = __webpack_require__(61); var isArrayIter = __webpack_require__(62); var toLength = __webpack_require__(39); var createProperty = __webpack_require__(123); var getIterFn = __webpack_require__(44); $export($export.S + $export.F * !__webpack_require__(67)(function (iter) { Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var aLen = arguments.length; var mapfn = aLen > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var index = 0; var iterFn = getIterFn(O); var length, result, step, iterator; if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for (result = new C(length); length > index; index++) { createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $defineProperty = __webpack_require__(7); var createDesc = __webpack_require__(17); module.exports = function (object, index, value) { if (index in object) $defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /* 124 */, /* 125 */, /* 126 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _CHARS; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = split; // split.join = join // Flags Characters // 0 1 2 3 4 5 // ------------------------------------------------------------------------ // \ ' " normal space \n // e,sq n/a n/a n/a n/a n/a n/a // 0 ue,sq a \ suq a " a + a _ EOF // 1 e,dq a \,ue a \',ue a ",ue a \+,ue a \_,ue ue // 2 ue,dq e a ' duq a + a _ EOF // 3 e,uq a \,ue a \',ue a \",ue a \+,ue a _,ue ue // 4 ue,uq e sq dq a + tp EOF var MATRIX = { // object is more readable than multi-dim array. 0: [a, suq, a, a, a, EOF], 1: [eaue, aue, eaue, aue, aue, ue], 2: [e, a, duq, a, a, EOF], 3: [eaue, aue, aue, aue, eaue, ue], 4: [e, sq, dq, a, tp, EOF] }; // - a: add // - e: turn on escape mode // - ue: turn off escape mode // - q: turn on quote mode // - sq: single quoted // - dq: double quoted // - uq: turn off quote mode // - tp: try to push if there is something in the stash // - EOF: end of file(input) var escaped = false; // 1 var single_quoted = false; // 2 var double_quoted = false; // 4 var ended = false; var FLAGS = { 2: 0, 5: 1, 4: 2, 1: 3, 0: 4 }; function y() { var sum = 0; if (escaped) { sum++; } if (single_quoted) { sum += 2; } if (double_quoted) { sum += 4; } return FLAGS[sum]; } var BACK_SLASH = '\\'; var SINGLE_QUOTE = "'"; var DOUBLE_QUOTE = '"'; var WHITE_SPACE = ' '; var CARRIAGE_RETURN = '\n'; function x() { return c in CHARS ? CHARS[c] : CHARS.NORMAL; } var CHARS = (_CHARS = {}, _defineProperty(_CHARS, BACK_SLASH, 0), _defineProperty(_CHARS, SINGLE_QUOTE, 1), _defineProperty(_CHARS, DOUBLE_QUOTE, 2), _defineProperty(_CHARS, 'NORMAL', 3), _defineProperty(_CHARS, WHITE_SPACE, 4), _defineProperty(_CHARS, CARRIAGE_RETURN, 5), _CHARS); var c = ''; var stash = ''; var ret = []; function reset() { escaped = false; single_quoted = false; double_quoted = false; ended = false; c = ''; stash = ''; ret.length = 0; } function a() { stash += c; } function sq() { single_quoted = true; } function suq() { single_quoted = false; } function dq() { double_quoted = true; } function duq() { double_quoted = false; } function e() { escaped = true; } function ue() { escaped = false; } // add a backslash and a normal char, and turn off escaping function aue() { stash += BACK_SLASH + c; escaped = false; } // add a escaped char and turn off escaping function eaue() { stash += c; escaped = false; } // try to push function tp() { if (stash) { ret.push(stash); stash = ''; } } function EOF() { ended = true; } function split(str) { if (typeof str !== 'string') { type_error('Str must be a string. Received ' + str, 'NON_STRING'); } reset(); var length = str.length; var i = -1; while (++i < length) { c = str[i]; MATRIX[y()][x()](); if (ended) { break; } } if (single_quoted) { error('unmatched single quote', 'UNMATCHED_SINGLE'); } if (double_quoted) { error('unmatched double quote', 'UNMATCHED_DOUBLE'); } if (escaped) { error('unexpected end with \\', 'ESCAPED_EOF'); } tp(); return ret; } function error(message, code) { var err = new Error(message); err.code = code; throw err; } function type_error(message, code) { var err = new TypeError(message); err.code = code; throw err; } // function join (args, options = {}) { // const quote = options.quote || "'" // return args.map(function (arg) { // if (!arg) { // return // } // return /\c+/.test(arg) // // a b c -> 'a b c' // // a 'b' -> 'a \'b\'' // ? quote + arg.replace("'", "\\'") + quote // : arg // }).join(WHITE_SPACE) // } /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var templates = { inputCmd: function inputCmd(_ref) { var id = _ref.id; return "<div id=\"" + id + "\"><span class=\"prompt\"></span>&nbsp;<span class=\"input\"><span class=\"left\"></span><span class=\"cursor\"></span><span class=\"right\"></span></span></div>"; }, inputSearch: function inputSearch(_ref2) { var id = _ref2.id; return "<div id=\"" + id + "\">(reverse-i-search)`<span class=\"searchterm\"></span>':&nbsp;<span class=\"input\"><span class=\"left\"></span><span class=\"cursor\"></span><span class=\"right\"></span></span></div>"; }, suggest: function suggest(_ref3) { var suggestions = _ref3.suggestions; return "<div>" + suggestions.map(function (suggestion) { return "<div>" + suggestion + "</div>"; }).join("") + "</div>"; }, prompt: function prompt(_ref4) { var node = _ref4.node; return "<span class=\"cmdPrompt\">" + node.path + " $</span>"; } }; exports.default = templates; /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(69); var _keys2 = _interopRequireDefault(_keys); var _getIterator2 = __webpack_require__(20); var _getIterator3 = _interopRequireDefault(_getIterator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var util = { escape: function escape(s) { return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); }, bestMatch: function bestMatch(partial, possible) { var result = { completion: null, suggestions: [] }; if (!possible || possible.length === 0) { return result; } var common = ""; if (!partial) { if (possible.length === 1) { result.completion = possible[0]; result.suggestions = possible; return result; } if (!possible.every(function (x) { return possible[0][0] === x[0]; })) { result.suggestions = possible; return result; } } for (var i = 0; i < possible.length; i++) { var option = possible[i]; if (option.slice(0, partial.length) === partial) { result.suggestions.push(option); if (!common) { common = option; } else if (option.slice(0, common.length) !== common) { var j = partial.length; while (j < common.length && j < option.length) { if (common[j] !== option[j]) { common = common.substr(0, j); break; } j++; } } } } result.completion = common.substr(partial.length); return result; }, parseArgs: function parseArgs(rawArgs) { var cmdArgs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var cmdOpts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var argsList = rawArgs.filter(function (a) { return a[0] !== "-"; }); var optsList = rawArgs.filter(function (a) { return a[0] === "-"; }).map(function (a) { return a.substr(1); }); if (optsList.includes("h")) { throw new Error(); } var opts = {}; var args = {}; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(optsList), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var name = _step.value; if (!cmdOpts[name]) { throw new Error("Unknown option -" + name); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = (0, _getIterator3.default)((0, _keys2.default)(cmdOpts || {})), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _name = _step2.value; opts[_name] = optsList.includes(_name); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (cmdArgs) { for (var n = 0; n < cmdArgs.length; n++) { var rawName = cmdArgs[n]; var optional = rawName[0] === "?"; var _name2 = optional ? rawName.substr(1) : rawName; if (optional) { if (argsList[n]) { args[_name2] = argsList[n]; } else { break; } } else if (argsList[n]) { args[_name2] = argsList[n]; } else { throw new Error("Missing parameter " + _name2); } } } return { opts: opts, args: args }; } }; exports.default = util; /***/ }), /* 129 */, /* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(68); var _stringify2 = _interopRequireDefault(_stringify); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var History = function (_Base) { (0, _inherits3.default)(History, _Base); function History() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _classCallCheck3.default)(this, History); var _this = (0, _possibleConstructorReturn3.default)(this, (History.__proto__ || (0, _getPrototypeOf2.default)(History)).call(this, config)); _this.history = config.history || [""]; _this.cursor = config.cursor || 0; _this.searchCursor = _this.cursor; _this.lastSearchTerm = ""; _this.storage = config.storage || window.localStorage; _this.key = config.key || "wsh.history"; _this.suspended = false; _this._load(); return _this; } (0, _createClass3.default)(History, [{ key: "_load", value: function _load() { if (!this.storage) { return; } try { var data = this.storage.getItem(this.key); if (data) { this.history = JSON.parse(data); this.searchCursor = this.cursor = this.history.length - 1; } else { this._save(); } } catch (error) { this._log("Error accessing storage", error); } } }, { key: "_save", value: function _save() { if (!this.storage) { return; } try { this.storage.setItem(this.key, (0, _stringify2.default)(this.history)); } catch (error) { this._log("Error accessing storage", error); } } }, { key: "_setHistory", value: function _setHistory() { this.searchCursor = this.cursor; this.lastSearchTerm = ""; return this.history[this.cursor]; } }, { key: "update", value: function update(text) { this._log("updating history to " + text); this.history[this.cursor] = text; this._save(); } }, { key: "suspend", value: function suspend() { this.suspended = true; } }, { key: "resume", value: function resume() { this.suspended = false; } }, { key: "accept", value: function accept(text) { if (this.suspended) { return this._log("history suspended " + text); } this._log("accepting history " + text); if (text) { var last = this.history.length - 1; if (this.cursor === last) { this._log("we're at the end already, update last position"); this.history[this.cursor] = text; } else if (!this.history[last]) { this._log("we're not at the end, but the end was blank, so update last position"); this.history[last] = text; } else { this._log("appending to end"); this.history.push(text); } this.history.push(""); } this.searchCursor = this.cursor = this.history.length - 1; this._save(); } }, { key: "items", value: function items() { return this.history.slice(0, -1); } }, { key: "clear", value: function clear() { this.history = [this.history[this.history.length - 1]]; this._save(); } }, { key: "hasNext", value: function hasNext() { return this.cursor < this.history.length - 1; } }, { key: "hasPrev", value: function hasPrev() { return this.cursor > 0; } }, { key: "prev", value: function prev() { --this.cursor; return this._setHistory(); } }, { key: "next", value: function next() { ++this.cursor; return this._setHistory(); } }, { key: "top", value: function top() { this.cursor = 0; return this._setHistory(); } }, { key: "end", value: function end() { this.cursor = this.history.length - 1; return this._setHistory(); } }, { key: "search", value: function search(term) { if (!term && !this.lastSearchTerm) { return null; } var iterations = this.history.length; if (term === this.lastSearchTerm) { this.searchCursor--; iterations--; } else if (!term) { term = this.lastSearchTerm; } this.lastSearchTerm = term; for (var n = 0; n < iterations; n++) { if (this.searchCursor < 0) { this.searchCursor = this.history.length - 1; } var idx = this.history[this.searchCursor].indexOf(term); if (idx !== -1) { return { text: this.history[this.searchCursor], cursoridx: idx, term: term }; } this.searchCursor--; } return null; } }, { key: "applySearch", value: function applySearch() { if (!this.lastSearchTerm) { return null; } this._log("setting history to position " + this.searchCursor + "(" + this.cursor + "): " + this.history[this.searchCursor]); this.cursor = this.searchCursor; return this.history[this.cursor]; } }]); return History; }(_base2.default); /* global window */ exports.default = History; /***/ }), /* 131 */, /* 132 */, /* 133 */, /* 134 */, /* 135 */, /* 136 */, /* 137 */, /* 138 */, /* 139 */, /* 140 */, /* 141 */, /* 142 */, /* 143 */, /* 144 */, /* 145 */, /* 146 */, /* 147 */, /* 148 */, /* 149 */, /* 150 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(151); /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _shell2 = __webpack_require__(152); var _shell3 = _interopRequireDefault(_shell2); var _pathhandler = __webpack_require__(166); var _pathhandler2 = _interopRequireDefault(_pathhandler); var _templates = __webpack_require__(127); var _templates2 = _interopRequireDefault(_templates); var _util = __webpack_require__(128); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Terminal = function () { function Terminal(config) { var _this = this; (0, _classCallCheck3.default)(this, Terminal); this.templates = _templates2.default; this.util = _util2.default; this.shell = new _shell3.default(config, this); this.pathhandler = new _pathhandler2.default(config, this.shell); this.pathhandler.current = { name: "", path: "/" }; this.pathhandler.getNode = function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(path) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", config.getNode(path)); case 1: case "end": return _context.stop(); } } }, _callee, _this); })); return function (_x) { return _ref.apply(this, arguments); }; }(); this.pathhandler.getChildNodes = function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(node) { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", config.getChildNodes(node.path)); case 1: case "end": return _context2.stop(); } } }, _callee2, _this); })); return function (_x2) { return _ref2.apply(this, arguments); }; }(); } (0, _createClass3.default)(Terminal, [{ key: "current", value: function current() { return this.pathhandler.current; } }, { key: "completePath", value: function () { var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(path) { return _regenerator2.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.pathhandler.pathCompletionHandler(null, path, null); case 2: return _context3.abrupt("return", _context3.sent); case 3: case "end": return _context3.stop(); } } }, _callee3, this); })); function completePath(_x3) { return _ref3.apply(this, arguments); } return completePath; }() }, { key: "log", value: function log(text) { this.shell.log(text); } }, { key: "setPrompt", value: function setPrompt(opts) { this.shell._renderPrompt(opts); } }, { key: "setCommandHandler", value: function setCommandHandler(name, cmdHandler) { this.shell.setCommandHandler(name, cmdHandler); } }, { key: "isActive", value: function isActive() { return this.shell.isActive(); } }, { key: "activate", value: function activate() { this.shell.activate(); } }, { key: "deactivate", value: function deactivate() { this.shell.deactivate(); } }, { key: "on", value: function on() { var _shell; (_shell = this.shell).on.apply(_shell, arguments); } }]); return Terminal; }(); exports.default = Terminal; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(68); var _stringify2 = _interopRequireDefault(_stringify); var _getIterator2 = __webpack_require__(20); var _getIterator3 = _interopRequireDefault(_getIterator2); var _promise = __webpack_require__(6); var _promise2 = _interopRequireDefault(_promise); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _keys = __webpack_require__(69); var _keys2 = _interopRequireDefault(_keys); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); var _history = __webpack_require__(130); var _history2 = _interopRequireDefault(_history); var _readline = __webpack_require__(154); var _readline2 = _interopRequireDefault(_readline); var _stream = __webpack_require__(157); var _stream2 = _interopRequireDefault(_stream); var _templates = __webpack_require__(127); var _templates2 = _interopRequireDefault(_templates); var _util = __webpack_require__(128); var _util2 = _interopRequireDefault(_util); var _argvSplit = __webpack_require__(126); var _argvSplit2 = _interopRequireDefault(_argvSplit); var _clear = __webpack_require__(158); var _clear2 = _interopRequireDefault(_clear); var _help = __webpack_require__(159); var _help2 = _interopRequireDefault(_help); var _history3 = __webpack_require__(160); var _history4 = _interopRequireDefault(_history3); var _grep = __webpack_require__(161); var _grep2 = _interopRequireDefault(_grep); var _echo = __webpack_require__(162); var _echo2 = _interopRequireDefault(_echo); var _tail = __webpack_require__(163); var _tail2 = _interopRequireDefault(_tail); var _head = __webpack_require__(164); var _head2 = _interopRequireDefault(_head); var _default = __webpack_require__(165); var _default2 = _interopRequireDefault(_default); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Shell = function (_Base) { (0, _inherits3.default)(Shell, _Base); function Shell(config, terminal) { (0, _classCallCheck3.default)(this, Shell); var _this = (0, _possibleConstructorReturn3.default)(this, (Shell.__proto__ || (0, _getPrototypeOf2.default)(Shell)).call(this, config)); _this.terminal = terminal; _this.prompt = config.prompt || "wsh $"; _this.shellViewId = config.shellViewId || "shell-view"; _this.shellPanelId = config.shellPanelId || "shell-panel"; _this.inputId = config.inputId || "shell-cli"; _this.blinktime = config.blinktime || 500; _this.history = config.history || new _history2.default(config); _this.readline = config.readline || new _readline2.default({ debug: config.debug, history: _this.history }); _this.active = false; _this.cursorVisible = false; _this.cmdHandlers = {}; _this.line = { text: "", cursor: 0 }; _this.searchMatch = ""; _this.view = null; _this.panel = null; _this.initialized = null; _this.obscure = null; _this.executing = []; _this.stdout = new _stream2.default(false); _this.stderr = new _stream2.default(false); _this.stdin = new _stream2.default(false); _this.promptRenderer = function () { return _this.prompt; }; _this.setCommandHandler("clear", _clear2.default); _this.setCommandHandler("help", _help2.default); _this.setCommandHandler("history", _history4.default); _this.setCommandHandler("grep", _grep2.default); _this.setCommandHandler("echo", _echo2.default); _this.setCommandHandler("tail", _tail2.default); _this.setCommandHandler("head", _head2.default); _this.setCommandHandler("_default", _default2.default); _this._load(); _this._readStdout(); _this._readStderr(); return _this; } (0, _createClass3.default)(Shell, [{ key: "_readStdout", value: function _readStdout() { var _this2 = this; this.stdout.on("data", function (data) { _this2.log(data); }); } }, { key: "_readStderr", value: function _readStderr() { var _this3 = this; this.stderr.on("data", function (data) { _this3.log(data); }); } }, { key: "isActive", value: function isActive() { return this.readline.isActive(); } }, { key: "activate", value: function activate() { this.readline.activate(); } }, { key: "deactivate", value: function deactivate() { this._log("deactivating"); this.active = false; this.readline.deactivate(); } }, { key: "setCommandHandler", value: function setCommandHandler(cmd, cmdHandler) { this.cmdHandlers[cmd] = cmdHandler; } }, { key: "getCommandHandler", value: function getCommandHandler(cmd) { return this.cmdHandlers[cmd]; } }, { key: "setDefaultPromptRenderer", value: function setDefaultPromptRenderer(renderFn) { this.promptRenderer = renderFn; } }, { key: "setPrompt", value: function setPrompt(prompt) { this.prompt = prompt; if (!this.active) { return; } this.refresh(); } }, { key: "render", value: function render() { var text = this.line.text || ""; var cursorIdx = this.line.cursor || 0; if (this.searchMatch) { cursorIdx = this.searchMatch.cursoridx || 0; text = this.searchMatch.text || ""; document.querySelector("#" + this.inputId + " .searchterm").textContent = this.searchMatch.term; } var left = _util2.default.escape(text.substr(0, cursorIdx)).replace(/ /g, "&nbsp;"); var cursor = text.substr(cursorIdx, 1); var right = _util2.default.escape(text.substr(cursorIdx + 1)).replace(/ /g, "&nbsp;"); var elCursor = document.querySelector("#" + this.inputId + " .input .cursor"); var elPrompt = document.querySelector("#" + this.inputId + " .prompt"); var elLeft = document.querySelector("#" + this.inputId + " .input .left"); var elRight = document.querySelector("#" + this.inputId + " .input .right"); elPrompt && (elPrompt.innerHTML = this.prompt); elLeft && (elLeft.innerHTML = left); if (elCursor) { if (!cursor) { elCursor.innerHTML = "&nbsp;"; elCursor.style.textDecoration = "underline"; } else { elCursor.textContent = cursor; elCursor.style.textDecoration = "underline"; } } elRight && (elRight.innerHTML = right); this.cursorVisible = true; this.scrollToBottom(); this._blinkCursor(); this._log("rendered '" + text + "' w/ cursor at " + cursorIdx); } }, { key: "refresh", value: function refresh() { document.getElementById(this.inputId).outerHTML = _templates2.default.inputCmd({ id: this.inputId }); this.render(); this._log("refreshed " + this.inputId); } }, { key: "scrollToBottom", value: function scrollToBottom() { this.panel.scrollTop = this.view.offsetHeight; } }, { key: "_createElement", value: function _createElement(html) { var el = document.createElement("span"); el.innerHTML = html; if (el.childNodes.length > 1) { return el; } return el.firstChild; } }, { key: "_commands", value: function _commands() { return (0, _keys2.default)(this.cmdHandlers).filter(function (x) { return x[0] !== "_"; }); } }, { key: "_blinkCursor", value: function _blinkCursor() { var _this4 = this; if (!this.active || this.blinkTimer) { return; } this.blinkTimer = setTimeout(function () { _this4.blinkTimer = null; if (!_this4.active) { return; } _this4.cursorVisible = !_this4.cursorVisible; var elCursor = document.querySelector("#" + _this4.inputId + " .input .cursor"); if (elCursor) { if (_this4.cursorVisible) { elCursor.style.textDecoration = "underline"; } else { elCursor.style.textDecoration = ""; } _this4._blinkCursor(); } }, this.blinktime); } }, { key: "_stopBlinkCursor", value: function _stopBlinkCursor() { var elCursor = document.querySelector("#" + this.inputId + " .input .cursor"); elCursor && (elCursor.style.textDecoration = ""); clearTimeout(this.blinkTimer); this.blinkTimer = null; } }, { key: "_getHandler", value: function _getHandler(cmd) { return this.cmdHandlers[cmd] || this.cmdHandlers._default; } }, { key: "log", value: function log(output) { if (output) { document.getElementById(this.shellViewId).appendChild(this._createElement(output)); this.scrollToBottom(); } } }, { key: "_renderHelp", value: function _renderHelp(cmd, cmdArgs, cmdOpts, cmdDescription) { var error = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var args = (cmdArgs || []).map(function (a) { return a[0] === "?" ? "[" + a.substr(1) + "]" : "&lt;" + a + "&gt;"; }); var opts = (0, _keys2.default)(cmdOpts || {}).map(function (o) { return " -" + o + " " + cmdOpts[o]; }); var err = error && error.message ? "<span class=\"error\">" + error + "</span>\n" : ""; return err + "\nUsage: " + cmd + " [options] " + args.join(" ") + "\n\n" + cmdDescription + "\n\nOptions:\n -h Print help\n" + opts.join("\n"); } }, { key: "_freezePrompt", value: function _freezePrompt() { this._stopBlinkCursor(); var elCursor = document.querySelector("#" + this.inputId + " .input .cursor"); var elInput = document.getElementById(this.inputId); elCursor && (elCursor.style.textDecoration = ""); elInput && elInput.removeAttribute("id"); } }, { key: "_renderPrompt", value: function _renderPrompt() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this._freezePrompt(); this.obscure = !!opts.obscure; var elShellView = document.getElementById(this.shellViewId); elShellView.appendChild(this._createElement(_templates2.default.inputCmd({ id: this.inputId }))); this.setPrompt(opts.prompt || this.promptRenderer()); this._blinkCursor(); } }, { key: "_renderOutput", value: function _renderOutput(output) { this._freezePrompt(); this.log(output); this._renderPrompt(); } }, { key: "_activateShell", value: function _activateShell() { this._log("activating shell"); if (!this.view) { this.view = document.getElementById(this.shellViewId); } if (!this.panel) { this.panel = document.getElementById(this.shellPanelId); } this._trigger("activating"); this._renderPrompt(); this.refresh(); this.active = true; this._trigger("activate"); } }, { key: "clear", value: function clear() { document.getElementById(this.shellViewId).innerHTML = ""; } }, { key: "_parseCommandLine", value: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(cmdline) { var cmdtexts, cmds, pipe, n, isLast, cmdtext, parts, cmdName, cmdArgs, handler, streams, parsed, help; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: cmdtexts = cmdline.split("|"); cmds = []; pipe = this.stdin; n = 0; case 4: if (!(n < cmdtexts.length)) { _context.next = 37; break; } isLast = n === cmdtexts.length - 1; cmdtext = cmdtexts[n]; parts = []; _context.prev = 8; parts = (0, _argvSplit2.default)(cmdtext); _context.next = 17; break; case 12: _context.prev = 12; _context.t0 = _context["catch"](8); _context.next = 16; return this.stderr.write("Unable to parse command: " + _context.t0.message); case 16: return _context.abrupt("return", []); case 17: cmdName = parts[0]; cmdArgs = parts.slice(1); handler = this._getHandler(cmdName); streams = { stdout: this.stdout, stdin: pipe, stderr: this.stderr }; if (!isLast) { pipe = streams.stdout = new _stream2.default(); } parsed = {}; _context.prev = 23; parsed = _util2.default.parseArgs(cmdArgs, handler.args || [], handler.opts || {}); _context.next = 33; break; case 27: _context.prev = 27; _context.t1 = _context["catch"](23); help = this._renderHelp(cmdName, handler.args || [], handler.opts || {}, handler.desc || "", _context.t1); _context.next = 32; return this.stderr.write(help); case 32: return _context.abrupt("return", []); case 33: cmds.push({ cmdtext: cmdtext, cmdName: cmdName, streams: streams, handler: handler, opts: parsed.opts, args: parsed.args }); case 34: n++; _context.next = 4; break; case 37: return _context.abrupt("return", cmds); case 38: case "end": return _context.stop(); } } }, _callee, this, [[8, 12], [23, 27]]); })); function _parseCommandLine(_x3) { return _ref.apply(this, arguments); } return _parseCommandLine; }() }, { key: "_load", value: function _load() { var _this5 = this; this.readline.on("eot", function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this5._trigger.apply(_this5, ["eot"].concat(args)); }); this.readline.on("activate", function () { if (_this5.initialized) { _this5.initialized = true; _this5._trigger("initialize", _this5._activateShell.bind(_this5)); } return _this5._activateShell(); }); this.readline.on("deactivate", function () { _this5._trigger("deactivate"); }); this.readline.on("change", function (line) { _this5.line = line; if (_this5.obscure) { _this5.line.text = _this5.line.text.replace(/./g, "*"); } _this5.render(); }); this.readline.on("clear", function () { _this5.clear(); _this5._renderOutput(); }); this.readline.on("searchStart", function () { document.getElementById(_this5.inputId).outerHTML = _templates2.default.inputSearch({ id: _this5.inputId }); _this5._log("started search"); }); this.readline.on("searchEnd", function () { document.getElementById(_this5.inputId).outerHTML = _templates2.default.inputSearch({ id: _this5.inputId }); _this5.searchMatch = null; _this5.render(); _this5._log("ended search"); }); this.readline.on("searchChange", function (match) { _this5.searchMatch = match; _this5.render(); }); this.readline.on("enter", function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(cmdtext) { var promises; return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(_this5.executing.length > 0)) { _context2.next = 3; break; } _this5._freezePrompt(); return _context2.abrupt("return", _this5.stdin.write(cmdtext)); case 3: _this5._log("got command: " + cmdtext); if (cmdtext) { _context2.next = 7; break; } _this5._renderOutput(); return _context2.abrupt("return"); case 7: _this5._freezePrompt(); _this5.history.suspend(); _context2.next = 11; return _this5._parseCommandLine(cmdtext); case 11: _this5.executing = _context2.sent; if (!(_this5.executing.length === 0)) { _context2.next = 15; break; } _this5.history.resume(); return _context2.abrupt("return", _this5._renderPrompt()); case 15: _this5.executing = _this5.executing.reverse(); promises = _this5.executing.map(function (cmd) { return cmd.handler.exec(_this5.terminal, cmd.streams, cmd.cmdName, cmd.opts, cmd.args).then(function () { cmd.streams.stdout.isPipe() && cmd.streams.stdout.close(); return null; }).catch(function (error) { cmd.streams.stdout.isPipe() && cmd.streams.stdout.close(); return _this5.stderr.write("Command failed: " + error.message + "\n"); }); }); _promise2.default.all(promises).then(function () { _this5.executing.length = 0; _this5.history.resume(); _this5._renderPrompt(); }).catch(function (error) { _this5.executing.length = 0; console.error(error); _this5.history.resume(); _this5._renderPrompt(); }); case 18: case "end": return _context2.stop(); } } }, _callee2, _this5); })); return function (_x4) { return _ref2.apply(this, arguments); }; }()); this.readline.on("cancel", (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() { var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cmd; return _regenerator2.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context3.prev = 3; for (_iterator = (0, _getIterator3.default)(_this5.executing); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { cmd = _step.value; cmd.streams.stdin.abort(); } _context3.next = 11; break; case 7: _context3.prev = 7; _context3.t0 = _context3["catch"](3); _didIteratorError = true; _iteratorError = _context3.t0; case 11: _context3.prev = 11; _context3.prev = 12; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 14: _context3.prev = 14; if (!_didIteratorError) { _context3.next = 17; break; } throw _iteratorError; case 17: return _context3.finish(14); case 18: return _context3.finish(11); case 19: case "end": return _context3.stop(); } } }, _callee3, _this5, [[3, 7, 11, 19], [12,, 14, 18]]); }))); this.readline.on("completion", function () { var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(line) { var text, parts, cmdName, handler, argName, args, match; return _regenerator2.default.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (line) { _context4.next = 2; break; } return _context4.abrupt("return"); case 2: text = line.text.substr(0, line.cursor).split("|").pop().replace(/^\s+/g, ""); parts = void 0; _context4.prev = 4; parts = (0, _argvSplit2.default)(text); _context4.next = 11; break; case 8: _context4.prev = 8; _context4.t0 = _context4["catch"](4); return _context4.abrupt("return"); case 11: cmdName = parts.shift() || ""; _this5._log("getting completion handler for " + cmdName); handler = _this5._getHandler(cmdName); if (!(handler !== _this5.cmdHandlers._default && cmdName && cmdName === text)) { _context4.next = 17; break; } _this5._log("valid cmd, no args: append space"); // the text to complete is just a valid command, append a space return _context4.abrupt("return", " "); case 17: if (handler.completion) { _context4.next = 20; break; } _this5._log("no completion method"); // handler has no completion function, so we can't complete return _context4.abrupt("return"); case 20: argName = null; if (!(handler !== _this5.cmdHandlers._default)) { _context4.next = 29; break; } args = parts.filter(function (a) { return a[0] !== "-"; }); // Remove flags _this5._log("args", args); argName = handler.args[Math.max(0, args.length - 1)]; _this5._log("argName", argName); if (argName) { _context4.next = 28; break; } return _context4.abrupt("return"); case 28: argName = argName[0] === "?" ? argName.substr(1) : argName; case 29: _this5._log("calling completion handler for " + cmdName); _context4.prev = 30; _context4.next = 33; return handler.completion(_this5.terminal, cmdName, argName, parts.pop(), line); case 33: match = _context4.sent; _this5._log("completion: " + (0, _stringify2.default)(match)); if (match) { _context4.next = 37; break; } return _context4.abrupt("return"); case 37: if (match.suggestions && match.suggestions.length > 1) { _this5._renderOutput(_templates2.default.suggest({ suggestions: match.suggestions })); } return _context4.abrupt("return", match.completion); case 41: _context4.prev = 41; _context4.t1 = _context4["catch"](30); _this5._log(_context4.t1); case 44: return _context4.abrupt("return", []); case 45: case "end": return _context4.stop(); } } }, _callee4, _this5, [[4, 8], [30, 41]]); })); return function (_x5) { return _ref4.apply(this, arguments); }; }()); } }]); return Shell; }(_base2.default); /* global document */ exports.default = Shell; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _from = __webpack_require__(120); var _from2 = _interopRequireDefault(_from); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return (0, _from2.default)(arr); } }; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); var _history = __webpack_require__(130); var _history2 = _interopRequireDefault(_history); var _killring = __webpack_require__(155); var _killring2 = _interopRequireDefault(_killring); var _keys = __webpack_require__(156); var _keys2 = _interopRequireDefault(_keys); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* global window */ var ReadLine = function (_Base) { (0, _inherits3.default)(ReadLine, _Base); function ReadLine() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _classCallCheck3.default)(this, ReadLine); var _this = (0, _possibleConstructorReturn3.default)(this, (ReadLine.__proto__ || (0, _getPrototypeOf2.default)(ReadLine)).call(this, config)); _this.history = config.history || new _history2.default(config); _this.killring = config.killring || new _killring2.default(config); _this.cursor = 0; _this.boundToElement = !!config.element; _this.element = config.element || window; _this.active = false; _this.inSearch = false; _this.searchMatch; _this.lastSearchText = ""; _this.text = ""; _this.cursor = 0; _this.lastCmd; _this.completionActive; _this.cmdQueue = []; _this.suspended = false; _this.cmdMap = { complete: _this._cmdComplete.bind(_this), done: _this._cmdDone.bind(_this), noop: _this._cmdNoOp.bind(_this), historyTop: _this._cmdHistoryTop.bind(_this), historyEnd: _this._cmdHistoryEnd.bind(_this), historyNext: _this._cmdHistoryNext.bind(_this), historyPrevious: _this._cmdHistoryPrev.bind(_this), end: _this._cmdEnd.bind(_this), home: _this._cmdHome.bind(_this), left: _this._cmdLeft.bind(_this), right: _this._cmdRight.bind(_this), cancel: _this._cmdCancel.bind(_this), "delete": _this._cmdDeleteChar.bind(_this), backspace: _this._cmdBackspace.bind(_this), killEof: _this._cmdKillToEOF.bind(_this), killWordback: _this._cmdKillWordBackward.bind(_this), killWordForward: _this._cmdKillWordForward.bind(_this), yank: _this._cmdYank.bind(_this), clear: _this._cmdClear.bind(_this), search: _this._cmdReverseSearch.bind(_this), wordBack: _this._cmdBackwardWord.bind(_this), wordForward: _this._cmdForwardWord.bind(_this), yankRotate: _this._cmdRotate.bind(_this), esc: _this._cmdEsc.bind(_this) }; _this.keyMap = { "default": {}, "control": {}, "meta": {} }; _this.bind(_keys2.default.Backspace, "default", "backspace"); _this.bind(_keys2.default.Tab, "default", "complete"); _this.bind(_keys2.default.Enter, "default", "done"); _this.bind(_keys2.default.Escape, "default", "esc"); _this.bind(_keys2.default.PageUp, "default", "historyTop"); _this.bind(_keys2.default.PageDown, "default", "historyEnd"); _this.bind(_keys2.default.End, "default", "end"); _this.bind(_keys2.default.Home, "default", "home"); _this.bind(_keys2.default.Left, "default", "left"); _this.bind(_keys2.default.Up, "default", "historyPrevious"); _this.bind(_keys2.default.Right, "default", "right"); _this.bind(_keys2.default.Down, "default", "historyNext"); _this.bind(_keys2.default.Delete, "default", "delete"); _this.bind(_keys2.default.CapsLock, "default", "noop"); _this.bind(_keys2.default.Pause, "default", "noop"); _this.bind(_keys2.default.Insert, "default", "noop"); _this.bind("A", "control", "home"); _this.bind("B", "control", "left"); _this.bind("C", "control", "cancel"); _this.bind("D", "control", "delete"); _this.bind("E", "control", "end"); _this.bind("F", "control", "right"); _this.bind("P", "control", "historyPrevious"); _this.bind("N", "control", "historyNext"); _this.bind("K", "control", "killEof"); _this.bind("Y", "control", "yank"); _this.bind("L", "control", "clear"); _this.bind("R", "control", "search"); _this.bind(_keys2.default.Backspace, "meta", "killWordback"); _this.bind("B", "meta", "wordBack"); _this.bind("D", "meta", "killWordForward"); _this.bind("F", "meta", "wordForward"); _this.bind("Y", "meta", "yankRotate"); if (_this.boundToElement) { _this.attach(_this.element); } else { _this._subscribeToKeys(); } return _this; } (0, _createClass3.default)(ReadLine, [{ key: "isActive", value: function isActive() { return this.active; } }, { key: "activate", value: function activate() { this.active = true; this._trigger("activate"); } }, { key: "deactivate", value: function deactivate() { this.active = false; this._trigger("deactivate"); } }, { key: "bind", value: function bind(key, modifier, action) { var cmd = this.cmdMap[action]; this._log("Bind key " + key + " with modifier " + modifier + " to action " + action); if (!cmd) { return; } if (typeof key === "number") { this.keyMap[modifier || "default"][key] = cmd; } else { this.keyMap[modifier || "default"][key.charCodeAt()] = cmd; this.keyMap[modifier || "default"][key.toLowerCase().charCodeAt()] = cmd; } } }, { key: "unbind", value: function unbind(key) { var modifier = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "default"; this._log("Unbind key " + key + " with modifier " + modifier); var code = typeof key === "number" ? key : key.charCodeAt(); delete this.keyMap[modifier][code]; } }, { key: "attach", value: function attach(el) { if (this.element) { this.detach(); } this._log("attaching", el); this.element = el; this.boundToElement = true; this._addEvent(this.element, "focus", this.activate.bind(this)); this._addEvent(this.element, "blur", this.deactivate.bind(this)); this._subscribeToKeys(); } }, { key: "detach", value: function detach() { this._this._removeEvent(this.element, "focus", this.activate.bind(this)); this._this._removeEvent(this.element, "blur", this.deactivate.bind(this)); this.element = null; this.boundToElement = false; } }, { key: "getLine", value: function getLine() { return { text: this.text, cursor: this.cursor }; } }, { key: "setLine", value: function setLine(line) { this.text = line.text; this.cursor = line.cursor; this._refresh(); } }, { key: "_addEvent", value: function _addEvent(element, name, callback) { if (element.addEventListener) { element.addEventListener(name, callback, false); } else if (element.attachEvent) { element.attachEvent("on" + name, callback); } } }, { key: "_removeEvent", value: function _removeEvent(element, name, callback) { if (element.removeEventListener) { element.removeEventListener(name, callback, false); } else if (element.detachEvent) { element.detachEvent("on" + name, callback); } } }, { key: "_getKeyInfo", value: function _getKeyInfo(e) { var code = e.keyCode || e.charCode; var c = String.fromCharCode(code); return { code: code, character: c, shift: e.shiftKey, ctrl: e.ctrlKey && !e.altKey, alt: e.altKey && !e.ctrlKey, meta: e.metaKey, isChar: true }; } }, { key: "_queue", value: function _queue(cmd) { if (this.suspended) { this.cmdQueue.push(cmd); return; } this._call(cmd); } }, { key: "_call", value: function _call(cmd) { this._log("calling: " + cmd.name + ", previous: " + this.lastCmd); if (this.inSearch && cmd.name !== "cmdKeyPress" && cmd.name !== "cmdReverseSearch") { this.inSearch = false; if (cmd.name === "cmdEsc") { this.searchMatch = null; } if (this.searchMatch) { if (this.searchMatch.text) { this.cursor = this.searchMatch.cursoridx; this.text = this.searchMatch.text; this.history.applySearch(); } this.searchMatch = null; } this._trigger("searchEnd"); } if (!this.inSearch && this.killring.isinkill() && cmd.name.substr(0, 7) !== "cmdKill") { this.killring.commit(); } this.lastCmd = cmd.name; cmd(); } }, { key: "_suspend", value: function _suspend(asyncCall) { this.suspended = true; asyncCall(this._resume.bind(this)); } }, { key: "_resume", value: function _resume() { var cmd = this.cmdQueue.shift(); if (!cmd) { this.suspended = false; return; } this._call(cmd); this._resume(); } }, { key: "_cmdNoOp", value: function _cmdNoOp() { // no-op, used for keys we capture and ignore } }, { key: "_cmdEsc", value: function _cmdEsc() { // no-op, only has an effect on reverse search and that action was taken in this._call() } }, { key: "_cmdBackspace", value: function _cmdBackspace() { if (this.cursor === 0) { return; } --this.cursor; this.text = this._remove(this.text, this.cursor, this.cursor + 1); this._refresh(); } }, { key: "_cmdComplete", value: function _cmdComplete() { var _this2 = this; if (!this.eventHandlers.completion) { return; } this._suspend(function (resumeCallback) { _this2._trigger("completion", _this2.getLine()).then(function (completion) { if (completion) { _this2.text = _this2._insert(_this2.text, _this2.cursor, completion); _this2._updateCursor(_this2.cursor + completion.length); } _this2.completionActive = true; resumeCallback(); }); }); } }, { key: "_cmdDone", value: function _cmdDone() { var _this3 = this; var text = this.text; this.history.accept(text); this.text = ""; this.cursor = 0; if (!this.eventHandlers.enter) { return; } this._suspend(function (resumeCallback) { _this3._trigger("enter", text).then(function (text) { if (text) { _this3.text = text; _this3.cursor = _this3.text.length; } _this3._trigger("change", _this3.getLine()); resumeCallback(); }); }); } }, { key: "_cmdEnd", value: function _cmdEnd() { this._updateCursor(this.text.length); } }, { key: "_cmdHome", value: function _cmdHome() { this._updateCursor(0); } }, { key: "_cmdLeft", value: function _cmdLeft() { if (this.cursor === 0) { return; } this._updateCursor(this.cursor - 1); } }, { key: "_cmdRight", value: function _cmdRight() { if (this.cursor === this.text.length) { return; } this._updateCursor(this.cursor + 1); } }, { key: "_cmdBackwardWord", value: function _cmdBackwardWord() { if (this.cursor === 0) { return; } this._updateCursor(this._findBeginningOfPreviousWord()); } }, { key: "_cmdForwardWord", value: function _cmdForwardWord() { if (this.cursor === this.text.length) { return; } this._updateCursor(this._findEndOfCurrentWord()); } }, { key: "_cmdHistoryPrev", value: function _cmdHistoryPrev() { if (!this.history.hasPrev()) { return; } this._getHistory(this.history.prev.bind(this.history)); } }, { key: "_cmdHistoryNext", value: function _cmdHistoryNext() { if (!this.history.hasNext()) { return; } this._getHistory(this.history.next.bind(this.history)); } }, { key: "_cmdHistoryTop", value: function _cmdHistoryTop() { this._getHistory(this.history.top.bind(this.history)); } }, { key: "_cmdHistoryEnd", value: function _cmdHistoryEnd() { this._getHistory(this.history.end.bind(this.history)); } }, { key: "_cmdDeleteChar", value: function _cmdDeleteChar() { if (this.text.length === 0) { if (this.eventHandlers.eot) { return this._trigger("eot"); } } if (this.cursor === this.text.length) { return; } this.text = this._remove(this.text, this.cursor, this.cursor + 1); this._refresh(); } }, { key: "_cmdCancel", value: function _cmdCancel() { this._trigger("cancel"); } }, { key: "_cmdKillToEOF", value: function _cmdKillToEOF() { this.killring.append(this.text.substr(this.cursor)); this.text = this.text.substr(0, this.cursor); this._refresh(); } }, { key: "_cmdKillWordForward", value: function _cmdKillWordForward() { if (this.text.length === 0) { return; } if (this.cursor === this.text.length) { return; } var end = this._findEndOfCurrentWord(); if (end === this.text.length - 1) { return this._cmdKillToEOF(); } this.killring.append(this.text.substring(this.cursor, end)); this.text = this._remove(this.text, this.cursor, end); this._refresh(); } }, { key: "_cmdKillWordBackward", value: function _cmdKillWordBackward() { if (this.cursor === 0) { return; } var oldCursor = this.cursor; this.cursor = this._findBeginningOfPreviousWord(); this.killring.prepend(this.text.substring(this.cursor, oldCursor)); this.text = this._remove(this.text, this.cursor, oldCursor); this._refresh(); } }, { key: "_cmdYank", value: function _cmdYank() { var yank = this.killring.yank(); if (!yank) { return; } this.text = this._insert(this.text, this.cursor, yank); this._updateCursor(this.cursor + yank.length); } }, { key: "_cmdRotate", value: function _cmdRotate() { var lastyanklength = this.killring.lastyanklength(); if (!lastyanklength) { return; } var yank = this.killring.rotate(); if (!yank) { return; } var oldCursor = this.cursor; this.cursor = this.cursor - lastyanklength; this.text = this._remove(this.text, this.cursor, oldCursor); this.text = this._insert(this.text, this.cursor, yank); this._updateCursor(this.cursor + yank.length); } }, { key: "_cmdClear", value: function _cmdClear() { if (this.eventHandlers.clear) { this._trigger("clear"); } else { this._refresh(); } } }, { key: "_cmdReverseSearch", value: function _cmdReverseSearch() { if (!this.inSearch) { this.inSearch = true; this._trigger("searchStart"); this._trigger("searchChange", {}); } else { if (!this.searchMatch) { this.searchMatch = { term: "" }; } this._search(); } } }, { key: "_updateCursor", value: function _updateCursor(position) { this.cursor = position; this._refresh(); } }, { key: "_addText", value: function _addText(text) { this.text = this._insert(this.text, this.cursor, text); this.cursor += text.length; this._refresh(); } }, { key: "_addSearchText", value: function _addSearchText(text) { if (!this.searchMatch) { this.searchMatch = { term: "" }; } this.searchMatch.term += text; this._search(); } }, { key: "_search", value: function _search() { this._log("searchtext: " + this.searchMatch.term); var match = this.history.search(this.searchMatch.term); if (match !== null) { this.searchMatch = match; this._log("match: " + match); this._trigger("searchChange", match); } } }, { key: "_refresh", value: function _refresh() { this._trigger("change", this.getLine()); } }, { key: "_getHistory", value: function _getHistory(historyCall) { this.history.update(this.text); this.text = historyCall(); this._updateCursor(this.text.length); } }, { key: "_findBeginningOfPreviousWord", value: function _findBeginningOfPreviousWord() { var position = this.cursor - 1; if (position < 0) { return 0; } var word = false; for (var i = position; i > 0; i--) { var word2 = this._isWordChar(this.text[i]); if (word && !word2) { return i + 1; } word = word2; } return 0; } }, { key: "_findEndOfCurrentWord", value: function _findEndOfCurrentWord() { if (this.text.length === 0) { return 0; } var position = this.cursor + 1; if (position >= this.text.length) { return this.text.length - 1; } var word = false; for (var i = position; i < this.text.length; i++) { var word2 = this._isWordChar(this.text[i]); if (word && !word2) { return i; } word = word2; } return this.text.length - 1; } }, { key: "_isWordChar", value: function _isWordChar(c) { if (!c) { return false; } var code = c.charCodeAt(0); return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122; } }, { key: "_remove", value: function _remove(text, from, to) { if (text.length <= 1 || text.length <= to - from) { return ""; } if (from === 0) { // delete leading characters return text.substr(to); } var left = text.substr(0, from); var right = text.substr(to); return left + right; } }, { key: "_insert", value: function _insert(text, idx, ins) { if (idx === 0) { return ins + text; } if (idx >= text.length) { return text + ins; } var left = text.substr(0, idx); var right = text.substr(idx); return left + ins + right; } }, { key: "_subscribeToKeys", value: function _subscribeToKeys() { var _this4 = this; // set up key capture this._addEvent(this.element, "keydown", function (e) { var key = _this4._getKeyInfo(e); // return as unhandled if we're not active or the key is just a modifier key if (!_this4.active || key.code === _keys2.default.Shift || key.code === _keys2.default.Ctrl || key.code === _keys2.default.Alt || key.code === _keys2.default.LeftWindowKey) { return true; } // check for some special first keys, regardless of modifiers _this4._log("key: " + key.code); var cmd = _this4.keyMap.default[key.code]; // intercept ctrl- and meta- sequences (may override the non-modifier cmd captured above var mod = void 0; if (key.ctrl && !key.shift && !key.alt && !key.meta) { mod = _this4.keyMap.control[key.code]; if (mod) { cmd = mod; } } else if ((key.alt || key.meta) && !key.ctrl && !key.shift) { mod = _this4.keyMap.meta[key.code]; if (mod) { cmd = mod; } } if (!cmd) { return true; } _this4._queue(cmd); e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; return false; }); this._addEvent(this.element, "keypress", function (e) { if (!_this4.active) { return true; } var key = _this4._getKeyInfo(e); if (key.code === 0 || e.defaultPrevented || key.meta || key.alt || key.ctrl) { return false; } _this4._queue(function () { if (_this4.inSearch) { _this4._addSearchText(key.character); } else { _this4._addText(key.character); } }); e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; return false; }); this._addEvent(this.element, "paste", function (e) { if (!_this4.active) { return true; } var pastedText = ""; if (window.clipboardData && window.clipboardData.getData) { pastedText = window.clipboardData.getData("Text"); } else if (e.clipboardData && e.clipboardData.getData) { pastedText = e.clipboardData.getData("text/plain"); } _this4._queue(function () { if (_this4.inSearch) { _this4._addSearchText(pastedText); } else { _this4._addText(pastedText); } }); e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; return false; }); } }]); return ReadLine; }(_base2.default); exports.default = ReadLine; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var KillRing = function (_Base) { (0, _inherits3.default)(KillRing, _Base); function KillRing() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _classCallCheck3.default)(this, KillRing); var _this = (0, _possibleConstructorReturn3.default)(this, (KillRing.__proto__ || (0, _getPrototypeOf2.default)(KillRing)).call(this, config)); _this.ring = config.ring || []; _this.cursor = config.cursor || 0; _this.uncommitted = false; _this.yanking = false; if (_this.ring.length === 0) { _this.cursor = -1; } else if (_this.cursor >= _this.ring.length) { _this.cursor = _this.ring.length - 1; } return _this; } (0, _createClass3.default)(KillRing, [{ key: "isinkill", value: function isinkill() { return this.uncommitted; } }, { key: "lastyanklength", value: function lastyanklength() { if (!this.yanking) { return 0; } return this.ring[this.cursor].length; } }, { key: "append", value: function append(value) { this.yanking = false; if (!value) { return; } if (this.ring.length === 0 || !this.uncommitted) { this.ring.push(""); } this.cursor = this.ring.length - 1; this._log("appending: " + value); this.uncommitted = true; this.ring[this.cursor] += value; } }, { key: "prepend", value: function prepend(value) { this.yanking = false; if (!value) { return; } if (this.ring.length === 0 || !this.uncommitted) { this.ring.push(""); } this.cursor = this.ring.length - 1; this._log("prepending: " + value); this.uncommitted = true; this.ring[this.cursor] = value + this.ring[this.cursor]; } }, { key: "commit", value: function commit() { this._log("committing"); this.yanking = false; this.uncommitted = false; } }, { key: "yank", value: function yank() { this.commit(); if (this.ring.length === 0) { return null; } this.yanking = true; return this.ring[this.cursor]; } }, { key: "rotate", value: function rotate() { if (!this.yanking || this.ring.length === 0) { return null; } --this.cursor; if (this.cursor < 0) { this.cursor = this.ring.length - 1; } return this.yank(); } }, { key: "items", value: function items() { return this.ring.slice(0); } }, { key: "clear", value: function clear() { this.ring = []; this.cursor = -1; this.yanking = false; this.uncommited = false; } }]); return KillRing; }(_base2.default); exports.default = KillRing; /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var keys = { Backspace: 8, Tab: 9, Enter: 13, Shift: 16, Ctrl: 17, Alt: 18, LeftWindowKey: 91, Pause: 19, CapsLock: 20, Escape: 27, Space: 32, PageUp: 33, PageDown: 34, End: 35, Home: 36, Left: 37, Up: 38, Right: 39, Down: 40, Insert: 45, Delete: 46 }; exports.default = keys; /***/ }), /* 157 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _promise = __webpack_require__(6); var _promise2 = _interopRequireDefault(_promise); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Deferred = function Deferred() { var _this = this; (0, _classCallCheck3.default)(this, Deferred); this.promise = new _promise2.default(function (resolve, reject) { _this.resolve = resolve; _this.reject = reject; }); }; var Stream = function (_Base) { (0, _inherits3.default)(Stream, _Base); function Stream() { var _this3 = this; var pipe = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; (0, _classCallCheck3.default)(this, Stream); var _this2 = (0, _possibleConstructorReturn3.default)(this, (Stream.__proto__ || (0, _getPrototypeOf2.default)(Stream)).call(this)); _this2.pipe = pipe; _this2.readDeferred = new Deferred(); _this2.buffer = []; _this2.aborted = false; _this2.on("data", function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(data) { var deferred; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _this2.buffer.push(data); deferred = _this2.readDeferred; _this2.readDeferred = new Deferred(); deferred.resolve(); case 4: case "end": return _context.stop(); } } }, _callee, _this3); })); return function (_x2) { return _ref.apply(this, arguments); }; }()); return _this2; } (0, _createClass3.default)(Stream, [{ key: "read", value: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!this.aborted) { _context2.next = 4; break; } this.aborted = false; this.buffer.length = 0; throw new Error("Command aborted"); case 4: if (!(this.buffer.length > 0)) { _context2.next = 6; break; } return _context2.abrupt("return", this.buffer.shift()); case 6: _context2.next = 8; return this.readDeferred.promise; case 8: return _context2.abrupt("return", this.read()); case 9: case "end": return _context2.stop(); } } }, _callee2, this); })); function read() { return _ref2.apply(this, arguments); } return read; }() }, { key: "write", value: function () { var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(data) { return _regenerator2.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(typeof data !== "string")) { _context3.next = 2; break; } throw new Error("data must be of type string"); case 2: _context3.next = 4; return this._trigger("data", data); case 4: case "end": return _context3.stop(); } } }, _callee3, this); })); function write(_x3) { return _ref3.apply(this, arguments); } return write; }() }, { key: "close", value: function () { var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4() { return _regenerator2.default.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._trigger("data", false); case 2: case "end": return _context4.stop(); } } }, _callee4, this); })); function close() { return _ref4.apply(this, arguments); } return close; }() }, { key: "abort", value: function () { var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5() { return _regenerator2.default.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: this.aborted = true; _context5.next = 3; return this._trigger("data", false); case 3: case "end": return _context5.stop(); } } }, _callee5, this); })); function abort() { return _ref5.apply(this, arguments); } return abort; }() }, { key: "isPipe", value: function isPipe() { return this.pipe; } }]); return Stream; }(_base2.default); exports.default = Stream; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Clear output", exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term /* , streams, cmd, opts, args */) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: term.shell.clear(); case 1: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 159 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _getIterator2 = __webpack_require__(20); var _getIterator3 = _interopRequireDefault(_getIterator2); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Print help", exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams /* , cmd, opts, args */) { var items, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, item; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: items = term.shell._commands(); _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context.prev = 4; _iterator = (0, _getIterator3.default)(items); case 6: if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { _context.next = 13; break; } item = _step.value; _context.next = 10; return streams.stdout.write(" " + item + "\n"); case 10: _iteratorNormalCompletion = true; _context.next = 6; break; case 13: _context.next = 19; break; case 15: _context.prev = 15; _context.t0 = _context["catch"](4); _didIteratorError = true; _iteratorError = _context.t0; case 19: _context.prev = 19; _context.prev = 20; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 22: _context.prev = 22; if (!_didIteratorError) { _context.next = 25; break; } throw _iteratorError; case 25: return _context.finish(22); case 26: return _context.finish(19); case 27: case "end": return _context.stop(); } } }, _callee, undefined, [[4, 15, 19, 27], [20,, 22, 26]]); })); function exec(_x, _x2) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Show history", exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts /* , args */) { var items, n; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!opts.c) { _context.next = 3; break; } term.shell.history.clear(); return _context.abrupt("return"); case 3: items = term.shell.history.items(); n = 0; case 5: if (!(n < items.length)) { _context.next = 11; break; } _context.next = 8; return streams.stdout.write(" " + n + " " + items[n] + "\n"); case 8: n++; _context.next = 5; break; case 11: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3, _x4) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 161 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Grep lines", args: ["match"], exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { var data; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: data = void 0; case 1: _context.next = 3; return streams.stdin.read(); case 3: _context.t0 = data = _context.sent; if (!(_context.t0 !== false)) { _context.next = 10; break; } if (!data.includes(args.match)) { _context.next = 8; break; } _context.next = 8; return streams.stdout.write(data); case 8: _context.next = 1; break; case 10: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Echo string", args: ["string"], exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return streams.stdout.write(args.string); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _getIterator2 = __webpack_require__(20); var _getIterator3 = _interopRequireDefault(_getIterator2); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Show last lines", args: ["?count"], exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { var data, count, buffer, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _data; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: data = void 0; count = args.count || 10; buffer = []; case 3: _context.next = 5; return streams.stdin.read(); case 5: _context.t0 = data = _context.sent; if (!(_context.t0 !== false)) { _context.next = 11; break; } buffer.push(data); if (buffer.length > count) { buffer.shift(); } _context.next = 3; break; case 11: _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context.prev = 14; _iterator = (0, _getIterator3.default)(buffer); case 16: if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { _context.next = 23; break; } _data = _step.value; _context.next = 20; return streams.stdout.write(_data); case 20: _iteratorNormalCompletion = true; _context.next = 16; break; case 23: _context.next = 29; break; case 25: _context.prev = 25; _context.t1 = _context["catch"](14); _didIteratorError = true; _iteratorError = _context.t1; case 29: _context.prev = 29; _context.prev = 30; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 32: _context.prev = 32; if (!_didIteratorError) { _context.next = 35; break; } throw _iteratorError; case 35: return _context.finish(32); case 36: return _context.finish(29); case 37: case "end": return _context.stop(); } } }, _callee, undefined, [[14, 25, 29, 37], [30,, 32, 36]]); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Show first lines", args: ["?count"], exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { var data, count; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: data = void 0; count = args.count || 10; case 2: _context.next = 4; return streams.stdin.read(); case 4: _context.t1 = data = _context.sent; _context.t0 = _context.t1 !== false; if (!_context.t0) { _context.next = 8; break; } _context.t0 = count > 0; case 8: if (!_context.t0) { _context.next = 14; break; } _context.next = 11; return streams.stdout.write(data); case 11: count--; _context.next = 2; break; case 14: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd /* , opts, args */) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return streams.stderr.write("Unrecognized command: " + cmd + "\n"); case 2: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3) { return _ref.apply(this, arguments); } return exec; }(), completion: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(term, cmd, name, value) { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!value) { value = cmd; } return _context2.abrupt("return", term.util.bestMatch(value, term.shell._commands())); case 2: case "end": return _context2.stop(); } } }, _callee2, undefined); })); function completion(_x4, _x5, _x6, _x7) { return _ref2.apply(this, arguments); } return completion; }() }; /***/ }), /* 166 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(32); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(33); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(50); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(51); var _inherits3 = _interopRequireDefault(_inherits2); var _base = __webpack_require__(52); var _base2 = _interopRequireDefault(_base); var _templates = __webpack_require__(127); var _templates2 = _interopRequireDefault(_templates); var _util = __webpack_require__(128); var _util2 = _interopRequireDefault(_util); var _cd = __webpack_require__(167); var _cd2 = _interopRequireDefault(_cd); var _ls = __webpack_require__(168); var _ls2 = _interopRequireDefault(_ls); var _pwd = __webpack_require__(169); var _pwd2 = _interopRequireDefault(_pwd); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PathHandler = function (_Base) { (0, _inherits3.default)(PathHandler, _Base); function PathHandler(config, shell) { (0, _classCallCheck3.default)(this, PathHandler); var _this = (0, _possibleConstructorReturn3.default)(this, (PathHandler.__proto__ || (0, _getPrototypeOf2.default)(PathHandler)).call(this, config)); _this.shell = shell; _this.current = null; _this.shell.setCommandHandler("cd", _cd2.default); _this.shell.setCommandHandler("ls", _ls2.default); _this.shell.setCommandHandler("pwd", _pwd2.default); _this.shell.setDefaultPromptRenderer(function () { return _this.getPrompt(); }); return _this; } (0, _createClass3.default)(PathHandler, [{ key: "getNode", value: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: case "end": return _context.stop(); } } }, _callee, this); })); function getNode() { return _ref.apply(this, arguments); } return getNode; }() }, { key: "getChildNodes", value: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: case "end": return _context2.stop(); } } }, _callee2, this); })); function getChildNodes() { return _ref2.apply(this, arguments); } return getChildNodes; }() }, { key: "getPrompt", value: function getPrompt() { return _templates2.default.prompt({ node: this.current }); } }, { key: "pathCompletionHandler", value: function () { var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(cmd, arg /* , line */) { var _node, lastPathSeparator, parent, partial, node, completion; return _regenerator2.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: this._log("completing '" + arg + "'"); if (arg) { _context3.next = 6; break; } this._log("completing on current"); _context3.next = 5; return this._completeChildren(this.current, ""); case 5: return _context3.abrupt("return", _context3.sent); case 6: if (!(arg[arg.length - 1] === "/")) { _context3.next = 17; break; } this._log("completing children w/o partial"); _context3.next = 10; return this.getNode(arg); case 10: _node = _context3.sent; if (_node) { _context3.next = 14; break; } this._log("no node for path"); return _context3.abrupt("return"); case 14: _context3.next = 16; return this._completeChildren(_node, ""); case 16: return _context3.abrupt("return", _context3.sent); case 17: lastPathSeparator = arg.lastIndexOf("/"); parent = arg.substr(0, lastPathSeparator + 1); partial = arg.substr(lastPathSeparator + 1); if (!(partial === ".." || partial === ".")) { _context3.next = 22; break; } return _context3.abrupt("return", { completion: "/", suggestions: [] }); case 22: this._log("completing children via parent '" + parent + "' w/ partial '" + partial + "'"); _context3.next = 25; return this.getNode(parent); case 25: node = _context3.sent; if (node) { _context3.next = 29; break; } this._log("no node for parent path"); return _context3.abrupt("return"); case 29: _context3.next = 31; return this._completeChildren(node, partial); case 31: completion = _context3.sent; if (!(completion && completion.completion === "" && completion.suggestions.length === 1)) { _context3.next = 34; break; } return _context3.abrupt("return", { completion: "/", suggestions: [] }); case 34: return _context3.abrupt("return", completion); case 35: case "end": return _context3.stop(); } } }, _callee3, this); })); function pathCompletionHandler(_x, _x2) { return _ref3.apply(this, arguments); } return pathCompletionHandler; }() }, { key: "_completeChildren", value: function () { var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(node, partial) { var childNodes; return _regenerator2.default.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.getChildNodes(node); case 2: childNodes = _context4.sent; return _context4.abrupt("return", _util2.default.bestMatch(partial, childNodes.map(function (x) { return x.name; }))); case 4: case "end": return _context4.stop(); } } }, _callee4, this); })); function _completeChildren(_x3, _x4) { return _ref4.apply(this, arguments); } return _completeChildren; }() }]); return PathHandler; }(_base2.default); exports.default = PathHandler; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Change location", args: ["path"], exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { var node, error; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return term.pathhandler.getNode(args.path); case 2: node = _context.sent; if (node) { _context.next = 8; break; } error = cmd + ": " + args.path + ": No such file or directory\n"; _context.next = 7; return streams.stderr.write(error); case 7: return _context.abrupt("return", _context.sent); case 8: term.pathhandler.current = node; case 9: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }(), completion: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(term, cmd, name, value) { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(name === "path")) { _context2.next = 4; break; } _context2.next = 3; return term.completePath(value); case 3: return _context2.abrupt("return", _context2.sent); case 4: return _context2.abrupt("return", []); case 5: case "end": return _context2.stop(); } } }, _callee2, undefined); })); function completion(_x6, _x7, _x8, _x9) { return _ref2.apply(this, arguments); } return completion; }() }; /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _getIterator2 = __webpack_require__(20); var _getIterator3 = _interopRequireDefault(_getIterator2); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "List items", args: ["?path"], opts: { 1: "Show as list" }, exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams, cmd, opts, args) { var node, separator, error, children, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, child; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!args.path) { _context.next = 6; break; } _context.next = 3; return term.pathhandler.getNode(args.path); case 3: _context.t0 = _context.sent; _context.next = 7; break; case 6: _context.t0 = term.current(); case 7: node = _context.t0; separator = !streams.stdout.isPipe() && !opts[1] ? " " : "\n"; if (node) { _context.next = 14; break; } error = "ls: " + args.path + ": No such file or directory\n"; _context.next = 13; return streams.stderr.write(error); case 13: return _context.abrupt("return", _context.sent); case 14: _context.next = 16; return term.pathhandler.getChildNodes(node); case 16: children = _context.sent; _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context.prev = 20; _iterator = (0, _getIterator3.default)(children); case 22: if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { _context.next = 29; break; } child = _step.value; _context.next = 26; return streams.stdout.write("" + child.name + separator); case 26: _iteratorNormalCompletion = true; _context.next = 22; break; case 29: _context.next = 35; break; case 31: _context.prev = 31; _context.t1 = _context["catch"](20); _didIteratorError = true; _iteratorError = _context.t1; case 35: _context.prev = 35; _context.prev = 36; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 38: _context.prev = 38; if (!_didIteratorError) { _context.next = 41; break; } throw _iteratorError; case 41: return _context.finish(38); case 42: return _context.finish(35); case 43: case "end": return _context.stop(); } } }, _callee, undefined, [[20, 31, 35, 43], [36,, 38, 42]]); })); function exec(_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); } return exec; }(), completion: function () { var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(term, cmd, name, value) { return _regenerator2.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(name === "path")) { _context2.next = 4; break; } _context2.next = 3; return term.completePath(value); case 3: return _context2.abrupt("return", _context2.sent); case 4: return _context2.abrupt("return", []); case 5: case "end": return _context2.stop(); } } }, _callee2, undefined); })); function completion(_x6, _x7, _x8, _x9) { return _ref2.apply(this, arguments); } return completion; }() }; /***/ }), /* 169 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(1); var _regenerator2 = _interopRequireDefault(_regenerator); var _asyncToGenerator2 = __webpack_require__(10); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { desc: "Print current location", exec: function () { var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(term, streams /* , cmd, opts, args */) { return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return streams.stdout.write(term.current().path + "\n"); case 2: case "end": return _context.stop(); } } }, _callee, undefined); })); function exec(_x, _x2) { return _ref.apply(this, arguments); } return exec; }() }; /***/ }) /******/ ]); }); //# sourceMappingURL=dist.js.map
'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('todos', { id: { allowNull: false, primaryKey: true, type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, }, // MAIN COLUMN title: { allowNull: false, type: Sequelize.STRING(64) }, description: { allowNull: false, type: Sequelize.STRING }, // created_at: { allowNull: false, type: Sequelize.DATE }, updated_at: { allowNull: false, type: Sequelize.DATE }, deleted_at: { allowNull: true, type: Sequelize.DATE }, // RELATION created_by: { allowNull: false, type: Sequelize.UUID, onDelete: 'cascade', references: { model: 'users', onDelete: 'cascade', } }, updated_by: { allowNull: true, type: Sequelize.STRING, }, deleted_by: { allowNull: true, type: Sequelize.STRING, } }) }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('todos') } };
from utils import default_args, name_from_file from datetime import timedelta from airflow import DAG from airflow_kubernetes_job_operator.kubernetes_job_operator import KubernetesJobOperator dag = DAG( name_from_file(__file__), default_args=default_args, description="Test base job operator", schedule_interval=None, catchup=False, ) namespace = None default_delete_policy = "IfSucceeded" with dag: KubernetesJobOperator( task_id="two-containers", namespace=namespace, body_filepath="./templates/test_multi_container_pod.yaml", dag=dag, delete_policy=default_delete_policy, ) if __name__ == "__main__": dag.clear(reset_dag_runs=True) dag.run()
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // RUN: (! %hermesc -dump-ast -pretty-json %s 2>&1 ) | %FileCheck --match-full-lines %s for (;false;) function foo() {} // CHECK: {{.*}}:10:15: error: declaration not allowed as expression statement // CHECK: for (;false;) function foo() {} // CHECK: ^~~~~~~~ for (;false;) class bar {} // CHECK: {{.*}}:15:15: error: declaration not allowed as expression statement // CHECK: for (;false;) class bar {} // CHECK: ^~~~~ for (;false;) let [x] = 3; // CHECK: {{.*}}:20:15: error: ambiguous 'let [': either a 'let' binding or a member expression // CHECK: for (;false;) let [x] = 3; // CHECK: ^~~~~ for (;false;) async function foo() {} // CHECK: {{.*}}:25:15: error: declaration not allowed as expression statement // CHECK: for (;false;) async function foo() {} // CHECK: ^~~~~
/** * @fileoverview * @enhanceable * @suppress {messageConventions} JS Compiler reports an error if a variable or * field starts with 'MSG_' and isn't a translatable message. * @public */ // GENERATED CODE -- DO NOT EDIT! var jspb = require('google-protobuf'); var goog = jspb; var global = Function('return this')(); var google_api_annotations_pb = require('../../../../../google/api/annotations_pb.js'); goog.exportSymbol('proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum', null, global); goog.exportSymbol('proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.ExternalConversionSource', null, global); /** * Generated by JsPbCodeGenerator. * @param {Array=} opt_data Optional initial data array, typically from a * server response, or constructed directly in Javascript. The array is used * in place and becomes part of the constructed object. It is not cloned. * If no data is provided, the constructed object will be empty, but still * valid. * @extends {jspb.Message} * @constructor */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum = function(opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum, jspb.Message); if (goog.DEBUG && !COMPILED) { proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.displayName = 'proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum'; } if (jspb.Message.GENERATE_TO_OBJECT) { /** * Creates an object representation of this proto suitable for use in Soy templates. * Field names that are reserved in JavaScript and will be renamed to pb_name. * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default. * For the list of reserved names please see: * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.prototype.toObject = function(opt_includeInstance) { return proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.toObject(opt_includeInstance, this); }; /** * Static version of the {@see toObject} method. * @param {boolean|undefined} includeInstance Whether to include the JSPB * instance for transitional soy proto support: * http://goto/soy-param-migration * @param {!proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum} msg The msg instance to transform. * @return {!Object} * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.toObject = function(includeInstance, msg) { var f, obj = { }; if (includeInstance) { obj.$jspbMessageInstance = msg; } return obj; }; } /** * Deserializes binary data (in protobuf wire format). * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum} */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.deserializeBinary = function(bytes) { var reader = new jspb.BinaryReader(bytes); var msg = new proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum; return proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.deserializeBinaryFromReader(msg, reader); }; /** * Deserializes binary data (in protobuf wire format) from the * given reader into the given message object. * @param {!proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum} msg The message object to deserialize into. * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum} */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.deserializeBinaryFromReader = function(msg, reader) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } var field = reader.getFieldNumber(); switch (field) { default: reader.skipField(); break; } } return msg; }; /** * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.prototype.serializeBinary = function() { var writer = new jspb.BinaryWriter(); proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.serializeBinaryToWriter(this, writer); return writer.getResultBuffer(); }; /** * Serializes the given message to binary data (in protobuf wire * format), writing to the given BinaryWriter. * @param {!proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum} message * @param {!jspb.BinaryWriter} writer * @suppress {unusedLocalVariables} f is only used for nested messages */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.serializeBinaryToWriter = function(message, writer) { var f = undefined; }; /** * @enum {number} */ proto.google.ads.googleads.v1.enums.ExternalConversionSourceEnum.ExternalConversionSource = { UNSPECIFIED: 0, UNKNOWN: 1, WEBPAGE: 2, ANALYTICS: 3, UPLOAD: 4, AD_CALL_METRICS: 5, WEBSITE_CALL_METRICS: 6, STORE_VISITS: 7, ANDROID_IN_APP: 8, IOS_IN_APP: 9, IOS_FIRST_OPEN: 10, APP_UNSPECIFIED: 11, ANDROID_FIRST_OPEN: 12, UPLOAD_CALLS: 13, FIREBASE: 14, CLICK_TO_CALL: 15, SALESFORCE: 16, STORE_SALES_CRM: 17, STORE_SALES_PAYMENT_NETWORK: 18, GOOGLE_PLAY: 19, THIRD_PARTY_APP_ANALYTICS: 20, GOOGLE_ATTRIBUTION: 21, STORE_SALES_DIRECT: 22 }; goog.object.extend(exports, proto.google.ads.googleads.v1.enums);
const createError = require("http-errors"); const OktaJwtVerifier = require("@okta/jwt-verifier"); const oktaVerifierConfig = require("../../config/okta"); const Profiles = require("../profile/profileModel"); const oktaJwtVerifier = new OktaJwtVerifier(oktaVerifierConfig.config); const makeProfileObj = (claims) => { return { id: claims.sub, email: claims.email, name: claims.name, }; }; /** * A simple middleware that asserts valid Okta idToken and sends 401 responses * if the token is not present or fails validation. If the token is valid its * contents are attached to req.profile */ // const authRequired = async (req, res, next) => { // try { // const authHeader = req.headers.authorization || ""; // const match = authHeader.match(/Bearer (.+)/); // // if (!match) throw new Error("Missing idToken"); // // const idToken = match[1]; // oktaJwtVerifier // .verifyAccessToken(idToken, oktaVerifierConfig.expectedAudience) // .then(async (data) => { // const jwtUserObj = makeProfileObj(data.claims); // const profile = await Profiles.findOrCreateUser(jwtUserObj); // if (profile) { // req.profile = profile; // } else { // throw new Error("Unable to process idToken"); // } // next(); // }); // } catch (err) { // next(createError(401, err.message)); // } // }; // UNCOMMENT BELOW AND COMMENT ABOVE FOR TEST FILES TO PASS THE AUTHENTICATION const authRequired = (req, res, next) => { next(); }; module.exports = authRequired;
const Promise = require('bluebird'), _ = require('lodash'), uuid = require('uuid'), crypto = require('crypto'), keypair = require('keypair'), ghostBookshelf = require('./base'), common = require('../lib/common'), validation = require('../data/validation'), settingsCache = require('../services/settings/cache'), internalContext = {context: {internal: true}}; let Settings, defaultSettings; const doBlock = fn => fn(); const getMembersKey = doBlock(() => { let UNO_KEYPAIRINO; return function getMembersKey(type) { if (!UNO_KEYPAIRINO) { UNO_KEYPAIRINO = keypair({bits: 1024}); } return UNO_KEYPAIRINO[type]; }; }); const getGhostKey = doBlock(() => { let UNO_KEYPAIRINO; return function getGhostKey(type) { if (!UNO_KEYPAIRINO) { UNO_KEYPAIRINO = keypair({bits: 1024}); } return UNO_KEYPAIRINO[type]; }; }); // For neatness, the defaults file is split into categories. // It's much easier for us to work with it as a single level // instead of iterating those categories every time function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: () => uuid.v4(), public_hash: () => crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: () => crypto.randomBytes(32).toString('hex'), members_session_secret: () => crypto.randomBytes(32).toString('hex'), theme_session_secret: () => crypto.randomBytes(32).toString('hex'), members_public_key: () => getMembersKey('public'), members_private_key: () => getMembersKey('private'), members_email_auth_secret: () => crypto.randomBytes(64).toString('hex'), ghost_public_key: () => getGhostKey('public'), ghost_private_key: () => getGhostKey('private') }; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; setting.getDefaultValue = function getDefaultValue() { const getDynamicDefault = dynamicDefault[setting.key]; if (getDynamicDefault) { return getDynamicDefault(); } else { return setting.defaultValue; } }; defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; } function getDefaultSettings() { if (!defaultSettings) { defaultSettings = parseDefaultSettings(); } return defaultSettings; } // Each setting is saved as a separate row in the database, // but the overlying API treats them as a single key:value mapping Settings = ghostBookshelf.Model.extend({ tableName: 'settings', defaults: function defaults() { return { type: 'core' }; }, emitChange: function emitChange(event, options) { const eventToTrigger = 'settings' + '.' + event; ghostBookshelf.Model.prototype.emitChange.bind(this)(this, eventToTrigger, options); }, onDestroyed: function onDestroyed(model, options) { ghostBookshelf.Model.prototype.onDestroyed.apply(this, arguments); model.emitChange('deleted', options); model.emitChange(model._previousAttributes.key + '.' + 'deleted', options); }, onCreated: function onCreated(model, response, options) { ghostBookshelf.Model.prototype.onCreated.apply(this, arguments); model.emitChange('added', options); model.emitChange(model.attributes.key + '.' + 'added', options); }, onUpdated: function onUpdated(model, response, options) { ghostBookshelf.Model.prototype.onUpdated.apply(this, arguments); model.emitChange('edited', options); model.emitChange(model.attributes.key + '.' + 'edited', options); }, onValidate: function onValidate() { var self = this; return ghostBookshelf.Model.prototype.onValidate.apply(this, arguments) .then(function then() { return validation.validateSettings(getDefaultSettings(), self); }); }, format() { const attrs = ghostBookshelf.Model.prototype.format.apply(this, arguments); // @NOTE: type TEXT will transform boolean to "0" if (_.isBoolean(attrs.value)) { attrs.value = attrs.value.toString(); } return attrs; }, parse() { const attrs = ghostBookshelf.Model.prototype.parse.apply(this, arguments); // transform "0" to false // transform "false" to false if (attrs.value === '0' || attrs.value === '1') { attrs.value = !!+attrs.value; } if (attrs.value === 'false' || attrs.value === 'true') { attrs.value = JSON.parse(attrs.value); } return attrs; } }, { findOne: function (data, options) { if (_.isEmpty(data)) { options = data; } // Allow for just passing the key instead of attributes if (!_.isObject(data)) { data = {key: data}; } return Promise.resolve(ghostBookshelf.Model.findOne.call(this, data, options)); }, edit: function (data, unfilteredOptions) { var options = this.filterOptions(unfilteredOptions, 'edit'), self = this; if (!Array.isArray(data)) { data = [data]; } return Promise.map(data, function (item) { // Accept an array of models as input if (item.toJSON) { item = item.toJSON(); } if (!(_.isString(item.key) && item.key.length > 0)) { return Promise.reject(new common.errors.ValidationError({message: common.i18n.t('errors.models.settings.valueCannotBeBlank')})); } item = self.filterData(item); return Settings.forge({key: item.key}).fetch(options).then(function then(setting) { if (setting) { // it's allowed to edit all attributes in case of importing/migrating if (options.importing) { return setting.save(item, options); } else { // If we have a value, set it. if (Object.prototype.hasOwnProperty.call(item, 'value')) { setting.set('value', item.value); } // Internal context can overwrite type (for fixture migrations) if (options.context && options.context.internal && Object.prototype.hasOwnProperty.call(item, 'type')) { setting.set('type', item.type); } // If anything has changed, save the updated model if (setting.hasChanged()) { return setting.save(null, options); } return setting; } } return Promise.reject(new common.errors.NotFoundError({message: common.i18n.t('errors.models.settings.unableToFindSetting', {key: item.key})})); }); }); }, populateDefaults: function populateDefaults(unfilteredOptions) { var options = this.filterOptions(unfilteredOptions, 'populateDefaults'), self = this; if (!options.context) { options.context = internalContext.context; } return this .findAll(options) .then(function checkAllSettings(allSettings) { var usedKeys = allSettings.models.map(function mapper(setting) { return setting.get('key'); }), insertOperations = []; _.each(getDefaultSettings(), function forEachDefault(defaultSetting, defaultSettingKey) { var isMissingFromDB = usedKeys.indexOf(defaultSettingKey) === -1; if (isMissingFromDB) { defaultSetting.value = defaultSetting.getDefaultValue(); insertOperations.push(Settings.forge(defaultSetting).save(null, options)); } }); if (insertOperations.length > 0) { return Promise.all(insertOperations).then(function fetchAllToReturn() { return self.findAll(options); }); } return allSettings; }); }, permissible: function permissible(modelId, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasAppPermission, hasApiKeyPermission) { let isEdit = (action === 'edit'); let isOwner; function isChangingMembers() { if (unsafeAttrs && unsafeAttrs.key === 'labs') { let editedValue = JSON.parse(unsafeAttrs.value); if (editedValue.members !== undefined) { return editedValue.members !== settingsCache.get('labs').members; } } } isOwner = loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Owner'}); if (isEdit && isChangingMembers()) { // Only allow owner to toggle members flag hasUserPermission = isOwner; } if (hasUserPermission && hasApiKeyPermission && hasAppPermission) { return Promise.resolve(); } return Promise.reject(new common.errors.NoPermissionError({ message: common.i18n.t('errors.models.post.notEnoughPermission') })); } }); module.exports = { Settings: ghostBookshelf.model('Settings', Settings) };
const { promisify } = require('util'); const build = promisify(require('electron-build-env')); build(['yarn', 'build:neon'], { electron: process.env.CURRENT_ELECTRON_VERSION }).then(() => process.exit(0));
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var AccountSchema = new Schema({ customerId: String, accountId: String, uci: String, riskScore: String, currencyCode: String, productType: String, loanAmount: Number, loanPurpose: String }, {collection: 'account_info'}); module.exports = mongoose.model('Account', AccountSchema);
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import time import matplotlib.pyplot as plt import os import sys path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if not path in sys.path: sys.path.insert(1, path) import nussl def speed_test(): freq = 3000 sr = nussl.constants.DEFAULT_SAMPLE_RATE # 44.1kHz dur = np.arange(5, 121, 5) # five second intervals from 5-120 seconds lengths = dur * sr trials = 25 librosa_stft_times = {} librosa_istft_times = {} nussl_stft_times = {} nussl_istft_times = {} # Make the signals and test for cur_len in lengths: librosa_stft_times[cur_len] = [] nussl_stft_times[cur_len] = [] librosa_istft_times[cur_len] = [] nussl_istft_times[cur_len] = [] for i in range(trials): # Make a new signal sig = np.array(np.sin(np.linspace(0, freq * 2 * np.pi, cur_len))) a = nussl.AudioSignal(audio_data_array=sig) n_st = time.time() nussl_stft = a.stft(use_librosa=False) n_end = time.time() - n_st nussl_stft_times[cur_len].append(n_end) a = nussl.AudioSignal(audio_data_array=sig) l_st = time.time() librosa_stft = a.stft(use_librosa=True) l_end = time.time() - l_st librosa_stft_times[cur_len].append(l_end) a = nussl.AudioSignal(stft=nussl_stft) n_st = time.time() a.istft(use_librosa=False) n_end = time.time() - n_st nussl_istft_times[cur_len].append(n_end) a = nussl.AudioSignal(stft=librosa_stft) l_st = time.time() a.istft(use_librosa=True) l_end = time.time() - l_st librosa_istft_times[cur_len].append(l_end) # Average over all trials nussl_stft_avg = [] librosa_stft_avg = [] nussl_istft_avg = [] librosa_istft_avg = [] for cur_len in lengths: nussl_stft_avg.append(np.mean(nussl_stft_times[cur_len])) librosa_stft_avg.append(np.mean(librosa_stft_times[cur_len])) nussl_istft_avg.append(np.mean(nussl_istft_times[cur_len])) librosa_istft_avg.append(np.mean(librosa_istft_times[cur_len])) # Plot STFT avgs plt.plot(lengths / sr, nussl_stft_avg, label='nussl stft') plt.plot(lengths / sr, librosa_stft_avg, label='librosa stft') plt.xlabel('Length of signal (sec)') plt.ylabel('Time to do STFT (sec)') plt.legend(loc='lower right') plt.title('Average time taken to do STFT over {} trials'.format(trials)) plt.savefig('speed_test_stft.png') # Plot iSTFT avgs plt.close('all') plt.plot(lengths / sr, nussl_istft_avg, label='nussl istft') plt.plot(lengths / sr, librosa_istft_avg, label='librosa istft') plt.xlabel('Length of signal (sec)') plt.ylabel('Time to do iSTFT (sec)') plt.legend(loc='lower right') plt.title('Average time taken to do iSTFT over {} trials'.format(trials)) plt.savefig('speed_test_istft.png') if __name__ == '__main__': speed_test()
import os MILVUS_HOST = os.getenv("MILVUS_HOST", "127.0.0.1") MILVUS_PORT = os.getenv("MILVUS_PORT", 19530) VECTOR_DIMENSION = os.getenv("VECTOR_DIMENSION", 512) DATA_PATH = os.getenv("DATA_PATH", "/data/jpegimages") DEFAULT_TABLE = os.getenv("DEFAULT_TABLE", "milvus") UPLOAD_PATH = "/tmp/search-images"
var data=[['20160812',4.839], ['20160815',5.335], ['20160816',5.879], ['20160817',6.478], ['20160818',7.138], ['20160819',7.866], ['20160822',8.665], ['20160823',9.545], ['20160824',10.509], ['20160825',11.571], ['20160826',12.741], ['20160829',14.027], ['20160830',15.442], ['20160831',17.000], ['20160901',18.710], ['20160902',20.594], ['20160905',22.665], ['20160906',24.942], ['20160907',26.027], ['20160908',24.326], ['20160909',23.348], ['20160912',25.696], ['20160913',24.647], ['20160914',23.938], ['20160919',24.147], ['20160920',24.473], ['20160921',23.915], ['20160922',22.942], ['20160923',22.205], ['20160926',21.089], ['20160927',21.183], ['20160928',21.982], ['20160929',23.304], ['20160930',22.397], ['20161010',23.299], ['20161011',24.393], ['20161012',24.071], ['20161013',23.353], ['20161014',23.536], ['20161017',23.527], ['20161018',23.634], ['20161019',23.679], ['20161020',23.357], ['20161021',22.911], ['20161024',22.786], ['20161025',23.839], ['20161026',23.054], ['20161027',24.125], ['20161028',24.170], ['20161031',22.527], ['20161101',22.804], ['20161102',22.875], ['20161103',22.598], ['20161104',23.545], ['20161107',23.768], ['20161108',24.772], ['20161109',26.982], ['20161110',27.071], ['20161111',26.223], ['20161114',25.241], ['20161115',25.406], ['20161116',24.013], ['20161117',23.991], ['20161118',24.036], ['20161121',24.536], ['20161122',25.482], ['20161123',24.304], ['20161124',24.478], ['20161125',24.424], ['20161128',24.790], ['20161129',23.616], ['20161130',22.777], ['20161201',23.071], ['20161202',22.228], ['20161205',21.938], ['20161206',22.027], ['20161207',22.129], ['20161208',21.817], ['20161209',21.232], ['20161212',19.103], ['20161213',19.000], ['20161214',19.875], ['20161215',19.674], ['20161216',19.527], ['20161219',19.406], ['20161220',19.156], ['20161221',19.393], ['20161222',19.705], ['20161223',18.509], ['20161226',18.835], ['20161227',18.705], ['20161228',18.299], ['20161229',18.138], ['20161230',18.129], ['20170103',18.482], ['20170104',18.826], ['20170105',18.375], ['20170106',17.701], ['20170109',17.397], ['20170110',17.335], ['20170111',16.594], ['20170112',16.451], ['20170113',15.366], ['20170116',14.308], ['20170117',14.964], ['20170118',14.460], ['20170119',14.692], ['20170120',15.058], ['20170123',15.129], ['20170124',14.701], ['20170125',14.938], ['20170126',15.143], ['20170203',14.978], ['20170206',15.455], ['20170207',15.504], ['20170208',15.938], ['20170209',15.893], ['20170210',15.625], ['20170213',16.045], ['20170214',16.933], ['20170215',17.295], ['20170216',17.710], ['20170217',17.107], ['20170220',16.455], ['20170221',16.741], ['20170222',16.366], ['20170223',16.554], ['20170224',16.652], ['20170227',16.549], ['20170228',16.531], ['20170301',16.679], ['20170302',16.446], ['20170303',16.621], ['20170306',17.295], ['20170307',17.339], ['20170308',17.839], ['20170309',19.634], ['20170310',19.366], ['20170313',18.942], ['20170314',19.147], ['20170315',18.397], ['20170316',18.692], ['20170317',18.446], ['20170320',18.545], ['20170321',18.969], ['20170322',19.348], ['20170323',18.942], ['20170324',20.330], ['20170327',20.268], ['20170328',18.893], ['20170329',17.504], ['20170330',16.929], ['20170331',16.839], ['20170405',17.036], ['20170406',17.719], ['20170407',17.116], ['20170410',15.629], ['20170411',16.004], ['20170412',16.313], ['20170413',16.375], ['20170414',16.348], ['20170417',15.469], ['20170418',15.634], ['20170419',15.879], ['20170420',16.036], ['20170421',15.866], ['20170424',15.009], ['20170425',15.161], ['20170426',15.286], ['20170427',15.455], ['20170428',15.335], ['20170502',14.853], ['20170503',15.067], ['20170504',14.982], ['20170505',15.576], ['20170508',15.656], ['20170509',15.732], ['20170510',15.554], ['20170511',15.290], ['20170512',14.996], ['20170515',14.781], ['20170516',15.388], ['20170517',15.246], ['20170518',15.348], ['20170519',15.125], ['20170522',14.201], ['20170523',12.866], ['20170524',12.741], ['20170525',12.616], ['20170526',12.763], ['20170531',12.781], ['20170601',11.714], ['20170602',12.094], ['20170605',12.098], ['20170606',12.536], ['20170607',13.308], ['20170608',13.317], ['20170609',13.353], ['20170612',12.951], ['20170613',13.350], ['20170614',13.214], ['20170615',13.857], ['20170616',13.471], ['20170619',13.436], ['20170620',13.336], ['20170621',13.357], ['20170622',12.743], ['20170623',13.121], ['20170626',13.221], ['20170627',13.271], ['20170628',13.057], ['20170629',13.064], ['20170630',13.000], ['20170703',13.014], ['20170704',12.936], ['20170705',13.114], ['20170706',13.086], ['20170707',13.271], ['20170710',12.950], ['20170711',12.600], ['20170712',12.407], ['20170713',12.093], ['20170714',11.986], ['20170717',10.779], ['20170718',10.886], ['20170719',11.114], ['20170720',11.507], ['20170721',11.614], ['20170724',11.550], ['20170725',11.871], ['20170726',11.950], ['20170727',12.329], ['20170728',12.714], ['20170731',12.764], ['20170801',12.943], ['20170802',12.643], ['20170803',12.693], ['20170804',12.221], ['20170807',12.371], ['20170808',12.321], ['20170809',12.279], ['20170810',12.036], ['20170811',11.893], ['20170814',11.886], ['20170815',11.743], ['20170816',12.021], ['20170817',11.871], ['20170818',11.571], ['20170821',11.793], ['20170822',11.571], ['20170823',11.586], ['20170824',11.471], ['20170825',11.786], ['20170828',11.986], ['20170829',11.986], ['20170830',11.936], ['20170831',11.786], ['20170901',11.650], ['20170904',11.457], ['20170905',11.543], ['20170906',11.507], ['20170907',11.643], ['20170908',11.514], ['20170911',11.593], ['20170912',11.436], ['20170913',11.300], ['20170914',11.164], ['20170915',11.207], ['20170918',11.300], ['20170919',11.129], ['20170920',11.257], ['20170921',11.914], ['20170922',12.600], ['20170925',12.129], ['20170926',11.807], ['20170927',12.179], ['20170928',11.893], ['20170929',12.021], ['20171009',11.979], ['20171010',12.214], ['20171011',12.021], ['20171012',12.007], ['20171013',12.000], ['20171016',11.379], ['20171017',11.343], ['20171018',11.143], ['20171019',10.764], ['20171020',10.907], ['20171023',10.986], ['20171024',10.986], ['20171025',11.429], ['20171026',11.371], ['20171027',11.207], ['20171030',10.929], ['20171031',11.057], ['20171101',11.214], ['20171102',11.200], ['20171103',10.957], ['20171106',11.071], ['20171107',10.971], ['20171108',11.214], ['20171109',11.186], ['20171110',11.164], ['20171113',10.993], ['20171114',10.943], ['20171115',10.993], ['20171116',10.907], ['20171117',10.614], ['20171120',10.829], ['20171121',11.014], ['20171122',10.786], ['20171123',10.536], ['20171124',10.414], ['20171127',10.021], ['20171128',10.214], ['20171129',9.993], ['20171130',9.629], ['20171201',9.629], ['20171204',9.393], ['20171205',8.450], ['20171206',8.271], ['20171207',8.307], ['20171208',8.379], ['20171211',8.514], ['20171212',8.271], ['20171213',8.421], ['20171214',8.436], ['20171215',8.471], ['20171218',8.307], ['20171219',8.400], ['20171220',8.157], ['20171221',8.143], ['20171222',8.029], ['20171225',7.821], ['20171226',8.436], ['20171227',8.214], ['20171228',8.186], ['20171229',8.493], ['20180102',8.429], ['20180103',8.443], ['20180104',8.643], ['20180105',9.329], ['20180108',8.986], ['20180109',8.779], ['20180110',8.529], ['20180111',8.636], ['20180112',8.493], ['20180115',8.114], ['20180116',8.200], ['20180117',8.336], ['20180118',8.329], ['20180119',8.293], ['20180122',8.379], ['20180123',8.600], ['20180124',8.614], ['20180125',8.529], ['20180126',8.429], ['20180129',8.343], ['20180130',8.329], ['20180131',8.014], ['20180201',7.686], ['20180202',7.593], ['20180205',7.429], ['20180206',6.971], ['20180207',7.079], ['20180208',7.164], ['20180209',6.936], ['20180212',7.121], ['20180213',7.036], ['20180214',7.086], ['20180222',7.193], ['20180223',7.221], ['20180226',7.443], ['20180227',7.571], ['20180228',7.721], ['20180301',8.086], ['20180302',7.993], ['20180305',8.029], ['20180306',8.136], ['20180307',7.986], ['20180308',7.971], ['20180309',8.107], ['20180312',8.371], ['20180313',8.379], ['20180314',8.179], ['20180315',7.929], ['20180316',7.929], ['20180319',8.014], ['20180320',8.157], ['20180321',8.221], ['20180322',8.250], ['20180323',7.736], ['20180326',8.514], ['20180327',8.721], ['20180328',8.429], ['20180329',8.707], ['20180330',8.714], ['20180402',8.514], ['20180403',8.464], ['20180404',8.714], ['20180409',8.986], ['20180410',8.879], ['20180411',9.129], ['20180412',9.157], ['20180413',8.950], ['20180416',8.779], ['20180417',8.621], ['20180418',9.007], ['20180419',9.271], ['20180420',9.107], ['20180423',9.636], ['20180424',9.657], ['20180425',9.750], ['20180426',9.236], ['20180427',9.279], ['20180502',9.014], ['20180503',9.921], ['20180504',9.850], ['20180507',9.786], ['20180508',9.779], ['20180509',9.500], ['20180510',9.707], ['20180511',9.457], ['20180514',9.521], ['20180515',9.514], ['20180516',9.443], ['20180517',9.029], ['20180518',8.886], ['20180521',9.086], ['20180522',9.186], ['20180523',9.057], ['20180524',9.171], ['20180525',9.357], ['20180528',9.407], ['20180529',9.557], ['20180530',9.443], ['20180531',9.750], ['20180601',9.429], ['20180604',8.479], ['20180605',8.350], ['20180606',8.536], ['20180607',8.329], ['20180608',7.893], ['20180611',7.907], ['20180612',7.957], ['20180613',7.836], ['20180614',7.764], ['20180615',7.357], ['20180619',6.993], ['20180620',7.086], ['20180621',6.657], ['20180622',7.329], ['20180625',7.221], ['20180626',7.407], ['20180627',7.357], ['20180628',7.264], ['20180629',7.329], ['20180702',7.286], ['20180703',7.543], ['20180704',7.307], ['20180705',7.343], ['20180706',7.264], ['20180709',7.400], ['20180710',7.464], ['20180711',7.314], ['20180712',7.643], ['20180713',7.707], ['20180716',7.514], ['20180717',7.536], ['20180718',7.493], ['20180719',7.450], ['20180720',7.479], ['20180723',7.650], ['20180724',7.693], ['20180725',7.664], ['20180726',7.686], ['20180727',7.593], ['20180730',7.393], ['20180731',7.414], ['20180801',7.371], ['20180802',7.679], ['20180803',7.336], ['20180806',7.257], ['20180807',7.393], ['20180808',7.379], ['20180809',7.500], ['20180810',7.557], ['20180813',7.700], ['20180814',7.686], ['20180815',7.629], ['20180816',7.757], ['20180817',8.536], ['20180820',8.936], ['20180821',9.136], ['20180822',8.693], ['20180823',8.607], ['20180824',8.450], ['20180827',8.421], ['20180828',8.929], ['20180829',8.407], ['20180830',8.293], ['20180831',8.043], ['20180903',8.064], ['20180904',8.507], ['20180905',8.500], ['20180906',8.736], ['20180907',8.707], ['20180910',8.893], ['20180911',8.571], ['20180912',8.571], ['20180913',8.571], ['20180914',8.621], ['20180917',8.471], ['20180918',8.600], ['20180919',8.600], ['20180920',8.393], ['20180921',8.679], ['20180925',9.021], ['20180926',9.214], ['20180927',9.221], ['20180928',9.357], ['20181008',9.564], ['20181009',9.543], ['20181010',9.514], ['20181011',9.636], ['20181012',10.029], ['20181015',10.643], ['20181016',10.607], ['20181017',10.479], ['20181018',10.014], ['20181019',9.814], ['20181022',10.136], ['20181023',9.879], ['20181024',10.107], ['20181025',9.879], ['20181026',9.907], ['20181029',9.914], ['20181030',9.107], ['20181031',9.307], ['20181101',9.350], ['20181102',9.729], ['20181105',9.664], ['20181106',9.450], ['20181107',9.314], ['20181108',9.693], ['20181109',9.779], ['20181112',9.771], ['20181113',9.786], ['20181114',9.764], ['20181115',9.736], ['20181116',10.014], ['20181119',10.336], ['20181120',9.650], ['20181121',9.086], ['20181122',9.079], ['20181123',8.857], ['20181126',8.914], ['20181127',9.000], ['20181128',9.071], ['20181129',9.071], ['20181130',9.064], ['20181203',9.193], ['20181204',9.129], ['20181205',8.964], ['20181206',8.771], ['20181207',9.071], ['20181210',8.907], ['20181211',8.929], ['20181212',8.936], ['20181213',8.871], ['20181214',8.821], ['20181217',8.757], ['20181218',8.714], ['20181219',8.664], ['20181220',8.679], ['20181221',8.721], ['20181224',8.807], ['20181225',8.986], ['20181226',8.886], ['20181227',9.036], ['20181228',9.107], ['20190102',9.071], ['20190103',9.121], ['20190104',9.179], ['20190107',9.293], ['20190108',9.157], ['20190109',9.107], ['20190110',8.986], ['20190111',8.836], ['20190114',8.821], ['20190115',9.107], ['20190116',9.450], ['20190117',9.307], ['20190118',9.300], ['20190121',9.343], ['20190122',9.521], ['20190123',9.471], ['20190124',9.393], ['20190125',9.193], ['20190128',9.079], ['20190129',9.243], ['20190130',8.864], ['20190131',8.671], ['20190201',8.857], ['20190211',8.893], ['20190212',8.893], ['20190213',9.336], ['20190214',9.250], ['20190215',9.300], ['20190218',9.529], ['20190219',9.743], ['20190220',9.529], ['20190221',9.543], ['20190222',9.750], ['20190225',10.014], ['20190226',10.036], ['20190227',10.107], ['20190228',10.043], ['20190301',9.993], ['20190304',10.221], ['20190305',10.236], ['20190306',10.486], ['20190307',10.629], ['20190308',11.150], ['20190311',11.900], ['20190312',11.900], ['20190313',11.821], ['20190314',11.950], ['20190315',11.964], ['20190318',12.250], ['20190319',11.829], ['20190320',12.014], ['20190321',12.029], ['20190322',11.857], ['20190325',11.607], ['20190326',11.050], ['20190327',11.271], ['20190328',10.821], ['20190329',10.971], ['20190401',11.236], ['20190402',11.193], ['20190403',11.193], ['20190404',11.950], ['20190408',12.686], ['20190409',12.643], ['20190410',12.593], ['20190411',12.464], ['20190412',12.657], ['20190415',13.286], ['20190416',13.529], ['20190417',13.536], ['20190418',13.436], ['20190419',13.350], ['20190422',13.186], ['20190423',13.414], ['20190424',13.179], ['20190425',13.350], ['20190426',13.486], ['20190429',13.436], ['20190430',13.236], ['20190506',11.907], ['20190507',11.207], ['20190508',10.086], ['20190509',9.071], ['20190510',9.507], ['20190513',9.407], ['20190514',9.193], ['20190515',9.343], ['20190516',9.621], ['20190517',9.243], ['20190520',8.936], ['20190521',9.107], ['20190522',9.143], ['20190523',8.900], ['20190524',8.921], ['20190527',9.307], ['20190528',9.171], ['20190529',9.129], ['20190530',9.143], ['20190531',9.371], ['20190603',9.243], ['20190604',9.100], ['20190605',9.071], ['20190606',9.221], ['20190610',9.579], ['20190611',9.779], ['20190612',9.607], ['20190613',9.764], ['20190614',9.464], ['20190617',9.471], ['20190618',9.414], ['20190619',9.850], ['20190620',9.786], ['20190621',9.821], ['20190624',9.657], ['20190625',9.621], ['20190626',9.614], ['20190627',9.614]]; var source='wstock.net';
"use strict"; // html demo $('#html').jstree(); // inline data demo $('#data').jstree({ 'core': { 'data': [ { "text": "Root node", "children": [ { "text": "Child node 1" }, { "text": "Child node 2" } ] } ] } }); // data format demo $('#frmt').jstree({ 'core': { 'data': [ { "text": "Root node", "state": { "opened": true }, "children": [ { "text": "Child node 1", "state": { "selected": true }, "icon": "jstree-file" }, { "text": "Child node 2", "state": { "disabled": true } } ] } ] } }); // ajax demo $('#ajax').jstree({ 'core': { 'data': { "url": "./root.json", "dataType": "json" // needed only if you do not supply JSON headers } } }); // lazy demo $('#lazy').jstree({ 'core': { 'data': { "url": "//www.jstree.com/fiddle/?lazy", "data": function (node) { return { "id": node.id }; } } } }); // data from callback $('#clbk').jstree({ 'core': { 'data': function (node, cb) { if (node.id === "#") { cb([{ "text": "Root", "id": "1", "children": true }]); } else { cb(["Child"]); } } } }); // interaction and events $('#evts_button').on("click", function () { var instance = $('#evts').jstree(true); instance.deselect_all(); instance.select_node('1'); }); $('#evts') .on("changed.jstree", function (e, data) { if (data.selected.length) { alert('The selected node is: ' + data.instance.get_node(data.selected[0]).text); } }) .jstree({ 'core': { 'multiple': false, 'data': [ { "text": "Root node", "children": [ { "text": "Child node 1", "id": 1 }, { "text": "Child node 2" } ] } ] } });
// D3 experiments for building Risk Battle probability charts // d3x02.html d3x02.js // Drawing the charts from pre-configured data // Compute graph specs var dx = Math.floor(500 / dataSpecs.graphDepth); var x0 = Math.floor(dx / 2); var dy = Math.floor(300 / dataSpecs.graphHeight); // SVG var svg = d3.select('#chart2') .append('svg') .attr('width', 500) .attr('height', 600) .style('border', '5px solid #666666'); // Caption var topCaptions = svg.append('text') .attr('x', 50) .attr('y', 30) .style('font', '16px sans-serif') .style('stroke', '#666666') .text('Risk-style Dice Battles - Probability Tree Chart'); // Update lines - draw the lines // Update lines - draw the diagonal part svg.selectAll('line-diag') .data(dataLines) .enter() .append('line') .attr('class', 'line-diag') .attr('x1', function (d) { return x0 + dx * d.end0[0]; }) .attr('y1', function (d) { return dy * d.end0[1]; }) .attr('x2', function (d) { return x0 + dx * (d.end0[0] + 1); }) .attr('y2', function (d) { return dy * d.end1[1]; }) .attr('stroke-width', 2) .style('stroke', function(d) { if (d.type == 'pw' || d.type == 'pww') {return '#339933';} if (d.type == 'pl' || d.type == 'pll') {return '#993333';} if (d.type == 'pwl') {return '#333399';} }); // Update lines - draw the straight part svg.selectAll('line-ext') .data(dataLines) .enter() .append('line') .attr('class', 'line-ext') .attr('x1', function (d) { return x0 + dx * (d.end0[0] + 1); }) .attr('y1', function (d) { return dy * d.end1[1]; }) .attr('x2', function (d) { return x0 + dx * d.end1[0]; }) .attr('y2', function (d) { return dy * d.end1[1]; }) .attr('stroke-width', 2) .style('stroke', function(d) { if (d.type == 'pw' || d.type == 'pww') {return '#339933';} if (d.type == 'pl' || d.type == 'pll') {return '#993333';} if (d.type == 'pwl') {return '#333399';} }); // Update nodes - draw the dot svg.selectAll('node-dot') .data(dataNodes) .enter() .append('circle') .attr('class', 'node-dot') .attr('cx', function (d) { return x0 + dx * d.loc[0]; }) .attr('cy', function (d) { return dy * d.loc[1]; }) .attr('r', 4) .style('fill', '#333399'); // Update nodes - show number of attacking armies svg.selectAll('att-number') .data(dataNodes) .enter() .append('text') .attr('class', 'att-number') .attr('x', function (d) { return x0 + dx * d.loc[0] - 10; }) .attr('y', function (d) { return dy * d.loc[1] - 5; }) .style('stroke', '#339933') .style('font', '14px sans-serif') .text(function (d) { return d.att.toString()}); // Update nodes - show number of defending armies svg.selectAll('def-number') .data(dataNodes) .enter() .append('text') .attr('class', 'def-number') .attr('x', function (d) { return x0 + dx * d.loc[0] - 10; }) .attr('y', function (d) { return dy * d.loc[1] + 15; }) .style('stroke', '#993333') .style('font', '14px sans-serif') .text(function (d) { return d.def.toString()}); // Define percentage text svg.selectAll('percent-text') .data(dataLines) .enter() .append('text') .attr('class', 'percent-text') .attr('x', function (d) { return Math.floor(x0 + dx * (d.end0[0] + 0.5) ) }) .attr('y', function (d) { return Math.floor(dy * (d.end0[1] + d.end1[1]) / 2) }) .style('font', '10px sans-serif') .style('font-weight', 'bold') .style('color', '#ff3333') .text(function (d) { return d.probsStr; });
/** * Name: Paridhi Khaitan * School: University of California, San Diego * Position: FullStack Internship * Description: A program that randomly sends users to one of two websites * Notes: It was really interesting to use Cloudflare's APIs. They are super powerful * specially the HTML Rewriter one, and I'll continue using it even after the project */ //The base url that fetches both the variants const API_URL = "https://cfw-takehome.developers.workers.dev/api/variants"; //Stores the variant array, and makes it globally available for other functions to use let variantsArray; /** * Computes the random number (which determines the group that a user is put in) * and make it globally accessible for other functions to use */ let randomNumber; addEventListener("fetch", event => { event.request = API_URL; event.respondWith(handleRequest(event.request)); }); /** * Respond with hello worker text * @param {Request} request */ async function handleRequest(request) { //Initialises HTMLRewriter on the components specified in the README let rewriter = new HTMLRewriter() .on("title", new ElementHandler()) .on("h1#title", new ElementHandler()) .on("p#description", new ElementHandler()) .on("a#url", new AttributeRewriter("href")); /** * Fetches the base API, parses the response to JSON and stores the variant array * Catches if an error occurs */ await fetch(API_URL) .then(response => { return response.json(); }) .then(response => { variantsArray = response.variants; }) .catch(error => console.log("Unable to fetch: ", error)); /** * Response returned by the cookie check function is the one that will be displayed */ let response = await cookieCheck(request); return rewriter.transform(response); } /** * An async function that checks if cookies have been established for this site. * If they have, it means a user has visited before, and the url that they * visited will persist * @param {Request} request */ async function cookieCheck(request) { //Checks cookies to see what's going on const USER_GROUP = "user-group"; const GROUP_ONE_RES = await fetch(variantsArray[0]); const GROUP_TWO_RES = await fetch(variantsArray[1]); const cookie = request.headers.get("cookie"); //If the cookies are set and the user belongs to GROUP ONE if (cookie && cookie.includes(`${USER_GROUP}=group_one`)) { randomNumber = 0; return GROUP_ONE_RES; } //If the cookies are set and the user belongs to GROUP TWO else if (cookie && cookie.includes(`${USER_GROUP}=group_two`)) { randomNumber = 1; return GROUP_TWO_RES; } //If a user is visiting for the first time, determine group and store cookies else { //Computes a random number (either 1 or 0) to determine the user group randomNumber = Math.floor((Math.random() * 100) % 2); //Gets the specific variant URL let response = await fetch(variantsArray[randomNumber]); //Copies over the response to make the headers mutiable //Source : https://developers.cloudflare.com/workers/templates/pages/alter_headers/ response = new Response(response.body, response); //Assigns the user to a group and sets the cookies for the user, //They'll always return to this variant let group = randomNumber === 0 ? "group_one" : "group_two"; response.headers.append("Set-Cookie", `${USER_GROUP}=${group}; path=/`); return response; } } /* From HTML Rewritter: Changes the inner content of the specified elements */ class ElementHandler { element(element) { //Changes the main title tag, keeps it consistent across both versions if (element.tagName === "title") { element.setInnerContent("Paridhi's Take-Home"); } //Changes the h1#title tag for different users if (element.tagName === "h1") { if (randomNumber === 0) { element.setInnerContent("I'm Paridhi, Student @UCSD"); } else { element.setInnerContent("I'm Paridhi, an advocate for diversity"); } } //Changes the p#description for different users if (element.tagName === "p") { if (randomNumber === 0) { element.setInnerContent( "I'm really passionate about the intersection of Computer Science and Design and want to better the world one line of code at a time." ); } else { element.setInnerContent( "I work with WIC (Women in Computing), ABLE (Anita B. Org Leadership) and GWC (Girls' Who Code) to promote representation in CS." ); } } } } /* To make changes to the attribute, in this case sending users who click on the button to my portfolio */ class AttributeRewriter { //Stores the attribute name constructor(attributeName) { this.attributeName = attributeName; } //Gets the href attribute of the a element. Changes it from that of cloudflare to my portfolio website element(element) { const attribute = element.getAttribute(this.attributeName); if (attribute) { element.setInnerContent("Visit My Website :)"); element.setAttribute( this.attributeName, attribute.replace( "https://cloudflare.com", "https://www.paridhikhaitan.me" ) ); } } }
# obsutil.py - utility functions for obsolescence # # Copyright 2017 Boris Feld <[email protected]> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from . import ( phases, util ) class marker(object): """Wrap obsolete marker raw data""" def __init__(self, repo, data): # the repo argument will be used to create changectx in later version self._repo = repo self._data = data self._decodedmeta = None def __hash__(self): return hash(self._data) def __eq__(self, other): if type(other) != type(self): return False return self._data == other._data def precnode(self): msg = ("'marker.precnode' is deprecated, " "use 'marker.prednode'") util.nouideprecwarn(msg, '4.4') return self.prednode() def prednode(self): """Predecessor changeset node identifier""" return self._data[0] def succnodes(self): """List of successor changesets node identifiers""" return self._data[1] def parentnodes(self): """Parents of the predecessors (None if not recorded)""" return self._data[5] def metadata(self): """Decoded metadata dictionary""" return dict(self._data[3]) def date(self): """Creation date as (unixtime, offset)""" return self._data[4] def flags(self): """The flags field of the marker""" return self._data[2] def getmarkers(repo, nodes=None, exclusive=False): """returns markers known in a repository If <nodes> is specified, only markers "relevant" to those nodes are are returned""" if nodes is None: rawmarkers = repo.obsstore elif exclusive: rawmarkers = exclusivemarkers(repo, nodes) else: rawmarkers = repo.obsstore.relevantmarkers(nodes) for markerdata in rawmarkers: yield marker(repo, markerdata) def closestpredecessors(repo, nodeid): """yield the list of next predecessors pointing on visible changectx nodes This function respect the repoview filtering, filtered revision will be considered missing. """ precursors = repo.obsstore.predecessors stack = [nodeid] seen = set(stack) while stack: current = stack.pop() currentpreccs = precursors.get(current, ()) for prec in currentpreccs: precnodeid = prec[0] # Basic cycle protection if precnodeid in seen: continue seen.add(precnodeid) if precnodeid in repo: yield precnodeid else: stack.append(precnodeid) def allprecursors(*args, **kwargs): """ (DEPRECATED) """ msg = ("'obsutil.allprecursors' is deprecated, " "use 'obsutil.allpredecessors'") util.nouideprecwarn(msg, '4.4') return allpredecessors(*args, **kwargs) def allpredecessors(obsstore, nodes, ignoreflags=0): """Yield node for every precursors of <nodes>. Some precursors may be unknown locally. This is a linear yield unsuited to detecting folded changesets. It includes initial nodes too.""" remaining = set(nodes) seen = set(remaining) while remaining: current = remaining.pop() yield current for mark in obsstore.predecessors.get(current, ()): # ignore marker flagged with specified flag if mark[2] & ignoreflags: continue suc = mark[0] if suc not in seen: seen.add(suc) remaining.add(suc) def allsuccessors(obsstore, nodes, ignoreflags=0): """Yield node for every successor of <nodes>. Some successors may be unknown locally. This is a linear yield unsuited to detecting split changesets. It includes initial nodes too.""" remaining = set(nodes) seen = set(remaining) while remaining: current = remaining.pop() yield current for mark in obsstore.successors.get(current, ()): # ignore marker flagged with specified flag if mark[2] & ignoreflags: continue for suc in mark[1]: if suc not in seen: seen.add(suc) remaining.add(suc) def _filterprunes(markers): """return a set with no prune markers""" return set(m for m in markers if m[1]) def exclusivemarkers(repo, nodes): """set of markers relevant to "nodes" but no other locally-known nodes This function compute the set of markers "exclusive" to a locally-known node. This means we walk the markers starting from <nodes> until we reach a locally-known precursors outside of <nodes>. Element of <nodes> with locally-known successors outside of <nodes> are ignored (since their precursors markers are also relevant to these successors). For example: # (A0 rewritten as A1) # # A0 <-1- A1 # Marker "1" is exclusive to A1 or # (A0 rewritten as AX; AX rewritten as A1; AX is unkown locally) # # <-1- A0 <-2- AX <-3- A1 # Marker "2,3" are exclusive to A1 or # (A0 has unknown precursors, A0 rewritten as A1 and A2 (divergence)) # # <-2- A1 # Marker "2" is exclusive to A0,A1 # / # <-1- A0 # \ # <-3- A2 # Marker "3" is exclusive to A0,A2 # # in addition: # # Markers "2,3" are exclusive to A1,A2 # Markers "1,2,3" are exclusive to A0,A1,A2 See test/test-obsolete-bundle-strip.t for more examples. An example usage is strip. When stripping a changeset, we also want to strip the markers exclusive to this changeset. Otherwise we would have "dangling"" obsolescence markers from its precursors: Obsolescence markers marking a node as obsolete without any successors available locally. As for relevant markers, the prune markers for children will be followed. Of course, they will only be followed if the pruned children is locally-known. Since the prune markers are relevant to the pruned node. However, while prune markers are considered relevant to the parent of the pruned changesets, prune markers for locally-known changeset (with no successors) are considered exclusive to the pruned nodes. This allows to strip the prune markers (with the rest of the exclusive chain) alongside the pruned changesets. """ # running on a filtered repository would be dangerous as markers could be # reported as exclusive when they are relevant for other filtered nodes. unfi = repo.unfiltered() # shortcut to various useful item nm = unfi.changelog.nodemap precursorsmarkers = unfi.obsstore.predecessors successormarkers = unfi.obsstore.successors childrenmarkers = unfi.obsstore.children # exclusive markers (return of the function) exclmarkers = set() # we need fast membership testing nodes = set(nodes) # looking for head in the obshistory # # XXX we are ignoring all issues in regard with cycle for now. stack = [n for n in nodes if not _filterprunes(successormarkers.get(n, ()))] stack.sort() # nodes already stacked seennodes = set(stack) while stack: current = stack.pop() # fetch precursors markers markers = list(precursorsmarkers.get(current, ())) # extend the list with prune markers for mark in successormarkers.get(current, ()): if not mark[1]: markers.append(mark) # and markers from children (looking for prune) for mark in childrenmarkers.get(current, ()): if not mark[1]: markers.append(mark) # traverse the markers for mark in markers: if mark in exclmarkers: # markers already selected continue # If the markers is about the current node, select it # # (this delay the addition of markers from children) if mark[1] or mark[0] == current: exclmarkers.add(mark) # should we keep traversing through the precursors? prec = mark[0] # nodes in the stack or already processed if prec in seennodes: continue # is this a locally known node ? known = prec in nm # if locally-known and not in the <nodes> set the traversal # stop here. if known and prec not in nodes: continue # do not keep going if there are unselected markers pointing to this # nodes. If we end up traversing these unselected markers later the # node will be taken care of at that point. precmarkers = _filterprunes(successormarkers.get(prec)) if precmarkers.issubset(exclmarkers): seennodes.add(prec) stack.append(prec) return exclmarkers def foreground(repo, nodes): """return all nodes in the "foreground" of other node The foreground of a revision is anything reachable using parent -> children or precursor -> successor relation. It is very similar to "descendant" but augmented with obsolescence information. Beware that possible obsolescence cycle may result if complex situation. """ repo = repo.unfiltered() foreground = set(repo.set('%ln::', nodes)) if repo.obsstore: # We only need this complicated logic if there is obsolescence # XXX will probably deserve an optimised revset. nm = repo.changelog.nodemap plen = -1 # compute the whole set of successors or descendants while len(foreground) != plen: plen = len(foreground) succs = set(c.node() for c in foreground) mutable = [c.node() for c in foreground if c.mutable()] succs.update(allsuccessors(repo.obsstore, mutable)) known = (n for n in succs if n in nm) foreground = set(repo.set('%ln::', known)) return set(c.node() for c in foreground) def getobsoleted(repo, tr): """return the set of pre-existing revisions obsoleted by a transaction""" torev = repo.unfiltered().changelog.nodemap.get phase = repo._phasecache.phase succsmarkers = repo.obsstore.successors.get public = phases.public addedmarkers = tr.changes.get('obsmarkers') addedrevs = tr.changes.get('revs') seenrevs = set(addedrevs) obsoleted = set() for mark in addedmarkers: node = mark[0] rev = torev(node) if rev is None or rev in seenrevs: continue seenrevs.add(rev) if phase(repo, rev) == public: continue if set(succsmarkers(node) or []).issubset(addedmarkers): obsoleted.add(rev) return obsoleted class _succs(list): """small class to represent a successors with some metadata about it""" def __init__(self, *args, **kwargs): super(_succs, self).__init__(*args, **kwargs) self.markers = set() def copy(self): new = _succs(self) new.markers = self.markers.copy() return new @util.propertycache def _set(self): # immutable return set(self) def canmerge(self, other): return self._set.issubset(other._set) def successorssets(repo, initialnode, closest=False, cache=None): """Return set of all latest successors of initial nodes The successors set of a changeset A are the group of revisions that succeed A. It succeeds A as a consistent whole, each revision being only a partial replacement. By default, the successors set contains non-obsolete changesets only, walking the obsolescence graph until reaching a leaf. If 'closest' is set to True, closest successors-sets are return (the obsolescence walk stops on known changesets). This function returns the full list of successor sets which is why it returns a list of tuples and not just a single tuple. Each tuple is a valid successors set. Note that (A,) may be a valid successors set for changeset A (see below). In most cases, a changeset A will have a single element (e.g. the changeset A is replaced by A') in its successors set. Though, it is also common for a changeset A to have no elements in its successor set (e.g. the changeset has been pruned). Therefore, the returned list of successors sets will be [(A',)] or [], respectively. When a changeset A is split into A' and B', however, it will result in a successors set containing more than a single element, i.e. [(A',B')]. Divergent changesets will result in multiple successors sets, i.e. [(A',), (A'')]. If a changeset A is not obsolete, then it will conceptually have no successors set. To distinguish this from a pruned changeset, the successor set will contain itself only, i.e. [(A,)]. Finally, final successors unknown locally are considered to be pruned (pruned: obsoleted without any successors). (Final: successors not affected by markers). The 'closest' mode respect the repoview filtering. For example, without filter it will stop at the first locally known changeset, with 'visible' filter it will stop on visible changesets). The optional `cache` parameter is a dictionary that may contains precomputed successors sets. It is meant to reuse the computation of a previous call to `successorssets` when multiple calls are made at the same time. The cache dictionary is updated in place. The caller is responsible for its life span. Code that makes multiple calls to `successorssets` *should* use this cache mechanism or risk a performance hit. Since results are different depending of the 'closest' most, the same cache cannot be reused for both mode. """ succmarkers = repo.obsstore.successors # Stack of nodes we search successors sets for toproceed = [initialnode] # set version of above list for fast loop detection # element added to "toproceed" must be added here stackedset = set(toproceed) if cache is None: cache = {} # This while loop is the flattened version of a recursive search for # successors sets # # def successorssets(x): # successors = directsuccessors(x) # ss = [[]] # for succ in directsuccessors(x): # # product as in itertools cartesian product # ss = product(ss, successorssets(succ)) # return ss # # But we can not use plain recursive calls here: # - that would blow the python call stack # - obsolescence markers may have cycles, we need to handle them. # # The `toproceed` list act as our call stack. Every node we search # successors set for are stacked there. # # The `stackedset` is set version of this stack used to check if a node is # already stacked. This check is used to detect cycles and prevent infinite # loop. # # successors set of all nodes are stored in the `cache` dictionary. # # After this while loop ends we use the cache to return the successors sets # for the node requested by the caller. while toproceed: # Every iteration tries to compute the successors sets of the topmost # node of the stack: CURRENT. # # There are four possible outcomes: # # 1) We already know the successors sets of CURRENT: # -> mission accomplished, pop it from the stack. # 2) Stop the walk: # default case: Node is not obsolete # closest case: Node is known at this repo filter level # -> the node is its own successors sets. Add it to the cache. # 3) We do not know successors set of direct successors of CURRENT: # -> We add those successors to the stack. # 4) We know successors sets of all direct successors of CURRENT: # -> We can compute CURRENT successors set and add it to the # cache. # current = toproceed[-1] # case 2 condition is a bit hairy because of closest, # we compute it on its own case2condition = ((current not in succmarkers) or (closest and current != initialnode and current in repo)) if current in cache: # case (1): We already know the successors sets stackedset.remove(toproceed.pop()) elif case2condition: # case (2): end of walk. if current in repo: # We have a valid successors. cache[current] = [_succs((current,))] else: # Final obsolete version is unknown locally. # Do not count that as a valid successors cache[current] = [] else: # cases (3) and (4) # # We proceed in two phases. Phase 1 aims to distinguish case (3) # from case (4): # # For each direct successors of CURRENT, we check whether its # successors sets are known. If they are not, we stack the # unknown node and proceed to the next iteration of the while # loop. (case 3) # # During this step, we may detect obsolescence cycles: a node # with unknown successors sets but already in the call stack. # In such a situation, we arbitrary set the successors sets of # the node to nothing (node pruned) to break the cycle. # # If no break was encountered we proceed to phase 2. # # Phase 2 computes successors sets of CURRENT (case 4); see details # in phase 2 itself. # # Note the two levels of iteration in each phase. # - The first one handles obsolescence markers using CURRENT as # precursor (successors markers of CURRENT). # # Having multiple entry here means divergence. # # - The second one handles successors defined in each marker. # # Having none means pruned node, multiple successors means split, # single successors are standard replacement. # for mark in sorted(succmarkers[current]): for suc in mark[1]: if suc not in cache: if suc in stackedset: # cycle breaking cache[suc] = [] else: # case (3) If we have not computed successors sets # of one of those successors we add it to the # `toproceed` stack and stop all work for this # iteration. toproceed.append(suc) stackedset.add(suc) break else: continue break else: # case (4): we know all successors sets of all direct # successors # # Successors set contributed by each marker depends on the # successors sets of all its "successors" node. # # Each different marker is a divergence in the obsolescence # history. It contributes successors sets distinct from other # markers. # # Within a marker, a successor may have divergent successors # sets. In such a case, the marker will contribute multiple # divergent successors sets. If multiple successors have # divergent successors sets, a Cartesian product is used. # # At the end we post-process successors sets to remove # duplicated entry and successors set that are strict subset of # another one. succssets = [] for mark in sorted(succmarkers[current]): # successors sets contributed by this marker base = _succs() base.markers.add(mark) markss = [base] for suc in mark[1]: # cardinal product with previous successors productresult = [] for prefix in markss: for suffix in cache[suc]: newss = prefix.copy() newss.markers.update(suffix.markers) for part in suffix: # do not duplicated entry in successors set # first entry wins. if part not in newss: newss.append(part) productresult.append(newss) markss = productresult succssets.extend(markss) # remove duplicated and subset seen = [] final = [] candidates = sorted((s for s in succssets if s), key=len, reverse=True) for cand in candidates: for seensuccs in seen: if cand.canmerge(seensuccs): seensuccs.markers.update(cand.markers) break else: final.append(cand) seen.append(cand) final.reverse() # put small successors set first cache[current] = final return cache[initialnode] def successorsandmarkers(repo, ctx): """compute the raw data needed for computing obsfate Returns a list of dict, one dict per successors set """ if not ctx.obsolete(): return None ssets = successorssets(repo, ctx.node(), closest=True) values = [] for sset in ssets: values.append({'successors': sset, 'markers': sset.markers}) return values
jQuery(function($){ var $search_results, $folders_center, $item_details; // end function global vars pyro.files.cache = {}; pyro.files.history = {}; pyro.files.timeout = {}; pyro.files.current_level = 0; // custom tooltips $('.files-tooltip').tipsy({ gravity: 'n', fade: true, html: true, live: true, delayIn: 800, delayOut: 300, title: function() { var text = $(this).find('span').html(); if (text.length > 15) { return text; } return ''; } }); // Default button set $('.item .folders-center').trigger('click'); /*************************************************************************** * Activity sidebar message handler * ***************************************************************************/ $(window).on('show-message', function(e, results) { if (typeof(results.message) !== "undefined" && results.message > '') { var li_status_class = 'info', status_class = 'icon-info-sign'; switch (results.status) { case true: li_status_class = 'success'; status_class = 'icon-ok-sign'; break; case false: li_status_class = 'failure'; status_class = 'icon-remove-sign'; break; } $('#activity').find('span').fadeOut(); $('#activity').html('<span class="' + li_status_class + '"><i class="' + status_class + '"></i> ' + results.message + '</span>'); } }); /*************************************************************************** * Sidebar search functionality * ***************************************************************************/ $search_results = $('ul#search-results'); $('.sidebar-right').find('.close').on('click', function() { $search_results.empty(); $('.sidebar-right').removeClass('fadeInRight').addClass('fadeOutRight'); $('.side, .center').removeClass('three_column'); }); $('input#file-search').keyup(function(e){ $search_results.empty(); // submit on Enter if (e.which === 13) { $.post(SITE_URL+'admin/files/search', { search : $(e.target).val() }, function(data){ var results = $.parseJSON(data); if (results.status) { $.each(results.data, function(type, item){ if (item.length > 0){ $.each(item, function(i, result){ $('<li>'+ '<div class="'+type+'"></div>'+ '<a data-parent="'+(type === 'folder' ? result.parent_id : result.folder_id)+'" href="'+SITE_URL+'admin/files#">'+result.name+'</a>'+ '</li>').appendTo('ul#search-results'); }); } }); } else { $('<li><div class="info"></div>' + results.message + '</li>').appendTo('ul#search-results'); } $('.sidebar-right').show().removeClass('fadeOutRight').addClass('fadeInRight'); $('.side, .center').addClass('three_column'); }); } }); $search_results.on('click', 'a', function(e){ e.preventDefault(); var $el = $(this), id = $el.attr('data-parent'), text = $el.html(); pyro.files.folder_contents(id); // after the folder contents have loaded highlight the results $(window).on('load-completed', function(e, results){ $('.folders-center').find('li').removeClass('selected'); $('.folders-center').find('[data-name="'+text+'"]').addClass('selected'); }); }); /*************************************************************************** * Open folders * ***************************************************************************/ $folders_center = $('.folders-center'); $folders_center.on('dblclick', '.folder', function(e){ // store element so it can be accessed the same as if it was right clicked pyro.files.$last_r_click = $(e.target).closest('li'); $('.context-menu-source [data-menu="open"]').trigger('click'); }); $('ul#folders-sidebar').find('li').has('ul').addClass('open'); // use a single left click in the left sidebar $('ul#folders-sidebar').on('click', '.folder', function(e){ e.preventDefault(); e.stopPropagation(); var $clicked = $(e.target); // did they click on the link or the icon if ($clicked.is('a')) { // store element so it can be accessed the same as if it was right clicked pyro.files.$last_r_click = $clicked.parent('li'); $('.context-menu-source [data-menu="open"]').trigger('click'); } else { $clicked .parent('li').toggleClass('open close') .children('ul').slideToggle(50); } }); // and use a single left click on the breadcrumbs $('#file-breadcrumbs').on('click', 'a', function(e){ e.preventDefault(); e.stopPropagation(); // store element so it can be accessed the same as if it was right clicked pyro.files.$last_r_click = $(e.target); $('.context-menu-source [data-menu="open"]').trigger('click'); }); /*************************************************************************** * Context / button menu management * ***************************************************************************/ // open a right click menu on items in the main area $('.item').on('contextmenu click', '.folders-center, .folders-center li', function(e){ e.preventDefault(); e.stopPropagation(); // make the right clicked element easily accessible pyro.files.$last_r_click = $(this); var $menu_sources = $('.context-menu-source, .button-menu-source'); var $context_menu_source = $('.context-menu-source'); var $button_menu_source = $('.button-menu-source'); // make sure the button menu is shown (it's hidden by css to prevent flash) $button_menu_source.fadeIn(); $menu_sources.find('li') // reset in case they've right clicked before .show() // what did the user click on? folder, pane, or file .filter(function(index){ var folder, pattern = new RegExp('pane'), // if they happen to click right on the name span then we need to shift to the parent $target = $(e.target).is('span') ? $(e.target).parent('li') : $(e.target); // make an exception cause the image thumbnail itself may be the target if ($target.hasClass('file') || $target.is('img')){ pattern = new RegExp('file'); } else if ($target.hasClass('folder')){ pattern = new RegExp('folder'); folder = true; } else if ($target.hasClass('pane') && pyro.files.current_level == '0'){ pattern = new RegExp('root-pane'); } // now hide this item if it's not allowed for that type if ( ! pattern.test($(this).attr('data-applies-to'))){ $(this).hide(); } // and hide it if they don't have permission for it if ( $(this).attr('data-role') && pyro.files.has_permissions( $(this).attr('data-role') ) === false ) { $(this).hide(); } // one final check for the oddball "synchronize". If it's a local folder we hide it anyway if (folder && $(this).attr('data-role') === 'synchronize') { // fetch the item's data so we can check what its location is $item = $(window).data('folder_'+pyro.files.$last_r_click.attr('data-id')); // sorry buddy, no cloud for you if ($item.location === 'local') { $(this).hide(); } } }); // IF this is a click on a folder // show the folder as selected // otherwise unselect any folder if ( $(e.target).hasClass('folder') ) { // Remove selected files $('.folders-center li.selected').removeClass('selected'); // Highlight folder $(e.target).addClass('highlight'); } else { $('.folders-center li.highlight').removeClass('highlight'); } // jquery UI position the context menu by the mouse IF e.type IS contextmenu if ( e.type == 'contextmenu' ) { $('.tipsy').remove(); $context_menu_source .fadeIn('fast') .position({ my: 'left top', at: 'left bottom', of: e, collision: 'fit' }); } // otherwise they clicked off the context menu else { $context_menu_source.hide(); } }); // call the correct function for the menu item they have clicked $('.context-menu-source, .button-menu-source').on('click', '[data-menu]', function(e){ var menu = $(this).attr('data-menu'), item; switch (menu){ case 'open': pyro.files.folder_contents( pyro.files.$last_r_click.attr('data-id') ); break; case 'upload': $(window).trigger('open-upload'); break; case 'new-folder': $('.no_data').fadeOut(100); // jQuery insists on adding the folder before no_data is removed. So we force it to wait setTimeout(function(){ pyro.files.new_folder(pyro.files.current_level); }, 150); break; case 'rename': pyro.files.rename(); break; case 'download': $item = $(window).data('file_'+pyro.files.$last_r_click.attr('data-id')); if ($item.type === 'i' && $item.location !== 'local') { window.open(SITE_URL+'files/download/'+$item.id); } else { window.location = SITE_URL+'files/download/'+$item.id; } break; case 'synchronize': pyro.files.synchronize(); break; case 'delete': if ( ! confirm(pyro.lang.dialog_message)) { return; } pyro.files.delete_item(pyro.files.current_level); // "Click" on the resulting folder $('.item .folders-center').trigger('click'); break; case 'replace': pyro.files.replace(); break; case 'details': pyro.files.details(); break; case 'refresh': pyro.files.folder_contents( pyro.files.current_level ); break; } }); /*************************************************************************** * Select files including with the control and shift keys * ***************************************************************************/ $folders_center.on('click', '.file[data-id]', function(e){ var first, last, $selected_files = $folders_center.find('.selected'); if ( ! e.ctrlKey && ! e.shiftKey) { if($selected_files.length > 0) { $('[data-id]').removeClass('selected'); } } $(this).toggleClass('selected'); // select if (e.shiftKey) { $folders_center .find('.selected') .last() .prevAll('.selected:first ~ *') .addClass('selected'); } }); // if they left click in the main area reset selected items or hide the context menu $('html').on('click', function(e){ $folders_center.find('li').removeClass('selected'); $('.context-menu-source').fadeOut('fast'); }); /*************************************************************************** * File and folder sorting * ***************************************************************************/ $folders_center.sortable({ cursor: 'move', delay: 100, update: function(e) { var order = { 'folder' : {}, 'file' : {} }; $(this).find('li').each(function(index, data){ var type = $(data).hasClass('folder') ? 'folder' : 'file'; order[type][index] = $(this).attr('data-id'); }); $.post(SITE_URL + 'admin/files/order', { order : order }, function(data){ var results = $.parseJSON(data), after_id, moved; if (results.status) { // synchronize the folders in the left sidebar after_id = $(e.target).prevAll('li.folder').attr('data-id'); moved = '[data-id="'+$(e.target).attr('data-id')+'"]'; if (after_id === undefined && $(moved).parent().is('.folders-sidebar')) { $('ul#folders-sidebar [data-id="0"]') .after($('ul#folders-sidebar '+moved)); } else if (after_id === undefined && $(moved).parent().is('ul')) { $('ul#folders-sidebar '+moved).parent('ul') .prepend($('ul#folders-sidebar '+moved)); } else { $('ul#folders-sidebar [data-id="'+after_id+'"]') .after($('ul#folders-sidebar '+moved)); } } $(window).trigger('show-message', results); }); } }); /*************************************************************************** * Files uploader section * ***************************************************************************/ $(window).on('open-upload', function(){ var folder; // we use the current level if they clicked in the open area or if they want to replace a file if ( ! pyro.files.$last_r_click.hasClass('file') && pyro.files.$last_r_click.attr('data-id') > '') { pyro.files.upload_to = pyro.files.$last_r_click.attr('data-id'); } else { pyro.files.upload_to = pyro.files.current_level; } folder = $(window).data('folder_'+pyro.files.upload_to); $.colorbox({ scrolling : false, inline : true, href : '#files-uploader', width : '920', height : '80%', opacity : 0.3, onComplete : function(){ $('#files-uploader-queue').empty(); $.colorbox.resize(); }, onCleanup : function(){ // we don't reload unless they are inside the folder that they uploaded to if (pyro.files.upload_to === pyro.files.current_level) { pyro.files.folder_contents(pyro.files.upload_to); } $('#files-uploader').find('form').fileUploadUI('option', 'maxFiles', 0); //not really an option, but the only way to reset it from here $('#files-uploader').find('form').fileUploadUI('option', 'currentFileCount', 0); $("#file-to-replace").hide(); }, onLoad : function(){ //onLoad is currently only used when replacing a file if( ! 'mode' in pyro.files || pyro.files.mode != 'replace' ) { return; } // the last thing that has been right clicked should be a file, so this might not be neccessary if ( pyro.files.$last_r_click.hasClass('file') ) { $("#file-to-replace").find('span.name').text(pyro.files.$last_r_click.attr('data-name')).end().show(); //set max file upload to 1 $('#files-uploader').find('form').fileUploadUI('option', 'maxFiles', 1); } } }); }); pyro.init_upload = function($form){ $form.find('form').fileUploadUI({ fieldName : 'file', uploadTable : $('#files-uploader-queue'), downloadTable : $('#files-uploader-queue'), previewSelector : '.file_upload_preview div', cancelSelector : '.file_upload_cancel div.cancel-icon', buildUploadRow : function(files, index, handler){ var resize = '', type = files[index]['type']; // if it isn't an image then they can't resize it if (type && type.search('image') >= 0) { resize = '<label id="width">'+pyro.lang.width+'</label>'+ '<select name="width" class="skip"><option value="0">'+pyro.lang.full_size+'</option><option value="100">100px</option><option value="200">200px</option><option value="300">300px</option><option value="400">400px</option><option value="500">500px</option><option value="600">600px</option><option value="700">700px</option><option value="800">800px</option><option value="900">900px</option><option value="1000">1000px</option><option value="1100">1100px</option><option value="1200">1200px</option><option value="1300">1300px</option><option value="1400">1400px</option><option value="1500">1500px</option><option value="1600">1600px</option><option value="1700">1700px</option><option value="1800">1800px</option><option value="1900">1900px</option><option value="2000">2000px</option></select>'+ '<label id="height">'+pyro.lang.height+'</label>'+ '<select name="height" class="skip"><option value="0">'+pyro.lang.full_size+'</option><option value="100">100px</option><option value="200">200px</option><option value="300">300px</option><option value="400">400px</option><option value="500">500px</option><option value="600">600px</option><option value="700">700px</option><option value="800">800px</option><option value="900">900px</option><option value="1000">1000px</option><option value="1100">1100px</option><option value="1200">1200px</option><option value="1300">1300px</option><option value="1400">1400px</option><option value="1500">1500px</option><option value="1600">1600px</option><option value="1700">1700px</option><option value="1800">1800px</option><option value="1900">1900px</option><option value="2000">2000px</option></select>'+ '<label id="ratio">'+pyro.lang.ratio+'</label>'+ '<input name="ratio" type="checkbox" value="1" checked="checked"/>'+ '<label id="alt">'+pyro.lang.alt_attribute+'</label>'+ '<input type="text" name="alt_attribute" class="alt_attribute" />'; } // build the upload html for this file return $('<li>'+ '<div class="file_upload_preview ui-corner-all"><div class="ui-corner-all preview-container"></div></div>' + '<div class="filename"><label for="file-name">' + files[index].name + '</label>' + '<input class="file-name" type="hidden" name="name" value="'+files[index].name+'" />' + '</div>' + '<div class="file_upload_progress"><div></div></div>' + '<div class="file_upload_cancel">' + '<div title="'+pyro.lang.start+'" class="start-icon ui-helper-hidden-accessible"></div>'+ '<div title="'+pyro.lang.cancel+'" class="cancel-icon"></div>' + '</div>' + '<div class="image_meta">'+ resize+ '</div>'+ '</li>'); }, buildDownloadRow: function(results){ if (results.message) { $(window).trigger('show-message', results); } }, beforeSend: function(event, files, index, xhr, handler, callBack){ if( ! handler.uploadRow ) //happens if someone trys to upload more than he's allowed to, e.g. during file replace { return; } var $progress_div = handler.uploadRow.find('.file_upload_progress'), regexp; // check if the server can handle it if (files[index].size > pyro.files.max_size_possible) { $progress_div.html(pyro.lang.exceeds_server_setting); return false; } else if (files[index].size > pyro.files.max_size_allowed) { $progress_div.html(pyro.lang.exceeds_allowed); return false; } // is it an allowed type? regexp = new RegExp('\\.('+pyro.files.valid_extensions+')$', 'i'); // Using the filename extension for our test, // as legacy browsers don't report the mime type if (!regexp.test(files[index].name.toLowerCase())) { $progress_div.html(pyro.lang.file_type_not_allowed); return false; } handler.uploadRow.find('div.start-icon').on('click', function() { handler.formData = { name: handler.uploadRow.find('input.file-name').val(), width: handler.uploadRow.find('[name="width"]').val(), height: handler.uploadRow.find('[name="height"]').val(), ratio: handler.uploadRow.find('[name="ratio"]').is(':checked'), alt_attribute: handler.uploadRow.find('[name="alt_attribute"]').val(), folder_id: pyro.files.upload_to, replace_id: 'mode' in pyro.files && pyro.files.mode == 'replace' ? pyro.files.$last_r_click.attr('data-id') : 0, csrf_hash_name: $.cookie(pyro.csrf_cookie_name) }; callBack(); }); }, onComplete: function (event, files, index, xhr, handler){ if (files.length === index + 1) { $('#files-uploader a.cancel-upload').click(); } } }); $form.on('click', '.start-upload', function(e){ e.preventDefault(); $('#files-uploader-queue div.start-icon').click(); }); $form.on('click', '.cancel-upload', function(e){ e.preventDefault(); $('#files-uploader-queue div.cancel-icon').click(); $.colorbox.close(); }); }; pyro.init_upload($('#files-uploader')); /*************************************************************************** * All functions that are part of the pyro.files namespace * ***************************************************************************/ pyro.files.new_folder = function(parent, name) { var new_class = Math.floor(Math.random() * 1000), post_data; if (typeof(name) === 'undefined') { name = pyro.lang.new_folder_name; } // add an editable one to the right pane $('.new-folder').clone() .removeClass('new-folder') .appendTo('.folders-center') .addClass('folder folder-' + new_class); post_data = { parent : parent, name : name }; $.post(SITE_URL + 'admin/files/new_folder', post_data, function(data){ var results = $.parseJSON(data); if (results.status) { // add the id in so we know who he is $('.folder-' + new_class).attr('data-id', results.data.id); // update the text and remove the temporary class $('.folder-' + new_class + ' .name-text') .html(results.data.name) .removeClass('folder-' + new_class); $parent_li = $('ul#folders-sidebar .folder[data-id="'+parent+'"]'); if (parent === 0 || $parent_li.hasClass('places')) { // this is a top level folder, we'll insert it after Places. Not really its parent $parent_li.after('<li class="folder" data-id="'+results.data.id+'" data-name="'+results.data.name+'"><div></div><a href="#">'+results.data.name+'</a></li>'); } else if ($parent_li.has('ul').length > 0) { // it already has children so we'll just append this li to its ul $parent_li.children('ul') .append('<li class="folder" data-id="'+results.data.id+'" data-name="'+results.data.name+'"><div></div><a href="#">'+results.data.name+'</a></li>'); } else { // it had no children, we'll have to add the <ul> and the icon class also $parent_li.append('<ul style="display:block"><li class="folder" data-id="'+results.data.id+'" data-name="'+results.data.name+'"><div></div><a href="#">'+results.data.name+'</a></li></ul>'); $parent_li.addClass('close'); } // save its data locally $(window).data('folder_'+results.data.id, results.data); // now they will want to rename it pyro.files.$last_r_click = $('.folder[data-id="'+results.data.id+'"]'); $('.context-menu-source [data-menu="rename"]').trigger('click'); $(window).trigger('show-message', results); } }); }; pyro.files.folder_contents = function(folder_id) { var level = pyro.files.current_level, folders = [], files = [], post_data, i = 0, items = [], content_interval, current; // let them know we're getting the stuff, it may take a second $(window).trigger('show-message', {message: pyro.lang.fetching}); post_data = { parent : folder_id }; $.post(SITE_URL + 'admin/files/folder_contents', post_data, function(data){ var results = $.parseJSON(data); if (results.status) { // iterate over all items so we can build a cache $folders_center.find('li').each(function(index){ var folder = {}, file = {}; if ($(this).hasClass('folder')) { folder.id = $(this).attr('data-id'); folder.name = $(this).attr('data-name'); folders[index] = folder; } else { file.id = $(this).attr('data-id'); file.name = $(this).attr('data-name'); files[index] = file; } }); // ok now we have a copy of what *was* there pyro.files.history[level] = { folder : folders, file : files }; // so let's wipe it clean... $('.folders-center').find('li').fadeOut('fast').remove(); $('.tipsy').remove(); // use the folder_id from results as we know that's numeric folder_id = results.data.parent_id; delete(results.data.parent_id); // iterate so that we have folders first, files second $.each(results.data, function(type, data){ $.each(data, function(index, item){ item.el_type = type; items.push(item); }); }); // we load all items with a small delay between, if we just appended all // elements at once it effectively launches a DOS attack on the server content_interval = window.setInterval(function(){ if (typeof(items[i]) == 'undefined') { clearInterval(content_interval); $(window).trigger('load-completed'); return; } var item = items[i]; i++; // if it's an image then we set the thumbnail as the content var li_content = '<span class="name-text">'+item.name+'</span>'; if (item.type && item.type === 'i') { /* without this the thumb doesn't update with Replace */ li_content = '<img src="'+SITE_URL+'files/cloud_thumb/'+item.id+'?'+new Date().getMilliseconds()+'" alt="'+item.name+'"/>'+li_content; } $folders_center.append( '<li class="files-tooltip '+item.el_type+' '+(item.el_type === 'file' ? 'type-'+item.type : '')+'" data-id="'+item.id+'" data-name="'+item.name+'">'+ li_content+ '</li>' ); // save all its details for other uses. The Details window for example $(window).data(item.el_type+'_'+item.id, item); }, 150); // Toto, we're not in Kansas anymore pyro.files.current_level = folder_id; // remove the old breadcrumbs from the title $('#file-breadcrumbs').find('.folder-crumb').remove(); // grab all the data for the current folder current = $(window).data('folder_'+folder_id); var url = ''; // build all the parent crumbs in reverse order starting with current while(typeof(current) !== 'undefined') { $('#file-breadcrumbs').find('#crumb-root').after('<span class="folder-crumb"> &nbsp;/&nbsp; <a data-id="'+current.id+'" href="#">'+current.name+'</a></span>'); url = current.slug + '/' + url; current = $(window).data('folder_'+current.parent_id); } if (url.length > 0) { window.location.hash = '#'+url; } // show the children in the left sidebar $('ul#folders-sidebar [data-id="'+folder_id+'"] > ul:hidden').parent('li').children('div').trigger('click'); // add the current indicator to the correct folder $('ul#folders-sidebar').find('li').removeClass('current'); $('ul#folders-sidebar [data-id="'+folder_id+'"]').not('.places').addClass('current'); // and we succeeded results.message = pyro.lang.fetch_completed; $(window).trigger('show-message', results); // Show the applicable buttons. $('.item .folders-center').trigger('click'); } }); }; pyro.files.rename = function() { // what type of item are we renaming? var type = pyro.files.$last_r_click.hasClass('folder') ? 'folder' : 'file', $item = pyro.files.$last_r_click.find('.name-text'); // if they have one selected already then undo it $('[name="rename"]').parent().html($('[name="rename"]').val()); $item.html('<input name="rename" value="'+$item.html()+'"/>'); $input = $item.find('input'); $input.select(); $input.keyup(function(e){ if(e.which === 13) { $input.trigger('blur'); } else { if ($(this).val().length > 49) { $(this).val($(this).val().slice(0, 50)); } } }); $input.blur(function(){ var item_data, post = { name: $input.val() }; post[type+'_id'] = $item.parent('li').attr('data-id'); item_data = ($(window).data(type+'_'+post[type+'_id']) || {}); if ( $.isEmptyObject(item_data) || item_data.name !== post['name']) { $.post(SITE_URL + 'admin/files/rename_'+type, post, function(data){ var results = $.parseJSON(data); $(window).trigger('show-message', results); // update the local data $.extend(item_data, results.data); $(window).data(type+'_'+item_data.id, item_data); // remove the input and place the text back in the span $('input[name="rename"]').parent().html(results.data.name); $('ul#folders-sidebar').find('[data-id="'+post.folder_id+'"] > a').html(results.data.name); $('.'+type+'[data-id="'+post[type+'_id']+'"]').attr('data-name', results.data.name); }); } $('input[name="rename"]').parent().html($('input[name="rename"]').val()); }); // Prevent form from submitting // if used outside of module // ie: form input for streams $input.keydown(function(e){ if ( e.which == '13' ) { $(this).blur(); // trigger the save return false; //don't submit form } }); }; pyro.files.replace = function() { pyro.files.mode = 'replace'; $(window).trigger('open-upload'); }; pyro.files.delete_item = function(current_level) { // only files can be multi-selected var items = $('.selected[data-id]'), // if there are selected items then they have to be files type = items.length > 0 ? 'file' : 'folder'; // end var // multiple files or a single file if (type === 'file' || pyro.files.$last_r_click.hasClass('file')) { // nothing multi-selected so we use the item clicked on // and make sure the `type` is file if (items.length === 0) { items = pyro.files.$last_r_click; type = 'file'; } } else { // it's a folder so we use the item clicked items = pyro.files.$last_r_click; } items.each(function (index, item) { var id = $(item).attr('data-id'), post_data = {}; post_data[type + '_id'] = id; $.post(SITE_URL + 'admin/files/delete_' + type, post_data, function (data) { var results = $.parseJSON(data); if (results.status) { // delete locally $(window).removeData(type + '_' + id); switch (type) { case 'file': $('.folders-center .file[data-id="' + id + '"]').remove(); break; case 'folder': // remove it from the left and right panes $('.folder[data-id="' + id + '"]').remove(); // adjust the parents $('.folder[data-id="' + current_level + '"] ul:empty').remove(); $('.folder[data-id="' + current_level + '"]').removeClass('open close'); break; } // if they are trying it out and created a folder and then removed it // then we show the no data messages again if ($folders_center.find('li').length === 0 && pyro.files.current_level === 0) { $('.no_data').fadeIn('fast'); } $(window).trigger('show-message', results); } }); }); }; $item_details = $('div#item-details'); pyro.files.details = function() { var timer, location, // file or folder? type = pyro.files.$last_r_click.hasClass('file') ? 'file' : 'folder', // figure out the ID from the last clicked item $item_id = pyro.files.$last_r_click.attr('data-id').length > 0 ? pyro.files.$last_r_click.attr('data-id') : pyro.files.current_level, // retrieve all the data that was stored when the item was initially loaded $item = $(window).data(type+'_'+$item_id), $select = $item_details.find('.location'); // end var // hide all the unused elements $item_details.find('li').hide(); $item_details.find('.meta-data').hide(); $item_details.find('.show-data > button').unbind().bind('click', function(){ $item_details.find('.meta-data, .item-description').slideToggle(); }); if ($item) { if ($item.id) { $item_details.find('.id') .html($item.id).parent().show(); } if ($item.name) { $item_details.find('.name') .html($item.name).parent().show(); } if ($item.slug) { $item_details.find('.slug') .html($item.slug).parent().show(); } if ($item.path) { $item_details.find('.path') .val($item.path).parent().show(); } if ($item.formatted_date) { $item_details.find('.added') .html($item.formatted_date).parent().show(); } if ($item.width > 0) { $item_details.find('.width') .html($item.width+'px').parent().show(); } if ($item.height > 0) { $item_details.find('.height') .html($item.height+'px').parent().show(); } if ($item.filesize) { $item_details.find('.filesize') .html(($item.filesize < 1000 ? $item.filesize+'Kb' : $item.filesize / 1000+'MB')).parent().show(); } if ($item.download_count) { $item_details.find('.download_count') .html($item.download_count).parent().show(); } if ($item.filename) { $item_details.find('.filename') .html($item.filename).parent().show(); } if (type === 'file') { $item_details.find('.description') .val($item.description).parent().show(); } if (type === 'file') { $item_details.find('#keyword_input') .val($item.keywords).parent().show(); } if (type === 'file') { $item_details.find('.show-data') .show(); } if ($item.type === 'i') { $item_details.find('.alt_attribute') .val($item.alt_attribute).parent().show(); } // they can only change the cloud provider if the folder is empty and they have permission if (type === 'folder' && $item.file_count === 0 && pyro.files.has_permissions('set_location') ){ // update the value and trigger an update on Chosen $select.val($item.location).find('option[value="'+$item.location+'"]').attr('selected', true); $select.trigger('liszt:updated').parents().show(); } else if (type === 'folder') { // show the location $item_details.find('.location-static').html($item.location).parent().show(); // show the bucket/container also if it has one if ($item.remote_container > '') { $item_details.find('.container-static').html($item.remote_container).parent().show(); } } // needed so that Keywords can return empty JSON $.ajaxSetup({ allowEmpty: true }); // set up keywords $('#keyword_input').tagsInput({ autocomplete_url: SITE_URL + 'admin/keywords/autocomplete' }); // when the colorbox is closed kill the tag input $item_details.bind('cbox_closed', function(){ $('#keyword_input_tagsinput').remove(); // if we don't unbind it will stay bound even if we cancel $item_details.find('.buttons').off('click', 'button'); }); // show/hide the bucket/container name field on change $select.change(function(e){ location = $(e.target).val(); $item_details.find('.container').parent().hide(); $('.'+location).parent().show(); }); // check if a container with that name exists $('.container-button').on('click', function(e){ var post_data = { name : $(this).siblings('.container').val(), location : location }; $.post(SITE_URL + 'admin/files/check_container', post_data, function(data) { var results = $.parseJSON(data); $(window).trigger('show-message', results); }); }); $.colorbox({ scrolling : false, inline : true, href : 'div#item-details', width : '520', height : (type === 'file') ? '600' : '475', opacity : 0 }); // save on click, then close the modal $item_details.find('.buttons').on('click', 'button', function() { if (type === 'file'){ pyro.files.save_description($item); } else { pyro.files.save_location($item); } $.colorbox.close(); }); } }; pyro.files.save_description = function(item) { var new_description = $item_details.find('textarea.description').val(), new_keywords = $item_details.find('#keyword_input').val(), new_alt_attribute = $item_details.find('input.alt_attribute').val(), post_data = { file_id : item.id, description : new_description, keywords : new_keywords, old_hash : item.keywords_hash, alt_attribute : new_alt_attribute }; // end var // only save it if it's different than the old one if (item.description !== new_description || item.keywords !== new_keywords || item.alt_attribute !== new_alt_attribute){ $.post(SITE_URL + 'admin/files/save_description', post_data, function(data){ var results = $.parseJSON(data); $(window).trigger('show-message', results); // resave it locally item.description = new_description; item.keywords = new_keywords; item.keywords_hash = results.data.keywords_hash; item.alt_attribute = new_alt_attribute; $(window).data('file_'+item.id, item); }); } }; pyro.files.save_location = function(item) { var new_location = $item_details.find('.location').val(), container = $('div#item-details .'+new_location).val(), post_data = { folder_id: item.id, location: new_location, container: container }; // end var $.post(SITE_URL + 'admin/files/save_location', post_data, function(data) { var results = $.parseJSON(data); $(window).trigger('show-message', results); if (results.status) { // resave it locally item.location = new_location; item.remote_container = container; $(window).data('folder_'+item.id, item); } }); }; pyro.files.synchronize = function() { var folder_id = pyro.files.$last_r_click.attr('data-id'), post_data = { folder_id: folder_id }; $(window).trigger('show-message', { status : null, message : pyro.lang.synchronization_started }); $.post(SITE_URL + 'admin/files/synchronize', post_data, function(data){ var results = $.parseJSON(data); $(window).trigger('show-message', results); if (results.status) { pyro.files.folder_contents(folder_id); } }); }; pyro.files.has_permissions = function(roles) { var actions = roles.split(' '); var max_actions = actions.length; for(var x = 0;x < max_actions;x++) { if( $.inArray(actions[x], pyro.files.permissions) === -1 ) { return false; } } return true; } /*************************************************************************** * And off we go... load the desired folder * ***************************************************************************/ if ($('.folders-center').find('.no_data').length === 0) { if (window.location.hash) { pyro.files.folder_contents(window.location.hash); } else { // deprecated pyro.files.folder_contents(pyro.files.initial_folder_contents); } } });
//document.getElementById("datetime").innerHTML = "WebSocket is not connected"; var websocket = new WebSocket('ws://'+location.hostname+'/'); var maxRow = 10; function changeRow() { console.log('changeRow'); var text = document.getElementById("maxrow"); console.log('text.value=', text.value); console.log('typeof(text.value)=', typeof(text.value)); maxRow = parseInt(text.value, 10); console.log('maxRow=', maxRow); let tableElem = document.getElementById('targetTable'); var row = targetTable.rows.length; console.log("row=%d maxRow=%d", row, maxRow); if (row > maxRow) { for (var i=maxRow;i<row;i++) { tableElem.deleteRow(1); } } } function clipboardWrite() { console.log('clipboardWrite'); var text = "hoge"; if(navigator.clipboard){ console.log("clipboard.writeText"); navigator.clipboard.writeText(str); } else { alert("This browser is not supported"); } } function sendText(name) { console.log('sendText'); /* var array = ["11", "22", "33"]; var data = {}; //data["foo"] = "abc"; data["foo"] = array; var array = ["aa"]; data["bar"] = array; data["hoge"] = 100; json_data = JSON.stringify(data); console.log(json_data); */ var data = {}; data["id"] = name; console.log('data=', data); json_data = JSON.stringify(data); console.log('json_data=' + json_data); websocket.send(json_data); } websocket.onopen = function(evt) { console.log('WebSocket connection opened'); var data = {}; data["id"] = "init"; console.log('data=', data); json_data = JSON.stringify(data); console.log('json_data=' + json_data); websocket.send(json_data); //document.getElementById("datetime").innerHTML = "WebSocket is connected!"; } websocket.onmessage = function(evt) { var msg = evt.data; console.log("msg=" + msg); var values = msg.split('\4'); // \4 is EOT console.log("values=" + values); switch(values[0]) { case 'BUTTON': console.log("BUTTON values[1]=" + values[1]); console.log("BUTTON values[2]=" + values[2]); console.log("BUTTON values[3]=" + values[3]); let buttonElem = document.getElementById(values[1]); if (values[2] == "class") { console.log("class=", values[3]); buttonElem.className = values[3]; } else if (values[2] == "visibility") { console.log("visible=", values[3]); buttonElem.style.visibility = values[3]; } else if (values[2] == "display") { console.log("block=", values[3]); buttonElem.style.display = values[3]; } break; case 'RELOAD': console.log("RELOAD values[1]=" + values[1]); console.log("RELOAD values[2]=" + values[2]); console.log("RELOAD values[3]=" + values[3]); window.location.reload(); case 'DATA': console.log("ADD values.length=" + values.length); for(var i=1;i<values.length;i++) { console.log("ADD values[%d]=[%s]", i, values[i]); } //console.log("ADD values[2]=" + values[2]); //console.log("ADD values[3]=" + values[3]); let tableElem = document.getElementById('targetTable'); var row = targetTable.rows.length; console.log("row=%d maxRow=%d", row, maxRow); if (row > maxRow) { for (var i=maxRow;i<row;i++) { tableElem.deleteRow(1); } } let newRow = tableElem.insertRow(); for(var i=1;i<values.length;i++) { let newCell = newRow.insertCell(); let newText = document.createTextNode(values[i]); newCell.appendChild(newText); } /* let newCell = newRow.insertCell(); let newText = document.createTextNode(values[1]); newCell.appendChild(newText); newCell = newRow.insertCell(); newText = document.createTextNode(values[2]); newCell.appendChild(newText); */ default: break; } } websocket.onclose = function(evt) { console.log('Websocket connection closed'); //document.getElementById("datetime").innerHTML = "WebSocket closed"; } websocket.onerror = function(evt) { console.log('Websocket error: ' + evt); //document.getElementById("datetime").innerHTML = "WebSocket error????!!!1!!"; }
export const addNote = (payload) => { return { type: "ADD_NOTE", payload, }; }; export const addContent = (payload) => { return { type: "ADD_CONTENT", payload, }; }; export const permanentDeleteNote = (payload) => { return { type: "PERMANENT_DELETE", payload, }; }; export const deleteNote = (payload) => { return { type: "DELETE_NOTE", payload, }; }; export const deleteNoteFromArchive = (payload) => { return { type: "DELETE_NOTE_FROM_ARCHIVE", payload, }; }; export const archiveNote = (payload) => { return { type: "ARCHIVE_NOTE", payload, }; }; export const restoreNote = (payload) => { return { type: "RESTORE_NOTE", payload, }; }; export const unarchiveNote = (payload) => { return { type: "UNARCHIVE_NOTE", payload, }; };
function initializevbox1288931495311() { vbox1288931495311 = new kony.ui.Box({ "id": "vbox1288931495311", "isVisible": true, "orientation": constants.BOX_LAYOUT_VERTICAL, "position": constants.BOX_POSITION_AS_NORMAL }, { "containerWeight": 100, "layoutType": constants.CONTAINER_LAYOUT_BOX, "margin": [0, 0, 0, 0], "marginInPixel": false, "padding": [0, 0, 0, 0], "paddingInPixel": false, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, {}); var hbox117989725234411 = new kony.ui.Box({ "id": "hbox117989725234411", "isVisible": true, "orientation": constants.BOX_LAYOUT_HORIZONTAL, "position": constants.BOX_POSITION_AS_NORMAL }, { "containerWeight": 100, "layoutAlignment": constants.BOX_LAYOUT_ALIGN_FROM_LEFT, "layoutType": constants.CONTAINER_LAYOUT_BOX, "margin": [0, 0, 0, 0], "marginInPixel": false, "padding": [0, 0, 0, 0], "paddingInPixel": false, "percent": true, "vExpand": false, "widgetAlignment": constants.WIDGET_ALIGN_TOP_LEFT }, {}); var image2117989725234414 = new kony.ui.Image2({ "id": "image2117989725234414", "isVisible": true }, { "containerWeight": 100, "imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO, "margin": [0, 0, 0, 0], "marginInPixel": false, "padding": [0, 0, 0, 0], "paddingInPixel": false, "referenceHeight": 100, "referenceWidth": 800, "widgetAlignment": constants.WIDGET_ALIGN_CENTER }, { "glossyEffect": constants.IMAGE_GLOSSY_EFFECT_DEFAULT }); hbox117989725234411.add(image2117989725234414); vbox1288931495311.add(hbox117989725234411); }
import React from 'react'; import 'jest-styled-components'; import { mount } from 'enzyme'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; import { ThemeProvider } from 'styled-components'; import { themeLight } from '../src/styles/themes/theme.light'; import { themeDark } from '../src/styles/themes/theme.dark'; import { BrowserRouter } from 'react-router-dom'; import Layout from '../src/Layout'; const mockStore = configureMockStore(); const patterns = [ { uuid: 'abc123', name: 'Prototype', type: 'creational', codeES5: 'Code ES5 - Prototype', codeES6: 'Code ES6 - Prototype', answered: false, answerId: null, correct: null }, { uuid: 'abc234', name: 'SIngleton', type: 'creational', codeES5: 'Code ES5 - Singleton', codeES6: 'Code ES6 - Singleton', answered: false, answerId: null, correct: null } ]; describe('Layout', () => { describe('Header - LIGHT mode', () => { let tree; const store = mockStore({ patterns: patterns, progress: { answers: [], remaining: [patterns[1]], current: patterns[0] }, intro: false, mode: 'light', js: 'es5' }); beforeEach(() => { tree = mount( <Provider store={store}> <BrowserRouter> <ThemeProvider theme={themeLight}> <Layout /> </ThemeProvider> </BrowserRouter> </Provider> ); }); it('has the correct title', () => { expect(tree.find('header h1').text()).toMatch('Design Patterns'); }); it('renders 2 links', () => { expect(tree.find('header a')).toHaveLength(2); }); it('renders 1 span', () => { expect(tree.find('header span')).toHaveLength(1); }); it('renders 2 toggle buttons', () => { expect(tree.find('Header button')).toHaveLength(2); }); }); describe('Header - DARK mode', () => { let tree; const store = mockStore({ patterns: patterns, progress: { answers: [], remaining: [patterns[1]], current: patterns[0] }, intro: false, mode: 'dark', js: 'es5' }); beforeEach(() => { tree = mount( <Provider store={store}> <BrowserRouter> <ThemeProvider theme={themeDark}> <Layout /> </ThemeProvider> </BrowserRouter> </Provider> ); }); it('has the correct title', () => { expect(tree.find('header h1').text()).toMatch('Design Patterns'); }); it('renders 2 links', () => { expect(tree.find('header a')).toHaveLength(2); }); it('renders 1 span', () => { expect(tree.find('header span')).toHaveLength(1); }); it('renders 2 toggle buttons', () => { expect(tree.find('Header button')).toHaveLength(2); }); }); });