text
stringlengths
1
1.05M
<reponame>chylex/Hardcore-Ender-Expansion<filename>src/main/java/chylex/hee/tileentity/spawner/SilverfishRavagedSpawnerLogic.java<gh_stars>10-100 package chylex.hee.tileentity.spawner; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import chylex.hee.system.abstractions.Pos; import chylex.hee.tileentity.TileEntityCustomSpawner; public class SilverfishRavagedSpawnerLogic extends CustomSpawnerLogic{ public SilverfishRavagedSpawnerLogic(TileEntityCustomSpawner spawnerTile){ super(spawnerTile); this.minSpawnDelay = 120; this.maxSpawnDelay = 220; this.spawnRange = 4; this.spawnCount = 2; this.maxNearbyEntities = 5; this.activatingRangeFromPlayer = 12; } @Override protected AxisAlignedBB getSpawnerCheckBB(){ int sx = getSpawnerX(), sy = getSpawnerY(), sz = getSpawnerZ(); return AxisAlignedBB.getBoundingBox(sx, sy, sz, sx+1, sy+1, sz+1).expand(spawnRange*2D, 0.5D, spawnRange*2D); } @Override protected boolean checkSpawnerConditions(){ int sx = getSpawnerX(), sy = getSpawnerY(), sz = getSpawnerZ(); return getSpawnerWorld().getEntitiesWithinAABB(EntitySilverfish.class, AxisAlignedBB.getBoundingBox(sx, sy, sz, sx+1, sy+1, sz+1).expand(10D, 10D, 10D)).size() <= 10; } @Override protected boolean canMobSpawn(EntityLiving entity){ for(int spawnerY = getSpawnerY(), yy = spawnerY; yy > spawnerY-5; yy--){ if (!Pos.at(entity.posX, yy, entity.posZ).isAir(entity.worldObj) || yy == spawnerY-4){ entity.setLocationAndAngles(entity.posX, yy+1, entity.posZ, entity.rotationYaw, 0F); if (entity.worldObj.checkNoEntityCollision(entity.boundingBox) && entity.worldObj.getCollidingBoundingBoxes(entity, entity.boundingBox).isEmpty()){ return true; } } } return false; } @Override protected EntityLiving createMob(World world){ return new EntitySilverfish(world); } }
<gh_stars>1-10 import React, {Component} from 'react' import {Form, Input, Icon} from 'semantic-ui-react' import {connect} from 'react-redux' //even though we might have this in an entirely separate page,to me it //makes sense to restrict access at the component level to have the //extra guarantee const mapState = ({user, categories}) => ({user, categories}) // const mapDispatchToProps = {addNewProduct} export class ProductForm extends Component { constructor(props) { super(props) const name = props.name ? props.name : '' const description = props.description ? props.description : '' const stock = props.stock ? props.stock : '' const price = props.price ? props.price : '' // const productCategories = props.categories // ? props.categories.map(category => category.id) // : '' this.state = { name, description, stock, price, imageUrl: '', productCategories: [] } } handleChange = evt => this.setState({[evt.target.name]: evt.target.value}) handleCategoryChange = evt => { const categoryId = Number(evt.target.id) if (this.state.productCategories.includes(categoryId)) { this.setState({ productCategories: this.state.productCategories.filter( id => id !== categoryId ) }) } else { this.setState({ productCategories: [...this.state.productCategories, categoryId] }) } } handleSubmit = evt => { evt.preventDefault() const { name, description, stock, price, imageUrl, productCategories } = this.state const {verb, action, id} = this.props const product = { name, description, stock, price, imageUrl, productCategories } if (verb === 'Edit') action(id, product) else action(product) this.setState({ name: '', description: '', stock: '', price: '', imageUrl: '', productCategories: [] }) } render() { const {name, description, stock, price, imageUrl} = this.state const {verb, categories} = this.props return ( <Form onSubmit={this.handleSubmit} size="big"> <Form.Group> <Form.Field> <label>Product Name</label> <Input type="text" placeholder="Product Name" name="name" value={name} onChange={this.handleChange} /> </Form.Field> <Form.Field> <label>Description</label> <Input type="text" placeholder="Description" name="description" value={description} onChange={this.handleChange} /> </Form.Field> </Form.Group> <Form.Group> <Form.Field> <label>Stock</label> <Input type="number" placeholder="Stock" name="stock" value={stock} onChange={this.handleChange} /> </Form.Field> <Form.Field> <label>Price</label> <Input type="number" placeholder="Price" name="price" value={price} onChange={this.handleChange} /> </Form.Field> </Form.Group> <Form.Group> <Form.Field> <label>Image URL</label> <Input type="text" placeholder="Image URL" name="imageUrl" value={imageUrl} onChange={this.handleChange} /> </Form.Field> <label htmlFor="">Categories</label> <Form.Group> {categories.length && categories.map(category => ( <Form.Field type="checkbox" id={category.id} key={category.id} control="input" name="category" label={category.name} value={category.id} onChange={this.handleCategoryChange} /> ))} </Form.Group> <Form.Button type="submit"> <Icon name={verb.toLowerCase()} /> {verb} Product </Form.Button> </Form.Group> </Form> ) } } export default connect(mapState)(ProductForm)
#!/bin/bash cd webapi/Guide.ObrasLiterarias.Api/ dotnet restore dotnet publish -c release -o ./publish -r linux-x64 docker build -t guide/webapi:1.0 . cd .. cd .. cd webapp/ObrasLit/ docker build -t guide/webapp:1.0 . cd .. cd .. docker-compose up
#!/bin/bash set -o pipefail # Is arduino-cli installed? arduino-cli version > /dev/null 2>&1 if [ "$?" -ne 0 ]; then go get -u github.com/arduino/arduino-cli # Create a config arduino-cli config init # probably not necessary just after install but just in case - update the # core and library indexes arduino-cli core update-index arduino-cli lib update-index # Install the arduino SAM cores first arduino-cli core install arduino:sam fi arduino-cli config dump | grep "stm32duino" > /dev/null 2>&1 if [ "$?" -ne 0 ]; then # Add the STM32 boards arduino-cli config add board_manager.additional_urls https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json # No need to update-index here since we will do it in the next step fi # Install the STM32 cores arduino-cli board listall | grep "STMicroelectronics:stm32:GenF1" > /dev/null 2>&1 if [ "$?" -ne 0 ]; then # Do an update just in case the arduino-cli wasn't installed this run and it # needs updated arduino-cli core update-index arduino-cli core install STMicroelectronics:stm32 # Just in case there are any libraries required by the STM32 boards? arduino-cli lib update-index arduino-cli lib upgrade else # Everything should be installed, just do an update of what is already # installed arduino-cli core update-index arduino-cli core upgrade arduino-cli lib update-index arduino-cli lib upgrade fi
<filename>modules/dreamview/frontend/src/utils/misc.js<gh_stars>1-10 export function copyProperty(toObj, fromObj) { for (const property in fromObj) { if (fromObj.hasOwnProperty(property)) { toObj[property] = fromObj[property]; } } } export function hideArrayObjects(objects, startIdx = 0) { if (objects.constructor === Array && objects.length > 0) { for (;startIdx < objects.length; startIdx++) { objects[startIdx].visible = false; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.quantconnect.lean.securities; /** * Specifies the open/close state for a <see cref="MarketHoursSegment"/> */ public enum MarketHoursState { /** * The market is not open */ Closed( "closed" ), /** * The market is open, but before normal trading hours */ PreMarket( "premarket" ), /** * The market is open and within normal trading hours */ Market( "market" ), /** * The market is open, but after normal trading hours */ PostMarket( "postmarket" ); private final String value; MarketHoursState( String value ) { this.value = value; } public String toString() { return value; } }
#!/usr/bin/env bash source $WORKSPACE/venv/bin/activate
#!/bin/bash REPO_DIR="$( cd "$(dirname $( dirname "${BASH_SOURCE[0]}" ))" &> /dev/null && pwd )" GEN_YAML_DIR="${REPO_DIR}/.generated-yaml" TEMPLATES_DIR="${REPO_DIR}/scripts/goreleaser-templates" MAIN_TEMPLATE="${TEMPLATES_DIR}/goreleaser.yaml" YQ=$(which yq) while getopts d:y: flag do case "${flag}" in d) distributions=${OPTARG};; y) YQ=${OPTARG};; esac done if [[ -z $distributions ]]; then echo "List of distributions to use with goreleaser not provided. Use '-d' to specify the names of the distributions. Ex.:" echo "$0 -d opentelemetry-collector" exit 1 fi mkdir -p "${GEN_YAML_DIR}" touch "${GEN_YAML_DIR}/last-generation" templates=$(ls ${TEMPLATES_DIR}/*.template.yaml | xargs -n 1 basename | sed 's/.template.yaml//gi') for template in $templates do for distribution in $(echo $distributions | tr "," "\n") do export CONTAINER_BASE_NAME="otel/{distribution}" DIST_CONF="${REPO_DIR}/distributions/${distribution}/distribution.conf" if [[ -f "${DIST_CONF}" ]]; then set -o allexport source "${DIST_CONF}" set +o allexport fi sed "s/{distribution}/${distribution}/gi" "${TEMPLATES_DIR}/${template}.template.yaml" | envsubst > "${GEN_YAML_DIR}/${distribution}-${template}.yaml" if [[ $? -ne 0 ]]; then echo "❌ ERROR: failed to generate '${template}' YAML snippets for '${distribution}'." exit 1 fi done done set -e -o pipefail ${YQ} eval-all '. as $item ireduce ({}; . *+ $item)' "${MAIN_TEMPLATE}" "${GEN_YAML_DIR}"/*.yaml > .goreleaser.yaml echo "✅ SUCCESS: goreleaser YAML generated"
export const environment = { production: true, firebase: { apiKey: '<KEY>', authDomain: 'app-mini-netflix.firebaseapp.com', databaseURL: 'https://app-mini-netflix.firebaseio.com', projectId: 'app-mini-netflix', storageBucket: 'app-mini-netflix.appspot.com', messagingSenderId: '513014570227', appId: '1:513014570227:web:dc8ded86bef56ecc3beb86', measurementId: 'G-0WZF81CVQH' } };
mkdir build cd build cmake ../ make cd ../ export GAZEBO_PLUGIN_PATH=./build gzserver -u --verbose blank.world
#!/bin/bash # Sleep 30 seconds to allow network to stabalize before attempting package install sleep 30 zypper install -y mdadm n=$(find /dev/disk/azure/scsi1/ -name "lun*"|wc -l) n="${n//\ /}" mdadm --create /dev/md0 --force --level=stripe --raid-devices=$n /dev/disk/azure/scsi1/lun* mkfs.xfs /dev/md0 mkdir /sas echo "$(blkid /dev/md0 | cut -d ' ' -f 2) /sas xfs defaults 0 0" | tee -a /etc/fstab mount /sas
import Carousel from 'antd/es/carousel' import 'antd/es/carousel/style/css' export { Carousel }
<reponame>Luxcium/redis-json import { promisify } from 'util'; import { Flattener, IFlattener } from './flattener'; import { IOptions, ISetOptions, IResult } from '../interfaces'; import { TYPE } from '../utils/type'; type IPromisified = (...args: any[]) => Promise<any>; type Methods = 'hmset' | 'hmget' | 'hgetall' | 'expire' | 'del' | 'scan' | 'hincrbyfloat'; type IRedisMethods = { [K in Methods]: IPromisified; }; type IRedisClient = IRedisMethods; type Transaction = any; type RecursivePartial<T> = { [P in keyof T]?: T[P] extends any[] ? Array<RecursivePartial<T[P]>> : T[P] extends any ? RecursivePartial<T[P]> : T[P]; }; interface IJSONCache<T> { set(key: string, obj: T, options: ISetOptions): Promise<any>; get(key: string, ...fields: string[]): Promise<Partial<T> | undefined>; rewrite(key: string, obj: T, options?: ISetOptions): Promise<any>; clearAll(): Promise<any>; del(key: string): Promise<any>; incr(key: string, obj: RecursivePartial<T>): Promise<any>; // Transaction methods setT(transaction: Transaction, key: string, obj: T, options: ISetOptions): Transaction; rewriteT(transaction: Transaction, key: string, obj: T, options?: ISetOptions): Transaction; delT(transaction: Transaction, key: string): Transaction; incrT(transaction: Transaction, key: string, obj: RecursivePartial<T>): Transaction; } const SCAN_COUNT = 100; /** * JSONCache eases the difficulties in storing a JSON in redis. * * It stores the JSON in hashset for simpler get and set of required * fields. It also allows you to override/set specific fields in * the JSON without rewriting the whole JSON tree. Which means that it * is literally possible to `Object.deepAssign()`. * * Everytime you store an object, JSONCache would store two hashset * in Redis, one for data and the other for type information. This helps * during retrieval of data, to restore the type of data which was originally * provided. All these workaround are needed because Redis DOES NOT support * any other data type apart from String. * * Well the easiest way is to store an object in Redis is * JSON.stringify(obj) and store the stringified result. * But this can cause issue when the obj is * too huge or when you would want to retrieve only specific fields * from the JSON but do not want to parse the whole JSON. * Also note that this method would end up in returing all the * fields as strings and you would have no clue to identify the type of * field. */ export default class JSONCache<T = any> implements IJSONCache<T> { private redisClientInt: IRedisClient; private flattener: IFlattener; /** * Intializes JSONCache instance * @param redisClient RedisClient instance(Preferred ioredis - cient). * It supports any redisClient instance that has * `'hmset' | 'hmget' | 'hgetall' | 'expire' | 'del' | 'keys'` * methods implemented * @param options Options for controlling the prefix */ constructor(redisClient: any, private options: IOptions = {}) { this.options.prefix = options.prefix || 'jc:'; this.redisClientInt = { hmset: promisify(redisClient.hmset).bind(redisClient), hmget: promisify(redisClient.hmget).bind(redisClient), hgetall: promisify(redisClient.hgetall).bind(redisClient), expire: promisify(redisClient.expire).bind(redisClient), del: promisify(redisClient.del).bind(redisClient), scan: promisify(redisClient.scan).bind(redisClient), hincrbyfloat: promisify(redisClient.hincrbyfloat).bind(redisClient), }; this.flattener = new Flattener(options.stringifier, options.parser); } /** * Flattens the given json object and * stores it in Redis hashset * * @param key Redis key * @param obj JSON object to be stored * @param options */ public async set(key: string, obj: T, options: ISetOptions = {}): Promise<any> { const flattened = this.flattener.flatten(obj); await Promise.all([ this.redisClientInt.hmset(this.getKey(key), flattened.data), this.redisClientInt.hmset(this.getTypeKey(key), flattened.typeInfo), ]); if (options.expire) { await Promise.all([ this.redisClientInt.expire(this.getKey(key), options.expire), this.redisClientInt.expire(this.getTypeKey(key), options.expire), ]); } } /** * Flattens the given json object and * stores it in Redis hashset using * the given transaction * * @param transaction redis transaction * @param key Redis key * @param obj JSON object to be stored * @param options */ public setT(transaction: Transaction, key: string, obj: T, options: ISetOptions = {}): Transaction { const flattened = this.flattener.flatten(obj); transaction.hmset(this.getKey(key), flattened.data); transaction.hmset(this.getTypeKey(key), flattened.typeInfo); if (options.expire) { transaction.expire(this.getKey(key), options.expire); transaction.expire(this.getTypeKey(key), options.expire); } return transaction; } /** * Retrieves the hashset from redis and * unflattens it back to the original Object * * @param key Redis key * @param fields List of fields to be retreived from redis. * This helps reduce network latency incase only a few fields are * needed. * * @returns request object from the cache */ public async get(key: string, ...fields: string[]): Promise<Partial<T> | undefined> { const [data, typeInfo] = await Promise.all([ this.redisClientInt.hgetall(this.getKey(key)), this.redisClientInt.hgetall(this.getTypeKey(key)), ]); // Empty object is returned when // the given key is not present // in the cache if (!data || Object.keys(data).length === 0) { return undefined; } let result: IResult; if (fields.length > 0) { let dataKeys: string[]; result = fields.reduce((res, field) => { if (field in data) { res.data[field] = data[field]; res.typeInfo[field] = typeInfo[field]; } else { const searchKey = `${field}.`; (dataKeys || (dataKeys = Object.keys(data))).forEach(flattenedKey => { if (flattenedKey.startsWith(searchKey)) { res.data[flattenedKey] = data[flattenedKey]; res.typeInfo[flattenedKey] = typeInfo[flattenedKey]; } }); } return res; }, { data: {}, typeInfo: {} }) as IResult; } else { result = { data, typeInfo }; } return this.flattener.unflatten(result) as T; } /** * Replace the entire hashset for the given key * * @param key Redis key * @param obj JSON Object of type T */ public async rewrite(key: string, obj: T, options?: ISetOptions): Promise<any> { await this.redisClientInt.del(this.getKey(key)); await this.set(key, obj, options); } /** * Replace the entire hashset for the given key * * @param transaction Redis transaction * @param key Redis key * @param obj JSON Object of type T */ public rewriteT(transaction: Transaction, key: string, obj: T, options?: ISetOptions): Transaction { transaction.del(this.getKey(key)); return this.setT(transaction, key, obj, options); } /** * Removes/deletes all the keys in the JSON Cache, * having the prefix. */ public async clearAll(): Promise<any> { let cursor = '0'; let keys: string[]; do { [cursor, keys] = await this.redisClientInt.scan(cursor, 'MATCH', `${this.options.prefix}*`, 'COUNT', SCAN_COUNT); if (keys.length > 0) { await this.redisClientInt.del(...keys); } } while (cursor !== '0'); } /** * Removes the given key from Redis * * Please use this method instead of * directly using `redis.del` as this method * ensures that even the corresponding type info * is removed. It also ensures that prefix is * added to key, ensuring no other key is * removed unintentionally * * @param key Redis key */ public async del(key: string): Promise<any> { await Promise.all([ this.redisClientInt.del(this.getKey(key)), this.redisClientInt.del(this.getTypeKey(key)), ]); } /** * Removes the given key from Redis * using the given transaction * * Please use this method instead of * directly using `redis.del` as this method * ensures that even the corresponding type info * is removed. It also ensures that prefix is * added to key, ensuring no other key is * removed unintentionally * * @param transaction Redis transaction * @param key Redis key */ public delT(transaction: Transaction, key: string): Transaction { transaction.del(this.getKey(key)); transaction.del(this.getTypeKey(key)); return transaction; } /** * Increments the value of a variable in the JSON * Note: You can increment multiple variables in the * same command (Internally it will split it into multiple * commands on the RedisDB) * * @example * ```JS * await jsonCache.incr(key, {messages: 10, profile: {age: 1}}) * ``` * * @param key Redis Cache key * @param obj Partial object specifying the path to the required * variable along with value */ public async incr(key: string, obj: RecursivePartial<T>): Promise<any> { const flattened = this.flattener.flatten(obj); await Promise.all(Object.entries(flattened.data).map(([path, incrVal]) => { // This check is needed to avoid redis errors. // It also helps while the user wants to increment the value // within an array. // Ex: rand: [null, null, 1] => this will increment the 3rd index by 1 if (flattened.typeInfo[path] !== TYPE.NUMBER) { return; } return this.redisClientInt.hincrbyfloat(this.getKey(key), path, incrVal); })); } public incrT(transaction: Transaction, key: string, obj: RecursivePartial<T>): Transaction { const flattened = this.flattener.flatten(obj); Object.entries(flattened.data).forEach(([path, incrVal]) => { // This check is needed to avoid redis errors. // It also helps while the user wants to increment the value // within an array. // Ex: rand: [null, null, 1] => this will increment the 3rd index by 1 if (flattened.typeInfo[path] !== TYPE.NUMBER) { return; } transaction.hincrbyfloat(this.getKey(key), path, incrVal); }); return transaction; } /****************** * PRIVATE METHODS ******************/ /** * Returns the redis storage key for storing data * by prefixing custom string, such that it * doesn't collide with other keys in usage * * @param key Storage key */ private getKey(key: string): string { return `${this.options.prefix}${key}`; } /** * Returns the redis storage key for storing * corresponding types by prefixing custom string, * such that it doesn't collide with other keys * in usage * * @param key Storage key */ private getTypeKey(key: string): string { return `${this.options.prefix}${key}_t`; } }
def is_number(s): try: float(s) return True except ValueError: return False
# # Copyright (c) 2013-2014, 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # -*- encoding: utf-8 -*- # from cgtsclient.common import base from cgtsclient.common import utils from cgtsclient import exc CREATION_ATTRIBUTES = ['ihost_uuid', 'istor_uuid', 'serial_id', 'device_node', 'device_num', 'device_type', 'device_path', 'capabilities', 'size_mib'] class idisk(base.Resource): def __repr__(self): return "<idisk %s>" % self._info class idiskManager(base.Manager): resource_class = idisk def list(self, ihost_id): path = '/v1/ihosts/%s/idisks' % ihost_id return self._list(path, "idisks") def get(self, idisk_id): path = '/v1/idisks/%s' % idisk_id try: return self._list(path)[0] except IndexError: return None def create(self, **kwargs): path = '/v1/idisks/' new = {} for (key, value) in kwargs.items(): if key in CREATION_ATTRIBUTES: new[key] = value else: raise exc.InvalidAttribute(key) return self._create(path, new) def delete(self, idisk_id): path = '/v1/idisks/%s' % idisk_id return self._delete(path) def update(self, idisk_id, patch): path = '/v1/idisks/%s' % idisk_id return self._update(path, patch) def get_disk_display_name(d): if d.device_node: return d.device_node else: return '(' + str(d.uuid)[-8:] + ')' def _find_disk(cc, ihost, idisk_id): if utils.is_uuid_like(idisk_id): try: disk = cc.idisk.get(idisk_id) except exc.HTTPNotFound: return None else: return disk else: disklist = cc.idisk.list(ihost.uuid) for disk in disklist: if disk.device_node == idisk_id or disk.device_path == idisk_id: return disk else: return None
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from . import shutil_get_terminal_size from . import weakref from . import shlex
<filename>src/components/Basic/PendingTransaction.tsx<gh_stars>0 import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import { connect } from 'react-redux'; import moment from 'moment'; import LoadingSpinner from 'components/Basic/LoadingSpinner'; import { Setting } from 'types'; import { State } from 'core/modules/initialState'; import { Label } from './Label'; const PendingTransactionWrapper = styled.div` border-top: 1px solid var(--color-bg-active); .title { padding: 16px; font-size: 20px; font-weight: 600; color: var(--color-text-main); } .content { display: flex; align-items: center; justify-content: space-between; padding: 20px; .content-info { display: flex; align-items: center; justify-content: flex-start; } .content-date { display: flex; align-items: center; justify-content: center; } span { margin-left: 10px; } } `; interface PendingTransactionProps { settings: Setting; } function PendingTransaction({ settings }: PendingTransactionProps) { const [curTime, setCurTime] = useState(''); useEffect(() => { const dateTime = new Date(); setCurTime(moment(dateTime).format('LLL')); }, []); return ( <PendingTransactionWrapper> <div className="title">Pending Transactions</div> <div className="content"> <div className="content-info"> <LoadingSpinner size={20} /> <Label size="16" primary> {settings.pendingInfo.type} </Label> <Label size="16" primary> {settings.pendingInfo && settings.pendingInfo.amount} </Label> <Label size="16" primary> {settings.pendingInfo && settings.pendingInfo.symbol} </Label> </div> <div className="content-data"> <Label size="14">{curTime}</Label> </div> </div> </PendingTransactionWrapper> ); } const mapStateToProps = ({ account }: State) => ({ settings: account.setting, }); export default connect(mapStateToProps)(PendingTransaction);
import helpers.CertbotDockerTagResolver; import io.homecentr.testcontainers.containers.GenericContainerEx; import io.homecentr.testcontainers.containers.wait.strategy.WaitEx; import io.homecentr.testcontainers.images.PullPolicyEx; import org.junit.Test; import org.testcontainers.containers.ContainerLaunchException; import java.time.Duration; import static io.homecentr.testcontainers.WaitLoop.waitFor; public class CertbotContainerWithoutWritableVolumesShould { @Test public void failWhenCertsDirNotWritable() throws Exception { GenericContainerEx container = new GenericContainerEx<>(new CertbotDockerTagResolver()) .withEnv("CRON_SCHEDULE", "* * * * *") .withEnv("CERTBOT_ARGS", "") .withEnv("PUID", "9001") .withEnv("PGID", "9002") .withTempDirectoryBind("/certs", 0) .withTempDirectoryBind("/logs", 9002) .withTempDirectoryBind("/state", 9002) .withImagePullPolicy(PullPolicyEx.never()) .waitingFor(WaitEx.forS6OverlayStart()); assertExits(container); } @Test public void failWhenLogsDirNotWritable() throws Exception { GenericContainerEx container = new GenericContainerEx<>(new CertbotDockerTagResolver()) .withEnv("CRON_SCHEDULE", "* * * * *") .withEnv("CERTBOT_ARGS", "") .withEnv("PUID", "9001") .withEnv("PGID", "9002") .withTempDirectoryBind("/certs", 9002) .withTempDirectoryBind("/logs", 0) .withTempDirectoryBind("/state", 9002) .withImagePullPolicy(PullPolicyEx.never()) .waitingFor(WaitEx.forS6OverlayStart()); assertExits(container); } @Test public void failWhenStateDirNotWritable() throws Exception { GenericContainerEx container = new GenericContainerEx<>(new CertbotDockerTagResolver()) .withEnv("CRON_SCHEDULE", "* * * * *") .withEnv("CERTBOT_ARGS", "") .withEnv("PUID", "9001") .withEnv("PGID", "9002") .withTempDirectoryBind("/certs", 9002) .withTempDirectoryBind("/logs", 9002) .withTempDirectoryBind("/state", 0) .withImagePullPolicy(PullPolicyEx.never()) .waitingFor(WaitEx.forS6OverlayStart()); assertExits(container); } private void assertExits(GenericContainerEx container) throws Exception { // start try { container.start(); } catch (ContainerLaunchException ex) { // Expected } waitFor(Duration.ofSeconds(10), () -> !container.isRunning()); waitFor(Duration.ofSeconds(10), () -> !container.getLogsAnalyzer().contains(".*not writable.*")); } }
#!/bin/bash xrandr xrandr --auto --output eDP1 --mode 1920x1080 --dpi 94 xrandr --auto --output eDP1 --mode 1920x1080 --same-as DP3 xrandr --auto --output DP1 --mode 1920x1080 --same-as eDP1 gsettings set org.gnome.desktop.interface scaling-factor 2
<filename>applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/iostreams/detail/vc6/close.hpp // (C) Copyright <NAME> 2005. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. namespace boost { namespace iostreams { namespace detail { template<typename T> struct close_impl; } // End namespace detail. template<typename T> void close(T& t, BOOST_IOS::openmode which) { typedef typename detail::unwrapped_type<T>::type unwrapped; detail::close_impl<T>::inner<unwrapped>::close(detail::unwrap(t), which); } template<typename T, typename Sink> void close(T& t, Sink& snk, BOOST_IOS::openmode which) { typedef typename detail::unwrapped_type<T>::type unwrapped; detail::close_impl<T>::inner<unwrapped>::close(detail::unwrap(t), snk, which); } namespace detail { //------------------Definition of close_impl----------------------------------// template<typename T> struct close_tag { typedef typename category_of<T>::type category; typedef typename mpl::eval_if< is_convertible<category, closable_tag>, mpl::if_< mpl::or_< is_convertible<category, two_sequence>, is_convertible<category, dual_use> >, two_sequence, closable_tag >, mpl::identity<any_tag> >::type type; }; template<typename T> struct close_impl : mpl::if_< is_custom<T>, operations<T>, close_impl<BOOST_DEDUCED_TYPENAME close_tag<T>::type> >::type { }; template<> struct close_impl<any_tag> { template<typename T> struct inner { static void close(T& t, BOOST_IOS::openmode which) { if ((which & BOOST_IOS::out) != 0) iostreams::flush(t); } template<typename Sink> static void close(T& t, Sink& snk, BOOST_IOS::openmode which) { if ((which & BOOST_IOS::out) != 0) { non_blocking_adapter<Sink> nb(snk); iostreams::flush(t, nb); } } }; }; template<> struct close_impl<closable_tag> { template<typename T> struct inner { static void close(T& t, BOOST_IOS::openmode which) { typedef typename category_of<T>::type category; const bool in = is_convertible<category, input>::value && !is_convertible<category, output>::value; if (in == ((which & BOOST_IOS::in) != 0)) t.close(); } template<typename Sink> static void close(T& t, Sink& snk, BOOST_IOS::openmode which) { typedef typename category_of<T>::type category; const bool in = is_convertible<category, input>::value && !is_convertible<category, output>::value; if (in == ((which & BOOST_IOS::in) != 0)) { non_blocking_adapter<Sink> nb(snk); t.close(nb); } } }; }; template<> struct close_impl<two_sequence> { template<typename T> struct inner { static void close(T& t, BOOST_IOS::openmode which) { t.close(which); } template<typename Sink> static void close(T& t, Sink& snk, BOOST_IOS::openmode which) { non_blocking_adapter<Sink> nb(snk); t.close(nb, which); } }; }; } // End namespace detail. } } // End namespaces iostreams, boost.
import { Meta, Story } from '@storybook/react' import { Logo, LogoProps } from '.' export default { title: 'Logo', component: Logo } as Meta export const Default: Story<LogoProps> = (args) => <Logo {...args} /> Default.args = { color: 'white', size: 'normal', hideOnMobile: false }
<filename>src/main/java/com/revature/model/Reimbursement.java package com.revature.model; import java.util.Objects; public class Reimbursement { private int reimbursementId; private double reimbursementAmount; private String reimbursementSubmitted; private String reimbursementResolved; private String reimbursementDescription; private String reimbursementReceipt; private User reimbursementAuthor; private User reimbursementResolver; private ReimbursementStatus reimbursementStatus; private ReimbursementType reimbursementType; public Reimbursement() {} public Reimbursement(int reimbursementId, double reimbursementAmount, String reimbursementSubmitted, String reimbursementResolved, String reimbursementDescription, String reimbursementReceipt, User reimbursementAuthor, User reimbursementResolver, ReimbursementStatus reimbursementStatus, ReimbursementType reimbursementType) { this.reimbursementId = reimbursementId; this.reimbursementAmount = reimbursementAmount; this.reimbursementSubmitted = reimbursementSubmitted; this.reimbursementResolved = reimbursementResolved; this.reimbursementDescription = reimbursementDescription; this.reimbursementReceipt = reimbursementReceipt; this.reimbursementAuthor = reimbursementAuthor; this.reimbursementResolver = reimbursementResolver; this.reimbursementStatus = reimbursementStatus; this.reimbursementType = reimbursementType; } public int getReimbursementId() { return reimbursementId; } public void setReimbursementId(int reimbursementId) { this.reimbursementId = reimbursementId; } public double getReimbursementAmount() { return reimbursementAmount; } public void setReimbursementAmount(double reimbursementAmount) { this.reimbursementAmount = reimbursementAmount; } public String getReimbursementSubmitted() { return reimbursementSubmitted; } public void setReimbursementSubmitted(String reimbursementSubmitted) { this.reimbursementSubmitted = reimbursementSubmitted; } public String getReimbursementResolved() { return reimbursementResolved; } public void setReimbursementResolved(String reimbursementResolved) { this.reimbursementResolved = reimbursementResolved; } public String getReimbursementDescription() { return reimbursementDescription; } public void setReimbursementDescription(String reimbursementDescription) { this.reimbursementDescription = reimbursementDescription; } public String getReimbursementReceipt() { return reimbursementReceipt; } public void setReimbursementReceipt(String reimbursementReceipt) { this.reimbursementReceipt = reimbursementReceipt; } public User getReimbursementAuthor() { return reimbursementAuthor; } public void setReimbursementAuthor(User reimbursementAuthor) { this.reimbursementAuthor = reimbursementAuthor; } public User getReimbursementResolver() { return reimbursementResolver; } public void setReimbursementResolver(User reimbursementResolver) { this.reimbursementResolver = reimbursementResolver; } public ReimbursementStatus getReimbursementStatus() { return reimbursementStatus; } public void setReimbursementStatus(ReimbursementStatus reimbursementStatus) { this.reimbursementStatus = reimbursementStatus; } public ReimbursementType getReimbursementType() { return reimbursementType; } public void setReimbursementType(ReimbursementType reimbursementType) { this.reimbursementType = reimbursementType; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Reimbursement that = (Reimbursement) o; return reimbursementId == that.reimbursementId && Double.compare(that.reimbursementAmount, reimbursementAmount) == 0 && Objects.equals(reimbursementSubmitted, that.reimbursementSubmitted) && Objects.equals(reimbursementResolved, that.reimbursementResolved) && Objects.equals(reimbursementDescription, that.reimbursementDescription) && Objects.equals(reimbursementReceipt, that.reimbursementReceipt) && Objects.equals(reimbursementAuthor, that.reimbursementAuthor) && Objects.equals(reimbursementResolver, that.reimbursementResolver) && Objects.equals(reimbursementStatus, that.reimbursementStatus) && Objects.equals(reimbursementType, that.reimbursementType); } @Override public int hashCode() { return Objects.hash(reimbursementId, reimbursementAmount, reimbursementSubmitted, reimbursementResolved, reimbursementDescription, reimbursementReceipt, reimbursementAuthor, reimbursementResolver, reimbursementStatus, reimbursementType); } @Override public String toString() { return "Reimbursement{" + "reimbursementId=" + reimbursementId + ", reimbursementAmount=" + reimbursementAmount + ", reimbursementSubmitted='" + reimbursementSubmitted + '\'' + ", reimbursementResolved='" + reimbursementResolved + '\'' + ", reimbursementDescription='" + reimbursementDescription + '\'' + ", reimbursementReceipt='" + reimbursementReceipt + '\'' + ", reimbursementAuthor=" + reimbursementAuthor + ", reimbursementResolver=" + reimbursementResolver + ", reimbursementStatus=" + reimbursementStatus + ", reimbursementType=" + reimbursementType + '}'; } }
import Vue from "vue"; import Vuex from "vuex"; import vehicle from "./modules/vehicleTypes"; import fee from "./modules/parkFees"; Vue.use(Vuex); export default new Vuex.Store({ state: { loadingScreenStatus: false, totalPrice: "" }, mutations: { setLoadingScreenStatus(state, payload) { state.loadingScreenStatus = payload; }, setTotalPrice(state, payload) { state.totalPrice = payload; } }, getters: { getLoadingScreenStatus(state) { return state.loadingScreenStatus; }, getTotalPrice(state) { return state.totalPrice; } }, actions: {}, modules: { vehicle, fee } });
(function(){ "use strict"; var regalo = document.querySelector('#regalo'); document.addEventListener('DOMContentLoaded', function(){ /* var map = L.map('mapa').setView([-34.573016, -58.503973], 18); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); L.marker([-34.573016, -58.503973]).addTo(map) .bindPopup('Instituto Politecnico Modelo') .openPopup(); */ //Campos datos usuarios var nombre = document.querySelector('#nombre'); var apellido = document.querySelector('#apellido'); var email = document.querySelector('#email'); //Botones y divs var calcular = document.querySelector('#calcular'); var errorDiv = document.querySelector('#error'); var registro = document.querySelector('#btnRegistro'); var lista_productos = document.querySelector('#lista-productos'); var suma = document.querySelector('#suma-total'); //Extras var camisas = document.querySelector('#camisa_evento'); var etiquetas = document.querySelector('#etiquetas'); calcular.addEventListener('click', calcularMontos); for(var i = 0; i < lista.length; i++){ console.log(lista[i]); lista[i].addEventListener('blur', mostrarDias); } nombre.addEventListener('blur', validarCampos); apellido.addEventListener('blur', validarCampos); email.addEventListener('blur', validarCampos); email.addEventListener('blur', validarMail); function validarCampos(){ if(this.value == ''){ errorDiv.style.display = 'block'; errorDiv.innerHTML = "Este campo es obligatorio"; this.style.border = "1px solid red"; errorDiv.style.border = "1px solid red"; } else{ errorDiv.style.display = 'none'; this.style.border = '1px solid #cccccc'; } } function validarMail(){ if(this.value.indexOf("@") > -1){ errorDiv.style.display = 'none'; this.style.border = '1px solid #cccccc'; } else{ errorDiv.style.display = 'block'; errorDiv.innerHTML = "Este campo debe tener @"; this.style.border = "1px solid red"; errorDiv.style.border = "1px solid red"; } } function calcularMontos(event){ event.preventDefault(); if(regalo.value === ''){ alert("Debes elegir un regalo"); regalo.focus(); } else{ console.log("Ya elegiste regalo"); var boletoDia = parseInt(lista[0].value, 10)||0, boletoDosDias = parseInt(lista[2].value, 10)||0, boletoCompleto = parseInt(lista[1].value, 10)||0, cantidadCamisas = parseInt(listaSuvenier[0].value, 10)||0, cantidadEtiquetas = parseInt(listaSuvenier[1].value, 10)||0; var totalAPagar = 0; var superLista = lista.concat(listaSuvenier); var superListaPrecios = listaPrecioBoleto.concat(listaPrecioSuvenier); var superListaDescripcion = listaDescripcionBoleto.concat(listaDescripcionSuvenier); var valor = 0 for(var i = 0; i < superLista.length; i++){ valor = parseInt(superLista[i].value, 10); console.log(valor); if(valor > 0){ totalAPagar = totalAPagar + (valor * (superListaPrecios[i])); } console.log(totalAPagar); } /*var totalAPagar = (boletoDia * listaPrecioBoleto[0]) + (boletoDosDias * listaPrecioBoleto[2]) + (boletoCompleto * listaPrecioBoleto[1]) + ((cantidadCamisas * listaPrecioSuvenier[0]) * .93) + (cantidadEtiquetas * listaPrecioSuvenier[1]); */ var listaProductos = []; /*if(boletoDia >= 1){ listaProductos.push(boletoDia + ' Pases por día'); } if(boletoDosDias >= 1){ listaProductos.push(boletoDosDias + ' Pases por dos día'); } if(boletoCompleto >= 1){ listaProductos.push(boletoCompleto + ' Pases completos'); } if(cantidadCamisas >= 1){ listaProductos.push(cantidadCamisas + ' Camisas'); } if(cantidadEtiquetas >= 1){ listaProductos.push(cantidadEtiquetas + ' Etiquetas'); }*/ for(var i = 0; i < superListaDescripcion.length; i++){ valor = superLista[i] if(superLista[i].value >= 1){ listaProductos.push(superLista[i].value + " " + superListaDescripcion[i]); console.log(listaProductos[i]) } } lista_productos.style.display = 'block'; lista_productos.innerHTML = ''; for(var i = 0; i < listaProductos.length; i++){ lista_productos.innerHTML += listaProductos[i] + '<br>' } suma.innerHTML = '$ ' + totalAPagar.toFixed(2); } } function mostrarDias(){ var boletoDia = parseInt(lista[0].value, 10)||0, boletoDosDias = parseInt(lista[2].value, 10)||0, boletoCompleto = parseInt(lista[1].value, 10)||0; var diasElegidos = []; if(boletoDia > 0){ diasElegidos.push('#viernes'); } if(boletoDosDias > 0){ diasElegidos.push('#viernes', '#sabado'); } if(boletoCompleto > 0){ diasElegidos.push('#viernes', '#sabado', '#domingo'); } for(var i = 0; i < diasElegidos.length; i++){ document.querySelector(diasElegidos[i]).style.display = 'block'; } } }); //Contenido del DOM cargado })()
<reponame>Nusushi/Nusushi /// <reference path="../jsx.ts" /> "use strict"; import { VNode, VNodeProperties } from "maquette"; declare var require: any; var velocity: any = require("velocity-animate"); import * as maquette from "maquette"; const h = maquette.h; import { CaliforniaApp, DEFAULT_EXCEPTION, getArrayForEnum, parseIntFromAttribute, parseStringFromAttribute } from "./CaliforniaApp"; import { PropertyBarMode, PropertyBarVM, PopupMode, PopupSecondaryMode, TransactionMode } from "./../ViewModels/PropertyBarVM"; import { StyleQuantum, StyleAtom, StyleValue, StyleAtomType, StyleMolecule, ResponsiveDevice, StyleMoleculeAtomMapping, LayoutBase, LayoutRow, LayoutBox, LayoutAtom, LayoutType, CaliforniaView, SpecialLayoutBoxType, ContentAtom, CaliforniaEvent } from "./CaliforniaGenerated"; import { EditViewMode, ReadyState, SelectionMode } from "./ClientState"; import * as popperjs from "popper.js"; import { ContentAtomType } from "../Typewriter/ContentAtomType"; let currentApp: CaliforniaApp; export const VERY_HIGH_VALUE: number = 2300000000; enum CaliforniaViewSpecialStyle { View = 0, Body = 1, Html = 2 } export class PropertyBar { public viewModel: PropertyBarVM; private propertyBarIndex: number = -1; private _visibleLayoutAtomDomNodeReferences: HTMLElement[] = []; private _activeViewLayoutAtomDomNodeReferences: { [key: string]: HTMLElement } = {}; private _visibleLayoutAtomKeys: string[] = []; private _mostUpperVisibleLayoutAtomId: number = 0; constructor(californiaAppArg: CaliforniaApp, targetIndex: number) { currentApp = californiaAppArg; this.propertyBarIndex = targetIndex; this.viewModel = new PropertyBarVM(this, targetIndex, californiaAppArg); this.viewModel.isSyncedWithBoxTreeToTheLeft = false;// TODO targetIndex != 0; this.viewModel.isSyncedWithPagePreview = false;// TODO targetIndex == 0; }; private get currentPropertyBar(): PropertyBar { return currentApp.propertyBars[this.propertyBarIndex]; }; private get nextExceptLastPropertyBar(): PropertyBar { let nextPropertyBarIndex: number = this.propertyBarIndex + 1; if (nextPropertyBarIndex < currentApp.state.visiblePropertyBarMaxCount) { return currentApp.propertyBars[nextPropertyBarIndex]; } else { return this.currentPropertyBar; } }; public get visibleLayoutAtomDomNodeReferences(): HTMLElement[] { return this._visibleLayoutAtomDomNodeReferences; }; public get visibleLayoutAtomKeys(): string[] { return this._visibleLayoutAtomKeys; }; public get mostUpperVisibleLayoutAtomId(): number { return this._mostUpperVisibleLayoutAtomId; }; public get activeViewLayoutAtomDomNodeReferences(): { [key: string]: HTMLElement } { return this._activeViewLayoutAtomDomNodeReferences; }; public renderPropertyBar = (): VNode => { let divPropertyBarsStyles = { // TODO scroll sync "flex": currentApp.state.editViewMode === EditViewMode.SidebarOnly ? "1 1 200px" : `1 1 200px`, // property bar width not invariant to browser zoom (%-value would be, but depends on viewport size) "display": "flex", "flex-flow": "row nowrap", "height": "100%", "min-width": "100px", "width": "200px", "z-index": "2" // TODO document }; let propertyBarStyles = { "flex": currentApp.state.editViewMode === EditViewMode.SidebarOnly ? "1 1 1px" : `1 1 1px`, // property bar width not invariant to browser zoom (%-value would be, but depends on viewport size) //"width": currentApp.state.editViewMode === EditViewMode.SidebarOnly ? "auto" //"100%" : `${currentApp.controlAreaWidthPx}px`, //"display": "flex", //"flex-flow": "column nowrap", //"overflow": "hidden", //"margin-top": /*currentApp.state.isShowSidebarOnly ? TODO*/currentApp.navigationHeigthPx + "px", TODO => moved to navigation element "border-right": this.propertyBarIndex < (currentApp.propertyBarCount - 1) && this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.CaliforniaView ? "solid 3px black" : undefined, // TODO pattern "width": "100%", "height": "100%", "display": "flex", "flex-flow": "column nowrap" }; return <div key={`p${this.propertyBarIndex.toString()}`} styles={divPropertyBarsStyles}> <div key="v0" styles={propertyBarStyles}> {this.currentPropertyBar.renderPropertyBarNavigation()} {this.currentPropertyBar.renderPropertyBarControls()} {this.propertyBarIndex != 0 ? this.currentPropertyBar.renderPropertyBarPoppersRenderOnce() : undefined} </div> </div> as VNode; }; public renderPropertyBarPoppersRenderOnce = (): VNode => { // TODO just render once... return <div key="k0"> {this.currentPropertyBar.renderAddCssPropertyPopup()} {this.currentPropertyBar.renderAllCssPropertiesPopup()} {this.currentPropertyBar.renderUpdateCssValuePopup()} {this.currentPropertyBar.renderMatchingQuantumsPopup()} {this.currentPropertyBar.renderUpdateCssQuantumPopup()} {this.currentPropertyBar.renderAllCssPropertiesForQuantumPopup()} {this.currentPropertyBar.insertLayoutRowIntoViewPopup()} {this.currentPropertyBar.insertLayoutAtomIntoBoxPopup()} {this.currentPropertyBar.insertLayoutBoxIntoBoxPopup()} {this.currentPropertyBar.moveStyleAtomToResponsiveDevicePopup()} {/*this.currentPropertyBar.moveLayoutMoleculeIntoPopup()*/} {/*this.currentPropertyBar.moveLayoutMoleculeBeforePopup()*/} {this.currentPropertyBar.renderSelectInteractionTargetPopup()} {this.currentPropertyBar.renderSelectInteractionTargetLayoutFilterPopup()} {this.currentPropertyBar.renderShareCaliforniaProjectPopup()} {this.currentPropertyBar.renderCaliforniaViewSelectionPopup()} {this.currentPropertyBar.renderEditUserDefinedCssPopup()} {this.currentPropertyBar.renderSuggestedCssValuesPopup()} </div> as VNode; }; public renderPropertyBarNavigation = (): VNode => { let propertyBarNavigationStyles = { "margin-top": /*currentApp.state.isShowSidebarOnly ? TODO*/currentApp.navigationHeigthPx + "px", "display": `flex`, "flex-flow": "row nowrap", "height": `auto`, "width": "100%", "flex": "0 0 auto" }; let hiddenModeButtons: number[] = [ PropertyBarMode.None, PropertyBarMode.AllStyleAtoms, PropertyBarMode.LayoutAtoms, PropertyBarMode.LayoutBase, PropertyBarMode.LayoutMolecules, PropertyBarMode.StyleMolecule ]; // TODO render whole UI static let propertyBarModeIconStrings: { [key: number]: string } = {}; propertyBarModeIconStrings[PropertyBarMode.AllCaliforniaViews] = "V"; propertyBarModeIconStrings[PropertyBarMode.AllLayoutMolecules] = "L"; propertyBarModeIconStrings[PropertyBarMode.AllStyleMolecules] = "S"; propertyBarModeIconStrings[PropertyBarMode.AllStyleQuantums] = "Q"; propertyBarModeIconStrings[PropertyBarMode.CaliforniaView] = ":)"; let propertyBarModeButtons: (VNode | undefined)[] = getArrayForEnum(PropertyBarMode).map((type: string, index: number) => { let modeButtonStyles = { "color": index === this.currentPropertyBar.viewModel.currentPropertyBarMode ? "red" : undefined, "width": "1px", "margin-right": "5px", "margin-left": "5px", "flex": "1 1 1px" }; if (hiddenModeButtons.findIndex(el => el == index) != -1) { return undefined; } return <button key={index} role="button" pid={index.toString()} onclick={this.currentPropertyBar.setPropertyBarMode} styles={modeButtonStyles}>{propertyBarModeIconStrings[index] !== undefined ? propertyBarModeIconStrings[index] : type}</button> as VNode; }); return <div key="n0" styles={propertyBarNavigationStyles}> {propertyBarModeButtons} {this.propertyBarIndex == 0 ? <button key="a" onclick={this.currentPropertyBar.logoutPopupClickHandler} styles={{ "flex": "0 0 auto", "width": "auto" }}>&#9993;&#8230;</button> : undefined} </div> as VNode; }; public setPropertyBarMode = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.currentPropertyBarMode = parseIntFromAttribute(evt.target, "pid"); }; public renderPropertyBarControls = (): VNode => { let divPropertyBarControlsStyles = { "flex": "1 1 auto", "height": "1px", // TODO was 100% before, but it got cut off on the bottom "width": "100%" }; let propertyBarControlsStyles = { "width": "100%", "height": "100%", // TODO fixme "overflow": "auto" }; return <div key={this.currentPropertyBar.viewModel.currentPropertyBarMode} styles={divPropertyBarControlsStyles}> { this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.AllStyleAtoms ? <div key={PropertyBarMode.AllStyleAtoms} styles={propertyBarControlsStyles}> {this.currentPropertyBar.viewModel.styleAtomProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.AllStyleQuantums ? <div key={PropertyBarMode.AllStyleQuantums} styles={propertyBarControlsStyles}> {this.currentPropertyBar.renderStyleQuantumControls()} {this.currentPropertyBar.viewModel.styleQuantumProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.AllStyleMolecules ? <div key={PropertyBarMode.AllStyleMolecules} styles={propertyBarControlsStyles}> {this.currentPropertyBar.viewModel.styleMoleculeProjector.results.map(r => r.renderMaquette())} </div> : (this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.StyleMolecule) ? <div key={PropertyBarMode.AllStyleMolecules} styles={propertyBarControlsStyles}> {this.currentPropertyBar.renderStyleMoleculeControls(this)} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.LayoutAtoms ? <div key={PropertyBarMode.LayoutAtoms} styles={propertyBarControlsStyles}> {this.currentPropertyBar.viewModel.instanceableAtomProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.LayoutMolecules ? <div key={PropertyBarMode.LayoutMolecules} styles={propertyBarControlsStyles}> {this.currentPropertyBar.viewModel.instanceableMoleculeProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.AllLayoutMolecules ? <div key={PropertyBarMode.AllLayoutMolecules} styles={propertyBarControlsStyles}> {this.currentPropertyBar.viewModel.allLayoutMoleculesProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.LayoutBase ? <div key={PropertyBarMode.LayoutBase} styles={propertyBarControlsStyles}> {this.currentPropertyBar.renderLayoutBaseControls()} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.AllCaliforniaViews ? <div key={PropertyBarMode.AllCaliforniaViews} styles={propertyBarControlsStyles}> {this.currentPropertyBar.renderCaliforniaViewControlsWhenAll()} {this.currentPropertyBar.viewModel.allCaliforniaViewsProjector.results.map(r => r.renderMaquette())} </div> : this.currentPropertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.CaliforniaView ? <div key={PropertyBarMode.CaliforniaView} styles={propertyBarControlsStyles}> {this.currentPropertyBar.renderCaliforniaViewControls()} </div> : undefined } </div> as VNode; }; /*public scrollTODO = (evt: UIEvent) => { console.log("in scroll"); let scrolledElement: HTMLElement = evt.target as HTMLElement; // TODO semi-const let scrollVerticalMinPx: number = 0; let scrollVerticalMaxPx: number = 222; scrollVerticalMaxPx = scrolledElement.scrollHeight - scrolledElement.clientHeight;//scrolledElement.scrollHeight - (((scrolledElement.firstElementChild as HTMLElement).lastElementChild as HTMLElement).firstElementChild as HTMLElement).clientHeight; let scrollTargetCssValueMin: number = 0; let scrollTargetCssValueMax: number = 222; let scrollDeltaStar: number = scrollVerticalMaxPx - scrollVerticalMinPx; let isInverted: boolean = true; // --- if (scrolledElement.scrollTop > scrollVerticalMinPx || scrolledElement.scrollTop < scrollVerticalMaxPx) { //TODO need to save state of previous scroll event for the case when the scroll distance is large let scrollDelta: number = scrolledElement.scrollTop - scrollVerticalMinPx; let scrollFraction: number = (scrollDelta / scrollDeltaStar); if (isInverted === true) { scrollFraction = 1.0 - scrollFraction; } let scrollTargetCssValue: number = scrollFraction * (scrollTargetCssValueMax - scrollTargetCssValueMin) + scrollTargetCssValueMin; let scrollTargetCssString: string = `rgb(${scrollTargetCssValue},${scrollTargetCssValue},${scrollTargetCssValue})`; scrolledElement.style.backgroundColor = scrollTargetCssString; } };*/ /*public scrollTODO = (evt: UIEvent) => { console.log("in scroll"); let scrolledElement: HTMLElement = evt.target as HTMLElement; // TODO semi-const let scrollVerticalMinPx: number = 0; let scrollVerticalMaxPx: number = 222; scrollVerticalMaxPx = scrolledElement.scrollHeight - scrolledElement.clientHeight;//scrolledElement.scrollHeight - (((scrolledElement.firstElementChild as HTMLElement).lastElementChild as HTMLElement).firstElementChild as HTMLElement).clientHeight; let scrollTargetCssValueMin: number = 0; let scrollTargetCssValueMax: number = 40; let scrollDeltaStar: number = scrollVerticalMaxPx - scrollVerticalMinPx; let isInverted: boolean = true; // --- if (scrolledElement.scrollTop > scrollVerticalMinPx || scrolledElement.scrollTop < scrollVerticalMaxPx) { //TODO need to save state of previous scroll event for the case when the scroll distance is large let scrollDelta: number = scrolledElement.scrollTop - scrollVerticalMinPx; let scrollFraction: number = (scrollDelta / scrollDeltaStar); if (isInverted === true) { scrollFraction = 1.0 - scrollFraction; } let scrollTargetCssValue: number = scrollFraction * (scrollTargetCssValueMax - scrollTargetCssValueMin) + scrollTargetCssValueMin; let paddingTargetCssString: string = `${scrollTargetCssValue}px`; scrolledElement.style.paddingLeft = paddingTargetCssString; } };*/ /*private isAnimationRunning: boolean = false; TODO code samples animations on scroll position reaching/leaving top private isAnimationInSecondState: boolean = false; public scrollTODO = (evt: UIEvent) => { let scrolledElement: HTMLElement = evt.target as HTMLElement; // TODO semi-const let scrollVerticalMinPx: number = 0; let scrollVerticalMaxPx: number = 222; //scrollVerticalMaxPx = scrolledElement.scrollHeight - scrolledElement.clientHeight;//scrolledElement.scrollHeight - (((scrolledElement.firstElementChild as HTMLElement).lastElementChild as HTMLElement).firstElementChild as HTMLElement).clientHeight; let scrollTargetCssValueMin: number = 0; let scrollTargetCssValueMax: number = 40; let scrollDeltaStar: number = scrollVerticalMaxPx - scrollVerticalMinPx; let isInverted: boolean = true; // --- // animation: fold in when scrolling away from top let isFirstTransition: boolean = !this.currentPropertyBar.isAnimationInSecondState; if (scrolledElement.scrollTop > 0) { // transition 2 => 1 if (this.currentPropertyBar.isAnimationInSecondState) { // do nothing return; } else { if (this.currentPropertyBar.isAnimationRunning) { velocity.animate(scrolledElement, "stop"); this.currentPropertyBar.isAnimationRunning = false; } } } else { // scrollTop == 0 // transition 1 => 2 if (this.currentPropertyBar.isAnimationInSecondState) { if (this.currentPropertyBar.isAnimationRunning) { velocity.animate(scrolledElement, "stop"); this.currentPropertyBar.isAnimationRunning = false; } } else { // TODO this should never happen console.log(DEFAULT_EXCEPTION); return; } } let durationMax: number = 100; let paddingLeft: string = scrolledElement.style.marginLeft as string; let paddingLeftPx: number = parseInt(paddingLeft.substring(0, paddingLeft.length - 2)); if (isFirstTransition) { this.currentPropertyBar.isAnimationInSecondState = true; let durationDelta = (paddingLeftPx - 0) / 40.0 * durationMax; if (durationDelta > 10) { this.currentPropertyBar.isAnimationRunning = true; velocity.animate(scrolledElement, { "margin-left": 0 }, { duration: durationDelta, easing: "ease-in", complete: () => { this.currentPropertyBar.isAnimationRunning = false; } }); } else { scrolledElement.style.marginLeft = "0px"; } } else { this.currentPropertyBar.isAnimationInSecondState = false; //domNode.style.overflow = "hidden"; let durationDelta = (40 - paddingLeftPx) / 40.0 * durationMax; if (durationDelta > 10) { this.currentPropertyBar.isAnimationRunning = true; velocity.animate(scrolledElement, { "margin-left": 40 }, { duration: durationDelta, easing: "ease-out", complete: () => { this.currentPropertyBar.isAnimationRunning = false; } }); } else { scrolledElement.style.marginLeft = "40px"; } } };*/ public renderStyleMoleculeControls = (propertyBar: PropertyBar): VNode | undefined => { if (propertyBar.viewModel.selectedStyleMoleculeId != 0) { let sourceStyleMoleculeIdString: string = propertyBar.viewModel.selectedStyleMoleculeId.toString(); let styleMolecule: StyleMolecule | undefined = currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleMoleculeId == propertyBar.viewModel.selectedStyleMoleculeId); // TODO find used repeatedly for render controls if (styleMolecule === undefined) { // can happen if style molecule got deleted in the mean time in other property bars return undefined; // TODO document } let isClonedStyle: boolean = false; let cloneRefStyleMoleculeIdString: string | undefined = undefined; if (styleMolecule.ClonedFromStyleId !== undefined) { isClonedStyle = true; cloneRefStyleMoleculeIdString = styleMolecule.ClonedFromStyleId.toString(); } let styledLayoutBaseIdString: string = styleMolecule.StyleForLayoutId.toString(); let propertyBarControlsStyles = { "height": "100%", "width": "100%", "display": "flex", "flex-flow": "column nowrap" }; // TODO clone reference style selector should always be visible (depends on cloneOfStyleId) // TODO ref style/clone style return <div key={PropertyBarMode.StyleMolecule} styles={propertyBarControlsStyles}> <div key="0" styles={{ "flex": "0 0 auto" }}> Selected StyleMolecule #{propertyBar.viewModel.selectedStyleMoleculeId} {isClonedStyle ? <div key="0"> <button key="a" role="button" mid={cloneRefStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>ref style (#{cloneRefStyleMoleculeIdString})</button> <button disabled key="b" role="button" mid={sourceStyleMoleculeIdString} onclick={propertyBar.createReferenceStyleMoleculeClickHandler}>make ref</button> <button disabled key="c" role="button" mid={sourceStyleMoleculeIdString} onclick={propertyBar.syncToReferenceStyleClickHandler}>sync to ref</button> <button disabled key="d" role="button" mid={sourceStyleMoleculeIdString} onclick={propertyBar.syncFromReferenceStyleClickHandler}>sync from ref</button> </div> : propertyBar.renderStyleMoleculeReferenceSelector()} {propertyBar.renderResponsiveDeviceSelectors()} {propertyBar.renderStateModifierSelectors()} {propertyBar.renderStyleAtomControls()} </div> <div key="1" styles={{ "flex": "1 1 1px", "overflow": "scroll" }}> {propertyBar.viewModel.styleAtomProjector.results.map(r => r.renderMaquette())} {propertyBar.renderStyleMoleculeChildren(propertyBar)} </div> <div key="2" styles={{ "flex": "0 0 auto" }}> <button key="a" role="button" lid={styledLayoutBaseIdString} onclick={propertyBar.selectLayoutBaseClickHandler}>layout #{styledLayoutBaseIdString}</button> </div> </div> as VNode; } else { return undefined; } }; public syncToReferenceStyleClickHandler = (evt: MouseEvent) => { currentApp.controller.SyncStyleMoleculeToReferenceStyleJson(parseIntFromAttribute(evt.target, "mid")).done(data => currentApp.router.updateData(data)); }; public syncFromReferenceStyleClickHandler = (evt: MouseEvent) => { currentApp.controller.SyncStyleMoleculeFromReferenceStyleJson(parseIntFromAttribute(evt.target, "mid")).done(data => currentApp.router.updateData(data)); }; public createReferenceStyleMoleculeClickHandler = (evt: MouseEvent) => { currentApp.controller.SetStyleMoleculeAsReferenceStyleJson(parseIntFromAttribute(evt.target, "mid")).done(data => currentApp.router.updateData(data)); }; public renderStyleMoleculeReferenceSelector = (): VNode => { // TODO enable when backend functionality is implemented return <div key="-1"> <select disabled onchange={this.currentPropertyBar.styleMoleculeReferenceChangedHandler}> {currentApp.clientData.CaliforniaProject.StyleMolecules.map(mol => { // TODO expensive if (mol.ClonedFromStyleId !== undefined) { // ignore styles which are not reference styles return undefined; } let styleMoleculeIdString: string = mol.StyleMoleculeId.toString(); if (mol.StyleMoleculeId == this.currentPropertyBar.viewModel.selectedStyleMoleculeId) { return <option selected key={styleMoleculeIdString} value={styleMoleculeIdString}>{mol.Name} #{mol.StyleMoleculeId}</option>; } else { return <option key={styleMoleculeIdString} value={styleMoleculeIdString}>{mol.Name} #{mol.StyleMoleculeId}</option>; } })} </select> </div> as VNode; }; public styleMoleculeReferenceChangedHandler = (evt: UIEvent) => { let targetSelect = evt.target as HTMLSelectElement; let parsedStyleMoleculeId: number | undefined = undefined; if (targetSelect.selectedIndex < targetSelect.childElementCount) { let selectOptionElement: HTMLOptionElement = targetSelect.options[targetSelect.selectedIndex]; parsedStyleMoleculeId = parseInt(selectOptionElement.value); } if (parsedStyleMoleculeId !== undefined) { currentApp.controller.SetStyleMoleculeReferenceJson(this.currentPropertyBar.viewModel.selectedStyleMoleculeId, parsedStyleMoleculeId).done(data => currentApp.router.updateData(data)); } else { console.log(DEFAULT_EXCEPTION); } }; public renderStyleMoleculeChildren = (propertyBar: PropertyBar): VNode => { let childMolecules: StyleMolecule[] = []; if (propertyBar.viewModel.selectedStyleMoleculeId != 0) { childMolecules = currentApp.clientData.CaliforniaProject.StyleMolecules.filter(s => s.ClonedFromStyleId == this.currentPropertyBar.viewModel.selectedStyleMoleculeId); // TODO expensive // TODO everywhere where something like s.ClonedFromStyleId is used: reset view before elements are deleted.. this can throw undefined } return <div key="-4"> affects styles: {childMolecules.map(s => { let styleMoleculeIdString: string = s.StyleMoleculeId.toString(); return <div key={styleMoleculeIdString}> <button key="a" role="button" mid={styleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>#{styleMoleculeIdString}</button> </div>; })} </div> as VNode; }; public renderBoxTreeForCaliforniaView = (propertyBar: PropertyBar): maquette.Mapping<CaliforniaView, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<CaliforniaView, any>( function getSectionSourceKey(source: CaliforniaView) { return source.CaliforniaViewId; }, function createSectionTarget(source: CaliforniaView) { let sourceCaliforniaViewIdString = source.CaliforniaViewId.toString(); let layoutRows = propertyBar.renderLayoutRowArray(propertyBar); layoutRows.map(source.PlacedLayoutRows); // TODO show body+html style molecule in page preview return { renderMaquette: function () { let treeViewStyles = { "display": "flex", "flex-direction": "row", "flex-wrap": "wrap", "margin-right": "-15px", "font-family": "sans-serif", //"width": "900px", // TODO workaround elements breaking line... "border-bottom": "solid, 1px, black", "width": "auto", "height": "auto", "padding-bottom": "123px" /*TODO size of n*element for add/create layout elements at end, currently 120+3*/ }; return (propertyBar.viewModel.selectedCaliforniaViewId == source.CaliforniaViewId) ? <div key={sourceCaliforniaViewIdString} styles={treeViewStyles}> {layoutRows.results.map(r => r.renderMaquette())} </div> : undefined; }, update: function (updatedSource: CaliforniaView) { source = updatedSource; layoutRows.map(source.PlacedLayoutRows); sourceCaliforniaViewIdString = source.CaliforniaViewId.toString(); } }; }, function updateSectionTarget(updatedSource: CaliforniaView, target: { renderMaquette(): any, update(updatedSource: CaliforniaView): void }) { target.update(updatedSource); }); }; public renderLayoutRowArray = (propertyBar: PropertyBar): maquette.Mapping<LayoutRow, { renderMaquette: () => maquette.VNode }> => { // TODO code duplication with page preview return maquette.createMapping<LayoutRow, any>( function getSectionSourceKey(source: LayoutRow) { return source.LayoutBaseId; }, function createSectionTarget(source: LayoutRow) { let sourceLayoutRowIdString = source.LayoutBaseId.toString(); let renderedLayoutBoxes = propertyBar.renderLayoutBoxArray(propertyBar); let unsortedBoxes: LayoutBox[] = source.AllBoxesBelowRow.filter(b => b.PlacedBoxInBoxId === undefined); let sortedBoxes: LayoutBox[] = unsortedBoxes.sort((boxA: LayoutBox, boxB: LayoutBox) => { if (boxA.LayoutSortOrderKey < boxB.LayoutSortOrderKey) { return -1; } else if (boxA.LayoutSortOrderKey == boxB.LayoutSortOrderKey) { return 0; } else { // boxA.LayoutSortOrderKey > boxB.LayoutSortOrderKey return 1; } }); renderedLayoutBoxes.map(sortedBoxes); let styleMoleculeId: number = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId; // TODO expensive let styleMoleculeIdString: string = styleMoleculeId.toString(); let layoutRowStyleClass: string = `s${styleMoleculeIdString}`; return { renderMaquette: function () { let treeRowStyles = { "flex-basis": "100%", "width": "100%", "max-width": "100%", "padding-left": "15px", "padding-right": "15px", "background-color": "rgb(222, 222, 222)" }; let captionStyles = { "flex-basis": "auto", "width": "auto", "color": "rgb(78, 78, 78)", "padding-left": "15px", "padding-right": "15px", "margin": "0", "background-color": "rgb(222, 222, 222)", "text-decoration": "underline" }; let divButtonStyles = { "display": "flex", "flex-direction": "row", "flex-wrap": "nowrap", //"margin-left": "-15px", "margin-right": "-15px", "width": "auto", "flex": "0 0 auto", }; let buttonStyles = { "font-size": "10px", "color": "rgb(78, 78, 78)", "background-color": "rgb(222, 222, 222)", // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": undefined, "outline-offset": undefined }; let isPreselectedAny: boolean = currentApp.state.preselectedLayoutBaseId != 0; let isPreselectedCurrent: boolean = isPreselectedAny && currentApp.state.preselectedLayoutBaseId == source.LayoutBaseId; let buttonStylesTarget = { // TODO append array "font-size": "10px", "color": !isPreselectedAny || isPreselectedCurrent ? "rgb(222, 222, 222)" : "rgb(78, 78, 78)", "background-color": "rgb(222, 222, 222)", // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": !isPreselectedAny || isPreselectedCurrent ? undefined : "solid 4px rgb(200,0,0)", "outline-offset": !isPreselectedAny || isPreselectedCurrent ? undefined : "-4px" }; let buttonStylesPreselectRow = { // TODO append array "font-size": "10px", "color": isPreselectedCurrent ? "rgb(222,222,222)" : isPreselectedAny ? "rgb(222, 222, 222)" : "rgb(78, 78, 78)", "background-color": isPreselectedCurrent ? "rgb(200,0,0)" : "rgb(222, 222, 222)", // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": isPreselectedCurrent || isPreselectedAny ? undefined : "solid 1px rgb(200,0,0)", "outline-offset": isPreselectedCurrent || isPreselectedAny ? undefined : "-1px" }; let divSubBoxStyles = { "flex-basis": "100%", "width": "100%", "max-width": "100%", "padding-left": "15px", "padding-right": "15px" }; return <div key={sourceLayoutRowIdString} styles={treeRowStyles} lid={sourceLayoutRowIdString} onmouseenter={propertyBar.layoutBaseMouseEnterHandler} onmouseleave={propertyBar.layoutBaseMouseLeaveHandler}> <div key="-2" styles={divButtonStyles}> <p key="-1" styles={captionStyles}>ROW</p> <button key="a" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.insertLayoutBoxIntoBoxClickHandler}>+(B)</button> <button key="b" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.selectLayoutBaseClickHandler}>&#8230;{/*ellipsis TODO check is this comment removed*/}</button> <button key="c" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.highlightLayoutBaseClickHandler}>?</button> <button key="d" styles={buttonStyles} mid={styleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>S&#8230;</button> <button key="e" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.saveLayoutMoleculeClickHandler}>!!!</button> {isPreselectedCurrent || !isPreselectedAny ? <button key="f" styles={buttonStylesPreselectRow} lid={sourceLayoutRowIdString} onclick={propertyBar.moveLayoutRowBeforeRowClickHandler}>MV(R)</button> : <button disabled key="f0" styles={buttonStylesPreselectRow} lid={sourceLayoutRowIdString} onclick={propertyBar.moveLayoutRowBeforeRowClickHandler}>MV(R)</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="g" styles={buttonStylesPreselectRow} lid={sourceLayoutRowIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(R)</button> : <button disabled key="g0" styles={buttonStylesPreselectRow} lid={sourceLayoutRowIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(R)</button>} {isPreselectedAny && !isPreselectedCurrent ? <button key="h" styles={buttonStylesTarget} lid={sourceLayoutRowIdString} onclick={propertyBar.finalizeLayoutRequest}>$(B:R)</button> : <button disabled key="h0" styles={buttonStylesTarget} lid={sourceLayoutRowIdString} onclick={propertyBar.finalizeLayoutRequest}>$(B:R)</button>} {!isPreselectedAny ? <button key="i" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button> : <button disabled key="i0" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button>} {!isPreselectedAny && sortedBoxes.length > 0 ? <button key="j" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.deleteBelowLayoutBaseClickHandler}>CLR</button> : <button disabled key="j0" styles={buttonStyles} lid={sourceLayoutRowIdString} onclick={propertyBar.deleteBelowLayoutBaseClickHandler}>CLR</button>} </div> <div key="0" styles={divSubBoxStyles}>{renderedLayoutBoxes.results.map(r => r.renderMaquette())}</div> </div>; }, update: function (updatedSource: LayoutRow) { source = updatedSource; sourceLayoutRowIdString = source.LayoutBaseId.toString(); unsortedBoxes = source.AllBoxesBelowRow.filter(b => b.PlacedBoxInBoxId === undefined); sortedBoxes = unsortedBoxes.sort((boxA: LayoutBox, boxB: LayoutBox) => { if (boxA.LayoutSortOrderKey < boxB.LayoutSortOrderKey) { return -1; } else if (boxA.LayoutSortOrderKey == boxB.LayoutSortOrderKey) { return 0; } else { // boxA.LayoutSortOrderKey > boxB.LayoutSortOrderKey return 1; } }); renderedLayoutBoxes.map(sortedBoxes); styleMoleculeId = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId; // TODO expensive styleMoleculeIdString = styleMoleculeId.toString(); layoutRowStyleClass = `s${styleMoleculeId}`; } }; }, function updateSectionTarget(updatedSource: LayoutRow, target: { renderMaquette(): any, update(updatedSource: LayoutRow): void }) { target.update(updatedSource); }); }; private renderLayoutBoxArray = (propertyBar: PropertyBar): maquette.Mapping<LayoutBox, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<LayoutBox, any>( function getSectionSourceKey(source: LayoutBox) { return source.LayoutBaseId; }, function createSectionTarget(source: LayoutBox) { let sourceLayoutBoxIdString = source.LayoutBaseId.toString(); let renderedLayoutAtoms = propertyBar.renderLayoutAtomArray(propertyBar); let renderedLayoutBoxes = propertyBar.renderLayoutBoxArray(propertyBar); let styleMoleculeId: number = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId; // TODO expensive let styleMoleculeIdString: string = styleMoleculeId.toString(); let layoutBoxStyleClass: string = `s${styleMoleculeId}`; // --- only render mode: tree --- let deepnessPadding: string = ""; let calculatedBackgroundColor: string = ""; let calculatedColor: string = ""; let calculatedBorderColor: string = ""; let hasSubAtoms: boolean = false; let isOddLevel: boolean = false; // --- deepnessPadding = `${(source.Level + 1) * 15}px`; calculatedBackgroundColor = propertyBar.calculateBackgroundColorForLevel(source.Level); calculatedColor = propertyBar.calculateColorForLevel(source.Level); calculatedBorderColor = `solid 1px ${propertyBar.calculateBackgroundColorForLevel(source.Level + 1)}`; hasSubAtoms = source.PlacedInBoxAtoms.length > 0; isOddLevel = (source.Level % 2) != 0; return { renderMaquette: function () { let renderedBoxContent: VNode[] = currentApp.pagePreview.mapAndRenderLayoutBoxContent(source, source.PlacedInBoxAtoms, renderedLayoutAtoms, source.PlacedInBoxBoxes, renderedLayoutBoxes); let treeBoxStyles = { "display": "flex", "flex-direction": "row", "flex-wrap": "wrap", //"margin-left": "-15px", TODO stair effect "margin-right": "-15px", "background-color": "rgb(222, 222, 222)", "border-bottom": hasSubAtoms ? calculatedBorderColor : undefined, "border-left": "solid 1px black",// hasSubAtoms ? calculatedBorderColor : undefined // TODO only next to atoms "zoom": "1.05" // TODO caleidoscope / zoom factor }; let boxCaptionStyles = { "padding-left": "15px", "padding-right": "15px", "width": "auto", "flex": "0 0 auto", "margin": "0", "text-decoration": "underline", "color": calculatedColor, "background-color": calculatedBackgroundColor, "font-stretch": isOddLevel ? "extra-condensed" : undefined }; let divButtonStyles = { "display": "flex", "flex-direction": "row", "flex-wrap": "nowrap", "margin-left": "-15px", "margin-right": "-15px" }; let buttonStyles = { "font-size": "10px", "color": calculatedColor, "background-color": calculatedBackgroundColor, "width": "auto", "flex": "0 0 auto", "outline": undefined, "outline-offset": undefined }; let buttonDisabledStyles = { "font-size": "10px", "background-color": "rgb(242,242,242)", "color": calculatedColor, "width": "auto", "flex": "0 0 auto", "outline": undefined, "outline-offset": undefined }; let isPreselectedAny: boolean = currentApp.state.preselectedLayoutBaseId != 0; let isPreselectedCurrent: boolean = isPreselectedAny && currentApp.state.preselectedLayoutBaseId == source.LayoutBaseId; let buttonStylesTarget = { // TODO append array "font-size": "10px", "color": !isPreselectedAny || isPreselectedCurrent ? calculatedBackgroundColor : calculatedColor, "background-color": calculatedBackgroundColor, // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": !isPreselectedAny || isPreselectedCurrent ? undefined : "solid 4px rgb(200,0,0)", "outline-offset": !isPreselectedAny || isPreselectedCurrent ? undefined : "-4px", }; let buttonStylesPreselectAny = { // TODO append array // TODO differentiate "font-size": "10px", "color": isPreselectedCurrent ? calculatedBackgroundColor : isPreselectedAny ? calculatedBackgroundColor : calculatedColor, "background-color": isPreselectedCurrent ? "rgb(200,0,0)" : calculatedBackgroundColor, // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": isPreselectedCurrent || isPreselectedAny ? undefined : "solid 1px rgb(200,0,0)", "outline-offset": isPreselectedCurrent || isPreselectedAny ? undefined : "-1px", }; let divSubTreeStyles = { "flex-basis": "100%", "width": "100%", "max-width": "100%", "padding-left": "15px", "padding-right": "15px", "background-color": calculatedBackgroundColor }; // TODO document: whole client app relies on database keys being strictly positive // TODO concept+do everywhere: in this case many html tags are set when 1 would be enough on parent return <div key={sourceLayoutBoxIdString} styles={treeBoxStyles}> <div key="0" styles={divSubTreeStyles} lid={sourceLayoutBoxIdString} onmouseenter={propertyBar.layoutBaseMouseEnterHandler} onmouseleave={propertyBar.layoutBaseMouseLeaveHandler}> <div key="-2" styles={divButtonStyles}> {<p key="-1" styles={boxCaptionStyles}>BOX{!isOddLevel ? " |" : undefined}</p>} <button key="a" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.insertLayoutAtomIntoBoxClickHandler}>+(A)</button> <button key="b" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.insertLayoutBoxIntoBoxClickHandler}>+(B)</button> <button key="c" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.selectLayoutBaseClickHandler}>&#8230;{/*Ellipsis*/}</button> <button key="d" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.highlightLayoutBaseClickHandler}>?</button> <button key="e" styles={buttonStyles} mid={styleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>S&#8230;{/*Ellipsis*/}</button> <button key="f" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.saveLayoutMoleculeClickHandler}>!!!</button> {isPreselectedCurrent || !isPreselectedAny ? <button key="g" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxIntoRowClickHandler}>IN(R)</button> : <button disabled key="g0" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxIntoRowClickHandler}>IN(R)</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="h" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxIntoBoxClickHandler}>IN(B)</button> : <button disabled key="h0" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxIntoBoxClickHandler}>IN(B)</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="i" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxBeforeBoxClickHandler}>MV(A:B)</button> : <button disabled key="i0" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.moveLayoutBoxBeforeBoxClickHandler}>MV(A:B)</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="j" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(B)</button> : <button disabled key="j0" styles={buttonStylesPreselectAny} lid={sourceLayoutBoxIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(B)</button>} {isPreselectedAny && !isPreselectedCurrent ? <button key="k" styles={buttonStylesTarget} lid={sourceLayoutBoxIdString} onclick={propertyBar.finalizeLayoutRequest}>$(A:B)</button> : <button disabled key="k0" styles={buttonStylesTarget} lid={sourceLayoutBoxIdString} onclick={propertyBar.finalizeLayoutRequest}>$(A:B)</button>} {!isPreselectedAny ? <button key="l" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button> : <button disabled key="l0" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button>} {!isPreselectedAny && renderedBoxContent.length > 0 ? <button key="m" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.deleteBelowLayoutBaseClickHandler}>CLR</button> : <button disabled key="m0" styles={buttonStyles} lid={sourceLayoutBoxIdString} onclick={propertyBar.deleteBelowLayoutBaseClickHandler}>CLR</button>} </div> {renderedBoxContent} </div> </div>; }, update: function (updatedSource: LayoutBox) { source = updatedSource; sourceLayoutBoxIdString = source.LayoutBaseId.toString(); styleMoleculeId = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId; // TODO expensive styleMoleculeIdString = styleMoleculeId.toString(); layoutBoxStyleClass = `s${styleMoleculeId}`; deepnessPadding = `${(source.Level + 1) * 15}px`; calculatedBackgroundColor = propertyBar.calculateBackgroundColorForLevel(source.Level); calculatedColor = propertyBar.calculateColorForLevel(source.Level); calculatedBorderColor = `solid 1px ${propertyBar.calculateBackgroundColorForLevel(source.Level + 1)}`; // TODO test if rendered too many times by setting break point in updater hasSubAtoms = source.PlacedInBoxAtoms.length > 0; isOddLevel = (source.Level % 2) != 0; } }; }, function updateSectionTarget(updatedSource: LayoutBox, target: { renderMaquette(): any, update(updatedSource: LayoutBox): void }) { target.update(updatedSource); }); }; public calculateColorForLevel = (level: number): string => { // TODO hardcoded precalculated table level = level < 0 ? 0 : level; let colorValue: number = level > 2 ? 222 : 78 + level * 12; // gray tone with limit to white return `rgb(${colorValue},${colorValue},${colorValue})`; }; public calculateBackgroundColorForLevel = (level: number): string => { level = level < 0 ? 0 : level; let colorValue: number = 200 - level * 22; colorValue = colorValue < 0 ? 0 : colorValue; return `rgb(${colorValue},${colorValue},${colorValue})`; }; private renderLayoutAtomArray = (propertyBar: PropertyBar): maquette.Mapping<LayoutAtom, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<LayoutAtom, any>( function getSectionSourceKey(source: LayoutAtom) { return source.LayoutBaseId; }, function createSectionTarget(source: LayoutAtom) { let sourceLayoutAtomIdString = source.LayoutBaseId.toString(); let sourceContentAtomIdString = source.HostedContentAtom.ContentAtomId.toString(); let styleMolecule: StyleMolecule = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule); // TODO expensive let styleMoleculeId: number = styleMolecule.StyleMoleculeId; let styleMoleculeIdString: string = styleMoleculeId.toString(); let layoutAtomStyleClass: string = `s${styleMoleculeIdString}`; // TODO create all of these constant strings when parsing data => one instance in memory !!! // --- only render mode: tree --- let calculatedPaddingPx: number = (propertyBar.viewModel.deepestLevelActiveView + 1 - source.Level) * 15; let calculatedMargin: string = ""; let calculatedColor: string = ""; let calculatedBackgroundColor: string = ""; // --- calculatedMargin = `${(source.Level) * 15 + 15}px`; calculatedColor = propertyBar.calculateColorForLevel(source.Level); calculatedBackgroundColor = propertyBar.calculateBackgroundColorForLevel(source.Level); let hostedContentAtom: ContentAtom = (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.ContentAtomId == source.HostedContentAtom.ContentAtomId) as ContentAtom); // TODO expensive (2 copies of content) return { renderMaquette: function () { let isRenderedAtomVisible: boolean = currentApp.pagePreview.visibleLayoutAtomKeys.findIndex(k => k === sourceLayoutAtomIdString) != -1; let isRenderedAtomHovered: boolean = currentApp.state.hoveredPagePreviewLayoutBaseId == source.LayoutBaseId; // TODO wiggle effect // TODO same stair effect right side margin let divAtomStyles = { "display": "flex", "flex-direction": "row", "flex-wrap": "nowrap", //"margin-left": "-15px", TODO stair effect "margin-right": "-15px", "border-left": "solid 1px black" }; let atomCaptionStyles = { "text-decoration": "underline", "flex": "0 0 auto", "width": "auto", "margin-left": "15px", // TODO stair effect "padding-left": `${(calculatedPaddingPx + (isRenderedAtomVisible ? -1 : 0)).toString()}px`, "padding-right": "15px", "margin": "0", "color": calculatedColor, "background-color": calculatedBackgroundColor, "font-size": undefined, "min-width": undefined, "border-left": isRenderedAtomHovered ? "solid 3px rgb(200,0,0)" : isRenderedAtomVisible ? "dashed 1px rgb(200,0,0)" : undefined }; let inputStyles = { // TODO input disappears when layoutatom hosted content atom text is: $\left.\right]$ "text-decoration": undefined, "flex": "0 0 auto", "width": "auto", "margin-left": "15px", // TODO stair effect "padding-left": undefined, "padding-right": "15px", "margin": "0", "color": undefined, "background-color": undefined, "font-size": "0.8rem", "min-width": "200px" }; let buttonStyles = { "font-size": "10px", "color": calculatedColor, "background-color": calculatedBackgroundColor, "width": "auto", "flex": "0 0 auto", "outline": undefined, "outline-offset": undefined }; let isPreselectedAny: boolean = currentApp.state.preselectedLayoutBaseId != 0; let isPreselectedCurrent: boolean = isPreselectedAny && currentApp.state.preselectedLayoutBaseId == source.LayoutBaseId; let buttonStylesTarget = { // TODO append array "font-size": "10px", "color": !isPreselectedAny || isPreselectedCurrent ? calculatedBackgroundColor : calculatedColor, "background-color": calculatedBackgroundColor, // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": !isPreselectedAny || isPreselectedCurrent ? undefined : "solid 4px rgb(200,0,0)", "outline-offset": !isPreselectedAny || isPreselectedCurrent ? undefined : "-4px" }; let buttonStylesPreselectAny = { // TODO append array "font-size": "10px", "color": isPreselectedCurrent ? calculatedBackgroundColor : isPreselectedAny ? calculatedBackgroundColor : calculatedColor, "background-color": isPreselectedCurrent ? "rgb(200,0,0)" : calculatedBackgroundColor, // TODO magic strings "width": "auto", "flex": "0 0 auto", "outline": isPreselectedCurrent || isPreselectedAny ? undefined : "solid 1px rgb(200,0,0)", "outline-offset": isPreselectedCurrent || isPreselectedAny ? undefined : "-1px" }; let description: string = ""; if (hostedContentAtom.ContentAtomType === ContentAtomType.Text && hostedContentAtom.TextContent !== undefined) { description = hostedContentAtom.TextContent.length > 20 ? hostedContentAtom.TextContent.substring(0, 20) + "..." : hostedContentAtom.TextContent; // TODO expensive // TODO ellipsis // TODO multiple places // TODO create when storing in DB? or when loading in client } else if (hostedContentAtom.ContentAtomType === ContentAtomType.Link && hostedContentAtom.Url !== undefined) { description = hostedContentAtom.Url.length > 20 ? hostedContentAtom.Url.substring(0, 20) + "..." : hostedContentAtom.Url; // TODO expensive // TODO ellipsis // TODO multiple places // TODO create when storing in DB? or when loading in client } else { console.log(DEFAULT_EXCEPTION); return undefined; } let renderedInputForContent: VNode | undefined = undefined; let isEditedLayoutAtomId: boolean = source.LayoutBaseId == propertyBar.viewModel.editedLayoutAtomId; if (isEditedLayoutAtomId) { // show input field instead of rendered atom renderedInputForContent = <input key={`inp${sourceLayoutAtomIdString}`} class={layoutAtomStyleClass} value={propertyBar.viewModel.tempContent} oninput={propertyBar.contentAtomInputHandler} onblur={propertyBar.contentAtomLostFocusHandler} onkeydown={propertyBar.contentAtomKeyDownHandler} styles={inputStyles} afterCreate={propertyBar.contentAtomAfterCreateHandler} cid={sourceContentAtomIdString} ></input> as VNode; } return <div key={sourceLayoutAtomIdString} lid={sourceLayoutAtomIdString} styles={divAtomStyles} afterCreate={propertyBar.layoutAtomAfterCreateHandler} onmouseenter={propertyBar.layoutBaseMouseEnterHandler} onmouseleave={propertyBar.layoutBaseMouseLeaveHandler}> {!isEditedLayoutAtomId ? <p key="0" styles={atomCaptionStyles} aid={sourceLayoutAtomIdString} cid={sourceContentAtomIdString} onclick={propertyBar.layoutAtomClickHandler}><small key="0" aid={sourceLayoutAtomIdString} cid={sourceContentAtomIdString}>{description}ATOM</small></p> : renderedInputForContent} <button key="a" styles={buttonStyles} lid={sourceLayoutAtomIdString} onclick={propertyBar.selectLayoutBaseClickHandler}>&#8230;{/*Ellipsis*/}</button> <button key="b" styles={buttonStyles} lid={sourceLayoutAtomIdString} onclick={propertyBar.highlightLayoutBaseClickHandler}>?</button> <button key="c" styles={buttonStyles} mid={styleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>S&#8230;{/*Ellipsis*/}</button> {isPreselectedCurrent || !isPreselectedAny ? <button key="d" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.moveLayoutAtomIntoBoxClickHandler}>IN</button> : <button disabled key="d0" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.moveLayoutAtomIntoBoxClickHandler}>IN</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="e" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.moveLayoutAtomBeforeAtomClickHandler}>MV</button> : <button disabled key="e0" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.moveLayoutAtomBeforeAtomClickHandler}>MV</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="f" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(A)</button> : <button disabled key="f0" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.syncLayoutBaseStylesClickHandler}>ST(A)</button>} {isPreselectedCurrent || !isPreselectedAny ? <button key="g" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.createBoxForAtomInPlaceClickHandler}>+(B).IN</button> : <button disabled key="g0" styles={buttonStylesPreselectAny} lid={sourceLayoutAtomIdString} onclick={propertyBar.createBoxForAtomInPlaceClickHandler}>+(B).IN</button>} {isPreselectedAny && !isPreselectedCurrent ? <button key="h" styles={buttonStylesTarget} lid={sourceLayoutAtomIdString} onclick={propertyBar.finalizeLayoutRequest}>$(A:B)</button> : <button disabled key="h0" styles={buttonStylesTarget} lid={sourceLayoutAtomIdString} onclick={propertyBar.finalizeLayoutRequest}>$(A:B)</button>} {!isPreselectedAny ? <button key="i" styles={buttonStyles} lid={sourceLayoutAtomIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button> : <button disabled key="i0" styles={buttonStyles} lid={sourceLayoutAtomIdString} onclick={propertyBar.deleteLayoutBaseClickHandler}>X</button>} </div>; }, update: function (updatedSource: LayoutAtom) { source = updatedSource; sourceLayoutAtomIdString = source.LayoutBaseId.toString(); sourceContentAtomIdString = source.HostedContentAtom.ContentAtomId.toString(); styleMolecule = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule); // TODO expensive styleMoleculeId = styleMolecule.StyleMoleculeId; styleMoleculeIdString = styleMoleculeId.toString(); layoutAtomStyleClass = `s${styleMoleculeId}`; calculatedPaddingPx = (propertyBar.viewModel.deepestLevelActiveView - source.Level) * 15 + 15; calculatedColor = propertyBar.calculateColorForLevel(source.Level); calculatedMargin = `${(source.Level) * 15 + 15}px`; calculatedBackgroundColor = propertyBar.calculateBackgroundColorForLevel(source.Level); hostedContentAtom = (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.ContentAtomId == source.HostedContentAtom.ContentAtomId) as ContentAtom); // TODO expensive (2 copies of content) } }; }, function updateSectionTarget(updatedSource: LayoutAtom, target: { renderMaquette(): any, update(updatedSource: LayoutAtom): void }) { target.update(updatedSource); }); }; private contentAtomAfterCreateHandler = (element: Element, projectionOptions: maquette.ProjectionOptions, vnodeSelector: string, properties: maquette.VNodeProperties, children: VNode[]) => { let targetElement: HTMLInputElement = element as HTMLInputElement; targetElement.focus(); }; private layoutBaseMouseEnterHandler = (evt: MouseEvent) => { let targetElement: HTMLElement = evt.target as HTMLInputElement; currentApp.state.hoveredBoxTreeLayoutBaseId = parseIntFromAttribute(targetElement, "lid"); }; private layoutBaseMouseLeaveHandler = (evt: MouseEvent) => { currentApp.state.hoveredBoxTreeLayoutBaseId = 0; // TODO remember what was entered before and rehighlight }; private layoutAtomAfterCreateHandler = (element: Element, projectionOptions: maquette.ProjectionOptions, vnodeSelector: string, properties: maquette.VNodeProperties, children: VNode[]) => { if (this.currentPropertyBar.propertyBarIndex == 0) { let targetElement: HTMLElement = element as HTMLElement; this.currentPropertyBar._activeViewLayoutAtomDomNodeReferences[properties.key as string] = targetElement; } }; private resetContentAtomEditMode = () => { currentApp.pagePreview.resetEquationNumbersWhenModifying(false); this.currentPropertyBar.viewModel.editedLayoutAtomId = 0; this.currentPropertyBar.viewModel.tempContent = ""; this.currentPropertyBar.viewModel.tempOriginalContent = ""; }; private contentAtomLostFocusHandler = (evt: FocusEvent) => { this.currentPropertyBar.updateContentAtom(parseIntFromAttribute(evt.target, "cid")); }; private updateContentAtom = (contentAtomId: number) => { if (this.currentPropertyBar.viewModel.editedLayoutAtomId != 0) { if (this.currentPropertyBar.viewModel.tempContent !== this.currentPropertyBar.viewModel.tempOriginalContent) { if (this.currentPropertyBar.viewModel.tempContent !== "") { let contentAtom: ContentAtom = (currentApp.clientData.CaliforniaProject.ContentAtoms.find(a => a.InstancedOnLayoutId == this.currentPropertyBar.viewModel.editedLayoutAtomId) as ContentAtom); // TODO expensive but feels better if (contentAtom.ContentAtomType === ContentAtomType.Text) { contentAtom.TextContent = this.currentPropertyBar.viewModel.tempContent; } else if (contentAtom.ContentAtomType === ContentAtomType.Link) { contentAtom.Url = this.currentPropertyBar.viewModel.tempContent; } else { console.log(DEFAULT_EXCEPTION); return; } currentApp.state.currentReadyState = ReadyState.Pending; currentApp.controller.UpdateTextContentAtomJson(contentAtomId, this.currentPropertyBar.viewModel.tempContent).done((data: any) => { currentApp.router.updateData(data); }).always((data: any) => currentApp.state.currentReadyState = ReadyState.Ok); } else { // do nothing TODO document => use button to delete layout atom instead, shows escape behaviour in current implementation (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.InstancedOnLayoutId == this.currentPropertyBar.viewModel.editedLayoutAtomId) as ContentAtom).TextContent = this.currentPropertyBar.viewModel.tempOriginalContent; // TODO expensive } } } this.currentPropertyBar.resetContentAtomEditMode(); }; private contentAtomKeyDownHandler = (evt: KeyboardEvent) => { // TODO code duplication if (evt.keyCode == 13 /*ENTER*/) { evt.preventDefault(); (evt.target as HTMLInputElement).blur(); } else if (evt.keyCode == 27 /*ESC*/) { evt.preventDefault(); (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.InstancedOnLayoutId == this.currentPropertyBar.viewModel.editedLayoutAtomId) as ContentAtom).TextContent = this.currentPropertyBar.viewModel.tempOriginalContent; // TODO expensive this.currentPropertyBar.resetContentAtomEditMode(); (evt.target as HTMLInputElement).blur(); } else if (evt.keyCode == undefined /*input focus lost*/) { evt.preventDefault(); } // TODO clean whitespaces // TODO autosize }; private contentAtomInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempContent = (evt.target as HTMLInputElement).value; (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.InstancedOnLayoutId == this.currentPropertyBar.viewModel.editedLayoutAtomId) as ContentAtom).TextContent = this.currentPropertyBar.viewModel.tempContent; // TODO expensive // TODO a nicer way would be to prevent update in rendered page and trigger formula update; formula is destroyed when rendered content changes }; private layoutAtomClickHandler = (evt: MouseEvent) => { evt.preventDefault(); // TODO this is set for every content atom in preview... performance? if (currentApp.state.currentReadyState !== ReadyState.Ok) { console.log("pending..."); return; } if (currentApp.state.currentSelectionMode === SelectionMode.Content) { let contentAtomId: number = parseIntFromAttribute(evt.target, "cid"); let layoutAtomId: number = parseIntFromAttribute(evt.target, "aid"); let hostedContentAtom: ContentAtom = (currentApp.clientData.CaliforniaProject.ContentAtoms.find(c => c.ContentAtomId == contentAtomId) as ContentAtom); // TODO expensive (2 copies of content) this.currentPropertyBar.viewModel.tempContent = ""; if (hostedContentAtom.ContentAtomType === ContentAtomType.Text) { // TODO code duplication for content selection at multiple places this.currentPropertyBar.viewModel.tempContent = hostedContentAtom.TextContent as string; } else if (hostedContentAtom.ContentAtomType === ContentAtomType.Link) { this.currentPropertyBar.viewModel.tempContent = hostedContentAtom.Url as string; } else { console.log(DEFAULT_EXCEPTION); return; } this.currentPropertyBar.viewModel.tempOriginalContent = this.currentPropertyBar.viewModel.tempContent; this.currentPropertyBar.viewModel.editedLayoutAtomId = layoutAtomId; } else { // TODO } }; public renderStateModifierSelectors = (): VNode => { let stateModifierGroupStyles = { "display": "flex", "flex-flow": "row nowrap" }; let stateModifiers: string[] = []; let styleMolecule: StyleMolecule = currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleMoleculeId == this.currentPropertyBar.viewModel.selectedStyleMoleculeId) as StyleMolecule; // TODO find used repeatedly for render controls for (let i = 0; i < styleMolecule.MappedStyleAtoms.length; i++) { let modifier: string | undefined = styleMolecule.MappedStyleAtoms[i].StateModifier; if (modifier === undefined) { modifier = ""; } if (stateModifiers.findIndex(s => s === modifier) == -1) { stateModifiers.push(modifier); } } let renderedModifiers: VNode[] = []; for (let i = 0; i < stateModifiers.length; i++) { let modifier: string = stateModifiers[i]; let modifierButtonStyles = { "flex": "0 0 auto", "background-color": modifier == this.currentPropertyBar.viewModel.selectedStateModifier ? "red" : undefined }; renderedModifiers.push(<button key={modifier} role="button" mid={modifier} onclick={this.currentPropertyBar.stateModifierClickHandler} styles={modifierButtonStyles}>{modifier}</button> as VNode); } return <div key="-2" styles={stateModifierGroupStyles}> {renderedModifiers} </div> as VNode; }; public stateModifierClickHandler = (evt: MouseEvent) => { let selectedStateModifier: string = parseStringFromAttribute(evt.target, "mid"); if (selectedStateModifier === this.currentPropertyBar.viewModel.selectedStateModifier) { this.currentPropertyBar.viewModel.selectedStateModifier = ""; } else { this.currentPropertyBar.viewModel.selectedStateModifier = selectedStateModifier; } }; public renderResponsiveDeviceSelectors = (): VNode => { let responsiveGroupStyles = { "display": "flex", "flex-flow": "row wrap" }; return <div key="-3" styles={responsiveGroupStyles}> {(currentApp.clientData.CaliforniaProject.ResponsiveDevices !== undefined) ? currentApp.clientData.CaliforniaProject.ResponsiveDevices.map(r => { let responsiveButtonStyles = { "flex": "0 0 auto", "background-color": r.ResponsiveDeviceId == this.currentPropertyBar.viewModel.selectedResponsiveDeviceId ? "red" : undefined }; let responsiveDeviceIdString: string = r.ResponsiveDeviceId.toString(); return <button key={responsiveDeviceIdString} role="button" rid={responsiveDeviceIdString} onclick={this.currentPropertyBar.selectResponsiveDeviceClickHandler} styles={responsiveButtonStyles}>{r.NameShort}</button> as VNode; }) : undefined} </div> as VNode; }; public selectResponsiveDeviceClickHandler = (evt: MouseEvent) => { let selectedResponsiveId: number = parseIntFromAttribute(evt.target, "rid"); if (this.currentPropertyBar.viewModel.selectedResponsiveDeviceId == selectedResponsiveId) { this.currentPropertyBar.viewModel.selectedResponsiveDeviceId = currentApp.state.noneResponsiveDeviceId; } else { this.currentPropertyBar.viewModel.selectedResponsiveDeviceId = selectedResponsiveId; } }; public renderStyleAtomControls = (): VNode => { return <div key="-1"> <select key="0" onchange={this.currentPropertyBar.styleAtomTypeChangedHandler}> {getArrayForEnum(StyleAtomType).map((type: string, index: number) => { let isSelected: boolean = index === this.currentPropertyBar.viewModel.selectedStyleAtomType; return isSelected ? <option selected key={index} value={index.toString()}>{type}</option> : <option key={index} value={index.toString()}>{type}</option>; })} </select> <input key="-1" placeholder={"optional :hover,:before,..."} value={this.currentPropertyBar.viewModel.tempPseudoSelector} oninput={this.currentPropertyBar.pseudoSelectorInputHandler}> </input> <button key="a" role="button" onclick={this.currentPropertyBar.createStyleAtomForMoleculeClickHandler}>+</button> </div> as VNode; }; public pseudoSelectorInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempPseudoSelector = (evt.target as HTMLInputElement).value; }; public styleAtomTypeChangedHandler = (evt: UIEvent) => { let targetSelect = evt.target as HTMLSelectElement; let parsedStyleAtomType: number | undefined = undefined; if (targetSelect.selectedIndex < targetSelect.childElementCount) { let selectOptionElement: HTMLOptionElement = targetSelect.options[targetSelect.selectedIndex]; parsedStyleAtomType = parseInt(selectOptionElement.value); } if (parsedStyleAtomType !== undefined) { this.currentPropertyBar.viewModel.selectedStyleAtomType = parsedStyleAtomType; } else { console.log(DEFAULT_EXCEPTION); } }; public createStyleAtomForMoleculeClickHandler = (evt: MouseEvent) => { if (this.currentPropertyBar.viewModel.tempPseudoSelector !== "") { this.currentPropertyBar.viewModel.selectedStateModifier = this.currentPropertyBar.viewModel.tempPseudoSelector; } currentApp.controller.CreateStyleAtomForMoleculeJson(this.currentPropertyBar.viewModel.selectedStyleMoleculeId, this.currentPropertyBar.viewModel.selectedStyleAtomType, this.currentPropertyBar.viewModel.selectedResponsiveDeviceId, this.currentPropertyBar.viewModel.selectedStateModifier).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.viewModel.tempPseudoSelector = ""; }; public renderStyleQuantumControls = (): VNode => { return <div key="0"> <input key="-3" value={this.currentPropertyBar.viewModel.tempQuantumName} oninput={this.currentPropertyBar.quantumNameInputHandler}> </input> <input key="-2" value={this.currentPropertyBar.viewModel.tempCssPropertyName} oninput={this.currentPropertyBar.cssPropertyNameInputHandler}> </input> <input key="-1" value={this.currentPropertyBar.viewModel.tempCssValue} oninput={this.currentPropertyBar.cssValueInputHandler}> </input> <button key="a" role="button" onclick={this.currentPropertyBar.createStyleQuantumClickHandler}>&#10004;</button> <button key="b" role="button" onclick={this.currentPropertyBar.showAllCssPropertiesForQuantumClickHandler}>?</button> </div> as VNode; }; public showAllCssPropertiesForQuantumClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.AllCssPropertiesForQuantum); }; public createStyleQuantumClickHandler = (evt: MouseEvent) => { currentApp.controller.CreateStyleQuantumJson(currentApp.clientData.CaliforniaProject.CaliforniaProjectId, this.currentPropertyBar.viewModel.tempQuantumName, this.currentPropertyBar.viewModel.tempCssPropertyName, this.currentPropertyBar.viewModel.tempCssValue).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.resetAddQuantumState(); }; public resetAddQuantumState = (): void => { this.currentPropertyBar.viewModel.tempQuantumName = "Quantum"; this.currentPropertyBar.viewModel.tempCssPropertyName = ""; this.currentPropertyBar.viewModel.tempCssValue = ""; }; public quantumNameInputHandler = (evt: KeyboardEvent): void => { this.currentPropertyBar.viewModel.tempQuantumName = (evt.target as HTMLInputElement).value; }; public renderStyleValueArray = (propertyBar: PropertyBar): maquette.Mapping<StyleValue, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<StyleValue, any>( function getSectionSourceKey(source: StyleValue) { return source.StyleValueId; }, function createSectionTarget(source: StyleValue) { let sourceIdString = source.StyleValueId.toString(); let styleValueButtonStyle = { "flex": "0 0 auto", "width": "auto", "height": "1rem" }; let styleValueTextStyle = { "outline": source.CssValue === "" ? "solid white 1px" : undefined, "outline-offset": source.CssValue === "" ? "-1px" : undefined, "flex": "0 0 auto", "width": "auto", "margin": "0" }; return { renderMaquette: function () { return <div key={sourceIdString} exitAnimation={propertyBar.styleElementExitAnimation} styles={{ "display":"flex", "flex-flow": "row nowrap"}}> <p styles={styleValueTextStyle}>{source.CssProperty}: {source.CssValue}</p> <button key="a" role="button" vid={sourceIdString} onclick={propertyBar.deleteStyleValueClickHandler} styles={styleValueButtonStyle}>X</button> <button key="b" role="button" aid={source.StyleAtomId.toString()} vid={sourceIdString} onclick={propertyBar.updateCssValueClickHandler} styles={styleValueButtonStyle}>Edit</button> </div> as VNode; }, update: function (updatedSource: StyleValue) { source = updatedSource; sourceIdString = source.StyleValueId.toString(); } }; }, function updateSectionTarget(updatedSource: StyleValue, target: { renderMaquette(): any, update(updatedSource: StyleValue): void }) { target.update(updatedSource); }); }; public renderStyleQuantumArrayForStyleAtom = (): maquette.Mapping<StyleQuantum, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<StyleQuantum, any>( function getSectionSourceKey(source: StyleQuantum) { return source.StyleQuantumId; }, function createSectionTarget(source: StyleQuantum) { let sourceIdString = source.StyleQuantumId.toString(); return { renderMaquette: function () { return <div key={sourceIdString}> <p styles={{"margin": "0"}}>{source.Name}: {source.CssProperty} ({source.CssValue})</p> </div> as VNode; }, update: function (updatedSource: StyleQuantum) { source = updatedSource; sourceIdString = source.StyleQuantumId.toString(); } }; }, function updateSectionTarget(updatedSource: StyleQuantum, target: { renderMaquette(): any, update(updatedSource: StyleQuantum): void }) { target.update(updatedSource); }); }; public renderStyleAtomArray = (propertyBar: PropertyBar): maquette.Mapping<StyleAtom, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<StyleAtom, any>( function getSectionSourceKey(source: StyleAtom) { return source.StyleAtomId; }, function createSectionTarget(source: StyleAtom) { let styleAtomIdString = source.StyleAtomId.toString(); let appliedValuesMap = propertyBar.renderStyleValueArray(propertyBar); let appliedQuantumsMap = propertyBar.renderStyleQuantumArrayForStyleAtom(); if (source.AppliedValues !== undefined) { appliedValuesMap.map(source.AppliedValues); } else { appliedValuesMap.map([]); } if (source.MappedQuantums !== undefined) { appliedQuantumsMap.map(source.MappedQuantums.map(qm => qm.StyleQuantum)); } else { appliedQuantumsMap.map([]); } return { renderMaquette: function () { let isDisplayStyleAtom: boolean = true; if (propertyBar.viewModel.currentPropertyBarMode === PropertyBarMode.StyleMolecule) { let styleMolecule: StyleMolecule = currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleMoleculeId == propertyBar.viewModel.selectedStyleMoleculeId) as StyleMolecule;// TODO slow very expensive let targetMappingIndex: number = styleMolecule.MappedStyleAtoms.findIndex(m => m.ResponsiveDeviceId == propertyBar.viewModel.selectedResponsiveDeviceId && m.StyleMoleculeAtomMappingId == source.MappedToMoleculeId && ((m.StateModifier === undefined && propertyBar.viewModel.selectedStateModifier === "") || (m.StateModifier === propertyBar.viewModel.selectedStateModifier))); isDisplayStyleAtom = targetMappingIndex != -1; } let divStyleAtomStyles = { "display": !isDisplayStyleAtom ? "none" : undefined, "width": "100%", "height": "auto" }; return <div key={styleAtomIdString} exitAnimation={propertyBar.styleElementExitAnimation} styles={divStyleAtomStyles}> <p key="0" styles={{ "margin": "0" }}>(#{styleAtomIdString}){source.Name}:</p> {appliedValuesMap.results.map(r => r.renderMaquette())} <button key="a" role="button" aid={styleAtomIdString} onclick={propertyBar.createCssPropertyForAtomClickHandler}>+</button> <button key="b" role="button" aid={styleAtomIdString} onclick={propertyBar.moveStyleAtomPopupClickHandler}>=></button> {source.IsDeletable ? <button key="b0" role="button" aid={styleAtomIdString} onclick={propertyBar.deleteStyleAtomClickHandler}>X</button> : <button disabled key="b1" role="button" aid={styleAtomIdString}>X</button>} {source.MappedQuantums.length > 0 ? <p key="-1">quantums:</p> : undefined} {appliedQuantumsMap.results.map(r => r.renderMaquette())} </div>; }, update: function (updatedSource: StyleAtom) { source = updatedSource; appliedValuesMap.map(updatedSource.AppliedValues); appliedQuantumsMap.map(updatedSource.MappedQuantums.map(qm => qm.StyleQuantum)); } }; }, function updateSectionTarget(updatedSource: StyleAtom, target: { renderMaquette(): any, update(updatedSource: StyleAtom): void }) { target.update(updatedSource); }); }; public moveStyleAtomPopupClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.selectedStyleAtomIdForPopup = parseIntFromAttribute(evt.target, "aid"); this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveStyleAtom); }; public createCssPropertyForAtomClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.selectedStyleAtomId = parseIntFromAttribute(evt.target, "aid"); this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.AddCssProperty); this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.AllCssProperties); // TODO render first popup, then use renderd question mark button as target (intermediate popup dom) }; public deleteStyleAtomClickHandler = (evt: MouseEvent) => { currentApp.controller.DeleteStyleAtomJson(parseIntFromAttribute(evt.target, "aid")).done(data => currentApp.router.updateData(data)); }; public updateCssValueClickHandler = (evt: MouseEvent) => { let styleValueId: number = parseIntFromAttribute(evt.target, "vid"); let styleAtomId: number = parseIntFromAttribute(evt.target, "aid"); this.currentPropertyBar.viewModel.selectedStyleValueId = styleValueId; this.currentPropertyBar.viewModel.selectedStyleAtomId = styleAtomId; let targetStyleValue: StyleValue = currentApp.clientData.CaliforniaProject.StyleValues.find(val => val.StyleValueId == styleValueId) as StyleValue; this.currentPropertyBar.viewModel.tempCssValue = targetStyleValue.CssValue; this.currentPropertyBar.viewModel.tempCssPropertyName = targetStyleValue.CssProperty; this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.UpdateCssValue); }; public deleteStyleValueClickHandler = (evt: MouseEvent) => { currentApp.controller.DeleteStyleValueJson(parseIntFromAttribute(evt.target, "vid")).done(data => currentApp.router.updateData(data)); }; public renderAddCssPropertyPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.AddCssProperty || this.viewModel.currentPopupMode === PopupMode.AllCssProperties; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.AddCssProperty]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.saveCssPropertyForAtomClickHandler}>&#10004;</button> <button key="b" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelAddCssPropertyForAtomClickHandler}>x</button> </div> <div> <input key="-1" value={this.currentPropertyBar.viewModel.tempCssPropertyName} oninput={this.currentPropertyBar.cssPropertyNameInputHandler}> </input> <button key="a" role="button" onclick={this.currentPropertyBar.showAllCssPropertiesClickHandler}>?</button> </div> </div> as VNode; }; public renderAllCssPropertiesForQuantumPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.AllCssPropertiesForQuantum; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.AllCssPropertiesForQuantum]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31" /*TODO document*/, "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelUpdateCssPropertyForQuantumClickHandler}>x</button> </div> {currentApp.clientData.AllCssProperties.map((prop: string) => { return <div key={prop}> {prop}<button key="a" role="button" cid={prop} onclick={this.currentPropertyBar.setSelectedCssPropertyForQuantumClickHandler}>&#10004;</button> </div>; })} </div> as VNode; }; public setSelectedCssPropertyForQuantumClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.tempCssPropertyName = parseStringFromAttribute(evt.target, "cid"); this.currentPropertyBar.closePopup(); }; public cancelUpdateCssPropertyForQuantumClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public insertLayoutRowIntoViewPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.InsertLayoutRowIntoView; let instanceableLayoutRows: LayoutRow[] = []; if (isPopupVisible) { // TODO will break when data is not supplied let instanceableRowsView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(view => view.IsInternal && view.Name === "[Internal] Instanceable Layout Rows") as CaliforniaView; // TODO magic string => const export instanceableLayoutRows.push(...instanceableRowsView.PlacedLayoutRows); let userInstanceableRowsView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(view => view.IsInternal && view.Name === "[Internal] User Layout Molecules") as CaliforniaView; // TODO magic string => const export for (let i = 1; i < userInstanceableRowsView.PlacedLayoutRows.length; i++) { // skip box holder instanceableLayoutRows.push(userInstanceableRowsView.PlacedLayoutRows[i]); } } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.InsertLayoutRowIntoView]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelInsertLayoutRowIntoViewClickHandler}>x</button> </div> {instanceableLayoutRows.map((prop: LayoutRow) => { return <div key={prop.LayoutBaseId}> <button styles={{ "width": "auto", "margin": "0" }} key="a" lid={prop.LayoutBaseId.toString()} onclick={this.currentPropertyBar.insertSelectedLayoutRowIntoViewClickHandler} onmouseenter={this.currentPropertyBar.insertRowShowPreviewHandler} onmouseleave={this.currentPropertyBar.insertRowHidePreviewHandler}>&#10004; </button> <p key="0" styles={{ "-webkit-user-select": "none", "width": "auto", "margin": "0", "float": "left" }} lid={prop.LayoutBaseId.toString()} ontouchstart={this.currentPropertyBar.insertRowShowPreviewHandler} ontouchend={this.currentPropertyBar.insertRowHidePreviewHandler}>{prop.LayoutBaseId}</p> </div>; })} </div> as VNode; }; public insertSelectedLayoutRowIntoViewClickHandler = (evt: MouseEvent) => { let layoutId: number = parseIntFromAttribute(evt.target, "lid"); currentApp.controller.CreateLayoutRowForViewJson(this.currentPropertyBar.viewModel.selectedCaliforniaViewId, layoutId).done(data => currentApp.router.updateData(data)); currentApp.state.lastCommand = CaliforniaEvent.CreateLayoutRowForView; currentApp.state.lastCaliforniaEventData = [this.currentPropertyBar.viewModel.selectedCaliforniaViewId, layoutId]; this.currentPropertyBar.closePopup(); }; public cancelInsertLayoutRowIntoViewClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public insertLayoutAtomIntoBoxPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.InsertLayoutAtomIntoBox; let instanceableLayoutAtoms: LayoutAtom[] = []; if (isPopupVisible) { // TODO will break when data is not supplied let instanceableAtomsView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(view => view.IsInternal && view.Name === "[Internal] Instanceable Layout Atoms") as CaliforniaView; // TODO magic string => const export let atomContainerBox: LayoutBox = instanceableAtomsView.PlacedLayoutRows[0].AllBoxesBelowRow.find(b => b.PlacedInBoxAtoms.length > 0) as LayoutBox; instanceableLayoutAtoms.push(...atomContainerBox.PlacedInBoxAtoms); } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.InsertLayoutAtomIntoBox]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelInsertLayoutAtomIntoBoxClickHandler}>x</button> </div> {instanceableLayoutAtoms.map((prop: LayoutAtom) => { let textPreview: string = ""; if (prop.HostedContentAtom.ContentAtomType === ContentAtomType.Text) { // TODO code duplication for content selection at multiple places textPreview = prop.HostedContentAtom.TextContent as string; } else if (prop.HostedContentAtom.ContentAtomType === ContentAtomType.Link) { textPreview = prop.HostedContentAtom.Url as string; } else { console.log(DEFAULT_EXCEPTION); return; } return <div key={prop.LayoutBaseId}> <button styles={{ "width": "auto", "margin": "0" }} key="a" lid={prop.LayoutBaseId.toString()} onclick={this.currentPropertyBar.insertSelectedLayoutAtomIntoBoxClickHandler} onmouseenter={this.currentPropertyBar.insertAtomShowPreviewHandler} onmouseleave={this.currentPropertyBar.insertAtomHidePreviewHandler}>&#10004; </button> <p key="0" styles={{ "-webkit-user-select": "none", "width": "auto", "margin": "0", "float": "left" }} lid={prop.LayoutBaseId.toString()} ontouchstart={this.currentPropertyBar.insertAtomShowPreviewHandler} ontouchend={this.currentPropertyBar.insertAtomHidePreviewHandler}>{prop.LayoutBaseId} {textPreview}</p> </div>; })} </div> as VNode; }; public insertSelectedLayoutAtomIntoBoxClickHandler = (evt: MouseEvent) => { let targetBoxId: number = currentApp.state.selectedLayoutBaseId; currentApp.controller.CreateLayoutAtomForBoxJson(targetBoxId, parseIntFromAttribute(evt.target, "lid")).done(data => { currentApp.router.updateData(data); currentApp.projector.renderNow(); // TODO let updatedSubAtoms: LayoutAtom[] = (currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == targetBoxId) as LayoutBox).PlacedInBoxAtoms; this.currentPropertyBar.viewModel.editedLayoutAtomId = updatedSubAtoms[updatedSubAtoms.length - 1].LayoutBaseId; // TODO just guessing, save all existing and compare to all new for safe variant }); this.currentPropertyBar.closePopup(); }; public cancelInsertLayoutAtomIntoBoxClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public displayPopup = (targetPosition: HTMLElement, popupMode: PopupMode) => { /*if (CaliforniaApp.CaliforniaAppInstance.state.currentPopupMode !== PopupMode.None) { TODO return; }*/ let popupElement: HTMLElement | null = null; popupElement = document.getElementById(`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[popupMode]}`) as HTMLElement; if (popupElement !== null) { this.viewModel.currentPopupMode = popupMode; var displayPopup = new popperjs.default(targetPosition, popupElement, { placement: 'bottom-end', modifiers: { /*flip: { behavior: ['left', 'bottom', 'top'] },*/ preventOverflow: { boundariesElement: document.body, } }, }); //document.body.style.backgroundColor = "rgb(245, 245, 245)"; TODO currentApp.projector.renderNow(); // required to update popup position to be contained by boundaries element return; } console.log(DEFAULT_EXCEPTION); }; public closePopup = () => { //document.body.style.background = "white"; TODO this.viewModel.currentPopupMode = PopupMode.None; this.viewModel.currentSecondaryPopupMode = PopupSecondaryMode.None; }; public insertLayoutBoxIntoBoxPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.SelectBox; let instanceableLayoutBoxes: LayoutBox[] = []; if (isPopupVisible) { // TODO will break when data is not supplied let instanceableRowsView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(view => view.IsInternal && view.Name === "[Internal] Instanceable Layout Rows") as CaliforniaView; // TODO magic string => const export let allBoxes: LayoutBox[] = instanceableRowsView.PlacedLayoutRows[0].AllBoxesBelowRow; let firstSubBox: LayoutBox = allBoxes.find(b => b.PlacedBoxInBoxId === undefined) as LayoutBox; //let targetBox: LayoutBox = allBoxes.find(b => b.PlacedBoxInBoxId == firstSubBox.LayoutBaseId) as LayoutBox; TODO kept as reference for previous project default with 2x2 boxes (now 1x2) instanceableLayoutBoxes.push(firstSubBox); let userInstanceableView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(view => view.IsInternal && view.Name === "[Internal] User Layout Molecules") as CaliforniaView; // TODO magic string => const export let userBoxes: LayoutBox[] = userInstanceableView.PlacedLayoutRows[0].AllBoxesBelowRow.filter(b => b.PlacedBoxInBoxId === undefined); instanceableLayoutBoxes.push(...userBoxes); } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.SelectBox]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelInsertLayoutBoxIntoBoxClickHandler}>x</button> </div> {instanceableLayoutBoxes.map((prop: LayoutBox) => { return <div key={prop.LayoutBaseId}> <button styles={{ "width": "auto", "margin": "0" }} key="a" role="button" lid={prop.LayoutBaseId.toString()} onclick={this.currentPropertyBar.insertSelectedLayoutBoxIntoBoxOrRowClickHandler} onmouseenter={this.currentPropertyBar.insertBoxShowPreviewHandler} onmouseleave={this.currentPropertyBar.insertBoxHidePreviewHandler}> &#10004; </button> <p key="0" styles={{ "-webkit-user-select": "none", "width": "auto", "margin": "0", "float": "left" }} lid={prop.LayoutBaseId.toString()} ontouchstart={this.currentPropertyBar.insertBoxShowPreviewHandler} ontouchend={this.currentPropertyBar.insertBoxHidePreviewHandler}>{prop.LayoutBaseId}</p> </div>; })} </div> as VNode; }; private insertRowShowPreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication let targetElement: HTMLElement = evt.target as HTMLElement; let hoveredLayoutId: number = parseIntFromAttribute(targetElement, "lid"); currentApp.state.hoveredInsertLayoutBaseId = hoveredLayoutId; let tempRow: LayoutRow = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == hoveredLayoutId) as LayoutRow; currentApp.state.backupSortOrder = tempRow.LayoutSortOrderKey; tempRow.LayoutSortOrderKey = VERY_HIGH_VALUE; // TODO very high value let californiaView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == this.currentPropertyBar.viewModel.selectedCaliforniaViewId) as CaliforniaView; californiaView.PlacedLayoutRows.push(tempRow); currentApp.router.setActiveCaliforniaView(californiaView); // TODO inconsistent data model leads to this manual refresh / boxtree not in sync }; private insertRowHidePreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication let californiaView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == this.currentPropertyBar.viewModel.selectedCaliforniaViewId) as CaliforniaView; let tempRowIndex: number = californiaView.PlacedLayoutRows.findIndex(r => r.LayoutBaseId == currentApp.state.hoveredInsertLayoutBaseId); if (tempRowIndex != -1) { let tempRow: LayoutRow = californiaView.PlacedLayoutRows.splice(tempRowIndex, 1)[0]; if (currentApp.state.backupSortOrder !== undefined) { tempRow.LayoutSortOrderKey = currentApp.state.backupSortOrder; } else { console.log(DEFAULT_EXCEPTION); } currentApp.state.backupSortOrder = undefined; currentApp.state.hoveredInsertLayoutBaseId = 0; currentApp.router.setActiveCaliforniaView(californiaView); } else { console.log(DEFAULT_EXCEPTION); } }; private insertBoxShowPreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication // TODO test / check is it necessary to add subbox references to parentRow=>allBoxesBelowRow for this temporary update? let targetElement: HTMLElement = evt.target as HTMLElement; let hoveredLayoutId: number = parseIntFromAttribute(targetElement, "lid"); currentApp.state.hoveredInsertLayoutBaseId = hoveredLayoutId; let tempBox: LayoutBox = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == hoveredLayoutId) as LayoutBox; currentApp.state.backupSortOrder = tempBox.LayoutSortOrderKey; tempBox.LayoutSortOrderKey = VERY_HIGH_VALUE; // TODO very high value let selectedBoxOrRow: LayoutBase = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutBase; if (selectedBoxOrRow.LayoutType === LayoutType.Box) { // seems to work without changing layout box owner row, unlike when inserting directly into layout row (selectedBoxOrRow as LayoutBox).PlacedInBoxBoxes.push(tempBox); } else if (selectedBoxOrRow.LayoutType === LayoutType.Row) { //let tempNewOwnerRow: LayoutRow = selectedBoxOrRow as LayoutRow; let tempNewOwnerRow: LayoutRow = (currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == currentApp.pagePreviewVM.activeCaliforniaViewId) as CaliforniaView).PlacedLayoutRows.find(ro => ro.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutRow; tempNewOwnerRow.AllBoxesBelowRow.push(tempBox); currentApp.state.backupOwnerRowId = tempBox.BoxOwnerRowId; tempBox.BoxOwnerRowId = tempNewOwnerRow.LayoutBaseId; tempBox.BoxOwnerRow = tempNewOwnerRow; currentApp.state.backupPlacedBoxInBoxId = tempBox.PlacedBoxInBoxId; tempBox.PlacedBoxInBoxId = undefined; } else { console.log(DEFAULT_EXCEPTION); } currentApp.router.setActiveCaliforniaView(currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == currentApp.pagePreviewVM.activeCaliforniaViewId) as CaliforniaView); // TODO inconsistent data model leads to this manual refresh / boxtree not in sync }; private insertBoxHidePreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication let selectedBoxOrRow: LayoutBase = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutBase; if (selectedBoxOrRow.LayoutType === LayoutType.Box) { let layoutBox: LayoutBox = selectedBoxOrRow as LayoutBox; let tempBoxIndex: number = layoutBox.PlacedInBoxBoxes.findIndex(b => b.LayoutBaseId == currentApp.state.hoveredInsertLayoutBaseId); if (tempBoxIndex != -1) { let tempBox: LayoutBox = layoutBox.PlacedInBoxBoxes.splice(tempBoxIndex, 1)[0]; if (currentApp.state.backupSortOrder !== undefined) { tempBox.LayoutSortOrderKey = currentApp.state.backupSortOrder; } else { // value always set console.log(DEFAULT_EXCEPTION); } currentApp.state.backupSortOrder = undefined; currentApp.state.hoveredInsertLayoutBaseId = 0; } else { console.log(DEFAULT_EXCEPTION); } } else if (selectedBoxOrRow.LayoutType === LayoutType.Row) { let layoutRow: LayoutRow = selectedBoxOrRow as LayoutRow; let tempBoxIndex: number = layoutRow.AllBoxesBelowRow.findIndex(b => b.LayoutBaseId == currentApp.state.hoveredInsertLayoutBaseId); if (tempBoxIndex != -1) { let tempBox: LayoutBox = layoutRow.AllBoxesBelowRow.splice(tempBoxIndex, 1)[0]; if (currentApp.state.backupSortOrder !== undefined) { tempBox.LayoutSortOrderKey = currentApp.state.backupSortOrder; } else { console.log(DEFAULT_EXCEPTION); } if (currentApp.state.backupOwnerRowId !== undefined) { // value set only in certain cases let backupRow = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(r => r.LayoutBaseId == currentApp.state.backupOwnerRowId) as LayoutRow; tempBox.BoxOwnerRowId = currentApp.state.backupOwnerRowId; tempBox.BoxOwnerRow = backupRow; if (currentApp.state.backupPlacedBoxInBoxId !== undefined) { tempBox.PlacedBoxInBoxId = currentApp.state.backupPlacedBoxInBoxId; } currentApp.state.backupOwnerRowId = undefined; currentApp.state.backupPlacedBoxInBoxId = undefined; } currentApp.state.backupSortOrder = undefined; currentApp.state.hoveredInsertLayoutBaseId = 0; } else { console.log(DEFAULT_EXCEPTION); } } else { console.log(DEFAULT_EXCEPTION); } currentApp.router.setActiveCaliforniaView(currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == currentApp.pagePreviewVM.activeCaliforniaViewId) as CaliforniaView); // TODO inconsistent data model leads to this manual refresh / boxtree not in sync }; private insertAtomShowPreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication // TODO everywhere make use of int8 and fix enum/bool to int32 default coercions let targetElement: HTMLElement = evt.target as HTMLElement; let hoveredLayoutId: number = parseIntFromAttribute(targetElement, "lid"); currentApp.state.hoveredInsertLayoutBaseId = hoveredLayoutId; let tempAtom: LayoutAtom = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == hoveredLayoutId) as LayoutAtom; currentApp.state.backupSortOrder = tempAtom.LayoutSortOrderKey; tempAtom.LayoutSortOrderKey = VERY_HIGH_VALUE; // TODO very high value let layoutBox: LayoutBox = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutBox; layoutBox.PlacedInBoxAtoms.push(tempAtom); }; private insertAtomHidePreviewHandler = (evt: MouseEvent | TouchEvent) => { // TODO code duplication let layoutBox: LayoutBox = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutBox; let tempAtomIndex: number = layoutBox.PlacedInBoxAtoms.findIndex(a => a.LayoutBaseId == currentApp.state.hoveredInsertLayoutBaseId); if (tempAtomIndex != -1) { let tempAtom: LayoutAtom = layoutBox.PlacedInBoxAtoms.splice(tempAtomIndex, 1)[0]; if (currentApp.state.backupSortOrder !== undefined) { tempAtom.LayoutSortOrderKey = currentApp.state.backupSortOrder; } else { console.log(DEFAULT_EXCEPTION); } currentApp.state.backupSortOrder = undefined; currentApp.state.hoveredInsertLayoutBaseId = 0; } else { console.log(DEFAULT_EXCEPTION); } }; public insertSelectedLayoutBoxIntoBoxOrRowClickHandler = (evt: MouseEvent) => { // TODO document popup is reused if (this.viewModel.currentSecondaryPopupMode === PopupSecondaryMode.SelectBoxIntoBox) { let layoutId: number = parseIntFromAttribute(evt.target, "lid"); let targetLayoutId: number = currentApp.state.selectedLayoutBaseId; currentApp.controller.CreateLayoutBoxForBoxOrRowJson(targetLayoutId, layoutId).done(data => { currentApp.router.updateData(data); // TODO focus last atom if one was created }); currentApp.state.lastCommand = CaliforniaEvent.CreateLayoutBoxForBoxOrRow; currentApp.state.lastCaliforniaEventData = [currentApp.state.selectedLayoutBaseId, layoutId]; } else if (this.viewModel.currentSecondaryPopupMode === PopupSecondaryMode.SelectBoxIntoBoxAtomInPlace) { currentApp.controller.CreateLayoutBoxForAtomInPlaceJson(currentApp.state.selectedLayoutBaseId, parseIntFromAttribute(evt.target, "lid")).done(data => { currentApp.router.updateData(data); // TODO focus last atom if one was created }); } else { console.log(DEFAULT_EXCEPTION); } this.currentPropertyBar.closePopup(); }; public cancelInsertLayoutBoxIntoBoxClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; /*public moveLayoutMoleculeIntoPopup = (): VNode => { let thisPopupMode: PopupMode = PopupMode.MoveLayoutMoleculeIntoLayoutMolecule; let isPopupVisible: boolean = this.viewModel.currentPopupMode === thisPopupMode; let isDataLoaded: boolean = currentApp.clientData.CaliforniaProject !== undefined && currentApp.clientData.CaliforniaProject.ResponsiveDevices !== undefined; // TODO code duplication / state return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[thisPopupMode]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelLayoutMoleculeIntoClickHandler}>x</button> </div> {isDataLoaded ? currentApp.clientData.CaliforniaProject.LayoutMolecules.map((layoutMolecule: LayoutBase) => { if (layoutMolecule.LayoutType === LayoutType.Atom) { return undefined; } let layoutBaseIdString: string = layoutMolecule.LayoutBaseId.toString(); let sourceStyleMoleculeIdString = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == layoutMolecule.LayoutBaseId) as StyleMolecule).StyleMoleculeId.toString(); // TODO expensive return <div key={layoutBaseIdString}> <button key="a" lid={layoutBaseIdString} onclick={this.currentPropertyBar.moveLayoutMoleculeIntoLayoutMoleculeClickHandler}>#{layoutBaseIdString} {LayoutType[layoutMolecule.LayoutType]} style #{sourceStyleMoleculeIdString}</button> </div> }) : undefined} </div> as VNode; }; public moveLayoutMoleculeIntoLayoutMoleculeClickHandler = (evt: MouseEvent) => { currentApp.controller.MoveLayoutMoleculeIntoLayoutMoleculeJson(currentApp.state.selectedLayoutBaseId, parseIntFromAttribute(evt.target, "lid")).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.closePopup(); }; public cancelLayoutMoleculeIntoClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); };*/ public moveLayoutMoleculeIntoLayoutMolecule = () => { currentApp.controller.MoveLayoutMoleculeIntoLayoutMoleculeJson(currentApp.state.preselectedLayoutBaseId, currentApp.state.selectedLayoutBaseId).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.closePopup(); }; /*public moveLayoutMoleculeBeforePopup = (): VNode => { TODO unused let thisPopupMode: PopupMode = PopupMode.MoveLayoutMoleculeBeforeLayoutMolecule; let isPopupVisible: boolean = this.viewModel.currentPopupMode === thisPopupMode; let isDataLoaded: boolean = currentApp.clientData.CaliforniaProject !== undefined && currentApp.clientData.CaliforniaProject.ResponsiveDevices !== undefined; // TODO code duplication / state return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[thisPopupMode]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelLayoutMoleculeBeforeClickHandler}>x</button> </div> {isDataLoaded ? currentApp.clientData.CaliforniaProject.LayoutMolecules.map((layoutMolecule: LayoutBase) => { let layoutBaseIdString: string = layoutMolecule.LayoutBaseId.toString(); let sourceStyleMoleculeIdString = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == layoutMolecule.LayoutBaseId) as StyleMolecule).StyleMoleculeId.toString(); // TODO expensive return <div key={layoutBaseIdString}> <button key="a" lid={layoutBaseIdString} onclick={this.currentPropertyBar.moveLayoutMoleculeBeforeLayoutMoleculeClickHandler}>#{layoutBaseIdString} {LayoutType[layoutMolecule.LayoutType]} style #{sourceStyleMoleculeIdString}</button> </div> }) : undefined} </div> as VNode; }; public moveLayoutMoleculeBeforeLayoutMoleculeClickHandler = (evt: MouseEvent) => { currentApp.controller.MoveLayoutMoleculeNextToLayoutMoleculeJson(currentApp.state.selectedLayoutBaseId, parseIntFromAttribute(evt.target, "lid"), true).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.closePopup(); }; public cancelLayoutMoleculeBeforeClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); };*/ public moveLayoutMoleculeBeforeLayoutMolecule = () => { currentApp.controller.MoveLayoutMoleculeNextToLayoutMoleculeJson(currentApp.state.preselectedLayoutBaseId, currentApp.state.selectedLayoutBaseId, true).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.closePopup(); }; public syncLayoutMoleculeStylesImitatingReferenceLayout = () => { // TODO everywhere checks move/duplicate to client currentApp.controller.SyncLayoutStylesImitatingReferenceLayoutJson(currentApp.state.selectedLayoutBaseId, currentApp.state.preselectedLayoutBaseId).done(data => currentApp.router.updateData(data)); // TODO concept: target/preselect order changes this.currentPropertyBar.closePopup(); }; public moveStyleAtomToResponsiveDevicePopup = (): VNode => { let thisPopupMode: PopupMode = PopupMode.MoveStyleAtom; let isPopupVisible: boolean = this.viewModel.currentPopupMode === thisPopupMode; let isDataLoaded: boolean = currentApp.clientData.CaliforniaProject !== undefined && currentApp.clientData.CaliforniaProject.ResponsiveDevices !== undefined; // TODO code duplication / state return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[thisPopupMode]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelMoveStyleAtomClickHandler}>x</button> </div> {isDataLoaded ? currentApp.clientData.CaliforniaProject.ResponsiveDevices.map((responsiveDevice: ResponsiveDevice) => { let responsiveDeviceIdString: string = responsiveDevice.ResponsiveDeviceId.toString(); let isSelectedResponsiveDeviceInPropertyBar: boolean = this.currentPropertyBar.viewModel.selectedResponsiveDeviceId == responsiveDevice.ResponsiveDeviceId; return <div key={responsiveDeviceIdString}> {!isSelectedResponsiveDeviceInPropertyBar ? <button key="a" rid={responsiveDeviceIdString} onclick={this.currentPropertyBar.moveStyleAtomToResponsiveDeviceClickHandler}>{responsiveDevice.NameShort}</button> : <button disabled key="a0" rid={responsiveDeviceIdString} onclick={this.currentPropertyBar.moveStyleAtomToResponsiveDeviceClickHandler}>{responsiveDevice.NameShort}</button> } </div> }) : undefined} </div> as VNode; }; public moveStyleAtomToResponsiveDeviceClickHandler = (evt: MouseEvent) => { let targetResponsiveDeviceId: number = parseIntFromAttribute(evt.target, "rid"); currentApp.controller.MoveStyleAtomToResponsiveDeviceJson(this.currentPropertyBar.viewModel.selectedStyleAtomIdForPopup, targetResponsiveDeviceId).done(data => { currentApp.router.updateData(data); this.currentPropertyBar.viewModel.selectedResponsiveDeviceId = targetResponsiveDeviceId; }); this.currentPropertyBar.viewModel.selectedStyleAtomIdForPopup = 0; this.currentPropertyBar.closePopup(); }; public cancelMoveStyleAtomClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.selectedStyleAtomIdForPopup = 0; this.currentPropertyBar.closePopup(); }; public renderAllCssPropertiesPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.AllCssProperties; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.AllCssProperties]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelUpdateCssPropertylickHandler}>x</button> </div> {currentApp.clientData.AllCssProperties.map((prop: string) => { let isPropertyUnmapped: boolean = true; let isPropertyVisible: boolean = false; if (this.currentPropertyBar.viewModel.selectedStyleAtomId != 0 && currentApp.clientData.CaliforniaProject !== undefined && currentApp.clientData.CaliforniaProject.StyleAtoms !== undefined) { let targetAtom: StyleAtom | undefined = currentApp.clientData.CaliforniaProject.StyleAtoms.find(s => s.StyleAtomId == this.currentPropertyBar.viewModel.selectedStyleAtomId); if (targetAtom !== undefined && targetAtom.AppliedValues !== undefined) { isPropertyVisible = currentApp.clientData.StyleAtomCssPropertyMapping[StyleAtomType[targetAtom.StyleAtomType]].findIndex(p => p === prop) != -1; isPropertyUnmapped = targetAtom.AppliedValues.findIndex(v => v.CssProperty === prop) == -1; } } return isPropertyVisible ? <div key={prop}> {prop}{ isPropertyUnmapped ? <button key="a0" role="button" cid={prop} onclick={this.currentPropertyBar.setSelectedCssPropertyClickHandler}>&#10004;</button> : <button disabled key="a1" role="button" cid={prop} onclick={this.currentPropertyBar.setSelectedCssPropertyClickHandler}>&#10004;</button>} </div> : undefined; })} </div> as VNode; }; public cancelUpdateCssPropertylickHandler = (evt: MouseEvent) => { this.viewModel.currentPopupMode = PopupMode.AddCssProperty; }; public showAllCssPropertiesClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.AllCssProperties); }; public setSelectedCssPropertyClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.tempCssPropertyName = parseStringFromAttribute(evt.target, "cid"); this.currentPropertyBar.saveCssPropertyForAtom(); }; public saveCssPropertyForAtomClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.saveCssPropertyForAtom(); }; private saveCssPropertyForAtom = (): void => { currentApp.controller.CreateStyleValueForAtomJson(this.currentPropertyBar.viewModel.selectedStyleAtomId, this.currentPropertyBar.viewModel.tempCssPropertyName).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.resetTempCssPropertyState(); }; public cancelAddCssPropertyForAtomClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.resetTempCssPropertyState(); }; public resetTempCssPropertyState = (): void => { this.currentPropertyBar.viewModel.tempCssPropertyName = ""; this.currentPropertyBar.viewModel.tempCssValue = ""; this.currentPropertyBar.viewModel.selectedStyleAtomId = 0; this.currentPropertyBar.viewModel.selectedStyleValueId = 0; this.currentPropertyBar.viewModel.selectedStyleQuantumId = 0; this.currentPropertyBar.closePopup(); }; public cssPropertyNameInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempCssPropertyName = (evt.target as HTMLInputElement).value; }; public renderUpdateCssValuePopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.UpdateCssValue || this.viewModel.currentPopupMode === PopupMode.MatchingQuantums; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.UpdateCssValue]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.saveUpdatedCssValueClickHandler}>&#10004;</button> <button key="b" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelUpdateCssValueClickHandler}>x</button> </div> <div> <input key="-1" value={this.currentPropertyBar.viewModel.tempCssValue} oninput={this.currentPropertyBar.cssValueInputHandler}> </input> <button key="a" role="button" onclick={this.currentPropertyBar.showMatchingQuantumsClickHandler}>?</button> <button key="b" role="button" onclick={this.currentPropertyBar.showSuggestedCssValuesClickHandler}>??</button> <button key="c" role="button" onclick={this.currentPropertyBar.setTempCssToZeroClickHandler}>0</button> <button key="d" role="button" onclick={this.currentPropertyBar.setTempCssToNoneClickHandler}>none</button> <button key="e" role="button" onclick={this.currentPropertyBar.setTempCssToNullClickHandler}>null</button> <button key="f" role="button" onclick={this.currentPropertyBar.setTempCssToAutoClickHandler}>auto</button> {this.currentPropertyBar.viewModel.lastUsedTempCssValue !== "" ? <button key="g" role="button" onclick={this.currentPropertyBar.setTempCssAppendLastUsedClickHandler}>+{this.currentPropertyBar.viewModel.lastUsedTempCssValue.length > 10 ? this.currentPropertyBar.viewModel.lastUsedTempCssValue.substring(0, 10) + "..." : this.currentPropertyBar.viewModel.lastUsedTempCssValue}</button> : undefined} </div> </div> as VNode; }; public showSuggestedCssValuesClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.SuggestedCssValues); }; public setTempCssToZeroClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.tempCssValue = "0"; }; public setTempCssToNullClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.tempCssValue = "null"; }; public setTempCssToNoneClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.tempCssValue = "none"; }; public setTempCssToAutoClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.tempCssValue = "auto"; }; public setTempCssAppendLastUsedClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.tempCssValue = this.currentPropertyBar.viewModel.tempCssValue + this.currentPropertyBar.viewModel.lastUsedTempCssValue; }; public renderUpdateCssQuantumPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.UpdateCssQuantum; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.UpdateCssQuantum]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.saveUpdatedCssQuantumClickHandler}>&#10004;</button> <button key="b" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelUpdateCssQuantumClickHandler}>x</button> </div> <div> <input key="-1" value={this.currentPropertyBar.viewModel.tempCssValue} oninput={this.currentPropertyBar.cssValueInputHandler}> </input> </div> </div> as VNode; }; public showMatchingQuantumsClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MatchingQuantums); }; public saveUpdatedCssQuantumClickHandler = (evt: MouseEvent) => { currentApp.controller.UpdateStyleQuantumJson(this.currentPropertyBar.viewModel.selectedStyleQuantumId, this.currentPropertyBar.viewModel.tempCssValue).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.viewModel.lastUsedTempCssValue = this.currentPropertyBar.viewModel.tempCssValue; this.currentPropertyBar.resetTempCssPropertyState(); }; public cancelUpdateCssQuantumClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.resetTempCssPropertyState(); }; public saveUpdatedCssValueFromAttrClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.tempCssValue = parseStringFromAttribute(evt.target, "fid"); this.currentPropertyBar.saveUpdatedCssValue(); }; public saveUpdatedCssValueClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.saveUpdatedCssValue(); }; public saveUpdatedCssValue = () => { currentApp.controller.UpdateStyleValueJson(this.currentPropertyBar.viewModel.selectedStyleValueId, this.currentPropertyBar.viewModel.tempCssValue).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.viewModel.lastUsedTempCssValue = this.currentPropertyBar.viewModel.tempCssValue; this.currentPropertyBar.resetTempCssPropertyState(); }; public cancelUpdateCssValueClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.resetTempCssPropertyState(); }; public cssValueInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempCssValue = (evt.target as HTMLInputElement).value; }; public cssValueForInteractionInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempCssValueForInteraction = (evt.target as HTMLInputElement).value; }; public renderSelectInteractionTargetPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.SelectInteractionTarget; let renderedOptions: VNode[] = []; if (isPopupVisible === true) { currentApp.clientData.CaliforniaProject.LayoutMolecules.map(m => { let layoutBaseIdString: string = m.LayoutBaseId.toString(); renderedOptions.push(<div key={layoutBaseIdString} styles={{ "flex": "0 0 100%", "width": "100%", "min-width": "100%" }}> layout #{layoutBaseIdString} <button key="a" role="button" bid={layoutBaseIdString} onclick={this.currentPropertyBar.selectLayoutBaseForInteractionTargetClickHandler}>&#10004;</button> </div> as VNode); }); } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.SelectInteractionTarget]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div key="0" styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelSelectInteractionTargetClickHandler}>x</button> </div> <div key="1" styles={{ "display": "flex", "flex-flow": "row wrap" }}> {renderedOptions} </div> </div> as VNode; }; public renderEditUserDefinedCssPopup = (): VNode => { // TODO prevent closing popup before user discarded/confirmed changes let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.EditUserDefinedCss; return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.EditUserDefinedCss]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index": "31", "background-color": "white", "border": "solid black 1px" }}> <div key="0" styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.confirmEditUserDefinedCssClickHandler}>&#10004;</button> <button key="b" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelEditUserDefinedCssClickHandler}>x</button> </div> <div key="1"> <textarea value={this.currentPropertyBar.viewModel.tempUserDefinedCss} oninput={this.currentPropertyBar.userDefinedCssInputHandler}> </textarea> </div> </div> as VNode; }; private userDefinedCssInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempUserDefinedCss = (evt.target as HTMLTextAreaElement).value; }; public updateUserDefinedCss = () => { if (this.currentPropertyBar.viewModel.tempUserDefinedCss !== undefined) { currentApp.controller.UpdateUserDefinedCssForViewJson(currentApp.state.preselectedCaliforniaViewId, this.currentPropertyBar.viewModel.tempUserDefinedCss).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.cancelEditUserDefinedCss(); } }; public cancelEditUserDefinedCssClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.cancelEditUserDefinedCss(); }; public confirmEditUserDefinedCssClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.updateUserDefinedCss(); }; public cancelEditUserDefinedCss = () => { this.currentPropertyBar.viewModel.tempUserDefinedCss = ""; currentApp.state.preselectedCaliforniaViewId = 0; this.currentPropertyBar.closePopup(); }; public selectLayoutBaseForInteractionTargetClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.viewModel.selectedLayoutBaseIdForFilter = parseIntFromAttribute(evt.target, "bid"); this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.SelectInteractionTargetLayoutFilter); }; public cancelSelectInteractionTargetClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); this.currentPropertyBar.viewModel.selectedLayoutBaseIdForFilter = 0; this.currentPropertyBar.viewModel.selectedLayoutStyleInteraction = 0; }; public renderSelectInteractionTargetLayoutFilterPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.SelectInteractionTargetLayoutFilter; let renderedOptions: VNode[] = []; if (isPopupVisible === true) { currentApp.clientData.CaliforniaProject.StyleValues.map(v => { let styleAtom: StyleAtom = currentApp.clientData.CaliforniaProject.StyleAtoms.find(a => a.AppliedValues.findIndex(map => map.StyleValueId == v.StyleValueId) != -1) as StyleAtom; // TODO expensive let styleMolecule: StyleMolecule = currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.MappedStyleAtoms.findIndex(map => map.StyleMoleculeAtomMappingId == styleAtom.MappedToMoleculeId) != -1) as StyleMolecule; // TODO expensive if (styleMolecule.StyleForLayoutId == this.currentPropertyBar.viewModel.selectedLayoutBaseIdForFilter) { let styleValueIdString: string = v.StyleValueId.toString(); renderedOptions.push(<div key={styleValueIdString} styles={{ "flex": "0 0 100%", "width": "100%", "min-width": "100%" }}> value #{styleValueIdString}: {v.CssProperty}:{v.CssValue} <button key="a" role="button" vid={styleValueIdString} onclick={this.currentPropertyBar.selectStyleValueForInteractionTargetClickHandler}>&#10004;</button> </div> as VNode); } }); } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.SelectInteractionTargetLayoutFilter]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div key="0" styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelSelectStyleValueForInteractionTargetClickHandler}>x</button> </div> <div key="1" styles={{ "display": "flex", "flex-flow": "row wrap" }}> {renderedOptions} </div> </div> as VNode; }; public selectStyleValueForInteractionTargetClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); currentApp.controller.CreateStyleValueInteractionJson(this.currentPropertyBar.viewModel.selectedLayoutStyleInteraction, parseIntFromAttribute(evt.target, "vid"), this.currentPropertyBar.viewModel.tempCssValueForInteraction).done(data => currentApp.router.updateData(data)); }; public cancelSelectStyleValueForInteractionTargetClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); this.currentPropertyBar.viewModel.selectedLayoutBaseIdForFilter = 0; this.currentPropertyBar.viewModel.selectedLayoutStyleInteraction = 0; }; public renderMatchingQuantumsPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.MatchingQuantums; let renderedOptions: VNode[] = []; if (isPopupVisible === true) { currentApp.clientData.CaliforniaProject.StyleQuantums.map(quantum => { let isMatchingProperty: boolean = quantum.CssProperty === this.currentPropertyBar.viewModel.tempCssPropertyName; if (isMatchingProperty === true) { renderedOptions.push(<div key={quantum.StyleQuantumId}> {quantum.Name} = {quantum.CssValue} <button key="a" role="button" qid={quantum.StyleQuantumId.toString()} onclick={this.currentPropertyBar.setQuantumOnAtomClickHandler}>&#10004;</button> </div> as VNode); } }); if (renderedOptions.length == 0) { renderedOptions.push(<div key="0">No quantums available.</div> as VNode); } } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.MatchingQuantums]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelSelectMatchingCssQuantumClickHandler}>x</button> </div> {renderedOptions} </div> as VNode; }; public cancelSelectMatchingCssQuantumClickHandler = (evt: MouseEvent) => { this.viewModel.currentPopupMode = PopupMode.UpdateCssValue; }; public renderSuggestedCssValuesPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.SuggestedCssValues; let renderedOptions: VNode[] = []; if (isPopupVisible === true) { if (this.currentPropertyBar.viewModel.tempCssPropertyName === "font-family") { currentApp.clientData.ThirdPartyFonts.map((family: string, index: number) => { renderedOptions.push(<div key={index}> Google Font: {family} <button key="a" role="button" fid={family} onclick={this.currentPropertyBar.saveUpdatedCssValueFromAttrClickHandler}>&#10004;</button> </div> as VNode); }); } if (renderedOptions.length == 0) { renderedOptions.push(<div key="0">No suggestions available.</div> as VNode); // TODO disable popup button when no suggestions available for property } } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.SuggestedCssValues]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index": "31", "background-color": "white", "border": "solid black 1px", "height": "300px", "overflow": "scroll" }}> <div styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="a" role="button" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelSuggestedCssValuesClickHandler}>x</button> </div> {renderedOptions} </div> as VNode; }; public cancelSuggestedCssValuesClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public setQuantumOnAtomClickHandler = (evt: MouseEvent) => { let quantumId: number = parseIntFromAttribute(evt.target, "qid"); currentApp.controller.ApplyStyleQuantumToAtomJson(this.currentPropertyBar.viewModel.selectedStyleAtomId, quantumId).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.resetTempCssPropertyState(); this.currentPropertyBar.viewModel.lastUsedTempCssValue = (currentApp.clientData.CaliforniaProject.StyleQuantums.find(q => q.StyleQuantumId == quantumId) as StyleQuantum).CssValue; // TODO expensive }; public renderStyleMoleculeArray = (propertyBar: PropertyBar): maquette.Mapping<StyleMolecule, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<StyleMolecule, any>( function getSectionSourceKey(source: StyleMolecule) { return source.StyleMoleculeId; }, function createSectionTarget(source: StyleMolecule) { let sourceStyleMoleculeIdString = source.StyleMoleculeId.toString(); return { renderMaquette: function () { return <div key={sourceStyleMoleculeIdString} exitAnimation={propertyBar.styleElementExitAnimation}> <p>(#{sourceStyleMoleculeIdString}){source.Name}</p> <button key="a" role="button" mid={sourceStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>Edit</button> </div>; }, update: function (updatedSource: StyleMolecule) { sourceStyleMoleculeIdString = updatedSource.StyleMoleculeId.toString(); source = updatedSource; } }; }, function updateSectionTarget(updatedSource: StyleMolecule, target: { renderMaquette(): any, update(updatedSource: StyleMolecule): void }) { target.update(updatedSource); }); }; public selectStyleMoleculeClickHandler = (evt: MouseEvent) => { this.nextExceptLastPropertyBar.viewModel.selectedStyleMoleculeId = parseIntFromAttribute(evt.target, "mid"); this.nextExceptLastPropertyBar.viewModel.selectedStateModifier = ""; // TODO reset state only when not available in new selected molecule this.nextExceptLastPropertyBar.viewModel.currentPropertyBarMode = PropertyBarMode.StyleMolecule; }; public showEditUserDefinedCssClickHandler = (evt: MouseEvent) => { let californiaViewId: number = parseIntFromAttribute(evt.target, "vid"); let californiaViewCss: string | undefined = (currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == californiaViewId) as CaliforniaView).UserDefinedCss; this.currentPropertyBar.viewModel.tempUserDefinedCss = californiaViewCss !== undefined ? californiaViewCss : ""; currentApp.state.preselectedCaliforniaViewId = californiaViewId; this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.EditUserDefinedCss); }; public highlightLayoutBaseClickHandler = (evt: MouseEvent) => { let targetLayoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.highlightedLayoutBaseId != targetLayoutBaseId) { currentApp.state.highlightedLayoutBaseId = targetLayoutBaseId; } else { currentApp.state.highlightedLayoutBaseId = 0; } }; public renderStyleQuantumArray = (propertyBar: PropertyBar): maquette.Mapping<StyleQuantum, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<StyleQuantum, any>( function getSectionSourceKey(source: StyleQuantum) { return source.StyleQuantumId; }, function createSectionTarget(source: StyleQuantum) { let sourceIdString = source.StyleQuantumId.toString(); return { renderMaquette: function () { return <div key={sourceIdString} exitAnimation={propertyBar.styleElementExitAnimation}> <p key="0" styles={{"margin":"0"}}>(#{sourceIdString}){source.Name}: {source.CssProperty} => {source.CssValue}</p> <button key="a" role="button" qid={sourceIdString} onclick={propertyBar.duplicateStyleQuantumClickHandler}>DD</button> {source.IsDeletable ? <button key="b0" role="button" qid={sourceIdString} onclick={propertyBar.deleteStyleQuantumClickHandler}>X</button> : <button disabled key="b1" role="button">X</button>} <button key="c" role="button" qid={sourceIdString} onclick={propertyBar.updateCssQuantumClickHandler}>Edit</button> </div>; }, update: function (updatedSource: StyleQuantum) { sourceIdString = updatedSource.StyleQuantumId.toString(); source = updatedSource; } }; }, function updateSectionTarget(updatedSource: StyleQuantum, target: { renderMaquette(): any, update(updatedSource: StyleQuantum): void }) { target.update(updatedSource); }); }; public updateCssQuantumClickHandler = (evt: MouseEvent) => { let styleQuantumId: number = parseIntFromAttribute(evt.target, "qid"); this.currentPropertyBar.viewModel.selectedStyleQuantumId = styleQuantumId; let targetStyleQuantum: StyleQuantum = currentApp.clientData.CaliforniaProject.StyleQuantums.find(val => val.StyleQuantumId == styleQuantumId) as StyleQuantum; this.currentPropertyBar.viewModel.tempCssValue = targetStyleQuantum.CssValue; this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.UpdateCssQuantum); }; public deleteStyleQuantumClickHandler = (evt: MouseEvent): void => { currentApp.controller.DeleteStyleQuantumJson(parseIntFromAttribute(evt.target, "qid")).done(data => currentApp.router.updateData(data)); }; public duplicateStyleQuantumClickHandler = (evt: MouseEvent): void => { currentApp.controller.DuplicateStyleQuantumJson(parseIntFromAttribute(evt.target, "qid")).done(data => currentApp.router.updateData(data)); }; public styleElementExitAnimation = (domNode: HTMLElement, removeElement: () => void, properties?: maquette.VNodeProperties) => { domNode.style.overflow = "hidden"; velocity.animate(domNode, { opacity: 0.5, height: 0 }, { duration: 100, easing: "ease-out", complete: removeElement }); }; public renderLayoutMoleculeArray = (propertyBar: PropertyBar): maquette.Mapping<LayoutBase, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<LayoutBase, any>( function getSectionSourceKey(source: LayoutBase) { // function that returns a key to uniquely identify each item in the data return source.LayoutBaseId; }, function createSectionTarget(source: LayoutBase) { // function to create the target based on the source // (the same function that you use in Array.map) let sourceLayoutBaseIdString = source.LayoutBaseId.toString(); let sourceStyleMoleculeIdString = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId.toString(); // TODO expensive let layoutControlButtonStyles = { "margin-right": "5px" }; return { renderMaquette: function () { let description: string | undefined = ""; if (source.LayoutType === LayoutType.Atom) { let sourceLayoutAtom: LayoutAtom = (source as LayoutAtom); let textContentString: string = ""; if (sourceLayoutAtom.HostedContentAtom.ContentAtomType === ContentAtomType.Text) { textContentString = sourceLayoutAtom.HostedContentAtom.TextContent as string; } else if (sourceLayoutAtom.HostedContentAtom.ContentAtomType === ContentAtomType.Link) { textContentString = sourceLayoutAtom.HostedContentAtom.Url as string; } else { console.log(DEFAULT_EXCEPTION); } description = textContentString.length > 20 ? textContentString.substring(0, 20) + "..." : textContentString; // TODO expensive // TODO ellipsis // TODO multiple places // TODO create when storing in DB? or when loading in client description += ` in box #${(source as LayoutAtom).PlacedAtomInBoxId}` } // TODO hide layout molecules, where style molecule is internal style return <div key={sourceLayoutBaseIdString}> {LayoutType[source.LayoutType].toString()} #{sourceLayoutBaseIdString} {description} <button key="a" role="button" lid={sourceLayoutBaseIdString} onclick={propertyBar.selectLayoutBaseClickHandler} styles={layoutControlButtonStyles}>?</button> <button key="b" role="button" mid={sourceStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler} styles={layoutControlButtonStyles}>S</button> <button key="c" role="button" lid={sourceLayoutBaseIdString} onclick={propertyBar.deleteLayoutBaseClickHandler} styles={layoutControlButtonStyles}>X</button> </div>; }, update: function (updatedSource: LayoutBase) { source = updatedSource; sourceLayoutBaseIdString = source.LayoutBaseId.toString(); let sourceStyleMoleculeIdString = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == source.LayoutBaseId) as StyleMolecule).StyleMoleculeId.toString(); // TODO expensive } }; }, function updateSectionTarget(updatedSource: LayoutBase, target: { renderMaquette(): any, update(updatedSource: LayoutBase): void }) { // This function can be used to update the component with the updated item target.update(updatedSource); }); }; public renderCaliforniaViewArray = (propertyBar: PropertyBar): maquette.Mapping<CaliforniaView, { renderMaquette: () => maquette.VNode }> => { return maquette.createMapping<CaliforniaView, any>( function getSectionSourceKey(source: CaliforniaView) { // function that returns a key to uniquely identify each item in the data return source.CaliforniaViewId; }, function createSectionTarget(source: CaliforniaView) { // function to create the target based on the source // (the same function that you use in Array.map) let sourceCaliforniaViewIdString = source.CaliforniaViewId.toString(); return { renderMaquette: function () { let isDeleteButtonEnabled: boolean = source.PlacedLayoutRows.length == 0; return <div key={sourceCaliforniaViewIdString}>{source.Name} View #{sourceCaliforniaViewIdString} <button key="a" role="button" vid={sourceCaliforniaViewIdString} onclick={propertyBar.selectCaliforniaViewClickHandler}>:)</button> {(!source.IsInternal && source.CaliforniaViewId != currentApp.pagePreview.viewModel.activeCaliforniaViewId) ? <button key="b" role="button" vid={sourceCaliforniaViewIdString} onclick={propertyBar.activateCaliforniaViewClickHandler}>&#10004;</button> : undefined} : {source.IsInternal ? "internal" : undefined} {source.Name} hosted by {source.HostedByLayoutMappings.length} layouts <button key="c" role="button" mid={source.SpecialStyleViewStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>style #{source.SpecialStyleViewStyleMoleculeIdString}</button> <button key="d" role="button" mid={source.SpecialStyleBodyStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>body style #{source.SpecialStyleBodyStyleMoleculeIdString}</button> <button key="e" role="button" mid={source.SpecialStyleHtmlStyleMoleculeIdString} onclick={propertyBar.selectStyleMoleculeClickHandler}>HTML style #{source.SpecialStyleHtmlStyleMoleculeIdString}</button> <button key="f" role="button" vid={sourceCaliforniaViewIdString} onclick={propertyBar.showEditUserDefinedCssClickHandler}>CSS</button> {isDeleteButtonEnabled ? <button key="g" role="button" vid={sourceCaliforniaViewIdString} onclick={propertyBar.deleteCaliforniaViewClickHandler}>X</button> : <button disabled key="g0" role="button" onclick={propertyBar.deleteCaliforniaViewClickHandler}>X</button>} </div>; }, update: function (updatedSource: CaliforniaView) { source = updatedSource; sourceCaliforniaViewIdString = source.CaliforniaViewId.toString(); } }; }, function updateSectionTarget(updatedSource: CaliforniaView, target: { renderMaquette(): any, update(updatedSource: CaliforniaView): void }) { // This function can be used to update the component with the updated item target.update(updatedSource); }); }; public logoutPopupClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.ShareCaliforniaProject); }; public renderShareCaliforniaProjectPopup = (): VNode => { // TODO multilanguage where text strings are everywhere let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.ShareCaliforniaProject; // TODO shorten ids everywhere return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.ShareCaliforniaProject]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index" : "31", "background-color": "white", "border": "solid black 1px" }}> <div key="0" styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="b" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelShareCaliforniaProjectClickHandler}>x</button> </div> <div key="1" styles={{ "display": "flex", "flex-flow": "row wrap" }}> <p key="a" styles={{ "flex": "0 0 100%", "width": "100%", "min-width": "100%" }}>{currentApp.clientData.UrlToReadOnly}</p> {/* TODO <p key="b">{currentApp.clientData.UrlToReadAndEdit}</p>*/} Bookmark! Clear browser history! <button key="c" type="button" onclick={this.currentPropertyBar.logoutClickHandler} styles={{ "flex": "0 0 10%", "width": "10%", "min-width": "10%" }}>&#128274;</button> <button key="d" type="button" onclick={this.currentPropertyBar.tokyoClickHandler} styles={{ "flex": "0 0 10%", "width": "10%", "min-width": "10%" }}>TOKYO</button> </div> </div> as VNode; }; public tokyoClickHandler = (evt: MouseEvent) => { window.location.assign(window.location.origin + "/tokyo/"); // TODO hardcoded link }; public cancelShareCaliforniaProjectClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public logoutClickHandler = (evt: MouseEvent) => { currentApp.controller.LogoutAction().done((response: any) => { window.location.assign(window.location.origin + "/california/"); // TODO hardcoded link }); }; public activateCaliforniaViewClickHandler = (evt: MouseEvent) => { let californiaViewId: number = parseIntFromAttribute(evt.target, "vid"); let userPages: CaliforniaView[] = currentApp.clientData.CaliforniaProject.CaliforniaViews.filter(view => !view.IsInternal); let activeView: CaliforniaView | undefined = undefined; let activePageIndex: number = userPages.findIndex(v => v.CaliforniaViewId == californiaViewId); if (activePageIndex > -1) { activeView = userPages[activePageIndex]; currentApp.router.setActiveCaliforniaView(activeView); currentApp.pagePreview.resetEquationNumbersWhenModifying(true); // TODO test this.currentPropertyBar.viewModel.setSelectedCaliforniaView(activeView, true); this.viewModel.currentPropertyBarMode = PropertyBarMode.CaliforniaView; // TODO everywhere: this.vieModel or this.currentPropertyBar.viewModel } else { console.log(DEFAULT_EXCEPTION); } }; public selectLayoutBaseClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); // TODO everywhere: use backend value instead of parsing where possible => saves multiple strings currentApp.state.selectedLayoutBaseId = layoutBaseId; this.currentPropertyBar.viewModel.currentPropertyBarMode = PropertyBarMode.LayoutBase; }; public selectCaliforniaViewClickHandler = (evt: MouseEvent) => { let californiaViewId: number = parseIntFromAttribute(evt.target, "vid"); let userPages: CaliforniaView[] = currentApp.clientData.CaliforniaProject.CaliforniaViews.filter(view => !view.IsInternal); let activeView: CaliforniaView | undefined = undefined; let activePageIndex: number = userPages.findIndex(v => v.CaliforniaViewId == californiaViewId); if (activePageIndex > -1) { activeView = userPages[activePageIndex]; if (this.currentPropertyBar.propertyBarIndex == 0) { currentApp.router.setActiveCaliforniaView(activeView); currentApp.pagePreview.resetEquationNumbersWhenModifying(true); // TODO test } else { this.currentPropertyBar.viewModel.isSyncedWithBoxTreeToTheLeft = false; } this.currentPropertyBar.viewModel.setSelectedCaliforniaView(activeView, true); } else { console.log(DEFAULT_EXCEPTION); } this.currentPropertyBar.viewModel.currentPropertyBarMode = PropertyBarMode.CaliforniaView; }; public deleteLayoutBaseClickHandler = (evt: MouseEvent) => { if (currentApp.state.preselectedLayoutBaseId != 0) { // TODO document // TODO disable button return; } currentApp.state.selectedLayoutBaseId = 0; currentApp.controller.DeleteLayoutJson(parseIntFromAttribute(evt.target, "lid"), false).done(data => currentApp.router.updateData(data)); }; public deleteBelowLayoutBaseClickHandler = (evt: MouseEvent) => { if (currentApp.state.preselectedLayoutBaseId != 0) { // TODO document // TODO disable button return; } currentApp.state.selectedLayoutBaseId = 0; currentApp.controller.DeleteLayoutJson(parseIntFromAttribute(evt.target, "lid"), true).done(data => currentApp.router.updateData(data)); }; public renderLayoutBaseControls = (): VNode | undefined => { if (currentApp.state.selectedLayoutBaseId == 0) { return undefined; } let selectedLayoutBase: LayoutBase = currentApp.clientData.CaliforniaProject.LayoutMolecules.find(l => l.LayoutBaseId == currentApp.state.selectedLayoutBaseId) as LayoutBase; let layoutBaseIdString: string = selectedLayoutBase.LayoutBaseId.toString(); let sourceStyleMoleculeIdString: string = (currentApp.clientData.CaliforniaProject.StyleMolecules.find(m => m.StyleForLayoutId == selectedLayoutBase.LayoutBaseId) as StyleMolecule).StyleMoleculeId.toString(); // TODO expensive if (selectedLayoutBase.LayoutType === LayoutType.Atom) { let selectedLayoutAtom: LayoutAtom = selectedLayoutBase as LayoutAtom; let isPictureContent: boolean = selectedLayoutAtom.HostedContentAtom.ContentAtomType === ContentAtomType.Picture; let pictureContentIdString: string | undefined = isPictureContent ? selectedLayoutAtom.HostedContentAtom.PictureContent.PictureContentId.toString() : undefined; return <div key={LayoutType.Atom}> Atom: <button key="a" role="button" mid={sourceStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>style #{sourceStyleMoleculeIdString}</button> <button key="b" role="button" lid={layoutBaseIdString} onclick={this.currentPropertyBar.deleteLayoutBaseClickHandler}>X</button> <button key="c" role="button" aid={layoutBaseIdString} onclick={this.currentPropertyBar.createLayoutStyleInteraction}>+ Interaction</button> {selectedLayoutAtom.LayoutStyleInteractions.map(interaction => { let interactionIdString: string = interaction.LayoutStyleInteractionId.toString(); return <div key={`i${interactionIdString}`}> <p key="0">Interaction #{interaction.LayoutStyleInteractionId}</p> <input key="1" value={this.currentPropertyBar.viewModel.tempCssValueForInteraction} oninput={this.currentPropertyBar.cssValueForInteractionInputHandler}> </input> {this.currentPropertyBar.viewModel.tempCssValueForInteraction !== "" ? <button key="a" role="button" lid={interactionIdString} onclick={this.currentPropertyBar.selectInteractionTargetClickHandler}>?</button> : <button disabled key="a0" role="button" lid={interactionIdString} onclick={this.currentPropertyBar.selectInteractionTargetClickHandler}>?</button>} <button key="b" role="button" lid={interactionIdString} onclick={this.currentPropertyBar.deleteLayoutStyleInteractionClickHandler}>X</button> {interaction.StyleValueInteractions.map(map => { let mappingIdString: string = map.StyleValueInteractionMappingId.toString(); return <div key={mappingIdString}> <p key="0">#{mappingIdString}: {map.CssValue}</p> <button key="a" role="button" vid={map.StyleValueId.toString()} lid={interactionIdString} onclick={this.currentPropertyBar.deleteStyleValueInteractionClickHandler}>X</button> </div> })} </div> })} <form key="0" action="UploadFiles" method="post" enctype="multipart/form-data"> <p key="0">picture id #{pictureContentIdString}</p> <input multiple key="1" type="file" name="formFiles" onchange={this.currentPropertyBar.uploadFileChangeHandler}></input> <button key="a" role="button" pid={pictureContentIdString} onclick={this.currentPropertyBar.uploadFileClickHandler}>...</button> </form> </div> as VNode; } else if (selectedLayoutBase.LayoutType === LayoutType.Box) { let selectedLayoutBox: LayoutBox = selectedLayoutBase as LayoutBox; let specialLayoutBoxTypeSelectors: VNode[] = []; getArrayForEnum(SpecialLayoutBoxType).map((type: string, index: number) => { let isLayoutBoxType: boolean = index == selectedLayoutBox.SpecialLayoutBoxType; let layoutBoxTypeString: string = index.toString(); specialLayoutBoxTypeSelectors.push(isLayoutBoxType ? <option selected key={layoutBoxTypeString} value={layoutBoxTypeString}>{type}</option> as VNode : <option key={layoutBoxTypeString} value={layoutBoxTypeString}>{type}</option> as VNode); }); return <div key={LayoutType.Box}> Box: <button key="a" role="button" mid={sourceStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>style #{sourceStyleMoleculeIdString}</button> <button disabled key="b" role="button" onclick={this.currentPropertyBar.createViewForBoxClickHandler}>Create View</button> <button key="c" role="button" lid={layoutBaseIdString} onclick={this.currentPropertyBar.deleteLayoutBaseClickHandler}>X</button> <select key="0" bid={layoutBaseIdString} onchange={this.currentPropertyBar.specialLayoutBoxTypeChangedHandler}> {specialLayoutBoxTypeSelectors} </select> </div> as VNode; } else if (selectedLayoutBase.LayoutType === LayoutType.Row) { let selectedLayoutRow: LayoutRow = selectedLayoutBase as LayoutRow; let currentBoxCount: number = selectedLayoutRow.AllBoxesBelowRow.filter(b => b.PlacedBoxInBoxId === undefined).length; let boxCountSelectors: VNode[] = []; for (let i = 0; i <= 12; i++) { let isSelected: boolean = i == currentBoxCount; let boxCountString: string = i.toString(); if (i == 0) { boxCountSelectors.push(isSelected ? <option disabled selected key={boxCountString} value={boxCountString}>{boxCountString}</option> as VNode : <option disabled key={boxCountString} value={boxCountString}>{boxCountString}</option> as VNode); } else { boxCountSelectors.push(isSelected ? <option selected key={boxCountString} value={boxCountString}>{boxCountString}</option> as VNode : <option key={boxCountString} value={boxCountString}>{boxCountString}</option> as VNode); } } return <div key={LayoutType.Row}> Row: <button key="a" role="button" mid={sourceStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>style #{sourceStyleMoleculeIdString}</button> <button key="b" role="button" lid={layoutBaseIdString} onclick={this.currentPropertyBar.deleteLayoutBaseClickHandler}>X</button> <select key="c" rid={layoutBaseIdString} onchange={this.currentPropertyBar.boxCountInRowChangedHandler}> {boxCountSelectors} </select> </div> as VNode; } console.log(DEFAULT_EXCEPTION); return undefined; }; public uploadFileChangeHandler = (evt: Event): void => { let fileSelector: HTMLInputElement = evt.target as HTMLInputElement; if (fileSelector.files !== null) { let fileArray: File[] = []; for (let index in fileSelector.files) { let file: File = fileSelector.files[index]; fileArray.push(file); console.log(file); let fileReader: FileReader = new FileReader(); fileReader.addEventListener("loadend", this.currentPropertyBar.fileProcessingLoadEndHandler); //fileReader.readAsText(new Blob([file]), undefined); } if (fileSelector.files.length == 0) { console.log("empty"); } //currentApp.controller.UploadFilesAction(fileArray); } else { console.log("undefined"); } }; public fileProcessingLoadEndHandler = (evt: ProgressEvent): void => { console.log(evt.total); console.log((evt.target as FileReader).result); }; public uploadFileClickHandler = (evt: MouseEvent): void => { evt.preventDefault(); let targetForm: HTMLFormElement = (evt.target as HTMLButtonElement).form as HTMLFormElement; console.log("upload dialog TODO"); jQuery.ajax(targetForm.action, { method: targetForm.method, contentType: "multipart/form-data", data: $(targetForm).serialize() } as JQueryAjaxSettings); }; public selectInteractionTargetClickHandler = (evt: MouseEvent): void => { this.currentPropertyBar.viewModel.selectedLayoutStyleInteraction = parseIntFromAttribute(evt.target, "lid"); // TODO hack this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.SelectInteractionTarget); }; public deleteStyleValueInteractionClickHandler = (evt: MouseEvent): void => { currentApp.controller.DeleteStyleValueInteractionJson(parseIntFromAttribute(evt.target, "lid"), parseIntFromAttribute(evt.target, "vid")).done(data => currentApp.router.updateData(data)); }; public deleteLayoutStyleInteractionClickHandler = (evt: MouseEvent): void => { currentApp.controller.DeleteLayoutStyleInteractionJson(parseIntFromAttribute(evt.target, "lid")).done(data => currentApp.router.updateData(data)); }; public createLayoutStyleInteraction = (evt: MouseEvent): void => { currentApp.controller.CreateLayoutStyleInteractionForLayoutAtomJson(parseIntFromAttribute(evt.target, "aid")).done(data => currentApp.router.updateData(data)); }; public specialLayoutBoxTypeChangedHandler = (evt: UIEvent) => { let targetSelect = evt.target as HTMLSelectElement; let selectedSpecialLayoutBoxType: number | undefined = undefined; if (targetSelect.selectedIndex < targetSelect.childElementCount) { let selectOptionElement: HTMLOptionElement = targetSelect.options[targetSelect.selectedIndex]; selectedSpecialLayoutBoxType = parseInt(selectOptionElement.value); } if (selectedSpecialLayoutBoxType !== undefined) { currentApp.controller.SetSpecialLayoutBoxTypeJson(parseIntFromAttribute(targetSelect, "bid"), selectedSpecialLayoutBoxType).done(data => currentApp.router.updateData(data)); } else { console.log(DEFAULT_EXCEPTION); } }; public boxCountInRowChangedHandler = (evt: UIEvent) => { let targetSelect = evt.target as HTMLSelectElement; let parsedBoxCount: number | undefined = undefined; if (targetSelect.selectedIndex < targetSelect.childElementCount) { let selectOptionElement: HTMLOptionElement = targetSelect.options[targetSelect.selectedIndex]; parsedBoxCount = parseInt(selectOptionElement.value); } if (parsedBoxCount !== undefined) { currentApp.controller.SetLayoutBoxCountForRowOrBoxJson(parseIntFromAttribute(targetSelect, "rid"), currentApp.state.newBoxStyleMoleculeId, parsedBoxCount, false).done(data => currentApp.router.updateData(data)); } else { console.log(DEFAULT_EXCEPTION); } }; public finalizeLayoutRequest = (evt: MouseEvent) => { // TODO differentiate mode currentApp.state.selectedLayoutBaseId = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.currentTransactionMode === TransactionMode.MoveLayoutMoleculeIntoLayoutMolecule) { this.currentPropertyBar.moveLayoutMoleculeIntoLayoutMolecule(); currentApp.state.preselectedLayoutBaseId = 0; } else if (currentApp.state.currentTransactionMode === TransactionMode.MoveLayoutMoleculeBeforeLayoutMolecule) { this.currentPropertyBar.moveLayoutMoleculeBeforeLayoutMolecule(); currentApp.state.preselectedLayoutBaseId = 0; } else if (currentApp.state.currentTransactionMode === TransactionMode.SyncLayoutStylesImitating) { this.currentPropertyBar.syncLayoutMoleculeStylesImitatingReferenceLayout(); // TODO document or rework sticky preselection } else { currentApp.state.preselectedLayoutBaseId = 0; console.log(DEFAULT_EXCEPTION); return; } }; public moveLayoutBoxIntoRowClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeIntoLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeIntoLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public moveLayoutBoxIntoBoxClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeIntoLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeIntoLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public moveLayoutBoxBeforeBoxClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeBeforeLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeBeforeLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public moveLayoutRowBeforeRowClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeBeforeLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeBeforeLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public syncLayoutBaseStylesClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.SyncLayoutStylesImitating; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.UNDEFINED); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public moveLayoutAtomIntoBoxClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeIntoLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeIntoLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public createBoxForAtomInPlaceClickHandler = (evt: MouseEvent) => { currentApp.state.selectedLayoutBaseId = parseIntFromAttribute(evt.target, "lid"); // TODO document: foreign popup is used, controller request differentiation by state this.viewModel.currentSecondaryPopupMode = PopupSecondaryMode.SelectBoxIntoBoxAtomInPlace; this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.SelectBox); }; public moveLayoutAtomBeforeAtomClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeBeforeLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeBeforeLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public moveLayoutAtomBeforeBoxClickHandler = (evt: MouseEvent) => { let layoutBaseId: number = parseIntFromAttribute(evt.target, "lid"); if (currentApp.state.preselectedLayoutBaseId != layoutBaseId) { currentApp.state.preselectedLayoutBaseId = layoutBaseId; currentApp.state.currentTransactionMode = TransactionMode.MoveLayoutMoleculeBeforeLayoutMolecule; //this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.MoveLayoutMoleculeBeforeLayoutMolecule); } else { currentApp.state.preselectedLayoutBaseId = 0; } }; public saveLayoutMoleculeClickHandler = (evt: MouseEvent) => { currentApp.controller.SetLayoutRowOrBoxAsInstanceableJson(currentApp.clientData.CaliforniaProject.CaliforniaProjectId, parseIntFromAttribute(evt.target, "lid")).done(data => currentApp.router.updateData(data)); }; public createViewForBoxClickHandler = (evt: MouseEvent) => { console.log("TODO"); }; public insertLayoutAtomIntoBoxClickHandler = (evt: MouseEvent) => { currentApp.state.selectedLayoutBaseId = parseIntFromAttribute(evt.target, "lid"); this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.InsertLayoutAtomIntoBox); }; public insertLayoutBoxIntoBoxClickHandler = (evt: MouseEvent) => { currentApp.state.selectedLayoutBaseId = parseIntFromAttribute(evt.target, "lid"); this.viewModel.currentSecondaryPopupMode = PopupSecondaryMode.SelectBoxIntoBox; this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.SelectBox); }; public renderCaliforniaViewControlsWhenAll = (): VNode => { let isAddButtonEnabled: boolean = this.currentPropertyBar.viewModel.tempCaliforniaViewName !== ""; return <div key="-1"> <input key="0" value={this.currentPropertyBar.viewModel.tempCaliforniaViewName} oninput={this.currentPropertyBar.californiaViewNameInputHandler}> </input> {isAddButtonEnabled ? <button key="a" role="button" onclick={this.currentPropertyBar.createCaliforniaViewClickHandler}>&#10004;</button> : <button disabled key="a0" role="button" onclick={this.currentPropertyBar.createCaliforniaViewClickHandler}>&#10004;</button>} {isAddButtonEnabled ? <button key="b" role="button" onclick={this.currentPropertyBar.createCaliforniaViewFromReferenceClickHandler}>x2</button> : <button disabled key="b0" role="button" onclick={this.currentPropertyBar.createCaliforniaViewFromReferenceClickHandler}>x2</button>} </div> as VNode; }; public createCaliforniaViewFromReferenceClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.CaliforniaViewSelection); }; public createCaliforniaViewClickHandler = (evt: MouseEvent) => { currentApp.controller.CreateCaliforniaViewJson(currentApp.clientData.CaliforniaProject.CaliforniaProjectId, this.currentPropertyBar.viewModel.tempCaliforniaViewName).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.viewModel.tempCaliforniaViewName = ""; }; public californiaViewNameInputHandler = (evt: KeyboardEvent) => { this.currentPropertyBar.viewModel.tempCaliforniaViewName = (evt.target as HTMLInputElement).value; }; public renderCaliforniaViewSelectionPopup = (): VNode => { let isPopupVisible: boolean = this.viewModel.currentPopupMode === PopupMode.CaliforniaViewSelection; // TODO shorten ids everywhere let renderedOptions: VNode[] = []; if (isPopupVisible === true) { currentApp.clientData.CaliforniaProject.CaliforniaViews.filter(m => !m.IsInternal).map(m => { let californiaViewIdString: string = m.CaliforniaViewId.toString(); renderedOptions.push(<div key={californiaViewIdString} styles={{ "flex": "0 0 100%", "width": "100%", "min-width": "100%" }}> view #{californiaViewIdString}: {m.Name} <button key="a" role="button" vid={californiaViewIdString} onclick={this.currentPropertyBar.selectCaliforniaViewInPopupClickHandler}>&#10004;</button> </div> as VNode); }); } return <div id={`${this.currentPropertyBar.propertyBarIndex}PopupMode${PopupMode[PopupMode.CaliforniaViewSelection]}`} styles={{ "display": isPopupVisible ? "block" : "none", "z-index": "31", "background-color": "white", "border": "solid black 1px" }}> <div key="0" styles={{ "display": "flex", "flex-flow": "row nowrap", "min-width": "250px" }}> <button key="b" styles={{ "flex": "1 0 10%", "width": "10%", "min-width": "10%" }} onclick={this.currentPropertyBar.cancelSelectCaliforniaViewPopupClickHandler}>x</button> </div> <div key="1" styles={{ "display": "flex", "flex-flow": "row wrap" }}> {renderedOptions} </div> </div> as VNode; }; public selectCaliforniaViewInPopupClickHandler = (evt: MouseEvent) => { currentApp.controller.CreateCaliforniaViewFromReferenceViewJson(currentApp.clientData.CaliforniaProject.CaliforniaProjectId, this.currentPropertyBar.viewModel.tempCaliforniaViewName, parseIntFromAttribute(evt.target, "vid")).done(data => currentApp.router.updateData(data)); this.currentPropertyBar.viewModel.tempCaliforniaViewName = ""; this.currentPropertyBar.closePopup(); }; public cancelSelectCaliforniaViewPopupClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.closePopup(); }; public renderCaliforniaViewControls = (): VNode | undefined => { if (this.currentPropertyBar.viewModel.selectedCaliforniaViewId == 0) { return undefined; } let selectedCaliforniaView: CaliforniaView = currentApp.clientData.CaliforniaProject.CaliforniaViews.find(v => v.CaliforniaViewId == this.currentPropertyBar.viewModel.selectedCaliforniaViewId) as CaliforniaView; // TODO potentially slow let californiaViewIdString: string = selectedCaliforniaView.CaliforniaViewId.toString(); let viewControlsButtonHolderStyles = { "flex": "0 0 auto", "height": "auto" }; let viewControlsBoxTreeHolderStyles = { /*TODO need set all div styles width/height in this box to either undefined or value // TODO do everywhere!!*/ "flex": "1 1 1px", "width": "100%", "height": "auto", "overflow": "scroll" };// TODO applied at many places: code sense for usage of boxTreeProjector should be coupled with renderBoxTree routine let isSyncWithPreviewActive: boolean = this.currentPropertyBar.propertyBarIndex == 0; let isSyncWithLeftActive: boolean = this.currentPropertyBar.propertyBarIndex != 0; let isDrawHelperLinesActive: boolean = this.currentPropertyBar.propertyBarIndex == 0; let syncWithLeftBoxTreeButtonStyles = { "outline": !isSyncWithLeftActive ? undefined : this.currentPropertyBar.viewModel.isSyncedWithBoxTreeToTheLeft ? "solid 1px rgb(200,0,0)" : "solid 1px rgb(0,242,0)", "outline-offset": !isSyncWithLeftActive ? undefined : "-1px" }; let syncWithPreviewButtonStyles = { "outline": !isSyncWithPreviewActive ? undefined : this.currentPropertyBar.viewModel.isSyncedWithPagePreview ? "solid 1px rgb(200,0,0)" : "solid 1px rgb(0,242,0)", "outline-offset": !isSyncWithPreviewActive ? undefined : "-1px" }; let drawHelperLinesButtonStyles = { "outline": !isDrawHelperLinesActive ? undefined : currentApp.state.isDrawHelperLines ? "solid 1px rgb(200,0,0)" : undefined, "outline-offset": !isDrawHelperLinesActive ? undefined : "-1px" }; return <div styles={{ "width": "100%", "height": "100%", "display": "flex", "flex-flow": "column nowrap" }}> View #{californiaViewIdString} <div key="0" styles={viewControlsButtonHolderStyles}> <button key="a" onclick={this.currentPropertyBar.insertLayoutRowIntoViewClickHandler}>+(R)</button> <button key="b" mid={selectedCaliforniaView.SpecialStyleViewStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>style #{selectedCaliforniaView.SpecialStyleViewStyleMoleculeIdString}</button> <button key="c" mid={selectedCaliforniaView.SpecialStyleBodyStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>body style #{selectedCaliforniaView.SpecialStyleBodyStyleMoleculeIdString}</button> <button key="d" mid={selectedCaliforniaView.SpecialStyleHtmlStyleMoleculeIdString} onclick={this.currentPropertyBar.selectStyleMoleculeClickHandler}>HTML style #{selectedCaliforniaView.SpecialStyleHtmlStyleMoleculeIdString}</button> <button key="e" onclick={this.currentPropertyBar.resetPreselectedLayoutClickHandler}>o</button> {isDrawHelperLinesActive ? <button key="f" onclick={this.currentPropertyBar.drawHelperLinesClickHandler} styles={drawHelperLinesButtonStyles}>\-\</button> : <button disabled key="f0" onclick={this.currentPropertyBar.drawHelperLinesClickHandler} styles={drawHelperLinesButtonStyles}>\-\</button>} {isSyncWithPreviewActive ? <button key="g" onclick={this.currentPropertyBar.syncWithPagePreviewClickHandler} styles={syncWithPreviewButtonStyles}>-=-</button> : <button disabled key="g0" onclick={this.currentPropertyBar.syncWithPagePreviewClickHandler} styles={syncWithPreviewButtonStyles}>-=-</button>} {isSyncWithLeftActive ? <button key="h" onclick={this.currentPropertyBar.syncWithLeftPropertyBarClickHandler} styles={syncWithLeftBoxTreeButtonStyles}>==</button> : <button disabled key="h0" onclick={this.currentPropertyBar.syncWithLeftPropertyBarClickHandler} styles={syncWithLeftBoxTreeButtonStyles}>==</button>} </div> <div key="1" styles={viewControlsBoxTreeHolderStyles} onscroll={this.currentPropertyBar.boxTreeScrollHandler} afterCreate={this.currentPropertyBar.boxTreeAfterCreateHandler}> {this.currentPropertyBar.viewModel.boxTreeProjector.results.map(r => r.renderMaquette())} </div> </div> as VNode; }; private boxTreeScrollHandler = (evt: UIEvent) => { // TODO instead: render in same div to synchronize scroll // TODO fix bug => bad handling when using scroll bars in edge... // TODO kaleidoscope effect selection / boxtree display range // TODO test case: show 4 box trees #1-#4, move #2, sync to left (#1 reads from #2), move #4, sync to left (#3 reads from #4), then activate sync to left in #3 => all movements should be synced // --- sync scroll with other property bars --- let currentPropertyBarIndex: number = this.currentPropertyBar.propertyBarIndex; let currentScrollDom: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[currentPropertyBarIndex] as HTMLDivElement /*TODO cast unsafe*/; if (currentApp.state.visiblePropertyBarMaxCount > 1 && currentApp.propertyBarBoxTreeScrollHandled[currentPropertyBarIndex] === false) { currentApp.propertyBarBoxTreeScrollHandled[currentPropertyBarIndex] = true; //console.log("onscroll for property bar #" + this.currentPropertyBar.propertyBarIndex + " to" + (evt.target as HTMLDivElement).scrollTop + " from max height" + (evt.target as HTMLDivElement).scrollHeight + ", diff: " + ((evt.target as HTMLDivElement).scrollHeight - (evt.target as HTMLDivElement).scrollTop).toString() + ", expected at max scroll: " + (evt.target as HTMLDivElement).clientHeight); let currentViewModel: PropertyBarVM = this.currentPropertyBar.viewModel; if (currentScrollDom === undefined) { console.log(DEFAULT_EXCEPTION); return; } let progressingPropertyBarIndex: number = currentPropertyBarIndex; // sync with left + progression to left let isKeepGoingLeft: boolean = currentPropertyBarIndex > 0; let currentIteration: number = 0; let maxIteration: number = currentPropertyBarIndex - 1; while (isKeepGoingLeft === true && progressingPropertyBarIndex > 0) { if (currentApp.propertyBarVMs[progressingPropertyBarIndex].isSyncedWithBoxTreeToTheLeft) { let targetScrollDom: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[progressingPropertyBarIndex - 1]; //console.log("LEFT: current: " + currentScrollDom.scrollTop + ", prev: " + (targetScrollDom as HTMLDivElement).scrollTop); if (targetScrollDom !== undefined && targetScrollDom.scrollTop != currentScrollDom.scrollTop) { currentApp.propertyBarBoxTreeScrollHandled[progressingPropertyBarIndex - 1] = true; targetScrollDom.scrollTop = currentScrollDom.scrollTop; } } else { isKeepGoingLeft = false; break; } if (currentIteration > maxIteration) { console.log(DEFAULT_EXCEPTION); break; } progressingPropertyBarIndex--; currentIteration++; } // sync with right + progression to right progressingPropertyBarIndex = currentPropertyBarIndex + 1; let isKeepGoingRight: boolean = true; currentIteration = 0; maxIteration = (currentApp.state.visiblePropertyBarMaxCount - 1) - currentPropertyBarIndex; while (isKeepGoingRight === true && progressingPropertyBarIndex < currentApp.state.visiblePropertyBarMaxCount) { if (currentApp.propertyBarVMs[progressingPropertyBarIndex].isSyncedWithBoxTreeToTheLeft) { let targetScrollDom: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[progressingPropertyBarIndex]; //console.log("RIGHT: current: " + currentScrollDom.scrollTop + ", prev: " + (targetScrollDom as HTMLDivElement).scrollTop); if (targetScrollDom !== undefined && targetScrollDom.scrollTop != currentScrollDom.scrollTop) { currentApp.propertyBarBoxTreeScrollHandled[progressingPropertyBarIndex] = true; targetScrollDom.scrollTop = currentScrollDom.scrollTop; } } else { isKeepGoingRight = false; break; } if (currentIteration > maxIteration) { console.log(DEFAULT_EXCEPTION); break; } progressingPropertyBarIndex++; currentIteration++; } //console.log("onscroll end for property bar #" + currentPropertyBarIndex); } else { for (let i = 0; i < currentApp.state.visiblePropertyBarMaxCount; i++) { currentApp.propertyBarBoxTreeScrollHandled[i] = false; } } // --- sync visible elements --- if (currentPropertyBarIndex == 0 && this.currentPropertyBar.viewModel.isSyncedWithPagePreview) { // TODO called too often TODO initial render // update visible layout atom dom node references this.currentPropertyBar._visibleLayoutAtomDomNodeReferences = []; this.currentPropertyBar._visibleLayoutAtomKeys = []; this.currentPropertyBar._mostUpperVisibleLayoutAtomId = 0; let processedElementCount: number = 0; let mostUpperVisibleIndex: number = -1; let mostUpperVisibleLayoutAtomId: number = 0; let mostUpperVisibleDeltaTopLeft: number = currentScrollDom.clientHeight + 1; // otherwise element is below visible area let staticOffsetPx: number = currentScrollDom.getBoundingClientRect().top; // TODO everywhere: pixel aliasing are maybe because comparing not numerically, but strictly (eps) let currentScrollTop: number = currentScrollDom.scrollTop; let minXPreview: number = 0; // 0 based for top left corner in viewport/pagepreview let maxXPreview: number = currentScrollDom.clientHeight; //console.log("scrolled boxtree to" + currentScrollTop + " at client height " + pagePreviewHolder.clientHeight + " from max height" + pagePreviewHolder.scrollHeight + " minX " + minXPreview + " maxX" + maxXPreview); for (let elementKey in this.currentPropertyBar._activeViewLayoutAtomDomNodeReferences) { // TODO order all layout elements and process only specific range or move processing range with scroll let domNode: HTMLElement = this.currentPropertyBar._activeViewLayoutAtomDomNodeReferences[elementKey]; let isDomNodeVisible: boolean = false; //console.log("processing element: clientTop " + domNode.clientHeight + ", offsetTop " + domNode.offsetTop); let boundingRectElement: ClientRect = domNode.getBoundingClientRect(); //let firstClientRectElement: ClientRect = domNode.getClientRects()[0]; let minXElementDeltaTopLeft: number = boundingRectElement.top - staticOffsetPx; let maxXElementDeltaBottomLeft: number = currentScrollDom.clientHeight - (boundingRectElement.top - staticOffsetPx + currentScrollTop + boundingRectElement.height) + currentScrollTop; if (boundingRectElement.height > 0) { // height can be 0 => invisible if (minXElementDeltaTopLeft >= 0.0 && minXElementDeltaTopLeft <= currentScrollDom.clientHeight) { isDomNodeVisible = true; } else if (maxXElementDeltaBottomLeft >= 0.0 && maxXElementDeltaBottomLeft <= currentScrollDom.clientHeight) { isDomNodeVisible = true; } else if (minXElementDeltaTopLeft <= 0.0 && maxXElementDeltaBottomLeft <= 0.0) { isDomNodeVisible = true; } } //console.log("element: bounding rect top " + boundingRectElement.top + ", rect bottom " + boundingRectElement.bottom + ", minXElementDeltaTopLeft: " + minXElementDeltaTopLeft + ", maxXElementDeltaBottomLeft: " + maxXElementDeltaBottomLeft); if (isDomNodeVisible) { this.currentPropertyBar._visibleLayoutAtomDomNodeReferences.push(domNode); this.currentPropertyBar._visibleLayoutAtomKeys.push(elementKey); //console.log("visible element: first client rect top " + firstClientRectElement.top + ", rect bottom " + firstClientRectElement.bottom); if (minXElementDeltaTopLeft < mostUpperVisibleDeltaTopLeft) { mostUpperVisibleDeltaTopLeft = minXElementDeltaTopLeft; mostUpperVisibleIndex = this.currentPropertyBar._visibleLayoutAtomKeys.length; mostUpperVisibleLayoutAtomId = parseIntFromAttribute(domNode, "lid"); } } processedElementCount++; } if (mostUpperVisibleLayoutAtomId != this.currentPropertyBar._mostUpperVisibleLayoutAtomId) { this.currentPropertyBar._mostUpperVisibleLayoutAtomId = mostUpperVisibleLayoutAtomId; if (mostUpperVisibleLayoutAtomId != 0 && this.currentPropertyBar.viewModel.isSyncedWithPagePreview) { currentApp.pagePreview.syncScrollPositionFromBoxTree(); } } //console.log("boxTree scroll: processed " + processedElementCount + " object positions, visible: " + this.currentPropertyBar._visibleLayoutAtomDomNodeReferences.length.toString() + " most upper visible index: " + mostUpperVisibleIndex + " most upper visible layout id: " + this.currentPropertyBar._mostUpperVisibleLayoutAtomId); } }; public syncScrollPositionFromPagePreview = (): void => { if (this.currentPropertyBar.viewModel.isSyncedWithPagePreview) { let currentPropertyBarIndex: number = this.currentPropertyBar.propertyBarIndex; let currentScrollDom: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[currentPropertyBarIndex]; if (currentScrollDom !== undefined) { let staticOffsetPx: number = currentScrollDom.getBoundingClientRect().top; let targetLayoutAtomId: number = currentApp.pagePreview.mostUpperVisibleLayoutAtomId; console.log("tree from preview for target layout #" + targetLayoutAtomId); let domNodeOfTargetLayout: HTMLElement | undefined = this.currentPropertyBar._visibleLayoutAtomDomNodeReferences.find(r => parseIntFromAttribute(r, "lid" /*TODO use dict*/) == targetLayoutAtomId); if (domNodeOfTargetLayout === undefined) { domNodeOfTargetLayout = this.currentPropertyBar._activeViewLayoutAtomDomNodeReferences[targetLayoutAtomId]; } if (domNodeOfTargetLayout !== undefined) { currentScrollDom.scrollTop = currentScrollDom.scrollTop + (domNodeOfTargetLayout.getBoundingClientRect().top - staticOffsetPx); } else { console.log(DEFAULT_EXCEPTION); } } else { // TODO test when this happens and fix } } }; private boxTreeAfterCreateHandler = (element: Element, projectionOptions: maquette.ProjectionOptions, vnodeSelector: string, properties: maquette.VNodeProperties, children: VNode[]) => { currentApp.propertyBarBoxTreeDomReferences[this.currentPropertyBar.propertyBarIndex] = element as HTMLDivElement; }; public deleteCaliforniaViewClickHandler = (evt: MouseEvent) => { let deleteCaliforniaViewId: number = parseIntFromAttribute(evt.target, "vid"); // TODO also need to clear stuff that is connected to view.. selected special style etc. currentApp.router.clearCaliforniaPropertyBars(false, deleteCaliforniaViewId); currentApp.controller.DeleteCaliforniaViewJson(deleteCaliforniaViewId).done(data => currentApp.router.updateData(data)); }; public insertLayoutRowIntoViewClickHandler = (evt: MouseEvent) => { this.currentPropertyBar.displayPopup(evt.target as HTMLElement, PopupMode.InsertLayoutRowIntoView); }; private resetPreselectedLayoutClickHandler = (evt: MouseEvent) => { currentApp.state.preselectedLayoutBaseId = 0; }; private drawHelperLinesClickHandler = (evt: MouseEvent) => { // TODO smooth line update when scrolling: use css transform to change start/end node dependent on scrolled distance+window currentApp.state.isDrawHelperLines = !currentApp.state.isDrawHelperLines; }; private syncWithPagePreviewClickHandler = (evt: MouseEvent) => { // only for the first property bar, toggle // TODO document let currentPropertyBarIndex: number = this.currentPropertyBar.propertyBarIndex; let currentViewModel: PropertyBarVM = this.currentPropertyBar.viewModel; if (currentPropertyBarIndex == 0) { currentViewModel.isSyncedWithPagePreview = !currentViewModel.isSyncedWithPagePreview; if (currentViewModel.isSyncedWithPagePreview) { // initial sync scroll position let currentBoxTreeDomReference: HTMLElement | undefined = currentApp.propertyBarBoxTreeDomReferences[currentPropertyBarIndex]; if (currentBoxTreeDomReference !== undefined) { if (currentBoxTreeDomReference.scrollTop <= 1.0/*px*/) {// TODO document // sync boxtree scroll originating in pagepreview this.currentPropertyBar.syncScrollPositionFromPagePreview(); } else { // sync pagepreview scroll originating in boxtree currentApp.pagePreview.syncScrollPositionFromBoxTree(); } } } } }; private syncWithLeftPropertyBarClickHandler = (evt: MouseEvent) => { // default when property bar immediately to the left displays equivalent box tree: toggle sync // TODO document // TODO instead: render in same div to synchronize scroll let currentPropertyBarIndex: number = this.currentPropertyBar.propertyBarIndex; let currentViewModel: PropertyBarVM = this.currentPropertyBar.viewModel; if (currentPropertyBarIndex != 0 && currentApp.propertyBarVMs[currentPropertyBarIndex - 1].currentPropertyBarMode === PropertyBarMode.CaliforniaView && currentApp.propertyBarVMs[currentPropertyBarIndex - 1].selectedCaliforniaViewId == currentViewModel.selectedCaliforniaViewId) { currentViewModel.isSyncedWithBoxTreeToTheLeft = !currentViewModel.isSyncedWithBoxTreeToTheLeft; if (currentViewModel.isSyncedWithBoxTreeToTheLeft === true) { // initial sync scroll position let currentBoxTreeDomReference: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[currentPropertyBarIndex]; let otherBoxTreeDomReference: HTMLDivElement | undefined = currentApp.propertyBarBoxTreeDomReferences[currentPropertyBarIndex - 1]; if (currentBoxTreeDomReference !== undefined && otherBoxTreeDomReference !== undefined) { otherBoxTreeDomReference.scrollTop = currentBoxTreeDomReference.scrollTop; } else { console.log(DEFAULT_EXCEPTION); currentViewModel.isSyncedWithBoxTreeToTheLeft = false; } } } else { currentViewModel.isSyncedWithBoxTreeToTheLeft = false; } }; }
<filename>client/src/components/Footer.js import React from 'react'; function Footer () { return ( <footer style={{ backgroundColor:"rgba(0,0,0,.7", minHeight:"2rem", alignContent:"center", marginTop:"2rem" }}> <p style={{ fontSize: ".9rem", color: "white", marginTop: "1rem" }}>&copy; bryan<span style={{ color: "rgba(172,135,80)" }}>moreno</span> 2021</p> </footer> ); }; export default Footer;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.atlas.io; import static org.apache.jena.atlas.io.IO.EOF ; import static org.apache.jena.atlas.io.IO.UNSET ; import java.io.FileInputStream ; import java.io.FileNotFoundException ; import java.io.IOException ; import java.io.InputStream ; import org.apache.jena.atlas.AtlasException ; /** Parsing-centric input stream. * @see PeekReader */ public final class PeekInputStream extends InputStream { // Change to looking at slices of a ByteBuffer and rework TokenizerBytes private final InputStreamBuffered source ; private static final int PUSHBACK_SIZE = 10 ; static final byte BYTE0 = (byte)0 ; private byte[] pushbackBytes ; private int idxPushback ; // Index into pushbackBytes: points to next pushBack. -1 => none. private int currByte = UNSET ; // Next byte to return when reading forwards. private long posn ; public static final int INIT_LINE = 1 ; public static final int INIT_COL = 1 ; private long colNum ; private long lineNum ; // ---- static construction methods. public static PeekInputStream make(InputStream inputStream) { return make(inputStream, InputStreamBuffered.DFT_BUFSIZE) ; } public static PeekInputStream make(InputStream inputStream, int bufferSize) { if ( inputStream instanceof PeekInputStream ) return (PeekInputStream)inputStream ; if ( inputStream instanceof InputStreamBuffered ) return new PeekInputStream((InputStreamBuffered)inputStream) ; InputStreamBuffered in = new InputStreamBuffered(inputStream, bufferSize) ; return new PeekInputStream(in) ; } public static PeekInputStream open(String filename) { try { InputStream in = new FileInputStream(filename) ; return make(in) ; } catch (FileNotFoundException ex){ throw new AtlasException("File not found: "+filename) ; } } private PeekInputStream(InputStreamBuffered input) { this.source = input ; this.pushbackBytes = new byte[PUSHBACK_SIZE] ; this.idxPushback = -1 ; this.colNum = INIT_COL ; this.lineNum = INIT_LINE ; this.posn = 0 ; // We start at byte "-1", i.e. just before the file starts. // Advance always so that the peek byte is valid (is byte 0) // Returns the byte before the file starts (i.e. UNSET). } public final InputStreamBuffered getInput() { return source ; } public long getLineNum() { return lineNum; } public long getColNum() { return colNum; } public long getPosition() { return posn; } //---- Do not access currByte except with peekByte/setCurrByte. public final int peekByte() { if ( idxPushback >= 0 ) return pushbackBytes[idxPushback] ; // If not started ... delayed initialization. if ( currByte == UNSET ) init() ; return currByte ; } // And the correct way to read the currByte is to call peekByte private final void setCurrByte(int b) { currByte = b ; } public final int readByte() { return nextByte() ; } /** push back a byte : does not alter underlying position, line or column counts*/ public final void pushbackByte(int b) { unreadByte(b) ; } @Override public final void close() throws IOException { source.close() ; } @Override public final int read() throws IOException { if ( eof() ) return EOF ; int x = readByte() ; return x ; } @Override public final int read(byte[] buf, int off, int len) throws IOException { if ( eof() ) return EOF ; for ( int i = 0 ; i < len ; i++ ) { int ch = readByte() ; if ( ch == EOF ) return (i == 0) ? EOF : i ; buf[i + off] = (byte)ch ; } return len ; } public final boolean eof() { return peekByte() == EOF ; } // ---------------- // The methods below are the only ones to manipulate the byte buffers. // Other methods may read the state of variables. private final void unreadByte(int b) { // The push back buffer is in the order where [0] is the oldest. // Does not alter the line number, column number or position count. if ( idxPushback >= pushbackBytes.length ) { // Enlarge pushback buffer. byte[] pushbackBytes2 = new byte[pushbackBytes.length * 2] ; System.arraycopy(pushbackBytes, 0, pushbackBytes2, 0, pushbackBytes.length) ; pushbackBytes = pushbackBytes2 ; // throw new JenaException("Pushback buffer overflow") ; } if ( b == EOF || b == UNSET ) IO.exception("Illegal byte to push back: " + b) ; idxPushback++ ; pushbackBytes[idxPushback] = (byte)b ; } private final void init() { advanceAndSet() ; if ( currByte == UNSET ) setCurrByte(EOF) ; } private final void advanceAndSet() { try { int ch = source.read() ; setCurrByte(ch) ; } catch (IOException ex) { IO.exception(ex) ; } } // Invariants. // currByte is either bytes[idx-1] or pushbackBytes[idxPushback] /** Return the next byte, moving on one place and resetting the peek byte */ private final int nextByte() { int b = peekByte() ; if ( b == EOF ) return EOF ; if ( idxPushback >= 0 ) { byte b2 = pushbackBytes[idxPushback] ; idxPushback-- ; return b2 ; } posn++ ; if ( b == '\n' ) { lineNum++ ; colNum = INIT_COL ; } else colNum++ ; advanceAndSet() ; return b ; } }
/** * 对websocket相关功能进行封装 */ import { Toast } from 'antd-mobile'; import { getToken } from 'utils/auth' import storage from './storage.js' var utils = { // 处理公司节点数据 handleCompanyNode: function(data){ storage.setItem('companyNode', data); let page = plus.webview.getWebviewById('home'); socket.mui.$fire(page, 'socket', data); }, // 处理收敛器节点数据 handleCmNode: function(data){ let localData = storage.getItem('cmNode'); localData = localData?localData:{}; localData[data.batteryGroupNumber] = data; storage.setItem('cmNode', localData); }, // 处理电池组节点数据 handleBtgNode: function(data){ let localData = storage.getItem('btgNode'); localData = localData?localData:{}; localData[data.batteryGroupNumber] = data; storage.setItem('btgNode', localData); }, // 处理告警信息列表数据 handleRealtimeAlarmData: function(data){ let localData = storage.getItem('realtimeAlarmData'); localData = localData?localData:[]; storage.setItem('realtimeAlarmData', [...data, ...localData]); }, // 处理文件下载 handleDownload: function(data){ } } var socket = { failCount: 0, // 重连失败次数 socket: null, utils: null, url:process.env.REACT_APP_SOCKET_URL, silent: false, typeList: [], log: function(...rest){ if(!this.silent){ console.log.apply(null, [...rest]) } }, init: function (utils) { let socketUrl = this.url; let token = getToken()?getToken():'4c22ad729ad176a1a82de2840f538eef'; // 设置socket数据默认值 this.setDefaultValue() this.utils = utils; this.socket = new WebSocket(socketUrl+token); this.socket.onopen = this.onopen.bind(this); this.socket.onmessage = this.onmessage.bind(this); this.socket.onerror = this.onerror.bind(this); this.socket.onclose = this.onclose.bind(this); }, close: function(){ this.socket.close('4001'); }, onopen: function () { this.log('%c --------------------websocket连接成功--------------------', 'color:#40a9ff') this.socket.send('连上了,哈哈哈哈') this.failCount = 0; }, onmessage: function (event) { try{ let data = JSON.parse(event.data); let type = data.type; let info = data.data; if(this.typeList.indexOf(type) == -1){ this.log('----------socket消息----------', data); this.typeList.push(type) } switch(type){ case 'companyNode': return this.utils.handleCompanyNode(info); case 'cmNode': return this.utils.handleCmNode(info); case 'btgNode': return this.utils.handleBtgNode(info); case 'realtimeAlarmData': return this.utils.handleRealtimeAlarmData(info); } }catch(error){ console.log('error', error) } }, onclose:function (event) { let code = event.code; if(code !== 4001){ this.reConnect.bind(this)(); } }, onerror: function (error) { this.log('--------------------websocket报错----------------------', error) }, reConnect() { if(this.failCount<2){ this.log(`%c ---------websocket连接异常,正在尝试第${this.failCount+1}次重新连接---------`, 'color:#40a9ff') setTimeout(this.init.bind(this), 10000); this.failCount++; } else { Toast.fail(`websocket连接异常!`) } }, setDefaultValue(){ storage.setItem('companyNode', {}); storage.setItem('cmNode', {}); storage.setItem('btgNode', {}); storage.setItem('realtimeAlarmData', []); } }; // console.log('process.env.socketUrl', process.env.socketUrl) export default socket;
cd docker ./docker.sh cd .. ansible-playbook analytics.yml -i vagrant #ansible-playbook analytics.yml -i vagrant --tag hdfs #ansible-playbook analytics.yml -i vagrant --tag spark #ansible-playbook analytics.yml -i vagrant --tag hbase #ansible-playbook analytics.yml -i vagrant --tag kafka
<filename>tests/utils/pracellation.py import unittest as ut import fmridenoise.parcellation from fmridenoise.parcellation import get_parcellation_file_path from os.path import join, dirname class ParcellationHelpers(ut.TestCase): def test_get_MNI152Nlin6Asym(self): path = get_parcellation_file_path('MNI152NLin6Asym') self.assertEqual(path, join(dirname(fmridenoise.parcellation.__file__), 'tpl-MNI152NLin6Asym_res-01_atlas-Schaefer2018_desc-200Parcels7Networks_dseg.nii.gz')) def test_get_MINI152NLin2009cAsym(self): path = get_parcellation_file_path('MNI152NLin2009cAsym') self.assertEqual(path, join(dirname(fmridenoise.parcellation.__file__), 'tpl-MNI152NLin2009cAsym_res-01_atlas-Schaefer2018_desc-200Parcels7Networks_dseg.nii.gz'))
import products.Product; import products.dumplings.Salmon; import products.pasta.Bolognese; import products.pasta.Carbonara; import products.pizza.Italiana; import org.junit.jupiter.api.Test; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.TearDown; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.*; import registrationclass.NoReflectionFactory; import registrationclass.ReflectionFactory; import java.lang.reflect.InvocationTargetException; public class TestRegistrationClasses { NoReflectionFactory factory1; ReflectionFactory factory2; @Setup public void setUp(){ factory1 = NoReflectionFactory.getInstance(); factory2 = ReflectionFactory.getInstance(); } @Test public void testExceptionForNotRegisteredProductNoReflection() { NoReflectionFactory factory = NoReflectionFactory.getInstance(); assertThrows(IllegalArgumentException.class, () -> { factory.getProduct("Carbonara"); }); } @Test public void testOrderAllProductsNoReflection() { NoReflectionFactory factory = NoReflectionFactory.getInstance(); factory.registerType("salmon", Salmon::new); factory.registerType("italiana", Italiana::new); factory.registerType("Bolognese", Bolognese::new); Product dumplings = factory.getProduct("salmon"); Product pasta = factory.getProduct("Bolognese"); Product pizza = factory.getProduct("italiana"); assertThat(dumplings, instanceOf(Salmon.class)); assertThat(pasta, instanceOf(Bolognese.class)); assertThat(pizza, instanceOf(Italiana.class)); assertEquals(dumplings.getName(), "Salmon"); assertEquals(pasta.getName(), "Bolognese"); assertEquals(pizza.getName(), "Italiana"); } //Test Reflection Factory @Test public void testExceptionForNotRegisteredProductReflection() { ReflectionFactory factory = ReflectionFactory.getInstance(); assertThrows(IllegalArgumentException.class, () -> { factory.getProduct("Carbonara"); }); } @Test public void testRegisterProduct() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { ReflectionFactory factory = ReflectionFactory.getInstance(); assertThrows(IllegalArgumentException.class, () -> { factory.getProduct("Carbonara"); }); factory.registerProduct("Carbonara", Carbonara.class); Product pasta = factory.getProduct("Carbonara"); assertEquals(pasta.getName(), "Carbonara"); } @Test public void testOrderAllProductsReflection() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { ReflectionFactory factory = ReflectionFactory.getInstance(); Product dumplings = factory.getProduct("salmon"); Product pasta = factory.getProduct("Bolognese"); Product pizza = factory.getProduct("italiana"); String actualMessageDum = dumplings.order(); String actualMessagePasta = pasta.order(); String actualMessagePizza = pizza.order(); String expectedDumplingsMessage = "Ordered Salmon dumplings."; String expectedPizzaMessage = "Ordered Italiana pizza."; String expectedPastaMessage = "Ordered Bolognese pasta."; assertThat(dumplings, instanceOf(Salmon.class)); assertThat(pasta, instanceOf(Bolognese.class)); assertThat(pizza, instanceOf(Italiana.class)); assertEquals(expectedPastaMessage, actualMessagePasta); assertEquals(expectedPizzaMessage, actualMessagePizza); assertEquals(expectedDumplingsMessage, actualMessageDum); } @TearDown public void tearDown(){ factory1 = null; factory2 = null; } }
<gh_stars>0 import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { MicroClass } from '../../models/microclass'; import { MicroClassVideo } from '../../models/microclassvideo'; import { MicroClassProvider } from '../../providers/micro-class/micro-class'; import { ListMicroclassvideoPage } from '../list-microclassvideo/list-microclassvideo'; /** * Generated class for the ListMicroclassPage page. * * See http://ionicframework.com/docs/components/#navigation for more info * on Ionic pages and navigation. */ @Component({ selector: 'page-list-microclass', templateUrl: 'list-microclass.html', }) export class ListMicroclassPage { currentMicroclasses: MicroClass[] = []; constructor(public navCtrl: NavController, public navParams: NavParams, public mcProvider: MicroClassProvider) { this.mcProvider.query().subscribe(data => this.resolve(data), err => this.reject(err)); } ionViewDidLoad() { console.log('ionViewDidLoad ListMicroclassPage'); } openMicroClass(microClassVideos) { this.navCtrl.push(ListMicroclassvideoPage, { microClassVideos : microClassVideos}); } private resolve(data) { this.currentMicroclasses.length = 0; if (data && data.success) { let ds = data.data; for (let d of ds) { this.currentMicroclasses.push(new MicroClass(d)); } } } private reject(err) { console.log(err); } }
#!/bin/bash set -euxo pipefail if [ "$(pwd)" = "/latest" ]; then until $(python /local/chromeless/__version__.py); do sleep 5; done fi cp /tests.py ./ cp /example.py ./ pytest tests.py -ra pytest example.py -ra
#!/bin/bash if [ -z $CHANNEL ]; then export CHANNEL='release' fi pushd $(dirname "$0") >/dev/null source config.sh # read nightly compiler from rust-toolchain file TOOLCHAIN=$(cat rust-toolchain) popd >/dev/null if [[ $(rustc -V) != $(rustc +${TOOLCHAIN} -V) ]]; then echo "rustc_codegen_cranelift is build for $(rustc +${TOOLCHAIN} -V) but the default rustc version is $(rustc -V)." echo "Using $(rustc +${TOOLCHAIN} -V)." fi cmd=$1 shift cargo +${TOOLCHAIN} $cmd $@
#!/usr/bin/env bash export PGPASSWORD=$POSTGRES_PASSWORD filename=backup_$(date +'%Y_%m_%dT%H_%M_%S').dump echo "create database backup file $filename" pg_dump -Fc -h database -U $POSTGRES_USER $POSTGRES_DB > /backups/$filename
#!/bin/bash -e cat > /tmp/setup.$$ <<"EOF" mkdir -p /data/kolla df -h dd if=/dev/zero of=/data/kolla/cinder-volumes.img bs=5M count=2048 LOOP=$(losetup -f) losetup $LOOP /data/kolla/cinder-volumes.img parted -s $LOOP mklabel gpt parted -s $LOOP mkpart 1 0% 100% parted -s $LOOP set 1 lvm on partprobe $LOOP pvcreate -y $LOOP vgcreate -y cinder-volumes $LOOP echo "Finished prepping lvm storage on $LOOP" EOF sudo bash /tmp/setup.$$
#! /bin/bash cargo build --release --target x86_64-unknown-linux-gnu # scp rust_cms_20200806p1.zip root@www.tianlang.tech:/home/www/web/rust_cms
if (process.env.NODE_ENV === "production") { module.exports = require("./storeProvider.prod") } else { module.exports = require("./storeProvider.dev") }
<reponame>cisocrgroup/ocrd-postcorrection package de.lmu.cis.ocrd.ml.features; public interface BinaryPrediction { boolean getPrediction(); double getConfidence(); }
import numpy as np from sklearn.preprocessing import OneHotEncoder from typing import Tuple def preprocess_data(X: np.ndarray, yFile: str) -> Tuple[np.ndarray, np.ndarray]: # Reshape the input features preprocessed_X = np.reshape(X, (212841, -1)) # Read the label data and perform One-Hot Encoding with open(yFile, "r") as yFile_r: labelLines = [_.strip("\n") for _ in yFile_r.readlines()] values = np.array(labelLines).reshape(-1, 1) encoder = OneHotEncoder(sparse=False) one_hot_encoded_y = encoder.fit_transform(values) return preprocessed_X, one_hot_encoded_y
#!/bin/sh set -e # started as hassio addon HASSIO_OPTIONSFILE=/data/options.json if [ -f ${HASSIO_OPTIONSFILE} ]; then CONFIG=$(grep config_file ${HASSIO_OPTIONSFILE}| cut -d ':' -f 2 | sed s/[\"}]//g ) echo "Using config file: ${CONFIG}" if [ ! -f ${CONFIG} ]; then echo "Config not found. Please create a config under ${CONFIG}." echo "For details see evcc documentation at https://github.com/mark-sch/evcc#readme." else echo "starting evcc: 'evcc --config ${CONFIG}'" exec evcc --config ${CONFIG} fi else if [ "$1" == '"evcc"' ] || expr "$1" : '-*' > /dev/null; then exec evcc "$@" else exec "$@" fi fi
<filename>acmicpc.net/source/13913.cpp // 13913. 숨바꼭질 4 // 2019.08.04 // BFS // https://tdm1223.tistory.com/89 #include<iostream> #include<queue> using namespace std; bool visit[200001]; // 방문 유무 저장 int dist[200001]; // dist[i] : i에 도착하는 가장 빠른 시간 int from[200001]; // from[i] : i가 어디서 왔는지 저장하는 배열 // 경로 출력하는 함수 void Print(int n, int m) { if (n != m) { Print(n, from[m]); } cout << m << ' '; } int main() { int n, k; cin >> n >> k; visit[n] = true; queue<int> q; q.push(n); while (!q.empty()) { int now = q.front(); q.pop(); if (now - 1 >= 0) // x-1로 이동 { if (visit[now - 1] == false) { q.push(now - 1); visit[now - 1] = true; from[now - 1] = now; dist[now - 1] = dist[now] + 1; } } if (now + 1 <= 200000) // x+1로 이동 { if (visit[now + 1] == false) { q.push(now + 1); visit[now + 1] = true; from[now + 1] = now; dist[now + 1] = dist[now] + 1; } } if (now * 2 <= 200000) // 순간이동 { if (visit[now * 2] == false) { q.push(now * 2); visit[now * 2] = true; from[now * 2] = now; dist[now * 2] = dist[now] + 1; } } } cout << dist[k] << "\n"; Print(n, k); return 0; }
package io.opensphere.controlpanels.styles.ui; import static org.junit.Assert.assertEquals; import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.junit.Before; import org.junit.Test; import io.opensphere.controlpanels.styles.model.StyleOptions; import io.opensphere.controlpanels.styles.model.Styles; import io.opensphere.core.util.collections.New; import javafx.application.Platform; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.Slider; import javafx.scene.paint.Color; /** * Unit test for {@link StyleOptionsBinder}. */ public class StyleOptionsBinderTestDisplay { /** Initializes the JavaFX platform. */ @Before public void initialize() { try { Platform.startup(() -> { }); } catch (IllegalStateException e) { // Platform already started; ignore } } /** * Tests the binding. */ @Test public void test() { EasyMockSupport support = new EasyMockSupport(); StyleOptionsView view = createView(support); support.replayAll(); StyleOptions model = new StyleOptions(); model.setColor(java.awt.Color.RED); model.setSize(12); model.setStyle(Styles.POINT); StyleOptionsBinder binder = new StyleOptionsBinder(view, model); assertEquals(Color.RED, view.getColorPicker().getValue()); assertEquals(12, view.getSize().getValue(), 0d); assertEquals(Styles.POINT, view.getStylePicker().getValue()); assertEquals(New.list(Styles.values()), view.getStylePicker().getItems()); view.getColorPicker().setValue(Color.BLUE); view.getSize().setValue(14); view.getStylePicker().setValue(Styles.ELLIPSE); assertEquals(java.awt.Color.BLUE, model.getColor()); assertEquals(14, model.getSize()); assertEquals(Styles.ELLIPSE, model.getStyle()); model.setColor(java.awt.Color.WHITE); model.setSize(15); model.setStyle(Styles.NONE); assertEquals(Color.WHITE, view.getColorPicker().valueProperty().get()); assertEquals(15, view.getSize().getValue(), 0d); assertEquals(Styles.NONE, view.getStylePicker().getValue()); binder.close(); view.getColorPicker().setValue(Color.YELLOW); view.getSize().setValue(16); view.getStylePicker().setValue(Styles.ICON); model.setColor(java.awt.Color.BLUE); model.setSize(14); model.setStyle(Styles.ELLIPSE); assertEquals(java.awt.Color.BLUE, model.getColor()); assertEquals(14, model.getSize()); assertEquals(Styles.ELLIPSE, model.getStyle()); assertEquals(Color.YELLOW, view.getColorPicker().valueProperty().get()); assertEquals(16, view.getSize().getValue(), 0d); assertEquals(Styles.ICON, view.getStylePicker().getValue()); support.verifyAll(); } /** * Creates a mocked {@link StyleOptionsView}. * * @param support Used to create the mock. * @return The style options view. */ private StyleOptionsView createView(EasyMockSupport support) { StyleOptionsView view = support.createMock(StyleOptionsView.class); ColorPicker colorPicker = new ColorPicker(); EasyMock.expect(view.getColorPicker()).andReturn(colorPicker).atLeastOnce(); Slider slider = new Slider(); EasyMock.expect(view.getSize()).andReturn(slider).atLeastOnce(); ComboBox<Styles> stylePicker = new ComboBox<>(); EasyMock.expect(view.getStylePicker()).andReturn(stylePicker).atLeastOnce(); return view; } }
#!/bin/bash # # launches the unit testing # # Copyright (C) # Honda Research Institute Europe GmbH # Carl-Legien-Str. 30 # 63073 Offenbach/Main # Germany # # UNPUBLISHED PROPRIETARY MATERIAL. # ALL RIGHTS RESERVED. # # source ${TOOLBOSCORE_ROOT}/include/Unittest.bash CWD=$(pwd) cd ${CWD}/ArgsManagerV2 && ./TestArgsManagerV2.py cd ${CWD}/ThreadPool && ./TestThreadPool.py # EOF
#!/bin/bash systemctl disable avahi-daemon
<filename>.storybook/main.js module.exports = { stories: ['../stories/**/*.stories.(ts|tsx)'], addons: [ '@storybook/addon-actions', '@storybook/addon-links', '@storybook/addon-docs', ], typescript: { check: false, reactDocgen: 'react-docgen-typescript', compilerOptions: { module: 'esnext', lib: ['dom', 'esnext'], importHelpers: true, declaration: true, sourceMap: true, rootDir: './', strict: true, noUnusedLocals: true, noUnusedParameters: true, noImplicitReturns: true, noFallthroughCasesInSwitch: true, moduleResolution: 'node', baseUrl: './', paths: { '@': ['./'], '*': ['src/*', 'node_modules/*'], }, jsx: 'react', esModuleInterop: true, }, reactDocgenTypescriptOptions: { compilerOptions: { allowSyntheticDefaultImports: true, esModuleInterop: false, module: 'esnext', lib: ['dom', 'esnext'], importHelpers: true, declaration: true, sourceMap: true, rootDir: './', strict: true, noUnusedLocals: false, noUnusedParameters: false, noImplicitReturns: false, noFallthroughCasesInSwitch: true, moduleResolution: 'node', }, }, }, webpackFinal: async config => { config.module.rules.push({ test: /\.(ts|tsx)$/, use: [ { loader: require.resolve('ts-loader'), options: { transpileOnly: false, }, }, { loader: require.resolve('react-docgen-typescript-loader'), }, ], }) config.resolve.extensions.push('.ts', '.tsx') return config }, }
package bd.edu.daffodilvarsity.classmanager.activities; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.chip.Chip; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; import bd.edu.daffodilvarsity.classmanager.R; import bd.edu.daffodilvarsity.classmanager.otherclasses.HelperClass; import bd.edu.daffodilvarsity.classmanager.otherclasses.ProfileObjectStudent; import bd.edu.daffodilvarsity.classmanager.otherclasses.SharedPreferencesHelper; import timber.log.Timber; public class CompleteNewProfileStudent extends AppCompatActivity implements View.OnClickListener { FirebaseAuth mAuth; FirebaseFirestore db; TextInputLayout mName; TextInputLayout mStudentId; Button mSave; Chip mDay; Chip mEvening; Chip mCse; Chip mBsc; Spinner mLevel; Spinner mTerm; Spinner mSection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_complete_new_profile_student); initializeVariables(); initializeSpinners(); initializeOnClickListeners(); } @Override public void onBackPressed() { super.onBackPressed(); try { mAuth.signOut(); } catch (Exception e) { Timber.e(e); } } private void initializeVariables() { db = FirebaseFirestore.getInstance(); mAuth = FirebaseAuth.getInstance(); mSave = findViewById(R.id.save); mName = findViewById(R.id.name); mStudentId = findViewById(R.id.student_id); mDay = findViewById(R.id.day); mEvening = findViewById(R.id.evening); mCse = findViewById(R.id.cse); mBsc = findViewById(R.id.bsc); mLevel = findViewById(R.id.level); mTerm = findViewById(R.id.term); mSection = findViewById(R.id.section_spinner); } private void initializeOnClickListeners() { mSave.setOnClickListener(this); } private void initializeSpinners() { String[] level = new String[]{"Level 1", "Level 2", "Level 3", "Level 4"}; String[] term = new String[]{"Term 1", "Term 2", "Term 3"}; String[] section = HelperClass.getAllSections(); ArrayAdapter<String> levelAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, level); ArrayAdapter<String> termAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, term); ArrayAdapter<String> sectionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, section); levelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sectionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mLevel.setAdapter(levelAdapter); mTerm.setAdapter(termAdapter); mSection.setAdapter(sectionAdapter); } private void checkInformationAndSave() { clearErrors(); if (!checkGivenInfo()) { return; } String name = mName.getEditText().getText().toString().trim(); String id = mStudentId.getEditText().getText().toString().trim(); final ProfileObjectStudent profile = new ProfileObjectStudent(); profile.setName(name); profile.setId(id); if (mBsc.isChecked()) { profile.setProgram(HelperClass.PROGRAM_BSC); } if (mDay.isChecked()) { profile.setShift("Day"); } else if (mEvening.isChecked()) { profile.setShift("Evening"); } if (mCse.isChecked()) { profile.setDepartment("CSE"); } final String level = mLevel.getSelectedItem().toString(); final String term = mTerm.getSelectedItem().toString(); final String section = mSection.getSelectedItem().toString(); profile.setLevel(level); profile.setTerm(term); profile.setSection(section); SharedPreferencesHelper.saveStudentProfileOffline(this, profile); sleep(100); SharedPreferencesHelper.saveCourseWithSharedPreference(this, profile.getProgram(), profile.getShift(), level, term, section); sleep(100); SharedPreferencesHelper.setUserType(this, HelperClass.USER_TYPE_STUDENT); Intent intent = new Intent(CompleteNewProfileStudent.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); /*DocumentReference docRef = db.document("/student_profiles/" + mAuth.getCurrentUser().getUid()); docRef.set(profile) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { makeToast("Information saved."); new SharedPreferencesHelper().saveCourseWithSharedPreference(getApplicationContext(),profile.getProgram(), profile.getShift(), level, term, section); startActivity(new Intent(CompleteNewProfileStudent.this, MainActivity.class)); finish(); } else { makeToast("Failed to save.Please check your internet connection."); } } });*/ } private boolean checkGivenInfo() { String name = mName.getEditText().getText().toString().trim(); String id = mStudentId.getEditText().getText().toString().trim(); if (name.isEmpty()) { makeToast("Name cannot be empty."); mName.setError("Name cannot be empty"); return false; } if (id.isEmpty()) { makeToast("ID cannot be empty."); mStudentId.setError("ID cannot be empty"); return false; } if (!name.matches("[a-zA-Z .]*")) { makeToast("Invalid characters in username."); mName.setError("Invalid characters"); return false; } if (!id.matches("[0-9-]*")) { makeToast("Invalid ID."); mStudentId.setError("Invalid student ID"); return false; } if (!checkChipSelection()) { return false; } return true; } private void clearErrors() { mName.setError(null); mStudentId.setError(null); } private boolean checkChipSelection() { if (mDay.isChecked() | mEvening.isChecked()) { if (mCse.isChecked()) { if (mBsc.isChecked()) { return true; } else { makeToast("Please select a program"); } } else { makeToast("Please select a department"); } } else { makeToast("Select your shift."); } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.save: checkInformationAndSave(); break; } } private void sleep(int s) { try { Thread.sleep(s); } catch (InterruptedException e) { Timber.e(e); } } private void makeToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
import DepotConnection from '../Connections/DepotConnection'; import GuidedCallback from '../Callbacks/GuidedCallback'; export function DepotGuide() { let promise = new Promise(() => { depotGuide(); }); } function depotGuide() { dcn = new DepotConnection(new GuidedCallback()); dcn.Complexity = "Guide"; dcn.Content = DataSpace.SphereOn; dcn.Initiate(); }
package com.iterlife.zeus.demo.entity; import com.iterlife.zeus.starter.annotation.IterLife; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import java.lang.annotation.Annotation; /** * @desc: * @author: lujie * @version: V1.0.0 * @datetime: 2020/10/7 16:51 **/ @Getter @Setter @NoArgsConstructor @IterLife(id = "000000", name = "iterlife-user", desc = "this is a test annotation for IterLife") @Slf4j public class User2 { public String id; public String name; public String gender; public int age; @Override public String toString() { return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender='" + gender + '\'' + ", age=" + age + '}'; } public void printAnnotation() { Class clazz = this.getClass(); if (clazz.isAnnotationPresent(IterLife.class)) { Annotation annotation = clazz.getAnnotation(IterLife.class); log.info(annotation.toString()); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import argparse from typing import Text from ai_flow.endpoint.server.server import AIFlowServer from ai_flow.endpoint.server.server_config import AIFlowServerConfig from ai_flow.client.ai_flow_client import get_ai_flow_client from ai_flow.util.net_utils import get_ip_addr import logging _SQLITE_DB_FILE = 'aiflow.db' _SQLITE_DB_URI = '%s%s' % ('sqlite:///', _SQLITE_DB_FILE) _MYSQL_DB_URI = 'mysql+pymysql://root:aliyunmysql@localhost:3306/aiflow' _PORT = '50051' GLOBAL_MASTER_CONFIG = {} class AIFlowServerRunner(object): """ AI flow server runner. This class is the runner class for the AIFlowServer. It parse the server configuration and manage the live cycle of the AIFlowServer. """ def __init__(self, config_file: Text = None, enable_ha=False, server_uri: str = None, ttl_ms=10000) -> None: """ Set the server attribute according to the server config file. :param config_file: server configuration file. """ super().__init__() self.config_file = config_file self.server = None self.server_config = AIFlowServerConfig() self.enable_ha = enable_ha self.server_uri = server_uri self.ttl_ms = ttl_ms def start(self, is_block=False) -> None: """ Start the AI flow runner. :param is_block: AI flow runner will run non-stop if True. """ if self.config_file is not None: self.server_config.load_from_file(self.config_file) else: self.server_config.set_server_port(str(_PORT)) global GLOBAL_MASTER_CONFIG GLOBAL_MASTER_CONFIG = self.server_config logging.info("AI Flow Master Config {}".format(GLOBAL_MASTER_CONFIG)) self.server = AIFlowServer( store_uri=self.server_config.get_db_uri(), port=str(self.server_config.get_server_port()), notification_server_uri=self.server_config.get_notification_server_uri(), start_meta_service=self.server_config.start_meta_service(), start_model_center_service=self.server_config.start_model_center_service(), start_metric_service=self.server_config.start_metric_service(), start_scheduler_service=self.server_config.start_scheduler_service(), scheduler_service_config=self.server_config.get_scheduler_service_config(), enabled_ha=self.server_config.get_enable_ha(), ha_server_uri=get_ip_addr() + ":" + str(self.server_config.get_server_port()), ttl_ms=self.server_config.get_ha_ttl_ms()) self.server.run(is_block=is_block) def stop(self, clear_sql_lite_db_file=True) -> None: """ Stop the AI flow runner. :param clear_sql_lite_db_file: If True, the sqlite database files will be deleted When the server stops working. """ self.server.stop(clear_sql_lite_db_file) def _clear_db(self): self.server._clear_db() def set_master_config(): code, config, message = get_ai_flow_client().get_master_config() for k, v in config.items(): GLOBAL_MASTER_CONFIG[k] = v if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--config', required=True, help='master config file') args = parser.parse_args() logging.info(args.config) config_file = args.config master = AIFlowServerRunner( config_file=config_file) master.start(is_block=True)
<reponame>QuidWallet/quid-wallet-app<gh_stars>1-10 import { createSelector } from 'reselect'; import { getActiveWalletTokensWithPrice, getActiveWalletAddress, getActiveWalletTotalBalance } from './wallet'; import { getAllTransfers } from './transfers'; export const portfolioUpdatedAt = createSelector( [getActiveWalletTokensWithPrice ], (tokens) => Math.min(...tokens.map(item => item.priceUpdatedAt)) ); const getAssetsFlow = createSelector( [getAllTransfers, getActiveWalletAddress, portfolioUpdatedAt], ({transfers}, address, portfolioUpdatedAt) => { const day = 1000 * 60 * 60 * 24; const flowDct = transfers //.toRefArray() // use timestamp of last price update as a reference .filter(tx => (tx.address === address && ((portfolioUpdatedAt - tx.timestamp*1000)/day < 1))).toRefArray() .reduce((dct, tx) => { const newDct = { ...dct }; newDct[tx.tokenAddress] = newDct[tx.tokenAddress] || 0; const sign = (tx.direction === 'IN') ? 1 : -1; const value = sign * tx.value; newDct[tx.tokenAddress] += value; return newDct; }, {}); return flowDct; } ); const getPositionChangeDct = createSelector( [getActiveWalletTokensWithPrice, getAssetsFlow ], (tokens, flowDct) => { const changeDct = tokens.reduce((dct, token) => { const qntyToday = token.qnty; const qntyYesterday = token.qnty - (flowDct[token.contractAddress] || 0); const priceToday = token.price; const priceYesterday = token.price - token.priceChangeAbs; const value = (qntyToday * priceToday) - (qntyYesterday * priceYesterday); let percent; // TODO: resolve bignumber fix if (qntyYesterday > 0.00000001) { percent = ((qntyToday * priceToday) / (qntyYesterday * priceYesterday) - 1) * 100; } else { percent = 0; } const tempDct = { ...dct }; tempDct[token.contractAddress] = { value, percent }; return tempDct; }, {}); return changeDct; } ); export const getPortfolioPositions = createSelector( [getActiveWalletTokensWithPrice, getPositionChangeDct ], (tokens, changeDct) => tokens .filter(token => token.qnty > 0) .map(token => ({ ...token, balanceChangeAbs: changeDct[token.contractAddress].value, balanceChangePerc: changeDct[token.contractAddress].percent })) ); export const getTotalPortfolioChangeAbs = createSelector( getPositionChangeDct, (changeDct) => { const totalChangeAbs = Object.keys(changeDct) .map(assetAddress => changeDct[assetAddress].value) .reduce((acc, diff) => { return (acc + diff); }, 0); return totalChangeAbs; } ); export const getTotalPortfolioChangePerc = createSelector( [ getActiveWalletTotalBalance, getTotalPortfolioChangeAbs ], (currentValue, changeAbs) => (currentValue / (currentValue - changeAbs) - 1) * 100 );
. helpers.sh start_test_server \ -line 1 -file data/require-digestauth-close -end -reconnect \ -line 4 -expect 'Authorization: Digest username="testuser",realm="testrealm",nonce="948647427",uri="/testrealm/",response="66481c52735a79763ec8ae9abbec36d7",algorithm=MD5' \ -line 4 -file data/framed trap "stop_test_server" EXIT request \ -realm testrealm -user testuser -password testpassword -digest-auth \ -get /testrealm/ \ -run
#!/bin/bash set -e printf "\n[-] Performing final cleanup...\n\n" # get out of the src dir, so we can delete it cd $APP_BUNDLE_DIR # Clean out docs rm -rf /usr/share/{doc,doc-base,man,locale,zoneinfo} # Clean out package management dirs rm -rf /var/lib/{cache,log} # remove app source rm -rf $APP_SOURCE_DIR # remove meteor rm -rf /usr/local/bin/meteor rm -rf /root/.meteor # clean additional files created outside the source tree rm -rf /root/{.npm,.cache,.config,.cordova,.local} rm -rf /tmp/* # remove npm npm cache clean --force rm -rf /opt/nodejs/bin/npm rm -rf /opt/nodejs/lib/node_modules/npm/ # remove os dependencies apt-get purge -y --auto-remove build-essential bsdtar bzip2 curl git python apt-get -y autoremove apt-get -y clean apt-get -y autoclean rm -rf /var/lib/apt/lists/*
#!/usr/bin/env bash # vim:ts=4:sts=4:sw=4:et # # Author: Hari Sekhon # Date: 2021-09-13 18:05:20 +0100 (Mon, 13 Sep 2021) # # https://github.com/HariSekhon/bash-tools # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish # # https://www.linkedin.com/in/HariSekhon # # https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories/update?view=azure-devops-rest-6.1#disable-repository set -euo pipefail [ -n "${DEBUG:-}" ] && set -x srcdir="$(dirname "${BASH_SOURCE[0]}")" # shellcheck disable=SC1090 . "$srcdir/lib/utils.sh" # shellcheck disable=SC2034,SC2154 usage_description=" Disables one or more given Azure DevOps repos (for after a migration to GitHub to prevent writes to the wrong server being left behind) For authentication and other details see: azure_devops_api.sh --help " # used by usage() in lib/utils.sh # shellcheck disable=SC2034 usage_args="<organization> <project> <repo> [<repo2> <repo3> ...]" help_usage "$@" min_args 3 "$@" org="$1" project="$2" shift || : shift || : disable_repo(){ local repo="$1" local id timestamp "getting repo id for Azure DevOps organization '$org' project '$project' repo '$repo'" set +euo pipefail response="$("$srcdir/azure_devops_api.sh" "/$org/$project/_apis/git/repositories/$repo")" # shellcheck disable=SC2181 if [ $? != 0 ]; then timestamp "repo not found or already disabled, skipping..." return 0 fi set -euo pipefail id="$(jq -e -r .id <<< "$response")" timestamp "disabling Azure DevOps organization '$org' project '$project' repo '$repo'" "$srcdir/azure_devops_api.sh" "/$org/$project/_apis/git/repositories/$id?api-version=6.1-preview.1" -X PATCH -d '{"isDisabled": true}' | jq -e -r '[ "Disabled: ", .isDisabled ] | @tsv' } for repo in "$@"; do disable_repo "$repo" done
import java.util.Scanner; public class UserData { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter your Full Name : "); String fullName = sc.nextLine(); System.out.println("Please enter your Age : "); int age = sc.nextInt(); System.out.println("Please enter your Address : "); String address = sc.nextLine(); System.out.println("Please enter your Phone Number : "); String phoneNumber = sc.nextLine(); //Printing the personal information System.out.println("Name : "+fullName); System.out.println("Age : "+age); System.out.println("Address : "+address); System.out.println("Phone Number : "+phoneNumber); } }
def encrypt(message): encrypted_text = "" for letter in message: encrypted_text += chr(ord(letter) + 3) return encrypted_text def decrypt(message): decrypted_text = "" for letter in message: decrypted_text += chr(ord(letter) - 3) return decrypted_text msg = "This is a secret message" encrypted_text = encrypt(msg) print("Encrypted text: " + encrypted_text) decrypted_text = decrypt(encrypted_text) print("Decrypted text: " + decrypted_text)
"use strict"; exports.__esModule = true; exports.BookDto = void 0; var BookDto = /** @class */ (function () { function BookDto() { } return BookDto; }()); exports.BookDto = BookDto;
<reponame>jmccrae/saffron<filename>core/src/test/java/org/insightcentre/nlp/saffron/data/ConceptTest.java<gh_stars>10-100 package org.insightcentre.nlp.saffron.data; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; /** * Unitary tests for {@code Concept} class * * @author <NAME> * */ public class ConceptTest { @Test public void testJsonSerialisation() throws IOException { //Prepare final String input = "{" + "\""+ Concept.JSON_ID +"\":\"1234\"," + "\"" + Concept.JSON_PREFERRED_TERM + "\":\"term string\"," + "\"" + Concept.JSON_SYNONYMS + "\": [" + "\"synonym 1\", \"synonym 2\",\"synonym 3\"" + "]" + "}"; Set<Term> expectedSynonyms = new HashSet<Term>(); expectedSynonyms.add(new Term.Builder("synonym 1").build()); expectedSynonyms.add(new Term.Builder("synonym 2").build()); expectedSynonyms.add(new Term.Builder("synonym 3").build()); //Call ObjectMapper mapper = new ObjectMapper(); final Concept actual = mapper.readValue(input, Concept.class); //Evaluate assertEquals("1234", actual.getId()); assertEquals(new Term.Builder("term string").build(), actual.getPreferredTerm()); assertEquals(expectedSynonyms, actual.getSynonyms()); } /** * Test with no synonyms * * @throws IOException */ @Test public void testJsonSerialisation2() throws IOException { //Prepare final String input = "{" + "\""+ Concept.JSON_ID +"\":\"1234\"," + "\"" + Concept.JSON_PREFERRED_TERM + "\":\"term string\"" + "}"; //Call ObjectMapper mapper = new ObjectMapper(); final Concept actual = mapper.readValue(input, Concept.class); //Evaluate assertEquals("1234", actual.getId()); assertEquals(new Term.Builder("term string").build(), actual.getPreferredTerm()); } /* FIXME: How to test serialisation when the order of the values in the array may change? @Test public void testJsonDeserialisation() throws IOException { //Prepare final String expected = "{" + "\""+ Concept.JSON_ID +"\":\"1234\"," + "\"" + Concept.JSON_PREFERRED_TERM + "\":\"term string\"," + "\"" + Concept.JSON_SYNONYMS + "\": [" + "\"synonym 1\", \"synonym 2\",\"synonym 3\"" + "]" + "}"; Concept input = new Concept.Builder("1234", "term string") .addSynonym("synonym 1") .addSynonym("synonym 2") .addSynonym("synonym 3") .build(); //Call ObjectMapper mapper = new ObjectMapper(); final String actual = mapper.writeValueAsString(input); //Evaluate assertEquals(expected,actual); }*/ /** * Test with no synonyms * * @throws IOException */ @Test public void testJsonDeserialisation2() throws IOException { //Prepare final String expected = "{" + "\""+ Concept.JSON_ID +"\":\"1234\"," + "\"" + Concept.JSON_PREFERRED_TERM + "\":\"term string\"" + "}"; Concept input = new Concept.Builder("1234", "term string") .build(); //Call ObjectMapper mapper = new ObjectMapper(); final String actual = mapper.writeValueAsString(input); //Evaluate assertEquals(expected,actual); } }
module.exports = pdf = {} var fs = require('fs') var Prince = require("prince") pdf.generate = function(htmlPath, pdfPath, success, error, license) { var prince = Prince() if (license) { prince = prince.license(license) } prince .inputs(htmlPath) .output(pdfPath) .execute() .then(function() { fs.readFile(pdfPath, function(err, pdfContent) { if (err) { error(err) } else { success(pdfContent) } }) }, function(err) { error(err) }) }
export VPC_ID="vpc-deadbeef" export SUBNET_ID="subnet-bad1dea5" export AZ="us-east-9z" export TEMPLATE_ID="lt-abcd0123"
#!/usr/bin/env bash # # 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. # apt-get -y update apt-get -y install curl cd /tmp curl -LO https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh bash /tmp/script.deb.sh apt-get -y install gitlab-ce cp /etc/gitlab/gitlab.rb /etc/gitlab/gitlab.rb.bak export PUBLIC_IP_ADDRESS=$(dig +short myip.opendns.com @resolver1.opendns.com) sed "s,external_url 'http://gitlab.example.com',external_url 'http://$PUBLIC_IP_ADDRESS',g" /etc/gitlab/gitlab.rb >> /etc/gitlab/gitlab.rb.tmp rm -f /etc/gitlab/gitlab.rb mv /etc/gitlab/gitlab.rb.tmp /etc/gitlab/gitlab.rb gitlab-ctl reconfigure
#!/bin/bash # simple script to automate the steps involved in running tests # prerequisites: chmod u+x run-tests.sh clear cd .. echo "==================" echo "CALLING [test_one] in 1 second..." echo "==================" sleep 1 python -m dimschema.tests.test_one sleep 2 clear echo "" echo "==================" echo "Completed." echo "=================="
#!/bin/bash USER_PATH=/mnt/ethereum MODULE_PATH=$USER_PATH/bitcore/packages NODE_PATH=$USER_PATH/.nvm/versions/node/v10.5.0/bin LOG_PATH=$USER_PATH/bitcore/logs cd $MODULE_PATH/bitcore-wallet-service mkdir -p pids # run_program (nodefile, pidfile, logfile) run_program () { nodefile=$1 pidfile=$2 logfile=$3 if [ -e "$pidfile" ] then echo "$nodefile is already running. Run 'npm stop' if you wish to restart." return 0 fi nohup $NODE_PATH/node $nodefile >> $logfile 2>&1 & PID=$! if [ $? -eq 0 ] then echo "Successfully started $nodefile. PID=$PID. Logs are at $logfile" echo $PID > $pidfile return 0 else echo "Could not start $nodefile - check logs at $logfile" exit 1 fi } ./stop_bws.sh pids/fiatrateservice.pid run_program ./ts_build/fiatrateservice/fiatrateservice.js pids/fiatrateservice.pid $LOG_PATH/fiatrateservice.log
<reponame>Bilallbayrakdar/blas // Go implementation of BLAS (Basic Linear Algebra Subprograms) package blas
<filename>7-assets/past-student-repos/LambdaSchool-master/m4/41b1/index.js<gh_stars>0 const express = require('express'); const Hubs = require('./hubs/hubs-model.js'); const server = express(); server.use(express.json()); server.get('/', (req, res) => { res.send(` <h2>Lambda Hubs API</h> <p>Welcome to the Lambda Hubs API</p> `); }); server.get('/api/hubs', (req, res) => { Hubs.find(req.query) .then(hubs => { res.status(200).json(hubs); }) .catch(error => { // log error to database console.log(error); res.status(500).json({ message: 'Error retrieving the hubs', }); }); }); server.get('/api/hubs/:id', (req, res) => { Hubs.findById(req.params.id) .then(hub => { if (hub) { res.status(200).json(hub); } else { res.status(404).json({ message: 'Hub not found' }); } }) .catch(error => { // log error to database console.log(error); res.status(500).json({ message: 'Error retrieving the hub', }); }); }); server.post('/api/hubs', (req, res) => { Hubs.add(req.body) .then(hub => { res.status(201).json(hub); }) .catch(error => { // log error to database console.log(error); res.status(500).json({ message: 'Error adding the hub', }); }); }); server.delete('/api/hubs/:id', (req, res) => { Hubs.remove(req.params.id) .then(count => { if (count > 0) { res.status(200).json({ message: 'The hub has been nuked' }); } else { res.status(404).json({ message: 'The hub could not be found' }); } }) .catch(error => { // log error to database console.log(error); res.status(500).json({ message: 'Error removing the hub', }); }); }); server.put('/api/hubs/:id', (req, res) => { const changes = req.body; Hubs.update(req.params.id, changes) .then(hub => { if (hub) { res.status(200).json(hub); } else { res.status(404).json({ message: 'The hub could not be found' }); } }) .catch(error => { // log error to database console.log(error); res.status(500).json({ message: 'Error updating the hub', }); }); }); // add an endpoint that returns all the messages for a hub // add an endpoint for adding new message to a hub server.listen(4000, () => { console.log('\n*** Server Running on http://localhost:4000 ***\n'); });
<filename>traveldb/abstract/out_d_statistik.sql /*D************************************************************/ /* Default: Aktion STATISTIK OUT_D_statistik */ /* Company: Demo */ /* */ /* Copyright: yafra.org, Switzerland */ /**************************************************************/ delete from root.aktionstexte where typ = 1011 and s_id = 1; insert into root.aktionstexte values (1, 1, 1, 'Seite', 1011); commit work; insert into root.aktionstexte values (2, 1, 1, 'Total', 1011); commit work; insert into root.aktionstexte values (3, 1, 1, 'Kategorie', 1011); commit work; insert into root.aktionstexte values (4, 1, 1, 'Kapazit�t', 1011); commit work; insert into root.aktionstexte values (5, 1, 1, 'lp -onb -oc -olandscape',1011); commit work; insert into root.aktionstexte values (6, 1, 1, 'Buchungen', 1011); commit work; insert into root.aktionstexte values (7, 1, 1, '%', 1011); commit work; insert into root.aktionstexte values (8, 1, 1, 'Optionen', 1011); commit work; insert into root.aktionstexte values (9, 1, 1, '%', 1011); commit work; insert into root.aktionstexte values (10, 1, 1, 'Einkauf', 1011); commit work; insert into root.aktionstexte values (11, 1, 1, 'Umsatz', 1011); commit work; insert into root.aktionstexte values (12, 1, 1, 'Reduktion', 1011); commit work; insert into root.aktionstexte values (13, 1, 1, 'Marge in %', 1011); commit work; insert into root.aktionstexte values (14, 1, 1, 'Marge', 1011); commit work; insert into root.aktionstexte values (15, 1, 1, 'S T A T I S T I K', 1011); commit work; insert into root.aktionstexte values (16, 1, 1, '-----------------', 1011); commit work; insert into root.aktionstexte values (17, 1, 1, 'Buchungen %', 1011); commit work; insert into root.aktionstexte values (18, 1, 1, 'Optionen %', 1011); commit work; insert into root.aktionstexte values (19, 1, 1, 'ohne Kategorie', 1011); commit work;
import graphviz from sklearn import tree # Create a Decision Tree model # ... # Visualize the model dot_data = tree.export_graphviz(model, out_file=None) graph = graphviz.Source(dot_data) graph.render('decision-tree.pdf')
#!/bin/bash status=`/usr/local/bin/etcdctl get /k8s/network/config/` if [ status -ne 0 ];then /usr/local/bin/etcdctl --endpoint=http://192.168.10.247:2379 mk /k8s/network/config '{"Network":"10.211.200.0/16", "SubnetLen":24, "Backend":{"Type":"vxlan"}}' && /usr/local/bin/etcdctl --endpoint=http://192.168.10.247:2379 mkdir /k8s/network else exit 0 fi
<reponame>ss-au/xoces //index.js import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import _ from 'lodash' import './styles/foundation.min.css' import './styles/core.scss' import reducer from './reducers' import {setConfig, setConfigTree} from './reducers/setConfig' import XocesWidget from './widgets/XocesWidget'; import ChordWidget from './widgets/ChordWidget'; import TreeWidget from './widgets/TreeWidget'; import graphProvider from './components/graph' let store = createStore(reducer) module.exports = { config: (config) => { }, widgets: { XocesWidget: { new: (config) => { let uid = _.uniqueId('xoces_widget_'); return { render(arg) { let container = _getContainer(arg.container); let props = _.assign({}, config, arg, { __widgetType: 'XocesWidget' }); store.dispatch(setConfig(props)) ReactDOM.render( <Provider store={store}> <XocesWidget {...props}/> </Provider>, container, arg.callback ) } } } }, ChordWidget: { new: (config) => { let uid = _.uniqueId('xoces_chord_widget_'); return { render(arg) { let container = _getContainer(arg.container); let props = _.assign({}, config, arg, { __widgetType: 'ChordWidget' }); store.dispatch(setConfig(props)) ReactDOM.render( <Provider store={store}> <ChordWidget {...props}/> </Provider>, container, arg.callback ) } } } }, TreeWidget: { new: (config) => { let uid = _.uniqueId('xoces_tree_widget_'); return { render(arg) { let container = _getContainer(arg.container); let props = _.assign({}, config, arg, { __widgetType: 'TreeWidget' }); store.dispatch(setConfigTree(props)) ReactDOM.render( <Provider store={store}> <TreeWidget {...props}/> </Provider>, container, arg.callback ) } } } } }, libs: { graphProvider }, } function _getContainer(container) { if (_.isString(container)) { return document.getElementById(container); } else if (container) { return container; } return container = document.body; }
# Copyright (c) 2014, 2016 Oracle and/or its affiliates. All rights reserved. This # code is released under a tri EPL/GPL/LGPL license. You can use it, # redistribute it and/or modify it under the terms of the: # # Eclipse Public License version 1.0 # GNU General Public License version 2 # GNU Lesser General Public License version 2.1 class Time def to_f seconds + nsec * 0.000000001 # Truffle: optimized end def localtime(offset = nil) if offset localtime_internal Rubinius::Type.coerce_to_utc_offset(offset) else localtime_internal end self end def +(other) raise TypeError, 'time + time?' if other.kind_of?(Time) case other = Rubinius::Type.coerce_to_exact_num(other) when Integer other_sec = other other_nsec = 0 else other_sec, nsec_frac = other.divmod(1) other_nsec = (nsec_frac * 1_000_000_000).to_i end # Don't use self.class, MRI doesn't honor subclasses here dup_internal(Time).add_internal! other_sec, other_nsec end def -(other) if other.kind_of?(Time) return (seconds - other.seconds) + ((nsec - other.nsec) * 0.000000001) end case other = Rubinius::Type.coerce_to_exact_num(other) when Integer other_sec = other other_nsec = 0 else other_sec, nsec_frac = other.divmod(1) other_nsec = (nsec_frac * 1_000_000_000 + 0.5).to_i end # Don't use self.class, MRI doesn't honor subclasses here dup_internal(Time).add_internal! -other_sec, -other_nsec end def round(places = 0) return dup if nsec == 0 roundable_time = (to_i + subsec.to_r).round(places) sec = roundable_time.floor nano = ((roundable_time - sec) * 1_000_000_000).floor dup_internal(Time).add_internal! sec - seconds, nano - nsec end def dup dup_internal self.class end def self.duplicate(other) other.dup end end
var myLocation; var map, placesService, directionsService; var Status = { OK: "", LOADING: "busy", WARNING: "warn" }; function setStatus(message, classname) { document.getElementById("status").className = "title " + classname; document.getElementById("status").innerHTML = message; } function init () { map = new google.maps.Map(document.getElementById("map-canvas"), { center: new google.maps.LatLng(0, 0), zoom: 15, disableDefaultUI: true, styles: [ { "featureType": "administrative", "elementType": "geometry", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "stylers": [ { "saturation": -75 } ] } ] }); placesService = new google.maps.places.PlacesService(map); directionsService = new google.maps.DirectionsService(map); locateMe(); } function locateMe() { setStatus("Locating you...", Status.LOADING); navigator.geolocation.getCurrentPosition(function (position) { foundMe(position.coords.latitude, position.coords.longitude); }, function (err) { setStatus("Unable to locate you", Status.WARNING); }); } function foundMe(lat, lng) { myLocation = new google.maps.LatLng(lat, lng); var searchRequest = { location: myLocation, rankBy: google.maps.places.RankBy.DISTANCE, types: ["cafe"], keyword: "espresso", openNow: true }; setStatus("Finding coffee...", Status.LOADING); placesService.nearbySearch(searchRequest, foundCoffee); } function foundCoffee(results, status) { if (status !== google.maps.places.PlacesServiceStatus.OK) { return setStatus("No coffee found nearby", Status.WARNING); } var bounds = new google.maps.LatLngBounds(myLocation); for (var i = 0; i < results.length; i++) { addMarker(results[i]); if (i < 3) bounds.extend(results[i].geometry.location); } map.fitBounds(bounds); google.maps.event.addListenerOnce(map, "idle", function () { document.getElementById("map-canvas").style.marginTop = "0"; }); searchRoute(results[0]); } function addMarker(cafe) { var cafeMarker = new google.maps.Marker({ position: cafe.geometry.location, map: map }); google.maps.event.addListener(cafeMarker, "click", function () { searchRoute(cafe); }); } function searchRoute(destination) { setStatus("Navigating...", Status.LOADING); var routeRequest = { origin: myLocation, destination: destination.geometry.location, travelMode: google.maps.TravelMode.WALKING }; directionsService.route(routeRequest, function (result, status) { foundRoute(destination.name, result, status) }); } function foundRoute(cafeName, result, status) { if (status !== google.maps.DirectionsStatus.OK) { return setStatus("No route found to " + cafeName, Status.WARNING); } var route = result.routes[0].legs[0]; var eta = Math.floor(route.duration.value / 60); var list = route.steps.map(function(step) { var icon = step.maneuver ? "<div class='adp-maneuver adp-" + step.maneuver + "'>&nbsp;</div>" : ""; var dist = "<i>" + Math.round(step.distance.value / 50) * 50 + " m</i>"; return icon + step.instructions + " " + dist; }); list.push("☕ omnomnom"); setStatus("<i>" + eta + " minutes</i>" + cafeName, Status.OK); document.getElementById("instructions").innerHTML = "<ul><li>" + list.join("</li><li>") + "</li></ul>"; } google.maps.event.addDomListener(window, "load", init);
import Configuration from 'Configuration'; import StringUtils from 'utils/StringUtils'; import URLUtils from 'utils/URLUtils'; import ArgumentError from 'errors/ArgumentError'; /** * Utility functions involving the API */ export default class ParliamentAPIUtils { private static readonly BASE_API_URL = Configuration.apiUrl; private static readonly BASE_VIEW_URL = Configuration.baseUrl; /** * Get the url to build the api path * @param relativePath */ public static getAPIURL(relativePath: string): string { if (StringUtils.isNullOrEmpty(relativePath)) { throw new ArgumentError('relativePath', relativePath, 'Value can not be null or empty'); } return URLUtils.buildURL(this.BASE_API_URL, relativePath); } /** * Get the url to view the path on openparliament.ca * @param relativePath */ public static getViewURL(relativePath: string): string { if (StringUtils.isNullOrEmpty(relativePath)) { throw new ArgumentError('relativePath', relativePath, 'Value can not be null or empty'); } return URLUtils.buildURL(this.BASE_VIEW_URL, relativePath); } }
<reponame>JackWFinlay/data-structures-ts export class AbstractNode<T> { constructor(private _value: T = null) {} public get value(): T { return this._value; } public set value(value: T){ this._value = value; } }
/* * Copyright (C) 2016 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.functional.membersinject; import dagger.Lazy; import dagger.MembersInjector; import javax.inject.Provider; // https://github.com/google/dagger/issues/419 @SuppressWarnings({"rawtypes", "unused"}) class RawFrameworkTypes { void nonInjectMethodWithARawProvider(Provider rawProvider) {} void nonInjectMethodWithARawLazy(Lazy rawLazy) {} void nonInjectMethodWithARawMembersInjector(MembersInjector rawMembersInjector) {} }
<filename>lib/ftp4j-1.7.2/src/it/sauronsoftware/ftp4j/connectors/SOCKS4Connector.java /* * ftp4j - A pure Java FTP client library * * Copyright (C) 2008-2010 <NAME> (www.sauronsoftware.it) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version * 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License 2.1 for more details. * * You should have received a copy of the GNU Lesser General Public * License version 2.1 along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package it.sauronsoftware.ftp4j.connectors; import it.sauronsoftware.ftp4j.FTPConnector; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; /** * This one connects a remote ftp host through a SOCKS4/4a proxy server. * * The connector's default value for the * <em>useSuggestedAddressForDataConnections</em> flag is <em>false</em>. * * @author <NAME> */ public class SOCKS4Connector extends FTPConnector { /** * The socks4 proxy host name. */ private String socks4host; /** * The socks4 proxy port. */ private int socks4port; /** * The socks4 proxy user (optional). */ private String socks4user; /** * It builds the connector. * * @param socks4host * The socks4 proxy host name. * @param socks4port * The socks4 proxy port. * @param socks4user * The socks4 proxy user (optional, can be set to null). */ public SOCKS4Connector(String socks4host, int socks4port, String socks4user) { this.socks4host = socks4host; this.socks4port = socks4port; this.socks4user = socks4user; } /** * It builds the connector. * * @param socks4host * The socks4 proxy host name. * @param socks4port * The socks4 proxy port. */ public SOCKS4Connector(String socks4host, int socks4port) { this(socks4host, socks4port, null); } private Socket socksConnect(String host, int port, boolean forDataTransfer) throws IOException { // Socks 4 or 4a? boolean socks4a = false; byte[] address; try { address = InetAddress.getByName(host).getAddress(); } catch (Exception e) { // Cannot resolve host, switch to version 4a. socks4a = true; address = new byte[] { 0x00, 0x00, 0x00, 0x01 }; } // A connection status flag. boolean connected = false; // The socket for the connection with the proxy. Socket socket = null; InputStream in = null; OutputStream out = null; // FTPConnection routine. try { if (forDataTransfer) { socket = tcpConnectForDataTransferChannel(socks4host, socks4port); } else { socket = tcpConnectForCommunicationChannel(socks4host, socks4port); } in = socket.getInputStream(); out = socket.getOutputStream(); // Send the request. // Version 4. out.write(0x04); // CONNECT method. out.write(0x01); // Remote port number. out.write(port >> 8); out.write(port); // Remote host address. out.write(address); // The user. if (socks4user != null) { out.write(socks4user.getBytes("UTF-8")); } // End of user. out.write(0x00); // Version 4a? if (socks4a) { out.write(host.getBytes("UTF-8")); out.write(0x00); } // Get and parse the response. int aux = read(in); if (aux != 0x00) { throw new IOException("SOCKS4Connector: invalid proxy response"); } aux = read(in); switch (aux) { case 0x5a: in.skip(6); connected = true; break; case 0x5b: throw new IOException( "SOCKS4Connector: connection refused/failed"); case 0x5c: throw new IOException( "SOCKS4Connector: cannot validate the user"); case 0x5d: throw new IOException("SOCKS4Connector: invalid user"); default: throw new IOException("SOCKS4Connector: invalid proxy response"); } } catch (IOException e) { throw e; } finally { if (!connected) { if (out != null) { try { out.close(); } catch (Throwable t) { ; } } if (in != null) { try { in.close(); } catch (Throwable t) { ; } } if (socket != null) { try { socket.close(); } catch (Throwable t) { ; } } } } return socket; } private int read(InputStream in) throws IOException { int aux = in.read(); if (aux < 0) { throw new IOException( "SOCKS4Connector: connection closed by the proxy"); } return aux; } public Socket connectForCommunicationChannel(String host, int port) throws IOException { return socksConnect(host, port, false); } public Socket connectForDataTransferChannel(String host, int port) throws IOException { return socksConnect(host, port, true); } }
# Aliases alias gst='git status' compdef _git gst=git-status alias gl='git pull' compdef _git gl=git-pull alias gup='git fetch && git rebase' compdef _git gup=git-fetch alias gp='git push' compdef _git gp=git-push gdv() { git diff -w "$@" | view - } compdef _git gdv=git-diff alias gc='git commit -v' compdef _git gc=git-commit alias gca='git commit -v -a' compdef _git gca=git-commit alias gco='git checkout' compdef _git gco=git-checkout alias gcm='git checkout master' alias gb='git branch' compdef _git gb=git-branch alias gba='git branch -a' compdef _git gba=git-branch alias gcount='git shortlog -sn' compdef gcount=git alias gcp='git cherry-pick' compdef _git gcp=git-cherry-pick alias glg='git log --stat --max-count=5' compdef _git glg=git-log alias glgg='git log --graph --max-count=5' compdef _git glgg=git-log alias gss='git status -s' compdef _git gss=git-status alias ga='git add' compdef _git ga=git-add alias gm='git merge' compdef _git gm=git-merge alias grh='git reset HEAD' alias grhh='git reset HEAD --hard' # Git and svn mix alias git-svn-dcommit-push='git svn dcommit && git push github master:svntrunk' compdef git-svn-dcommit-push=git alias gsr='git svn rebase' alias gsd='git svn dcommit' # # Will return the current branch name # Usage example: git pull origin $(current_branch) # function current_branch() { ref=$(git symbolic-ref HEAD 2> /dev/null) || return echo ${ref#refs/heads/} } # these aliases take advantage of the previous function alias ggpull='git pull origin $(current_branch)' compdef ggpull=git alias ggpush='git push origin $(current_branch)' compdef ggpush=git alias ggpnp='git pull origin $(current_branch) && git push origin $(current_branch)' compdef ggpnp=git
<reponame>mirzak/gui import parse from 'parse-link-header'; import * as DeploymentConstants from '../constants/deploymentConstants'; import DeploymentsApi from '../api/deployments-api'; import { startTimeSort } from '../helpers'; const apiUrl = '/api/management/v1'; const deploymentsApiUrl = `${apiUrl}/deployments`; // default per page until pagination and counting integrated const default_per_page = 20; const default_page = 1; const transformDeployments = (deployments, deploymentsById) => deployments.sort(startTimeSort).reduce( (accu, item) => { accu.deployments[item.id] = { ...deploymentsById[item.id], ...item }; accu.deploymentIds.push(item.id); return accu; }, { deployments: {}, deploymentIds: [] } ); /*Deployments */ // all deployments export const getDeployments = (page = default_page, per_page = default_per_page) => (dispatch, getState) => DeploymentsApi.get(`${deploymentsApiUrl}/deployments?page=${page}&per_page=${per_page}`).then(res => { const deploymentsByStatus = res.body.reduce( (accu, item) => { accu[item.status].push(item); return accu; }, { finished: [], inprogress: [], pending: [] } ); return Promise.all( Object.entries(deploymentsByStatus).map(([status, value]) => { const { deployments, deploymentIds } = transformDeployments(value, getState().deployments.byId); return dispatch({ type: DeploymentConstants[`RECEIVE_${status.toUpperCase()}_DEPLOYMENTS`], deployments, deploymentIds }); }) ); }); export const getDeploymentsByStatus = (status, page = default_page, per_page = default_per_page, startDate, endDate, group) => (dispatch, getState) => { var created_after = startDate ? `&created_after=${startDate}` : ''; var created_before = endDate ? `&created_before=${endDate}` : ''; var search = group ? `&search=${group}` : ''; return DeploymentsApi.get( `${deploymentsApiUrl}/deployments?status=${status}&per_page=${per_page}&page=${page}${created_after}${created_before}${search}` ).then(res => { const { deployments, deploymentIds } = transformDeployments(res.body, getState().deployments.byId); let tasks = [ dispatch({ type: DeploymentConstants[`RECEIVE_${status.toUpperCase()}_DEPLOYMENTS`], deployments, deploymentIds, status }), dispatch({ type: DeploymentConstants[`SELECT_${status.toUpperCase()}_DEPLOYMENTS`], deploymentIds, status }) ]; tasks.push(...deploymentIds.map(deploymentId => dispatch(getSingleDeploymentStats(deploymentId)))); return Promise.all(tasks); }); }; export const getDeploymentCount = (status, startDate, endDate, group) => (dispatch, getState) => { var created_after = startDate ? `&created_after=${startDate}` : ''; var created_before = endDate ? `&created_before=${endDate}` : ''; var search = group ? `&search=${group}` : ''; const DeploymentCount = (page = 1, per_page = 500, deployments = []) => DeploymentsApi.get(`${deploymentsApiUrl}/deployments?status=${status}&per_page=${per_page}&page=${page}${created_after}${created_before}${search}`).then( res => { var links = parse(res.headers['link']); deployments.push(...res.body); if (links.next) { page++; return DeploymentCount(page, per_page, deployments); } return Promise.resolve(deployments); } ); return DeploymentCount().then(deploymentList => { const { deployments, deploymentIds } = transformDeployments(deploymentList, getState().deployments.byId); return dispatch({ type: DeploymentConstants[`RECEIVE_${status.toUpperCase()}_DEPLOYMENTS_COUNT`], deployments, deploymentIds, status }); }); }; export const createDeployment = newDeployment => dispatch => DeploymentsApi.post(`${deploymentsApiUrl}/deployments`, newDeployment).then(data => { const lastslashindex = data.location.lastIndexOf('/'); const deploymentId = data.location.substring(lastslashindex + 1); const deployment = { ...newDeployment, devices: newDeployment.devices.map(id => ({ id, status: 'pending' })) }; return Promise.all([ dispatch({ type: DeploymentConstants.CREATE_DEPLOYMENT, deployment, deploymentId }), dispatch(getSingleDeployment(deploymentId)) ]); }); export const getSingleDeployment = id => dispatch => DeploymentsApi.get(`${deploymentsApiUrl}/deployments/${id}`).then(res => dispatch({ type: DeploymentConstants.RECEIVE_DEPLOYMENT, deployment: res.body }) ); export const getSingleDeploymentStats = id => dispatch => DeploymentsApi.get(`${deploymentsApiUrl}/deployments/${id}/statistics`).then(res => dispatch({ type: DeploymentConstants.RECEIVE_DEPLOYMENT_STATS, stats: res.body, deploymentId: id }) ); export const getSingleDeploymentDevices = id => dispatch => DeploymentsApi.get(`${deploymentsApiUrl}/deployments/${id}/devices`).then(res => { const devices = res.body.reduce((accu, item) => { accu[item.id] = item; return accu; }, {}); return dispatch({ type: DeploymentConstants.RECEIVE_DEPLOYMENT_DEVICES, devices, deploymentId: id }); }); export const getDeviceLog = (deploymentId, deviceId) => (dispatch, getState) => DeploymentsApi.getText(`${deploymentsApiUrl}/deployments/${deploymentId}/devices/${deviceId}/log`).then(log => { const devices = getState().deployments.byId[deploymentId].devices; devices[deviceId].log = log; return dispatch({ type: DeploymentConstants.RECEIVE_DEPLOYMENT_DEVICE_LOG, devices, deploymentId }); }); export const abortDeployment = deploymentId => (dispatch, getState) => DeploymentsApi.put(`${deploymentsApiUrl}/deployments/${deploymentId}/status`, { status: 'aborted' }).then(() => { const state = getState(); let status = 'pending'; let index = state.deployments.byStatus.pending.deploymentIds.findIndex(id => id === deploymentId); if (index < 0) { status = 'inprogress'; index = state.deployments.byStatus.inprogress.deploymentIds.findIndex(id => id === deploymentId); } const deploymentIds = [ ...state.deployments.byStatus[status].deploymentIds.slice(0, index), ...state.deployments.byStatus[status].deploymentIds.slice(index) ]; const deployments = deploymentIds.reduce((accu, id) => { accu[id] = state.deployments.byId[id]; return accu; }, {}); return Promise.all([ dispatch({ type: DeploymentConstants[`RECEIVE_${status.toUpperCase()}_DEPLOYMENTS`], deployments, deploymentIds, status }), dispatch({ type: DeploymentConstants.REMOVE_DEPLOYMENT, deploymentId }) ]); }); export const selectDeployment = deploymentId => dispatch => { let tasks = [ dispatch({ type: DeploymentConstants.SELECT_DEPLOYMENT, deploymentId }) ]; if (deploymentId) { tasks.push(dispatch(getSingleDeployment(deploymentId))); } return Promise.all(tasks); };
<reponame>levsthings/somnolence import React, {PureComponent} from 'react' import {dashboardTitle} from '../../common.styles.js' import {compass, compassSection} from './Compass.styles' const compassProps = { fill: 'none', stroke: '#fff', strokeWidth: 3 } export default class Compass extends PureComponent { render() { return ( <div className={compassSection}> <h1 className={dashboardTitle}>Compass</h1> <svg className={compass} viewBox='0 0 252 252'> <circle style={compassProps} cx='126' cy='126' r='125' /> <rect x='50.95' y='151.27' style={compassProps} width='50' height='50' /> <rect x='50.95' y='101.27' style={compassProps} width='50' height='50' /> <rect x='150.95' y='101.27' style={compassProps} width='50' height='50' /> <rect x='100.95' y='101.27' style={compassProps} width='50' height='50' /> <rect x='150.95' y='51.27' style={compassProps} width='50' height='50' /> </svg> </div> ) } }
### Helpers ### function sr_err { echo \> $'\033[0;31m'$*$'\033[0m' >&2 exit 1 } function sr_call_docker { /usr/bin/env docker > /dev/null 2> /dev/null || sr_err "Please install docker. "$'\n\t'"Ubuntu: https://docs.docker.com/engine/installation/linux/ubuntulinux/"$'\n\t'"Mac: https://docs.docker.com/docker-for-mac/" /usr/bin/env docker ps > /dev/null 2> /dev/null || sr_err "Please start docker." /usr/bin/env docker $@ } ### Built-in commands ### function sr_version { echo "Swifty Robot Environment v$SR_VERSION" if [[ $1 != "short" ]]; then echo # Add swift + libs version in the future fi } function sr_help { cat <<HEREDOC $(sr_version short) Built-in commands: help - Shows this help message self-update - Get the latest version of Swifty Robot Environment pull-image - Pull the docker image required for the current version run - Execute an arbitrary command in the environment shell - Create a temporary container and start a shell Commands: $(sr_command_list) HEREDOC } function sr_self_update { /usr/bin/env curl -s $SR_UPDATE_URL | /usr/bin/env bash -s update $SR_VERSION } function sr_pull_image { sr_call_docker pull $SR_IMAGE } function sr_run { sr_call_docker run -e SR_HOST_FS -e SR_DIR --rm -v /:$SR_HOST_FS -w="$SR_HOST_FS`pwd`" $SR_IMAGE $@ } function sr_shell { sr_call_docker run --rm -v /:$SR_HOST_FS -w="$SR_HOST_FS`pwd`" -ti $SR_IMAGE /bin/bash -l $@ } ### Commands ### function sr_command_desc { # Ugly as hell. This needs to get improved. unset $SR_COMMAND_DESC eval $( cat $SR_DIR/commands/$1 | grep "SR_COMMAND_DESC" | head -n 1 ) if [[ "$SR_COMMAND_DESC" ]]; then echo " - $SR_COMMAND_DESC" else echo fi } function sr_command_list { ls -1 $SR_DIR/commands/ | while read COMMAND; do echo -n $' '$COMMAND sr_command_desc $COMMAND done } function sr_has_command { [[ -f $SR_DIR/commands/$1 ]] } function sr_run_command { sr_run "$SR_HOST_FS$SR_DIR/commands/$1" ${@:2} }
<reponame>coding-new-talking/taste-spring<filename>src/main/java/org/cnt/nots/asm/_ClassVisitor.java package org.cnt.nots.asm; import java.util.Arrays; import org.springframework.asm.AnnotationVisitor; import org.springframework.asm.ClassVisitor; import org.springframework.asm.FieldVisitor; import org.springframework.asm.MethodVisitor; import org.springframework.asm.Opcodes; import org.springframework.asm.TypePath; /** * @author lixinjie * @since 2019-07-18 */ public class _ClassVisitor extends ClassVisitor { private int version; public _ClassVisitor() { super(Opcodes.ASM7); this.version = _AsmMain.getCvVersion(); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { log("---ClassVisitor-visit---"); log("version", version); log("access", access); log("name", name); log("signature", signature); log("superName", superName); log("interfaces", Arrays.toString(interfaces)); } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { log("---ClassVisitor-visitAnnotation---"); log("descriptor", descriptor); log("visible", visible); return new _AnnotationVisitor(); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String descriptor, boolean visible) { log("---ClassVisitor-visitTypeAnnotation---"); log("typeRef", typeRef); log("typePath", typePath); log("descriptor", descriptor); log("visible", visible); return new _AnnotationVisitor(); } @Override public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { log("---ClassVisitor-visitField---"); log("access", access); log("name", name); log("descriptor", descriptor); log("signature", signature); log("value", value); return new _FieldVisitor(); } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { log("---ClassVisitor-visitMethod---"); log("access", access); log("name", name); log("descriptor", descriptor); log("signature", signature); log("exceptions", Arrays.toString(exceptions)); return new _MethodVisitor(); } @Override public void visitEnd() { log("---ClassVisitor-visitEnd---"); } void log(String key, Object value) { System.out.println(key + " = " + value); } void log(String str) { System.out.println(str + version + "--"); } }
#!/bin/bash # Copyright 2016 Crunchy Data Solutions, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. kubectl delete service master-1 kubectl delete service slave-1 kubectl delete pod master-1 kubectl delete pod slave-1 $BUILDBASE/examples/waitforterm.sh master-1 kubectl $BUILDBASE/examples/waitforterm.sh slave-1 kubectl
#!/bin/bash region="default" name="test-cluster" request_body=$(cat<<EOF { "name": "test-cluster", "namespace": "default", "region": "default", "clusterType": "kubernetes", "masterList": [ { "ip": "192.168.1.10" }, { "ip": "192.168.1.11" } ], "nodeList": [ { "ip": "192.168.1.12" }, { "ip": "192.168.1.12" } ], "etcdList": [ { "ip": "192.168.1.12" }, { "ip": "192.168.1.12" } ], "kubeconfig": "", "success": true, "message": "" } EOF ) curl -s -XPOST -d "${request_body}" \ http://127.0.0.1:8080/api/v1/region/${region}/cluster/${name}/create/callback
package todolist import ( "regexp" "time" ) type DateFilter struct { Todos []*Todo Location *time.Location } func NewDateFilter(todos []*Todo) *DateFilter { return &DateFilter{Todos: todos, Location: time.Now().Location()} } func filterOnDue(todo *Todo) string { return todo.Due } func filterOnCompletedDate(todo *Todo) string { return todo.CompletedDateToDate() } func (f *DateFilter) FilterDate(input string) []*Todo { agendaRegex, _ := regexp.Compile(`agenda.*$`) if agendaRegex.MatchString(input) { return f.filterAgenda(bod(time.Now())) } // filter due items r, _ := regexp.Compile(`due .*$`) match := r.FindString(input) switch { case match == "due tod" || match == "due today": return f.filterDueToday(bod(time.Now())) case match == "due tom" || match == "due tomorrow": return f.filterDueTomorrow(bod(time.Now())) case match == "due sun" || match == "due sunday": return f.filterDay(bod(time.Now()), time.Sunday) case match == "due mon" || match == "due monday": return f.filterDay(bod(time.Now()), time.Monday) case match == "due tue" || match == "due tuesday": return f.filterDay(bod(time.Now()), time.Tuesday) case match == "due wed" || match == "due wednesday": return f.filterDay(bod(time.Now()), time.Wednesday) case match == "due thu" || match == "due thursday": return f.filterDay(bod(time.Now()), time.Thursday) case match == "due fri" || match == "due friday": return f.filterDay(bod(time.Now()), time.Friday) case match == "due sat" || match == "due saturday": return f.filterDay(bod(time.Now()), time.Saturday) case match == "due this week": return f.filterThisWeek(bod(time.Now())) case match == "due next week": return f.filterNextWeek(bod(time.Now())) case match == "due last week": return f.filterLastWeek(bod(time.Now())) case match == "overdue": return f.filterOverdue(bod(time.Now())) } // filter completed items r, _ = regexp.Compile(`completed .*$`) match = r.FindString(input) switch { case match == "completed tod" || match == "completed today": return f.filterCompletedToday(bod(time.Now())) case match == "completed this week": return f.filterCompletedThisWeek(bod(time.Now())) } return f.Todos } func (f *DateFilter) filterAgenda(pivot time.Time) []*Todo { var ret []*Todo for _, todo := range f.Todos { if todo.Due == "" || todo.Completed { continue } dueTime, _ := time.ParseInLocation("2006-01-02", todo.Due, f.Location) if dueTime.Before(pivot) || todo.Due == pivot.Format("2006-01-02") { ret = append(ret, todo) } } return ret } func (f *DateFilter) filterToExactDate(pivot time.Time, filterOn func(*Todo) string) []*Todo { var ret []*Todo for _, todo := range f.Todos { if filterOn(todo) == pivot.Format("2006-01-02") { ret = append(ret, todo) } } return ret } func (f *DateFilter) filterDueToday(pivot time.Time) []*Todo { return f.filterToExactDate(pivot, filterOnDue) } func (f *DateFilter) filterDueTomorrow(pivot time.Time) []*Todo { pivot = pivot.AddDate(0, 0, 1) return f.filterToExactDate(pivot, filterOnDue) } func (f *DateFilter) filterCompletedToday(pivot time.Time) []*Todo { return f.filterToExactDate(pivot, filterOnCompletedDate) } func (f *DateFilter) filterDay(pivot time.Time, day time.Weekday) []*Todo { thisWeek := NewDateFilter(f.filterThisWeek(pivot)) pivot = f.FindSunday(pivot).AddDate(0, 0, int(day)) return thisWeek.filterToExactDate(pivot, filterOnDue) } func (f *DateFilter) filterBetweenDatesInclusive(begin, end time.Time, filterOn func(*Todo) string) []*Todo { var ret []*Todo for _, todo := range f.Todos { dueTime, _ := time.ParseInLocation("2006-01-02", filterOn(todo), f.Location) if (begin.Before(dueTime) || begin.Equal(dueTime)) && end.After(dueTime) { ret = append(ret, todo) } } return ret } func (f *DateFilter) filterThisWeek(pivot time.Time) []*Todo { begin := bod(f.FindSunday(pivot)) end := begin.AddDate(0, 0, 7) return f.filterBetweenDatesInclusive(begin, end, filterOnDue) } func (f *DateFilter) filterCompletedThisWeek(pivot time.Time) []*Todo { begin := bod(f.FindSunday(pivot)) end := begin.AddDate(0, 0, 7) return f.filterBetweenDatesInclusive(begin, end, filterOnCompletedDate) } func (f *DateFilter) filterBetweenDatesExclusive(begin, end time.Time) []*Todo { var ret []*Todo for _, todo := range f.Todos { dueTime, _ := time.ParseInLocation("2006-01-02", todo.Due, f.Location) if begin.Before(dueTime) && end.After(dueTime) { ret = append(ret, todo) } } return ret } func (f *DateFilter) filterNextWeek(pivot time.Time) []*Todo { begin := f.FindSunday(pivot).AddDate(0, 0, 7) end := begin.AddDate(0, 0, 7) return f.filterBetweenDatesExclusive(begin, end) } func (f *DateFilter) filterLastWeek(pivot time.Time) []*Todo { begin := f.FindSunday(pivot).AddDate(0, 0, -7) end := begin.AddDate(0, 0, 7) return f.filterBetweenDatesExclusive(begin, end) } func (f *DateFilter) filterOverdue(pivot time.Time) []*Todo { var ret []*Todo pivotDate := pivot.Format("2006-01-02") for _, todo := range f.Todos { dueTime, _ := time.ParseInLocation("2006-01-02", todo.Due, f.Location) if dueTime.Before(pivot) && pivotDate != todo.Due { ret = append(ret, todo) } } return ret } func (f *DateFilter) FindSunday(pivot time.Time) time.Time { switch pivot.Weekday() { case time.Sunday: return pivot case time.Monday: return pivot.AddDate(0, 0, -1) case time.Tuesday: return pivot.AddDate(0, 0, -2) case time.Wednesday: return pivot.AddDate(0, 0, -3) case time.Thursday: return pivot.AddDate(0, 0, -4) case time.Friday: return pivot.AddDate(0, 0, -5) case time.Saturday: return pivot.AddDate(0, 0, -6) } return pivot }
# Create the states state0 = { 'name': 'state0', 'message': 'Hello! How can I help you?', 'replies': {'I need some advice': 'state1', 'Can you answer my questions?': 'state2'} } state1 = { 'name': 'state1', 'message': 'Sure, what kind of advice do you need?', 'replies': {'Career advice': 'state3','Health advice': 'state4'} } state2 = { 'name': 'state2', 'message': 'Yes, I'll do my best! What do you want to know?', 'replies': {'Where can I find good tutorials': 'state5', 'Why is coding so hard': 'state6'} } state3 = { 'name': 'state3', 'message': 'It is always a good idea to research the field you are interested in and creating a plan to learn the skills that are required. Make sure to contact professionals in the field to understand their experience.', 'replies': {} } state4 = { 'name': 'state4', 'message': 'Focus on eating healthy and staying active. Make sure to consult a medical professional if you have any concerns.', 'replies': {} } state5 = { 'name': 'state5', 'message': 'You can find tutorials online or join coding communities to get help from experienced coders. StackOverflow and Cod Academy are great resources.', 'replies': {} } state6 = { 'name': 'state6', 'message': 'Coding can be challenging, especially at first. Just remember that with practice, patience and problem solving skills you can overcome the obstacles.', 'replies': {} } # Initialize the state current_state = state0 # Keep a record of conversation conversation = [] while True: # Print the current state message print(current_state['message']) conversation.append(current_state['message']) # Get the user input user_input = input('>> ') conversation.append(user_input) # Update the state if user_input in current_state['replies']: current_state = eval(current_state['replies'][user_input]) else: print("I don't understand what you mean. Please try again.") # End the conversation when the state is terminal if not bool(current_state['replies']): print('Goodbye!') break print("=========================") print("Conversation:") for message in conversation: print(message)
def validate_profile(profile): for attr, value in profile.items(): if not (all(x >= 0 for x in value.opt) and all(x >= 0 for x in value.max)): return False if not all(opt <= max for opt, max in zip(value.opt, value.max)): return False return True
export interface Tile { id: string; cols: number; rows: number; } export const CardsColsSize = 2;
<reponame>jrfaller/maracas package main.unused.interfaceAdded; public class InterfaceAdded implements IInterfaceAdded { @Override public int methodAbs() { return 0; } }
# shellcheck shell=bash # run-shellcheck test_audit() { describe Running on blank host register_test retvalshouldbe 0 dismiss_count_for_test # shellcheck disable=2154 run blank /opt/debian-cis/bin/hardening/"${script}".sh --audit-all local test_user="testcrontabduser" describe Tests purposely failing touch /etc/cron.deny /etc/at.deny register_test retvalshouldbe 1 register_test contain "/etc/cron.deny exists" register_test contain "/etc/at.deny exists" run noncompliant /opt/debian-cis/bin/hardening/"${script}".sh --audit-all describe correcting situation sed -i 's/audit/enabled/' /opt/debian-cis/etc/conf.d/"${script}".cfg /opt/debian-cis/bin/hardening/"${script}".sh --apply || true touch /etc/cron.allow /etc/at.allow describe Tests purposely failing useradd "$test_user" chown "$test_user":"$test_user" /etc/cron.allow chown "$test_user":"$test_user" /etc/at.allow register_test retvalshouldbe 1 register_test contain "/etc/cron.allow ownership was not set to" register_test contain "/etc/at.allow ownership was not set to" run noncompliant /opt/debian-cis/bin/hardening/"${script}".sh --audit-all userdel "$test_user" describe correcting situation sed -i 's/audit/enabled/' /opt/debian-cis/etc/conf.d/"${script}".cfg /opt/debian-cis/bin/hardening/"${script}".sh --apply || true describe Tests purposely failing useradd "$test_user" chmod 777 /etc/cron.allow chmod 777 /etc/at.allow register_test retvalshouldbe 1 register_test contain "/etc/cron.allow permissions were not set to" register_test contain "/etc/at.allow permissions were not set to" run noncompliant /opt/debian-cis/bin/hardening/"${script}".sh --audit-all userdel "$test_user" describe correcting situation sed -i 's/audit/enabled/' /opt/debian-cis/etc/conf.d/"${script}".cfg /opt/debian-cis/bin/hardening/"${script}".sh --apply || true describe Checking resolved state register_test retvalshouldbe 0 register_test contain "/etc/cron.allow has correct permissions" register_test contain "/etc/cron.allow has correct ownership" register_test contain "/etc/at.allow has correct permissions" register_test contain "/etc/at.allow has correct ownership" run resolved /opt/debian-cis/bin/hardening/"${script}".sh --audit-all }
class BankAccount: def __init__(self, account_holder): self.account_holder = account_holder self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: print("Insufficient funds") else: self.balance -= amount def get_balance(self): return self.balance def display_info(self): print(f"Account Holder: {self.account_holder}") print(f"Balance: {self.balance}")
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class ProblemTest { @Test void testExampleFromProblem() { // Since solution is probabilistic test many times! for (int i = 0; 1_000 > i; ++i) { assertEquals(3141, (int)(Problem.estimatePi() * 1000)); } } }
export default [ { name: '<NAME>', stationId: 'home', userId: 'hsdgHZY233 ', time: '2:17:06 pm', }, { name: "<NAME>", stationId: 'tulipHQ', userId: 'hsdgHZY233 ', time: '2:15:06 pm', }, { name: "<NAME>", stationId: 'tulipHQ', userId: 'hsdgHZY233 ', time: '2:13:06 pm', }, { name: "<NAME>", stationId: 'tulipHQ', userId: 'hsdgHZY233 ', time: '2:12:06 pm', }, { name: "<NAME>", stationId: 'tulipHQ', userId: 'hsdgHZY233 ', time: '2:07:06 pm', }, { name: "<NAME>", stationId: 'tulipHQ', userId: 'hsdgHZY233 ', time: '2:00:06 pm', }, ];
<reponame>1aurabrown/ervell import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Cookies from 'cookies-js'; import HeaderMetadataLinkUnlessCurrent from 'react/components/UI/HeaderMetadata/HeaderMetadataLinkUnlessCurrent'; export default class ProfileLinkUnlessCurrent extends Component { static propTypes = { name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, } setCookie = () => { const { name, value } = this.props; Cookies.set(name, value); } render() { const { name: _name, value: _value, ...rest } = this.props; return ( <HeaderMetadataLinkUnlessCurrent {...rest} onClick={this.setCookie} /> ); } }
#!/bin/sh checkerror() { if test $? -ne 0 then echo "failure: ${cmd}" exit 1 fi } if test $# -eq 0 then echo "Usage: $0 <matchfile>" exit 1 fi # VALGRIND=valgrind.sh matchfile=$1 chainopts="-local 10b" cmd="${VALGRIND} ./chain2dim.x ${chainopts} -silent ${matchfile}" ${cmd} > .tmp1 checkerror cmd="Vmatchtrans.pl open ${matchfile}" ${cmd} > .shit checkerror cmd="${VALGRIND} ./chain2dim.x ${chainopts} -silent .shit" ${cmd} > .tmp2 checkerror cmd="cmp -s .tmp1 .tmp2" ${cmd} checkerror cmd="./vmatchselect.x -sort sa ${matchfile}" ${cmd} > .shit checkerror if test -f ./chain2dim.dbg.x then cmd="${VALGRIND} ./chain2dim.dbg.x ${chainopts} -silent .shit" ${cmd} > /dev/null checkerror fi cmd="${VALGRIND} ./chain2dim.x ${chainopts} -silent .shit" ${cmd} > /dev/null checkerror rm -f .tmp[12] .shit
<reponame>Montimage/mmt-probe /* * dpdk_malloc.c * * Created on: Aug 23, 2018 * by: <NAME> */ #include <stdlib.h> #include <string.h> #include "dpdk_malloc.h"
import { Element } from '../../../../../client/element' export interface Props { value?: string } export default class _Text extends Element<any, Props> { private _text_el: Text constructor($props: Props) { super($props) let { value = '' } = $props const text_node = document.createTextNode(value) this._text_el = text_node this.$element = text_node } onPropChanged(prop: string, current: any): void { if (prop === 'value') { this._text_el.nodeValue = current || '' } } focus(options: FocusOptions | undefined = { preventScroll: true }) { // NOOP } blur() { // NOOP } }
package pkg import ( "github.com/123shang60/zk" "k8s.io/klog/v2" "strings" "time" ) type ZooKeeper struct { *zk.Conn } type KerberosConfig struct { Keytab []byte Krb5 string PrincipalStr string } func AutoConnZk(quorum string, conf *KerberosConfig) (*ZooKeeper, error) { host := strings.Split(quorum, ",") connect, _, err := func() (*zk.Conn, <-chan zk.Event, error) { if conf == nil { return zk.Connect(host, 30*time.Second) } else { return zk.Connect(host, 30*time.Second, zk.WithSASLConfig(&zk.SASLConfig{ Enable: true, KerberosConfig: &zk.KerberosConfig{ Keytab: conf.Keytab, Krb5: conf.Krb5, PrincipalStr: conf.PrincipalStr, ServiceName: "zookeeper", }, })) } }() if err != nil { klog.Error("zk 连接失败!", err) return nil, err } return &ZooKeeper{ connect, }, nil } // AutoDelete 删除指定路径下全部数据 func (zoo *ZooKeeper) AutoDelete(path string) error { path = strings.TrimRight(path, "/") klog.Infof("准备删除zk 路径: %s", path) _, _, err := zoo.Get(path) if err != nil { klog.Error("zk 路径检查失败!,停止zk删除流程", err) return err } if err := zoo.deletePath(path); err != nil { klog.Error("zk 递归删除失败!", err) return err } klog.Infof("zk 路径删除成功!%s", path) return nil } func (zoo *ZooKeeper) deletePath(path string) error { childs, _, err := zoo.Children(path) if err != nil { return err } for _, child := range childs { err := zoo.deletePath(path + "/" + child) if err != nil { return err } } _, stat, err := zoo.Get(path) if err != nil { return err } err = zoo.Delete(path, stat.Version) return err }
#!/bin/sh curl http://$DOCKER_HOST_IP:8083/customer
#!/bin/bash tag="" docker_run_mode="-it" IMAGE="lgsm-test" container="lgsm-test" run_image=(docker run) while [ $# -ge 1 ]; do key="$1" shift case "$key" in -h|--help) echo "[help][run] run.sh [option] [args]" echo "[help][run] " echo "[help][run] options:" echo "[help][run] -c --container x container name default=lgsm-test" echo "[help][run] -d --debug set entrypoint to bash" echo "[help][run] --detach run in background instead of foreground" echo "[help][run] -i --image x target image, default=lgsm-test" echo "[help][run] --tag x \"lgsm\" run lgsm image or \"specific\" run last created $IMAGE:$tag" echo "[help][run] --quick enforce quick monitoring" echo "[help][run] -v --volume x use volume x" echo "[help][run] " echo "[help][run] args:" echo "[help][run] x every other argument is added to docker run ... [args] IMAGE" exit 0;; -c|--container) container="$1" shift;; -d|--debug) run_image+=(--entrypoint "bash");; --detach) docker_run_mode="-dt";; -i|--image) IMAGE="$key";; -t|--tag) tag="$1" shift;; --quick) run_image+=(--health-interval=10s --health-start-period=60s);; -v|--volume) run_image+=(-v "$1:/home/linuxgsm") shift;; *) if [ -n "$key" ]; then echo "[info][run] additional argument to docker: $key" run_image+=("$key") fi ;; esac done run_image+=("$docker_run_mode" --name "$container" "$IMAGE:$tag") if [ -z "$tag" ]; then echo "please provide the tag to execute as first argument lgsm or specific" exit 1 fi echo "${run_image[@]}" "${run_image[@]}"
<reponame>oueya1479/OpenOLAT /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.course.assessment.model; import static org.olat.course.assessment.AssessmentHelper.KEY_ATTEMPTS; import static org.olat.course.assessment.AssessmentHelper.KEY_DETAILS; import static org.olat.course.assessment.AssessmentHelper.KEY_IDENTIFYER; import static org.olat.course.assessment.AssessmentHelper.KEY_INDENT; import static org.olat.course.assessment.AssessmentHelper.KEY_LAST_COACH_MODIFIED; import static org.olat.course.assessment.AssessmentHelper.KEY_LAST_USER_MODIFIED; import static org.olat.course.assessment.AssessmentHelper.KEY_MAX; import static org.olat.course.assessment.AssessmentHelper.KEY_MIN; import static org.olat.course.assessment.AssessmentHelper.KEY_PASSED; import static org.olat.course.assessment.AssessmentHelper.KEY_SCORE; import static org.olat.course.assessment.AssessmentHelper.KEY_SCORE_F; import static org.olat.course.assessment.AssessmentHelper.KEY_SELECTABLE; import static org.olat.course.assessment.AssessmentHelper.KEY_TITLE_LONG; import static org.olat.course.assessment.AssessmentHelper.KEY_TITLE_SHORT; import static org.olat.course.assessment.AssessmentHelper.KEY_TYPE; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.olat.core.gui.components.form.flexible.FormItem; import org.olat.core.util.StringHelper; import org.olat.course.assessment.AssessmentHelper; import org.olat.course.assessment.IndentedNodeRenderer.IndentedCourseNode; import org.olat.course.nodes.CourseNode; import org.olat.modules.assessment.model.AssessmentEntryStatus; /** * * Initial date: 23.10.2015<br> * @author srosse, <EMAIL>, http://www.frentix.com * */ public class AssessmentNodeData implements IndentedCourseNode { private int recursionLevel; private String ident; private String type; private String shortTitle; private String longTitle; private String details; private Integer attempts; private Float score; private String roundedScore; private boolean ignoreInCourseAssessment; private FormItem scoreDesc; private Float maxScore; private Float minScore; private Boolean passed; private Boolean passedOverriden; private Boolean userVisibility; private AssessmentEntryStatus assessmentStatus; private int numOfAssessmentDocs; private Date lastModified; private Date lastUserModified; private Date lastCoachModified; private boolean selectable; private boolean onyx = false; public AssessmentNodeData() { // } public AssessmentNodeData(Map<String,Object> data) { fromMap(data); } public AssessmentNodeData(int indent, CourseNode courseNode) { this(indent, courseNode.getIdent(), courseNode.getType(), courseNode.getShortTitle(), courseNode.getLongTitle()); } public AssessmentNodeData(int recursionLevel, String ident, String type, String shortTitle, String longTitle) { this.recursionLevel = recursionLevel; this.ident = ident; this.type = type; this.shortTitle = shortTitle; this.longTitle = longTitle; } public String getIdent() { return ident; } public void setIdent(String ident) { this.ident = ident; } @Override public int getRecursionLevel() { return recursionLevel; } public void setRecursionLevel(int recursionLevel) { this.recursionLevel = recursionLevel; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getShortTitle() { return shortTitle; } public void setShortTitle(String shortTitle) { this.shortTitle = shortTitle; } @Override public String getLongTitle() { return longTitle; } public void setLongTitle(String longTitle) { this.longTitle = longTitle; } public Integer getAttempts() { return attempts; } public void setAttempts(Integer attempts) { this.attempts = attempts; } public Boolean getUserVisibility() { return userVisibility; } public void setUserVisibility(Boolean userVisibility) { this.userVisibility = userVisibility; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } public String getRoundedScore() { return roundedScore; } public void setRoundedScore(String roundedScore) { this.roundedScore = roundedScore; } public boolean isIgnoreInCourseAssessment() { return ignoreInCourseAssessment; } public void setIgnoreInCourseAssessment(boolean ignoreInCourseAssessment) { this.ignoreInCourseAssessment = ignoreInCourseAssessment; } public FormItem getScoreDesc() { return scoreDesc; } public void setScoreDesc(FormItem scoreDesc) { this.scoreDesc = scoreDesc; } public Float getMaxScore() { return maxScore; } public void setMaxScore(Float maxScore) { this.maxScore = maxScore; } public Float getMinScore() { return minScore; } public void setMinScore(Float minScore) { this.minScore = minScore; } public Boolean getPassed() { return passed; } public void setPassed(Boolean passed) { this.passed = passed; } public Boolean getPassedOverriden() { return passedOverriden; } public void setPassedOverriden(Boolean passedOverriden) { this.passedOverriden = passedOverriden; } public AssessmentEntryStatus getAssessmentStatus() { return assessmentStatus; } public void setAssessmentStatus(AssessmentEntryStatus assessmentStatus) { this.assessmentStatus = assessmentStatus; } public int getNumOfAssessmentDocs() { return numOfAssessmentDocs; } public void setNumOfAssessmentDocs(int numOfAssessmentDocs) { this.numOfAssessmentDocs = numOfAssessmentDocs; } public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public Date getLastUserModified() { return lastUserModified; } public void setLastUserModified(Date lastUserModified) { this.lastUserModified = lastUserModified; } public Date getLastCoachModified() { return lastCoachModified; } public void setLastCoachModified(Date lastCoachModified) { this.lastCoachModified = lastCoachModified; } public boolean isOnyx() { return onyx; } public void setOnyx(boolean onyx) { this.onyx = onyx; } public boolean isSelectable() { return selectable; } public void setSelectable(boolean selectable) { this.selectable = selectable; } public Map<String,Object> toMap() { Map<String,Object> nodeData = new HashMap<>(); nodeData.put(KEY_INDENT, Integer.valueOf(recursionLevel)); nodeData.put(KEY_TYPE, getType()); nodeData.put(KEY_TITLE_SHORT, getShortTitle()); nodeData.put(KEY_TITLE_LONG, getLongTitle()); nodeData.put(KEY_IDENTIFYER, getIdent()); if(details != null) { nodeData.put(KEY_DETAILS, details); } if(attempts != null) { nodeData.put(KEY_ATTEMPTS, attempts); } if(score != null) { nodeData.put(KEY_SCORE, roundedScore); nodeData.put(KEY_SCORE_F, score); } if(maxScore != null) { nodeData.put(KEY_MAX, maxScore); } if(minScore != null) { nodeData.put(KEY_MIN, minScore); } if (passed != null) { nodeData.put(KEY_PASSED, passed); } if(lastUserModified != null) { nodeData.put(KEY_LAST_USER_MODIFIED, lastUserModified); } if(lastCoachModified != null) { nodeData.put(KEY_LAST_COACH_MODIFIED, lastCoachModified); } nodeData.put(KEY_SELECTABLE, selectable ? Boolean.TRUE : Boolean.FALSE); return nodeData; } private void fromMap(Map<String,Object> nodeData) { if(nodeData.get(KEY_INDENT) instanceof Integer) { recursionLevel = ((Integer)nodeData.get(KEY_INDENT)).intValue(); } type = (String)nodeData.get(KEY_TYPE); shortTitle = (String)nodeData.get(KEY_TITLE_SHORT); longTitle = (String)nodeData.get(KEY_TITLE_LONG); ident = (String)nodeData.get(KEY_IDENTIFYER); details = (String)nodeData.get(KEY_DETAILS); attempts = (Integer)nodeData.get(KEY_ATTEMPTS); score = (Float)nodeData.get(KEY_SCORE_F); roundedScore = (String)nodeData.get(KEY_SCORE); maxScore = (Float)nodeData.get(KEY_MAX); minScore = (Float)nodeData.get(KEY_MIN); passed = (Boolean)nodeData.get(KEY_PASSED); if(nodeData.get(KEY_SELECTABLE) instanceof Boolean) { selectable = ((Boolean)nodeData.get(KEY_SELECTABLE)).booleanValue(); } if(nodeData.get(KEY_LAST_USER_MODIFIED) instanceof Date) { lastUserModified = ((Date)nodeData.get(KEY_LAST_USER_MODIFIED)); } if(nodeData.get(KEY_LAST_COACH_MODIFIED) instanceof Date) { lastCoachModified = ((Date)nodeData.get(KEY_LAST_COACH_MODIFIED)); } } @Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append("data[title=").append(StringHelper.containsNonWhitespace(longTitle) ? longTitle : (shortTitle == null ? "" : shortTitle)) .append(":score=").append(score == null ? "" : AssessmentHelper.getRoundedScore(score)) .append(":passed=").append(passed == null ? "" : passed.toString()) .append("]"); return sb.toString(); } }
StartTest(function (t) { setTimeout(function () { var Grid = new Ext.grid.Panel({ width : 300, height : 200, renderTo : Ext.getBody(), columns : [ { text : 'foo', flex : 1 } ], store : new Ext.data.Store({ fields : ['id', 'name'], data : [{ id : 1, name : 'foo' }] }) }); }, 2000); t.chain( { waitForComponentQuery : 'grid' }, function (next, result) { // Do some stuff next(); }, { click : '>>gridcolumn' } ) });