text
stringlengths 3
1.05M
|
---|
import React, { Component } from 'react';
import { BrowserRouter, Redirect, Switch, Route } from 'react-router-dom';
import {
CUSTOMERS_URI_PATTERN,
CUSTOMER_URI_PATTERN,
QUOTATIONS_URI_PATTERN,
QUOTATION_URI_PATTERN,
SIGN_IN_URI_PATTERN,
} from './routes';
import PrivateRoute from './containers/privateRoute';
import SignIn from './containers/signIn';
import SignOut from './containers/signOut';
import CustomersContainer from './containers/customersContainer';
import CustomerEditContainer from './containers/customerEditContainer';
import QuotationsContainer from './containers/quotationsContainer';
import QuotationContainer from './containers/quotationContainer';
import Header from './components/header';
import { Footer } from './components/footer';
export default class App extends Component {
render() {
return (
<BrowserRouter>
<div style={{position: 'relative', minHeight: '100%'}}>
<Header>
<SignOut />
</Header>
<div className="container" style={{paddingBottom: '50px'}}>
<Switch>
<PrivateRoute
path={CUSTOMERS_URI_PATTERN}
exact
component={CustomersContainer}
/>
<PrivateRoute
path={CUSTOMER_URI_PATTERN}
exact
component={CustomerEditContainer}
/>
<PrivateRoute
path={QUOTATIONS_URI_PATTERN}
exact
component={QuotationsContainer}
/>
<PrivateRoute
path={QUOTATION_URI_PATTERN}
component={QuotationContainer}
/>
<Route
path={SIGN_IN_URI_PATTERN}
exact
component={SignIn}
/>
<Redirect from="/" to={CUSTOMERS_URI_PATTERN} />
</Switch>
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
|
VAR=1
REF=2
PAIR=3
CONST=4
# unnamed variable
def var() :
v=[None]
v[0]=v
return v
# named variable
def nvar(name):
v=[None,name]
v[0]=v
return v
# return type of data object
def type_of(x) :
if isinstance(x,list) :
return VAR+(not x is x[0]) # VAR or REF
elif isinstance(x,tuple) :
return PAIR
else:
return CONST
# finding the reference of a variable
def deref(x) :
while True :
t=type_of(x)
if t==REF:
x=x[0]
else:
return x,t
# return term with all vars in it dereferenced
def iron(a,size=200) :
def iron0(a, k):
if k <= 0: return ".?."
x, t = deref(a)
if t == PAIR:
u, v = x
k -= 1
return iron0(u, k), iron0(v, k)
else:
return x
return iron0(a,size)
def to_pterm(x) :
x,t=deref(x)
if VAR==t : return x
elif CONST==t : return x
else :
assert PAIR==t
a, b = x
args=[None,to_pterm(a)]
while True:
b, t = deref(b)
if PAIR == t :
a,b=b
args.append(to_pterm(a))
else :
args[0]=to_pterm(b)
return list(args)
# converts a "."/2 lists to actual lists
def dot2list(a):
def is_dot_list(a):
return isinstance(a,list) and len(a)>0 and '.'==a[0]
def walk(x) :
if is_dot_list(x) :
args=[]
while is_dot_list(x) :
e=dot2list(x[1])
args.append(e)
y=x
x=x[2]
if x=='[]' :
return args
else :
y=(y[0],dot2list(y[1]),dot2list(y[2]))
args.append(y)
return args
elif VAR==type_of(x) :
return x
elif isinstance(x,tuple) or isinstance(x,list) :
return tuple(map(dot2list,x))
else :
return x
return walk(a)
# turn term int more readable string
def pt(a,size=200) :
def pt0(a, k):
if k <= 0: return ".?."
x, t = deref(a)
if t == PAIR:
u, v = x
k -= 1
return f'({pt0(u, k)}=>{pt0(v, k)})'
elif t == VAR:
if len(x) == 2:
return str(x[1])
else:
return "_" + str(id(x))
else:
return str(x)
return pt0(a,size)
# undo bindings on the trail
def unwind(trail,ttop) :
#print('UNWIND',pt(trail[-1]),':',len(trail),'-',ttop)
for _ in range(len(trail)-ttop):
v = trail.pop()
v[0] = v
# unify two terms
def unify(x,y,trail) :
ustack=[]
ustack.append(y)
ustack.append(x)
while ustack :
x1,t1=deref(ustack.pop())
x2,t2=deref(ustack.pop())
if x1 is x2:
pass
elif VAR==t1 :
x1[0]=x2
trail.append(x1)
elif VAR==t2:
x2[0]=x1
trail.append(x2)
elif t1!=t2 :
return False
elif t1==CONST:
if x1!=x2 :
return False
else :
#assert t1 == PAIR and len(x1)==2
#assert t2 == PAIR and len(x2)==2
a1,b1=x1
a2,b2=x2
ustack.append(b2)
ustack.append(b1)
ustack.append(a2)
ustack.append(a1)
return True
# load from an "assembler" code file
def tload(fname='out/tnf_asm.txt'):
def to_const(x) :
try :
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x
with open(fname,'r') as f: txt=f.read()
ls = txt.split('\n')
code = []
vars=dict()
cs=[]
for l in ls:
xs=l.split(' ')
if len(xs)<=1 :continue # skip extra new lines
for j,x in enumerate(xs) :
if x[0].isupper():
if x in vars:
v=vars[x]
else:
v=[len(vars),x]
vars[x]=v
xs[j]=v
elif x[0]=="_":
v = [len(vars), x]
vars[x] = v
xs[j] = v
elif x=='[|]':
xs[j]='.'
else :
xs[j] = to_const(x)
cs.append(xs)
if xs[0]=='p' :
code.append(cs)
vars=dict() # new vars scoped over next clause
cs=[]
return code
# creates actual variables from code skeletons
def activate(instr,vars) :
newinstr=[]
for c in instr :
if isinstance(c,list): # a variable
n=c[0]
if n<len(vars) :
d=vars[n]
else:
d=nvar(c[1])
vars.append(d)
else: # const
d=c
newinstr.append(d)
return newinstr
# builds goal assuming goal(X):- ... is
# a clause in the source program
def get_goal(code) :
r= (nvar('Answer'),('true','goal'))
return r
FAIL, DONE, DO, UNDO = 0, 1, 2, 3
def step(G, i, code, trail):
ttop = len(trail)
while i < len(code):
unwind(trail, ttop)
clause = code[i]
i += 1 # next clause
vars = []
for instr in clause:
c = activate(instr, vars)
op = c[0]
if op == 'u' or op == 'b':
r = unify((c[1], c[2]), c[3], trail)
if not r:
break
elif op == 'd':
assert VAR == type_of(c[1])
c[1][0] = G
trail.append(c[1])
else: # op==p
NewG, tg = deref(c[1])
if NewG == 'true' and CONST == tg:
return (DONE, G, ttop, i)
else:
assert PAIR == tg
return (DO, NewG, G, ttop, i)
return (FAIL,)
# code interpreter
def interp(code,goal) :
l=len(code)
todo=[(DO,goal,None,0,None)]
trail=[]
while todo :
instr=todo.pop()
op=instr[0]
if DO==op :
_,NewG,G,ttop,i=instr
r=step(NewG,0,code,trail)
todo.append((UNDO,G,ttop,i))
todo.append(r)
elif DONE==op:
_, G, ttop, i = instr
todo.append((UNDO,G,ttop,i))
yield iron(goal)
elif UNDO==op :
_, G, ttop, i=instr
unwind(trail,ttop)
if i!=None and i<l :
todo.append(step(G,i,code,trail))
else : #FAIL == op:
pass
# tests
def go() :
code=tload()
ctr=0
max_ctr=1000000
for g in interp(code,get_goal(code)):
answer=iron(g[0])
ctr+=1
answer=to_pterm(answer)
print('ANSWER:',dot2list(answer))
if ctr>=max_ctr :
print('TOO MANY ANSWERS?')
break
print('TOTAL ANSWERS:',ctr)
# tests unification
def utest() :
X=var()
Y=var()
a=(X,'a')
b=('b',Y)
print('AB',a,type_of(a),b,type_of(b))
trail=[]
r=unify(a,b,trail)
print(r)
print('FINAL AB',a,type_of(a),b,type_of(b))
print('TR',trail)
print("PT",pt((a,(nvar("X"),var()))))
# tests conversion to Horn form
def ptest():
A = nvar('A')
B = nvar('B')
print(to_pterm((((A, (A, 'b')), 'a'), (B, 'c'))))
print(to_pterm(((1, 'g'), (2, (3, 'f')))))
go()
|
import { UnavailabilityError } from '@unimodules/core';
import { PermissionStatus, createPermissionHook, } from 'expo-modules-core';
import { Platform } from 'react-native';
import ExpoBrightness from './ExpoBrightness';
// @needsAudit
export var BrightnessMode;
(function (BrightnessMode) {
/**
* Means that the current brightness mode cannot be determined.
*/
BrightnessMode[BrightnessMode["UNKNOWN"] = 0] = "UNKNOWN";
/**
* Mode in which the device OS will automatically adjust the screen brightness depending on the
* ambient light.
*/
BrightnessMode[BrightnessMode["AUTOMATIC"] = 1] = "AUTOMATIC";
/**
* Mode in which the screen brightness will remain constant and will not be adjusted by the OS.
*/
BrightnessMode[BrightnessMode["MANUAL"] = 2] = "MANUAL";
})(BrightnessMode || (BrightnessMode = {}));
export { PermissionStatus };
/**
* Returns whether the Brightness API is enabled on the current device. This does not check the app
* permissions.
* @return Async `boolean`, indicating whether the Brightness API is available on the current device.
* Currently this resolves `true` on iOS and Android only.
*/
export async function isAvailableAsync() {
return !!ExpoBrightness.getBrightnessAsync;
}
// @needsAudit
/**
* Gets the current brightness level of the device's main screen.
* @return A `Promise` that fulfils with a number between `0` and `1`, inclusive, representing the
* current screen brightness.
*/
export async function getBrightnessAsync() {
if (!ExpoBrightness.getBrightnessAsync) {
throw new UnavailabilityError('expo-brightness', 'getBrightnessAsync');
}
return await ExpoBrightness.getBrightnessAsync();
}
// @needsAudit
/**
* Sets the current screen brightness. On iOS, this setting will persist until the device is locked,
* after which the screen brightness will revert to the user's default setting. On Android, this
* setting only applies to the current activity; it will override the system brightness value
* whenever your app is in the foreground.
* @param brightnessValue A number between `0` and `1`, inclusive, representing the desired screen
* brightness.
* @return A `Promise` that fulfils when the brightness has been successfully set.
*/
export async function setBrightnessAsync(brightnessValue) {
if (!ExpoBrightness.setBrightnessAsync) {
throw new UnavailabilityError('expo-brightness', 'setBrightnessAsync');
}
const clampedBrightnessValue = Math.max(0, Math.min(brightnessValue, 1));
if (isNaN(clampedBrightnessValue)) {
throw new TypeError(`setBrightnessAsync cannot be called with ${brightnessValue}`);
}
return await ExpoBrightness.setBrightnessAsync(clampedBrightnessValue);
}
// @needsAudit
/**
* __Android only.__ Gets the global system screen brightness.
* @return A `Promise` that is resolved with a number between `0` and `1`, inclusive, representing
* the current system screen brightness.
*/
export async function getSystemBrightnessAsync() {
if (Platform.OS !== 'android') {
return await getBrightnessAsync();
}
return await ExpoBrightness.getSystemBrightnessAsync();
}
// @needsAudit
/**
* > __WARNING:__ This method is experimental.
*
* __Android only.__ Sets the global system screen brightness and changes the brightness mode to
* `MANUAL`. Requires `SYSTEM_BRIGHTNESS` permissions.
* @param brightnessValue A number between `0` and `1`, inclusive, representing the desired screen
* brightness.
* @return A `Promise` that fulfils when the brightness has been successfully set.
*/
export async function setSystemBrightnessAsync(brightnessValue) {
const clampedBrightnessValue = Math.max(0, Math.min(brightnessValue, 1));
if (isNaN(clampedBrightnessValue)) {
throw new TypeError(`setSystemBrightnessAsync cannot be called with ${brightnessValue}`);
}
if (Platform.OS !== 'android') {
return await setBrightnessAsync(clampedBrightnessValue);
}
return await ExpoBrightness.setSystemBrightnessAsync(clampedBrightnessValue);
}
// @needsAudit
/**
* __Android only.__ Resets the brightness setting of the current activity to use the system-wide
* brightness value rather than overriding it.
* @return A `Promise` that fulfils when the setting has been successfully changed.
*/
export async function useSystemBrightnessAsync() {
if (Platform.OS !== 'android') {
return;
}
// eslint-disable-next-line react-hooks/rules-of-hooks
return await ExpoBrightness.useSystemBrightnessAsync();
}
// @needsAudit
/**
* __Android only.__ Returns a boolean specifying whether or not the current activity is using the
* system-wide brightness value.
* @return A `Promise` that fulfils with `true` when the current activity is using the system-wide
* brightness value, and `false` otherwise.
*/
export async function isUsingSystemBrightnessAsync() {
if (Platform.OS !== 'android') {
return false;
}
return await ExpoBrightness.isUsingSystemBrightnessAsync();
}
// @needsAudit
/**
* __Android only.__ Gets the system brightness mode (e.g. whether or not the OS will automatically
* adjust the screen brightness depending on ambient light).
* @return A `Promise` that fulfils with a [`BrightnessMode`](#brightnessmode). Requires
* `SYSTEM_BRIGHTNESS` permissions.
*/
export async function getSystemBrightnessModeAsync() {
if (Platform.OS !== 'android') {
return BrightnessMode.UNKNOWN;
}
return await ExpoBrightness.getSystemBrightnessModeAsync();
}
// @needsAudit
/**
* __Android only.__ Sets the system brightness mode.
* @param brightnessMode One of `BrightnessMode.MANUAL` or `BrightnessMode.AUTOMATIC`. The system
* brightness mode cannot be set to `BrightnessMode.UNKNOWN`.
*/
export async function setSystemBrightnessModeAsync(brightnessMode) {
if (Platform.OS !== 'android' || brightnessMode === BrightnessMode.UNKNOWN) {
return;
}
return await ExpoBrightness.setSystemBrightnessModeAsync(brightnessMode);
}
// @needsAudit
/**
* Checks user's permissions for accessing system brightness.
* @return A promise that fulfils with an object of type [PermissionResponse](#permissionrespons).
*/
export async function getPermissionsAsync() {
return ExpoBrightness.getPermissionsAsync();
}
// @needsAudit
/**
* Asks the user to grant permissions for accessing system brightness.
* @return A promise that fulfils with an object of type [PermissionResponse](#permissionrespons).
*/
export async function requestPermissionsAsync() {
return ExpoBrightness.requestPermissionsAsync();
}
// @needsAudit
/**
* Check or request permissions to modify the system brightness.
* This uses both `requestPermissionAsync` and `getPermissionsAsync` to interact with the permissions.
*
* @example
* ```ts
* const [status, requestPermission] = Brightness.usePermissions();
* ```
*/
export const usePermissions = createPermissionHook({
getMethod: getPermissionsAsync,
requestMethod: requestPermissionsAsync,
});
//# sourceMappingURL=Brightness.js.map |
(function() {
'use strict';
angular.module('app', [
'app.core',
'app.home',
'app.dashboard'
]);
})();
|
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {BookendShareWidget} from './bookend-share';
import {createElementWithAttributes, escapeHtml} from '../../../src/dom';
import {dev} from '../../../src/log';
/**
* @typedef {{
* shareProviders: (!JsonObject|undefined),
* relatedArticles: !Array<!./related-articles.RelatedArticleSet>
* }}
*/
export let BookendConfig;
/**
* @param {!./related-articles.RelatedArticle} articleData
* @return {!string}
*/
// TODO(alanorozco): link
// TODO(alanorozco): reading time
// TODO(alanorozco): domain name
function articleHtml(articleData) {
// TODO(alanorozco): Consider using amp-img and what we need to get it working
const imgHtml = articleData.image ? (
`<div class="i-amphtml-story-bookend-article-image">
<img src="${articleData.image}"
width="116"
height="116">
</img>
</div>`
) : '';
return (
`${imgHtml}
<h2 class="i-amphtml-story-bookend-article-heading">
${articleData.title}
</h2>
<div class="i-amphtml-story-bookend-article-meta">
example.com - 10 mins
</div>`
);
}
/**
* Bookend component for <amp-story>.
*/
export class Bookend {
/**
* @param {!Window} win
*/
constructor(win) {
/** @private {!Window} */
this.win_ = win;
/** @private {boolean} */
this.isBuilt_ = false;
/** @private {?Element} */
this.root_ = null;
/** @private {!BookendShareWidget} */
this.shareWidget_ = BookendShareWidget.create(win);
}
/**
* @return {!Element}
*/
build() {
if (this.isBuilt_) {
return this.getRoot();
}
this.isBuilt_ = true;
this.root_ = this.win_.document.createElement('section');
this.root_.classList.add('i-amphtml-story-bookend');
this.root_.appendChild(this.shareWidget_.build());
return this.getRoot();
}
/**
* @retun {boolean}
*/
isBuilt() {
return this.isBuilt_;
}
/** @private */
assertBuilt_() {
dev().assert(this.isBuilt(), 'Bookend component needs to be built.');
}
/**
* @param {!BookendConfig} bookendConfig
*/
setConfig(bookendConfig) {
this.assertBuilt_();
if (bookendConfig.shareProviders) {
this.shareWidget_.setProviders(
dev().assert(bookendConfig.shareProviders));
}
this.setRelatedArticles_(bookendConfig.relatedArticles);
}
/**
* @param {!Array<!./related-articles.RelatedArticleSet>} articleSets
* @private
*/
setRelatedArticles_(articleSets) {
const fragment = this.win_.document.createDocumentFragment();
articleSets.forEach(articleSet =>
fragment.appendChild(this.buildArticleSet_(articleSet)));
this.getRoot().appendChild(fragment);
}
/**
* @param {!./related-articles.RelatedArticleSet} articleSet
* @return {!DocumentFragment}
*/
// TODO(alanorozco): typing and format
buildArticleSet_(articleSet) {
const fragment = this.win_.document.createDocumentFragment();
if (articleSet.heading) {
fragment.appendChild(
this.buildArticleSetHeading_(articleSet.heading));
}
fragment.appendChild(this.buildArticleList_(articleSet.articles));
return fragment;
}
/**
* @param {!Array<!./related-articles.RelatedArticle>} articleList
* @return {!Element}
* @private
*/
buildArticleList_(articleList) {
const container = createElementWithAttributes(this.win_.document, 'div', {
'class': 'i-amphtml-story-bookend-article-set',
});
articleList.forEach(article =>
container.appendChild(this.buildArticle_(article)));
return container;
}
/**
* @param {!string} heading
* @return {!Element}
*/
buildArticleSetHeading_(heading) {
const headingEl = createElementWithAttributes(this.win_.document, 'h3', {
'class': 'i-amphtml-story-bookend-heading',
});
headingEl.innerText = escapeHtml(heading);
return headingEl;
}
/**
* @param {!./related-articles.RelatedArticle} article
* @return {!Element}
*/
// TODO(alanorozco): typing and format
buildArticle_(article) {
const el = this.win_.document.createElement('article');
el./*OK*/innerHTML = articleHtml(article);
return el;
}
/**
* @return {!Element}
*/
getRoot() {
this.assertBuilt_();
return dev().assertElement(this.root_);
}
}
|
import request from '@/utils/request'
export async function taskVariable(params) {
return request(`/bpm/task/variable`, {
params
})
}
export async function taskHistoric(params) {
return request(`/bpm/task/historic`, {
params
})
}
export async function taskFileQuery(params) {
return request(`/bpm/task/file`, {
params
})
}
export async function taskGoback(params) {
return request(`/bpm/task/goback`, {
method: 'POST',
params
})
}
export async function getDictType(dictType) {
return request(`/sys-dict-entrys/dictType/${dictType}`, {
method: 'GET'
})
}
export async function getUnitCode(unitCode) {
return request(`/business-lines/list/${unitCode}`, {
method: 'GET'
})
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Pradeep Jairamani , github.com/pradeepjairamani
import socket
import socks
import time
import json
import threading
import string
import random
import sys
import struct
import re
import os
from OpenSSL import crypto
import ssl
from core.alert import *
from core.targets import target_type
from core.targets import target_to_host
from core.load_modules import load_file_path
from lib.socks_resolver.engine import getaddrinfo
from core._time import now
from core.log import __log_into_file
import requests
def extra_requirements_dict():
return {
"ome_vuln_ports": [80, 443]
}
def conn(targ, port, timeout_sec, socks_proxy):
try:
if socks_proxy is not None:
socks_version = socks.SOCKS5 if socks_proxy.startswith(
'socks5://') else socks.SOCKS4
socks_proxy = socks_proxy.rsplit('://')[1]
if '@' in socks_proxy:
socks_username = socks_proxy.rsplit(':')[0]
socks_password = socks_proxy.rsplit(':')[1].rsplit('@')[0]
socks.set_default_proxy(socks_version, str(socks_proxy.rsplit('@')[1].rsplit(':')[0]),
int(socks_proxy.rsplit(':')[-1]), username=socks_username,
password=socks_password)
socket.socket = socks.socksocket
socket.getaddrinfo = getaddrinfo
else:
socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]),
int(socks_proxy.rsplit(':')[1]))
socket.socket = socks.socksocket
socket.getaddrinfo = getaddrinfo()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sys.stdout.flush()
s.settimeout(timeout_sec)
s.connect((targ, port))
return s
except Exception as e:
return None
def options_method(target, port, timeout_sec, log_in_file, language, time_sleep,
thread_tmp_filename, socks_proxy, scan_id, scan_cmd):
try:
s = conn(target, port, timeout_sec, socks_proxy)
if not s:
return False
else:
if target_type(target) != "HTTP" and port == 443:
target = 'https://' + target
if target_type(target) != "HTTP" and port == 80:
target = 'http://' + target
req = requests.options(target)
if req.status_code == 200:
try:
global header
header = req.headers['allow']
return True
except:
return False
else:
return False
except Exception as e:
# some error warning
return False
def __options_method(target, port, timeout_sec, log_in_file, language, time_sleep,
thread_tmp_filename, socks_proxy, scan_id, scan_cmd):
if options_method(target, port, timeout_sec, log_in_file, language, time_sleep,
thread_tmp_filename, socks_proxy, scan_id, scan_cmd):
info(messages(language, "target_vulnerable").format(target, port,
'Options Method enabled (Methods Available) - ' + header))
__log_into_file(thread_tmp_filename, 'w', '0', language)
data = json.dumps({'HOST': target, 'USERNAME': '', 'PASSWORD': '', 'PORT': port, 'TYPE': 'options_method_enabled_vuln',
'DESCRIPTION': messages(language, "vulnerable").format(''), 'TIME': now(),
'CATEGORY': "vuln",
'SCAN_ID': scan_id, 'SCAN_CMD': scan_cmd})
__log_into_file(log_in_file, 'a', data, language)
return True
else:
return False
def start(target, users, passwds, ports, timeout_sec, thread_number, num, total, log_in_file, time_sleep, language,
verbose_level, socks_proxy, retries, methods_args, scan_id, scan_cmd): # Main function
if target_type(target) != 'SINGLE_IPv4' or target_type(target) != 'DOMAIN' or target_type(target) != 'HTTP':
# requirements check
new_extra_requirements = extra_requirements_dict()
if methods_args is not None:
for extra_requirement in extra_requirements_dict():
if extra_requirement in methods_args:
new_extra_requirements[
extra_requirement] = methods_args[extra_requirement]
extra_requirements = new_extra_requirements
if ports is None:
ports = extra_requirements["ome_vuln_ports"]
if target_type(target) == 'HTTP':
target = target_to_host(target)
threads = []
total_req = len(ports)
thread_tmp_filename = '{}/tmp/thread_tmp_'.format(load_file_path()) + ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(20))
__log_into_file(thread_tmp_filename, 'w', '1', language)
trying = 0
keyboard_interrupt_flag = False
for port in ports:
port = int(port)
t = threading.Thread(target=__options_method,
args=(target, int(port), timeout_sec, log_in_file, language, time_sleep,
thread_tmp_filename, socks_proxy, scan_id, scan_cmd))
threads.append(t)
t.start()
trying += 1
if verbose_level > 3:
info(
messages(language, "trying_message").format(trying, total_req, num, total, target, port, 'options_method_enabled_vuln'))
while 1:
try:
if threading.activeCount() >= thread_number:
time.sleep(0.01)
else:
break
except KeyboardInterrupt:
keyboard_interrupt_flag = True
break
if keyboard_interrupt_flag:
break
# wait for threads
kill_switch = 0
kill_time = int(
timeout_sec / 0.1) if int(timeout_sec / 0.1) is not 0 else 1
while 1:
time.sleep(0.1)
kill_switch += 1
try:
if threading.activeCount() is 1 or kill_switch is kill_time:
break
except KeyboardInterrupt:
break
thread_write = int(open(thread_tmp_filename).read().rsplit()[0])
if thread_write is 1 and verbose_level is not 0:
info(messages(language, "no_vulnerability_found").format(
'Options method not enabled'))
data = json.dumps({'HOST': target, 'USERNAME': '', 'PASSWORD': '', 'PORT': '', 'TYPE': 'options_method_enabled_vuln',
'DESCRIPTION': messages(language, "no_vulnerability_found").format('Options method not enabled'), 'TIME': now(),
'CATEGORY': "scan", 'SCAN_ID': scan_id, 'SCAN_CMD': scan_cmd})
__log_into_file(log_in_file, 'a', data, language)
os.remove(thread_tmp_filename)
else:
warn(messages(language, "input_target_error").format(
'options_method_vuln', target))
|
/*!
* Jeff Christian Co - Agency v5.0.2 (https://startbootstrap.com/template-overviews/agency)
* Copyright 2013-2018 Jeff Christian Co
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-agency/blob/master/LICENSE)
*/
!function(m){var u=[],t={options:{prependExistingHelpBlock:!1,sniffHtml:!0,preventSubmit:!0,submitError:!1,submitSuccess:!1,semanticallyStrict:!1,autoAdd:{helpBlocks:!0},filter:function(){return!0}},methods:{init:function(a){var v=m.extend(!0,{},t);v.options=m.extend(!0,v.options,a);var e=m.unique(this.map(function(){return m(this).parents("form")[0]}).toArray());return m(e).bind("submit",function(a){var e=m(this),i=0,t=e.find("input,textarea,select").not("[type=submit],[type=image]").filter(v.options.filter);t.trigger("submit.validation").trigger("validationLostFocus.validation"),t.each(function(a,e){var t=m(e).parents(".form-group").first();t.hasClass("warning")&&(t.removeClass("warning").addClass("error"),i++)}),t.trigger("validationLostFocus.validation"),i?(v.options.preventSubmit&&a.preventDefault(),e.addClass("error"),m.isFunction(v.options.submitError)&&v.options.submitError(e,a,t.jqBootstrapValidation("collectErrors",!0))):(e.removeClass("error"),m.isFunction(v.options.submitSuccess)&&v.options.submitSuccess(e,a))}),this.each(function(){var l=m(this),t=l.parents(".form-group").first(),i=t.find(".help-block").first(),r=l.parents("form").first(),n=[];if(!i.length&&v.options.autoAdd&&v.options.autoAdd.helpBlocks&&(i=m('<div class="help-block" />'),t.find(".controls").append(i),u.push(i[0])),v.options.sniffHtml){var a="";if(void 0!==l.attr("pattern")&&(a="Not in the expected format\x3c!-- data-validation-pattern-message to override --\x3e",l.data("validationPatternMessage")&&(a=l.data("validationPatternMessage")),l.data("validationPatternMessage",a),l.data("validationPatternRegex",l.attr("pattern"))),void 0!==l.attr("max")||void 0!==l.attr("aria-valuemax")){var e=void 0!==l.attr("max")?l.attr("max"):l.attr("aria-valuemax");a="Too high: Maximum of '"+e+"'\x3c!-- data-validation-max-message to override --\x3e",l.data("validationMaxMessage")&&(a=l.data("validationMaxMessage")),l.data("validationMaxMessage",a),l.data("validationMaxMax",e)}if(void 0!==l.attr("min")||void 0!==l.attr("aria-valuemin")){var o=void 0!==l.attr("min")?l.attr("min"):l.attr("aria-valuemin");a="Too low: Minimum of '"+o+"'\x3c!-- data-validation-min-message to override --\x3e",l.data("validationMinMessage")&&(a=l.data("validationMinMessage")),l.data("validationMinMessage",a),l.data("validationMinMin",o)}void 0!==l.attr("maxlength")&&(a="Too long: Maximum of '"+l.attr("maxlength")+"' characters\x3c!-- data-validation-maxlength-message to override --\x3e",l.data("validationMaxlengthMessage")&&(a=l.data("validationMaxlengthMessage")),l.data("validationMaxlengthMessage",a),l.data("validationMaxlengthMaxlength",l.attr("maxlength"))),void 0!==l.attr("minlength")&&(a="Too short: Minimum of '"+l.attr("minlength")+"' characters\x3c!-- data-validation-minlength-message to override --\x3e",l.data("validationMinlengthMessage")&&(a=l.data("validationMinlengthMessage")),l.data("validationMinlengthMessage",a),l.data("validationMinlengthMinlength",l.attr("minlength"))),void 0===l.attr("required")&&void 0===l.attr("aria-required")||(a=v.builtInValidators.required.message,l.data("validationRequiredMessage")&&(a=l.data("validationRequiredMessage")),l.data("validationRequiredMessage",a)),void 0!==l.attr("type")&&"number"===l.attr("type").toLowerCase()&&(a=v.builtInValidators.number.message,l.data("validationNumberMessage")&&(a=l.data("validationNumberMessage")),l.data("validationNumberMessage",a)),void 0!==l.attr("type")&&"email"===l.attr("type").toLowerCase()&&(a="Not a valid email address\x3c!-- data-validator-validemail-message to override --\x3e",l.data("validationValidemailMessage")?a=l.data("validationValidemailMessage"):l.data("validationEmailMessage")&&(a=l.data("validationEmailMessage")),l.data("validationValidemailMessage",a)),void 0!==l.attr("minchecked")&&(a="Not enough options checked; Minimum of '"+l.attr("minchecked")+"' required\x3c!-- data-validation-minchecked-message to override --\x3e",l.data("validationMincheckedMessage")&&(a=l.data("validationMincheckedMessage")),l.data("validationMincheckedMessage",a),l.data("validationMincheckedMinchecked",l.attr("minchecked"))),void 0!==l.attr("maxchecked")&&(a="Too many options checked; Maximum of '"+l.attr("maxchecked")+"' required\x3c!-- data-validation-maxchecked-message to override --\x3e",l.data("validationMaxcheckedMessage")&&(a=l.data("validationMaxcheckedMessage")),l.data("validationMaxcheckedMessage",a),l.data("validationMaxcheckedMaxchecked",l.attr("maxchecked")))}void 0!==l.data("validation")&&(n=l.data("validation").split(",")),m.each(l.data(),function(a,e){var t=a.replace(/([A-Z])/g,",$1").split(",");"validation"===t[0]&&t[1]&&n.push(t[1])});for(var s=n,d=[];m.each(n,function(a,e){n[a]=g(e)}),n=m.unique(n),d=[],m.each(s,function(a,e){if(void 0!==l.data("validation"+e+"Shortcut"))m.each(l.data("validation"+e+"Shortcut").split(","),function(a,e){d.push(e)});else if(v.builtInValidators[e.toLowerCase()]){var t=v.builtInValidators[e.toLowerCase()];"shortcut"===t.type.toLowerCase()&&m.each(t.shortcut.split(","),function(a,e){e=g(e),d.push(e),n.push(e)})}}),0<(s=d).length;);var c={};m.each(n,function(a,t){var i=l.data("validation"+t+"Message"),e=void 0!==i,n=!1;if(i=i||"'"+t+"' validation failed \x3c!-- Add attribute 'data-validation-"+t.toLowerCase()+"-message' to input to change this message --\x3e",m.each(v.validatorTypes,function(a,e){void 0===c[a]&&(c[a]=[]),n||void 0===l.data("validation"+t+g(e.name))||(c[a].push(m.extend(!0,{name:g(e.name),message:i},e.init(l,t))),n=!0)}),!n&&v.builtInValidators[t.toLowerCase()]){var o=m.extend(!0,{},v.builtInValidators[t.toLowerCase()]);e&&(o.message=i);var r=o.type.toLowerCase();"shortcut"===r?n=!0:m.each(v.validatorTypes,function(a,e){void 0===c[a]&&(c[a]=[]),n||r!==a.toLowerCase()||(l.data("validation"+t+g(e.name),o[e.name.toLowerCase()]),c[r].push(m.extend(o,e.init(l,t))),n=!0)})}n||m.error("Cannot find validation info for '"+t+"'")}),i.data("original-contents",i.data("original-contents")?i.data("original-contents"):i.html()),i.data("original-role",i.data("original-role")?i.data("original-role"):i.attr("role")),t.data("original-classes",t.data("original-clases")?t.data("original-classes"):t.attr("class")),l.data("original-aria-invalid",l.data("original-aria-invalid")?l.data("original-aria-invalid"):l.attr("aria-invalid")),l.bind("validation.validation",function(a,e){var i=h(l),n=[];return m.each(c,function(t,a){(i||i.length||e&&e.includeEmpty||v.validatorTypes[t].blockSubmit&&e&&e.submitting)&&m.each(a,function(a,e){v.validatorTypes[t].validate(l,i,e)&&n.push(e.message)})}),n}),l.bind("getValidators.validation",function(){return c}),l.bind("submit.validation",function(){return l.triggerHandler("change.validation",{submitting:!0})}),l.bind(["keyup","focus","blur","click","keydown","keypress","change"].join(".validation ")+".validation",function(a,n){var e=h(l),o=[];t.find("input,textarea,select").each(function(a,e){var t=o.length;if(m.each(m(e).triggerHandler("validation.validation",n),function(a,e){o.push(e)}),o.length>t)m(e).attr("aria-invalid","true");else{var i=l.data("original-aria-invalid");m(e).attr("aria-invalid",void 0!==i&&i)}}),r.find("input,select,textarea").not(l).not('[name="'+l.attr("name")+'"]').trigger("validationLostFocus.validation"),(o=m.unique(o.sort())).length?(t.removeClass("success error").addClass("warning"),v.options.semanticallyStrict&&1===o.length?i.html(o[0]+(v.options.prependExistingHelpBlock?i.data("original-contents"):"")):i.html('<ul role="alert"><li>'+o.join("</li><li>")+"</li></ul>"+(v.options.prependExistingHelpBlock?i.data("original-contents"):""))):(t.removeClass("warning error success"),0<e.length&&t.addClass("success"),i.html(i.data("original-contents"))),"blur"===a.type&&t.removeClass("success")}),l.bind("validationLostFocus.validation",function(){t.removeClass("success")})})},destroy:function(){return this.each(function(){var a=m(this),e=a.parents(".form-group").first(),t=e.find(".help-block").first();a.unbind(".validation"),t.html(t.data("original-contents")),e.attr("class",e.data("original-classes")),a.attr("aria-invalid",a.data("original-aria-invalid")),t.attr("role",a.data("original-role")),-1<u.indexOf(t[0])&&t.remove()})},collectErrors:function(a){var o={};return this.each(function(a,e){var t=m(e),i=t.attr("name"),n=t.triggerHandler("validation.validation",{includeEmpty:!0});o[i]=m.extend(!0,n,o[i])}),m.each(o,function(a,e){0===e.length&&delete o[a]}),o},hasErrors:function(){var t=[];return this.each(function(a,e){t=t.concat(m(e).triggerHandler("getValidators.validation")?m(e).triggerHandler("validation.validation",{submitting:!0}):[])}),0<t.length},override:function(a){t=m.extend(!0,t,a)}},validatorTypes:{callback:{name:"callback",init:function(a,e){return{validatorName:e,callback:a.data("validation"+e+"Callback"),lastValue:a.val(),lastValid:!0,lastFinished:!0}},validate:function(a,e,t){if(t.lastValue===e&&t.lastFinished)return!t.lastValid;if(!0===t.lastFinished){t.lastValue=e,t.lastValid=!0,t.lastFinished=!1;var i=t,n=a;!function(a,e){for(var t=Array.prototype.slice.call(arguments).splice(2),i=a.split("."),n=i.pop(),o=0;o<i.length;o++)e=e[i[o]];e[n].apply(this,t)}(t.callback,window,a,e,function(a){i.lastValue===a.value&&(i.lastValid=a.valid,a.message&&(i.message=a.message),i.lastFinished=!0,n.data("validation"+i.validatorName+"Message",i.message),setTimeout(function(){n.trigger("change.validation")},1))})}return!1}},ajax:{name:"ajax",init:function(a,e){return{validatorName:e,url:a.data("validation"+e+"Ajax"),lastValue:a.val(),lastValid:!0,lastFinished:!0}},validate:function(e,a,t){return""+t.lastValue==""+a&&!0===t.lastFinished?!1===t.lastValid:(!0===t.lastFinished&&(t.lastValue=a,t.lastValid=!0,t.lastFinished=!1,m.ajax({url:t.url,data:"value="+a+"&field="+e.attr("name"),dataType:"json",success:function(a){""+t.lastValue==""+a.value&&(t.lastValid=!!a.valid,a.message&&(t.message=a.message),t.lastFinished=!0,e.data("validation"+t.validatorName+"Message",t.message),setTimeout(function(){e.trigger("change.validation")},1))},failure:function(){t.lastValid=!0,t.message="ajax call failed",t.lastFinished=!0,e.data("validation"+t.validatorName+"Message",t.message),setTimeout(function(){e.trigger("change.validation")},1)}})),!1)}},regex:{name:"regex",init:function(a,e){return{regex:(t=a.data("validation"+e+"Regex"),new RegExp("^"+t+"$"))};var t},validate:function(a,e,t){return!t.regex.test(e)&&!t.negative||t.regex.test(e)&&t.negative}},required:{name:"required",init:function(a,e){return{}},validate:function(a,e,t){return!(0!==e.length||t.negative)||!!(0<e.length&&t.negative)},blockSubmit:!0},match:{name:"match",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.data("validation"+e+"Match")+'"]').first();return t.bind("validation.validation",function(){a.trigger("change.validation",{submitting:!0})}),{element:t}},validate:function(a,e,t){return e!==t.element.val()&&!t.negative||e===t.element.val()&&t.negative},blockSubmit:!0},max:{name:"max",init:function(a,e){return{max:a.data("validation"+e+"Max")}},validate:function(a,e,t){return parseFloat(e,10)>parseFloat(t.max,10)&&!t.negative||parseFloat(e,10)<=parseFloat(t.max,10)&&t.negative}},min:{name:"min",init:function(a,e){return{min:a.data("validation"+e+"Min")}},validate:function(a,e,t){return parseFloat(e)<parseFloat(t.min)&&!t.negative||parseFloat(e)>=parseFloat(t.min)&&t.negative}},maxlength:{name:"maxlength",init:function(a,e){return{maxlength:a.data("validation"+e+"Maxlength")}},validate:function(a,e,t){return e.length>t.maxlength&&!t.negative||e.length<=t.maxlength&&t.negative}},minlength:{name:"minlength",init:function(a,e){return{minlength:a.data("validation"+e+"Minlength")}},validate:function(a,e,t){return e.length<t.minlength&&!t.negative||e.length>=t.minlength&&t.negative}},maxchecked:{name:"maxchecked",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.attr("name")+'"]');return t.bind("click.validation",function(){a.trigger("change.validation",{includeEmpty:!0})}),{maxchecked:a.data("validation"+e+"Maxchecked"),elements:t}},validate:function(a,e,t){return t.elements.filter(":checked").length>t.maxchecked&&!t.negative||t.elements.filter(":checked").length<=t.maxchecked&&t.negative},blockSubmit:!0},minchecked:{name:"minchecked",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.attr("name")+'"]');return t.bind("click.validation",function(){a.trigger("change.validation",{includeEmpty:!0})}),{minchecked:a.data("validation"+e+"Minchecked"),elements:t}},validate:function(a,e,t){return t.elements.filter(":checked").length<t.minchecked&&!t.negative||t.elements.filter(":checked").length>=t.minchecked&&t.negative},blockSubmit:!0}},builtInValidators:{email:{name:"Email",type:"shortcut",shortcut:"validemail"},validemail:{name:"Validemail",type:"regex",regex:"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}",message:"Not a valid email address\x3c!-- data-validator-validemail-message to override --\x3e"},passwordagain:{name:"Passwordagain",type:"match",match:"password",message:"Does not match the given password\x3c!-- data-validator-paswordagain-message to override --\x3e"},positive:{name:"Positive",type:"shortcut",shortcut:"number,positivenumber"},negative:{name:"Negative",type:"shortcut",shortcut:"number,negativenumber"},number:{name:"Number",type:"regex",regex:"([+-]?\\d+(\\.\\d*)?([eE][+-]?[0-9]+)?)?",message:"Must be a number\x3c!-- data-validator-number-message to override --\x3e"},integer:{name:"Integer",type:"regex",regex:"[+-]?\\d+",message:"No decimal places allowed\x3c!-- data-validator-integer-message to override --\x3e"},positivenumber:{name:"Positivenumber",type:"min",min:0,message:"Must be a positive number\x3c!-- data-validator-positivenumber-message to override --\x3e"},negativenumber:{name:"Negativenumber",type:"max",max:0,message:"Must be a negative number\x3c!-- data-validator-negativenumber-message to override --\x3e"},required:{name:"Required",type:"required",message:"This is required\x3c!-- data-validator-required-message to override --\x3e"},checkone:{name:"Checkone",type:"minchecked",minchecked:1,message:"Check at least one option\x3c!-- data-validation-checkone-message to override --\x3e"}}},g=function(a){return a.toLowerCase().replace(/(^|\s)([a-z])/g,function(a,e,t){return e+t.toUpperCase()})},h=function(a){var e=a.val(),t=a.attr("type");return"checkbox"===t&&(e=a.is(":checked")?e:""),"radio"===t&&(e=0<m('input[name="'+a.attr("name")+'"]:checked').length?e:""),e};m.fn.jqBootstrapValidation=function(a){return t.methods[a]?t.methods[a].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof a&&a?(m.error("Method "+a+" does not exist on jQuery.jqBootstrapValidation"),null):t.methods.init.apply(this,arguments)},m.jqBootstrapValidation=function(a){m(":input").not("[type=image],[type=submit]").jqBootstrapValidation.apply(this,arguments)}}(jQuery); |
# Copyright 2013 Devsim LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from devsim import *
from devsim.python_packages.model_create import *
def Set_Mobility_Parameters(device, region):
#As
set_parameter(device=device, region=region, name="mu_min_e", value=52.2)
set_parameter(device=device, region=region, name="mu_max_e", value=1417)
set_parameter(device=device, region=region, name="theta1_e", value=2.285)
set_parameter(device=device, region=region, name="m_e", value=1.0)
set_parameter(device=device, region=region, name="f_BH", value=3.828)
set_parameter(device=device, region=region, name="f_CW", value=2.459)
set_parameter(device=device, region=region, name="c_D", value=0.21)
set_parameter(device=device, region=region, name="Nref_D", value=4.0e20)
set_parameter(device=device, region=region, name="Nref_1_e", value=9.68e16)
set_parameter(device=device, region=region, name="alpha_1_e", value=0.68)
#B
set_parameter(device=device, region=region, name="mu_min_h", value=44.9)
set_parameter(device=device, region=region, name="mu_max_h", value=470.5)
set_parameter(device=device, region=region, name="theta1_h", value=2.247)
set_parameter(device=device, region=region, name="m_h", value=1.258)
set_parameter(device=device, region=region, name="c_A", value=0.50)
set_parameter(device=device, region=region, name="Nref_A", value=7.2e20)
set_parameter(device=device, region=region, name="Nref_1_h", value=2.2e17)
set_parameter(device=device, region=region, name="alpha_1_h", value=0.719)
#F_Pe F_Ph equations
set_parameter(device=device, region=region, name="r1", value=0.7643)
set_parameter(device=device, region=region, name="r2", value=2.2999)
set_parameter(device=device, region=region, name="r3", value=6.5502)
set_parameter(device=device, region=region, name="r4", value=2.3670)
set_parameter(device=device, region=region, name="r5", value=-0.01552)
set_parameter(device=device, region=region, name="r6", value=0.6478)
#G_Pe G_Ph equations
set_parameter(device=device, region=region, name="s1", value=0.892333)
set_parameter(device=device, region=region, name="s2", value=0.41372)
set_parameter(device=device, region=region, name="s3", value=0.19778)
set_parameter(device=device, region=region, name="s4", value=0.28227)
set_parameter(device=device, region=region, name="s5", value=0.005978)
set_parameter(device=device, region=region, name="s6", value=1.80618)
set_parameter(device=device, region=region, name="s7", value=0.72169)
# velocity saturation
set_parameter(device=device, region=region, name="vsat_e", value=1.0e7)
set_parameter(device=device, region=region, name="vsat_h", value=1.0e7)
#Lucent Mobility
set_parameter(device=device, region=region, name="alpha_e", value=6.85e-21)
set_parameter(device=device, region=region, name="alpha_h", value=7.82e-21)
set_parameter(device=device, region=region, name="A_e", value=2.58)
set_parameter(device=device, region=region, name="A_h", value=2.18)
set_parameter(device=device, region=region, name="B_e", value=3.61e7)
set_parameter(device=device, region=region, name="B_h", value=1.51e7)
set_parameter(device=device, region=region, name="C_e", value=1.70e4)
set_parameter(device=device, region=region, name="C_h", value=4.18e3)
set_parameter(device=device, region=region, name="kappa_e", value=1.7)
set_parameter(device=device, region=region, name="kappa_h", value=0.9)
set_parameter(device=device, region=region, name="tau_e", value=0.0233)
set_parameter(device=device, region=region, name="tau_h", value=0.0119)
set_parameter(device=device, region=region, name="eta_e", value=0.0767)
set_parameter(device=device, region=region, name="eta_h", value=0.123)
set_parameter(device=device, region=region, name="delta_e", value=3.58e18)
set_parameter(device=device, region=region, name="delta_h", value=4.10e15)
#mobility_h="(Electrons@n0*Electrons@n1)^(0.5)"
#mobility_e="(Holes@n0*Holes@n1)^(0.5)"
#assumption is we will substitute As or P as appropriate
#remember the derivatives as well
### This is the Klaassen mobility, need to adapt to Darwish
def Klaassen_Mobility(device, region):
# require Electrons, Holes, Donors, Acceptors already exist
mu_L_e="(mu_max_e * (300 / T)^theta1_e)"
mu_L_h="(mu_max_h * (300 / T)^theta1_h)"
CreateNodeModel(device, region, "mu_L_e", mu_L_e)
CreateNodeModel(device, region, "mu_L_h", mu_L_h)
mu_e_N="(mu_max_e * mu_max_e / (mu_max_e - mu_min_e) * (T/300)^(3*alpha_1_e - 1.5))"
mu_h_N="(mu_max_h * mu_max_h / (mu_max_h - mu_min_h) * (T/300)^(3*alpha_1_h - 1.5))"
CreateNodeModel(device, region, "mu_e_N", mu_e_N)
CreateNodeModel(device, region, "mu_h_N", mu_h_N)
mu_e_c="(mu_min_e * mu_max_e / (mu_max_e - mu_min_e)) * (300/T)^(0.5)"
mu_h_c="(mu_min_h * mu_max_h / (mu_max_h - mu_min_h)) * (300/T)^(0.5)"
CreateNodeModel(device, region, "mu_e_c", mu_e_c)
CreateNodeModel(device, region, "mu_h_c", mu_h_c)
PBH_e="(1.36e20/(Electrons + Holes) * (m_e) * (T/300)^2)"
PBH_h="(1.36e20/(Electrons + Holes) * (m_h) * (T/300)^2)"
CreateNodeModel (device, region, "PBH_e", PBH_e)
CreateNodeModelDerivative(device, region, "PBH_e", PBH_e, "Electrons", "Holes")
CreateNodeModel (device, region, "PBH_h", PBH_h)
CreateNodeModelDerivative(device, region, "PBH_h", PBH_h, "Electrons", "Holes")
Z_D="(1 + 1 / (c_D + (Nref_D / Donors)^2))"
Z_A="(1 + 1 / (c_A + (Nref_A / Acceptors)^2))"
CreateNodeModel (device, region, "Z_D", Z_D)
CreateNodeModel (device, region, "Z_A", Z_A)
N_D="(Z_D * Donors)"
N_A="(Z_A * Acceptors)"
CreateNodeModel (device, region, "N_D", N_D)
CreateNodeModel (device, region, "N_A", N_A)
N_e_sc="(N_D + N_A + Holes)"
N_h_sc="(N_A + N_D + Electrons)"
CreateNodeModel (device, region, "N_e_sc", N_e_sc)
CreateNodeModelDerivative(device, region, "N_e_sc", N_e_sc, "Electrons", "Holes")
CreateNodeModel (device, region, "N_h_sc", N_h_sc)
CreateNodeModelDerivative(device, region, "N_h_sc", N_h_sc, "Electrons", "Holes")
PCW_e="(3.97e13 * (1/(Z_D^3 * N_e_sc) * (T/300)^3)^(2/3))"
PCW_h="(3.97e13 * (1/(Z_A^3 * N_h_sc) * (T/300)^3)^(2/3))"
CreateNodeModel (device, region, "PCW_e", PCW_e)
CreateNodeModelDerivative(device, region, "PCW_e", PCW_e, "Electrons", "Holes")
CreateNodeModel (device, region, "PCW_h", PCW_h)
CreateNodeModelDerivative(device, region, "PCW_h", PCW_h, "Electrons", "Holes")
Pe="(1/(f_CW / PCW_e + f_BH/PBH_e))"
Ph="(1/(f_CW / PCW_h + f_BH/PBH_h))"
CreateNodeModel (device, region, "Pe", Pe)
CreateNodeModelDerivative(device, region, "Pe", Pe, "Electrons", "Holes")
CreateNodeModel (device, region, "Ph", Ph)
CreateNodeModelDerivative(device, region, "Ph", Ph, "Electrons", "Holes")
G_Pe="(1 - s1 / (s2 + (1.0/m_e * T/300)^s4 * Pe)^s3 + s5/((m_e * 300/T)^s7*Pe)^s6)"
G_Ph="(1 - s1 / (s2 + (1.0/m_h * T/300)^s4 * Ph)^s3 + s5/((m_h * 300/T)^s7*Ph)^s6)"
CreateNodeModel (device, region, "G_Pe", G_Pe)
CreateNodeModelDerivative(device, region, "G_Pe", G_Pe, "Electrons", "Holes")
CreateNodeModel (device, region, "G_Ph", G_Ph)
CreateNodeModelDerivative(device, region, "G_Ph", G_Ph, "Electrons", "Holes")
F_Pe="((r1 * Pe^r6 + r2 + r3 * m_e/m_h)/(Pe^r6 + r4 + r5 * m_e/m_h))"
F_Ph="((r1 * Ph^r6 + r2 + r3 * m_h/m_e)/(Ph^r6 + r4 + r5 * m_h/m_e))"
CreateNodeModel (device, region, "F_Pe", F_Pe)
CreateNodeModelDerivative(device, region, "F_Pe", F_Pe, "Electrons", "Holes")
CreateNodeModel (device, region, "F_Ph", F_Ph)
CreateNodeModelDerivative(device, region, "F_Ph", F_Ph, "Electrons", "Holes")
N_e_sc_eff="(N_D + G_Pe * N_A + Holes / F_Pe)"
N_h_sc_eff="(N_A + G_Ph * N_D + Electrons / F_Ph)"
CreateNodeModel (device, region, "N_e_sc_eff", N_e_sc_eff)
CreateNodeModelDerivative(device, region, "N_e_sc_eff", N_e_sc_eff, "Electrons", "Holes")
CreateNodeModel (device, region, "N_h_sc_eff", N_h_sc_eff)
CreateNodeModelDerivative(device, region, "N_h_sc_eff", N_h_sc_eff, "Electrons", "Holes")
mu_e_D_A_h="mu_e_N * N_e_sc/N_e_sc_eff * (Nref_1_e / N_e_sc)^alpha_1_e + mu_e_c * ((Electrons + Holes)/N_e_sc_eff)"
mu_h_D_A_e="mu_h_N * N_h_sc/N_h_sc_eff * (Nref_1_h / N_h_sc)^alpha_1_h + mu_h_c * ((Electrons + Holes)/N_h_sc_eff)"
CreateNodeModel (device, region, "mu_e_D_A_h", mu_e_D_A_h)
CreateNodeModelDerivative(device, region, "mu_e_D_A_h", mu_e_D_A_h, "Electrons", "Holes")
CreateNodeModel (device, region, "mu_h_D_A_e", mu_h_D_A_e)
CreateNodeModelDerivative(device, region, "mu_h_D_A_e", mu_h_D_A_e, "Electrons", "Holes")
mu_bulk_e_Node="mu_e_D_A_h * mu_L_e / (mu_e_D_A_h + mu_L_e)"
CreateNodeModel (device, region, "mu_bulk_e_Node", mu_bulk_e_Node)
CreateNodeModelDerivative(device, region, "mu_bulk_e_Node", mu_bulk_e_Node, "Electrons", "Holes")
mu_bulk_h_Node="mu_h_D_A_e * mu_L_h / (mu_h_D_A_e + mu_L_h)"
CreateNodeModel (device, region, "mu_bulk_h_Node", mu_bulk_h_Node)
CreateNodeModelDerivative(device, region, "mu_bulk_h_Node", mu_bulk_h_Node, "Electrons", "Holes")
CreateGeometricMean (device, region, "mu_bulk_e_Node", "mu_bulk_e")
CreateGeometricMeanDerivative(device, region, "mu_bulk_e_Node", "mu_bulk_e", "Electrons", "Holes")
CreateGeometricMean (device, region, "mu_bulk_h_Node", "mu_bulk_h")
CreateGeometricMeanDerivative(device, region, "mu_bulk_h_Node", "mu_bulk_h", "Electrons", "Holes")
# mu_bulk is the original bulk model on the edge
# mu_sat is the saturation velocity model name
# vsat is the name of the parameter for velocity saturation
# eparallel is the name of the parallel efield model
def Philips_VelocitySaturation(device, region, mu_sat, mu_bulk, eparallel, vsat):
mu="2*({mu_bulk}) / (1 + (1 + 4 * (max(0, ({mu_bulk}) * {eparallel})/{vsat})^2)^0.5)".format(mu_bulk=mu_bulk, eparallel=eparallel, vsat=vsat)
CreateElementModel2d (device, region, mu_sat, mu)
CreateElementModelDerivative2d (device, region, mu_sat, mu, "Potential", "Electrons", "Holes")
#### Later on need model for temperature on edge
#### Assumption is Enormal is a magnitude
def Philips_Surface_Mobility(device, region, enormal_e, enormal_h):
#### for now, we assume that temperature is an edge quantity and not variable dependent
T_prime_e="(T/300)^kappa_e"
T_prime_h="(T/300)^kappa_h"
CreateEdgeModel(device, region, "T_prime_e", T_prime_e)
CreateEdgeModel(device, region, "T_prime_h", T_prime_h)
# no variables, only parameters
CreateNodeModel (device, region, "NI_node", "(N_D + N_A)")
CreateGeometricMean(device, region, "NI_node", "NI")
#CreateGeometricMean(device, region, "Electrons", edgeElectrons)
#CreateGeometricMeanDerivative(device, region, "Electrons", edgeElectrons Electrons)
#CreateGeometricMean(device, region, "Holes", edgeHoles)
#CreateGeometricMeanDerivative(device, region, "Holes", edgeHoles Holes)
#### Need to prevent ridiculus mobilities for small Enormal
mu_ac_e="B_e /max({0},1e2) + (C_e * NI^tau_e * max({0},1e2)^(-1/3)) / T_prime_e".format(enormal_e)
mu_ac_h="B_h /max({0},1e2) + (C_h * NI^tau_h * max({0},1e2)^(-1/3)) / T_prime_h".format(enormal_h)
CreateElementModel2d (device, region, "mu_ac_e", mu_ac_e)
CreateElementModelDerivative2d(device, region, "mu_ac_e", mu_ac_e, "Potential")
CreateElementModel2d (device, region, "mu_ac_h", mu_ac_h)
CreateElementModelDerivative2d(device, region, "mu_ac_h", mu_ac_h, "Potential")
#gamma_e="A_e + alpha_e * (edgeElectrons + edgeHoles) * NI^(-eta_e)"
#gamma_h="A_h + alpha_h * (edgeElectrons + edgeHoles) * NI^(-eta_h)"
#CreateElementModel2d (device, region, "gamma_e", gamma_e)
#CreateElementModelDerivative2d(device, region, "gamma_e", gamma_e Potential Electrons Holes)
#CreateElementModel2d (device, region, "gamma_h", gamma_h)
#CreateElementModelDerivative2d(device, region, "gamma_h", gamma_h Potential Electrons Holes)
# Hopefully a less problematic formulation
gamma_e="A_e + alpha_e * (Electrons + Holes) * NI_node^(-eta_e)"
gamma_h="A_h + alpha_h * (Electrons + Holes) * NI_node^(-eta_h)"
CreateNodeModel (device, region, "gamma_e_Node", gamma_e)
CreateNodeModelDerivative (device, region, "gamma_e_Node", gamma_e, "Electrons", "Holes")
CreateGeometricMean (device, region, "gamma_e_Node", "gamma_e")
CreateGeometricMeanDerivative(device, region, "gamma_e_Node", "gamma_e", "Electrons", "Holes")
CreateNodeModel (device, region, "gamma_h_Node", gamma_h)
CreateNodeModelDerivative (device, region, "gamma_h_Node", gamma_h, "Electrons", "Holes")
CreateGeometricMean (device, region, "gamma_h_Node", "gamma_h")
CreateGeometricMeanDerivative(device, region, "gamma_h_Node", "gamma_h", "Electrons", "Holes")
#### Need to prevent ridiculus mobilities for small Enormal
mu_sr_e="delta_e *(max({0},1e2))^(-gamma_e)".format(enormal_e)
mu_sr_h="delta_h *(max({0},1e2))^(-gamma_h)".format(enormal_h)
#mu_sr_e="1e8"
#mu_sr_h="1e8"
CreateElementModel2d (device, region, "mu_sr_e", mu_sr_e)
CreateElementModelDerivative2d(device, region, "mu_sr_e", mu_sr_e, "Potential", "Electrons", "Holes")
CreateElementModel2d (device, region, "mu_sr_h", mu_sr_h)
CreateElementModelDerivative2d(device, region, "mu_sr_h", mu_sr_h, "Potential", "Electrons", "Holes")
mu_e_0="mu_bulk_e * mu_ac_e * mu_sr_e / (mu_bulk_e*mu_ac_e + mu_bulk_e*mu_sr_e + mu_ac_e*mu_sr_e)"
mu_h_0="mu_bulk_h * mu_ac_h * mu_sr_h / (mu_bulk_h*mu_ac_h + mu_bulk_h*mu_sr_h + mu_ac_h*mu_sr_h)"
CreateElementModel2d (device, region, "mu_e_0", mu_e_0)
CreateElementModel2d (device, region, "mu_h_0", mu_h_0)
#### complicated derivation here
for k in ("e", "h"):
for i in ("Potential", "Electrons", "Holes"):
for j in ("@en0", "@en1", "@en2"):
ex="mu_{k}_0^2 * (mu_bulk_{k}^(-2)*mu_bulk_{k}:{i}{j} + mu_ac_{k}^(-2)*mu_ac_{k}:{i}{j} + mu_sr_{k}^(-2) * mu_sr_{k}:{i}{j})".format(i=i, j=j, k=k)
CreateElementModel2d(device, region, "mu_{k}_0:{i}{j}".format(i=i, j=j, k=k), ex)
#CreateElementModelDerivative2d(device, region, "mu_e_0", mu_sr_e Potential Electrons Holes)
#CreateElementModelDerivative2d(device, region, "mu_h_0", mu_sr_h Potential Electrons Holes)
#### do we need to consider what happens if the j dot e in wrong direction
#### or do we take care of this before
#mu_e_ph="2*mu_e_0 / ((1 + (1 + 4 * (mu_e_0 * eparallel_e)^2))^(0.5))"
#mu_h_ph="2*mu_h_0 / ((1 + (1 + 4 * (mu_h_0 * eparallel_h)^2))^(0.5))"
### do geometric mean so that
#emobility = sqrt(mobility@n0 * mobility@n1)
#emobility:mobility@n0 = emobility/mobility@n0
#emobility:mobility@n1 = emobility/mobility@n1
# The @n0 means the quantity mobility:Electrons @n0, not the derivative of an node quantity by an edge quantitiy
#emobility:Electrons@n0 = emobility:mobility@n0 * mobility:Electrons@n0
#emobility:Electrons@n1 = emobility:mobility@n1 * mobility:Electrons@n1
|
{
executable: 'php',
arguments: '-l -f "%1"',
onparse: function(output, error){
var check = true;
var errors = [];
var re = /([a-zA-Z ]+):(.+) in .+ on line (\d+)/;
var target = output.split("\n");
for(var i = 0; i < target.length; i++){
var t = target[i];
if(t != ""){
var m = re.exec(t);
if(m != null){
errors.push({
"type": m[1],
"text": m[2],
"line": m[3]
});
check = false;
}
}
}
return {
"check" : check,
"errors" : errors,
"console" : output
};
}
};
|
# SimpleCV Feature library
#
# Tools return basic features in feature sets
# # x = 0.00
# y = 0.00
# _mMaxX = None
# _mMaxY = None
# _mMinX = None
# _mMinY = None
# _mWidth = None
# _mHeight = None
# _mSrcImgW = None
# mSrcImgH = None
#load system libraries
from SimpleCV.base import *
from SimpleCV.Color import *
import copy
class FeatureSet(list):
"""
**SUMMARY**
FeatureSet is a class extended from Python's list which has special functions so that it is useful for handling feature metadata on an image.
In general, functions dealing with attributes will return numpy arrays, and functions dealing with sorting or filtering will return new FeatureSets.
**EXAMPLE**
>>> image = Image("/path/to/image.png")
>>> lines = image.findLines() #lines are the feature set
>>> lines.draw()
>>> lines.x()
>>> lines.crop()
"""
def __getitem__(self,key):
"""
**SUMMARY**
Returns a FeatureSet when sliced. Previously used to
return list. Now it is possible to use FeatureSet member
functions on sub-lists
"""
if type(key) is types.SliceType: #Or can use 'try:' for speed
return FeatureSet(list.__getitem__(self, key))
else:
return list.__getitem__(self,key)
def __getslice__(self, i, j):
"""
Deprecated since python 2.0, now using __getitem__
"""
return self.__getitem__(slice(i,j))
def count(self):
'''
This function returns the length / count of the all the items in the FeatureSet
'''
return len(self)
def draw(self, color = Color.GREEN,width=1, autocolor = False):
"""
**SUMMARY**
Call the draw() method on each feature in the FeatureSet.
**PARAMETERS**
* *color* - The color to draw the object. Either an BGR tuple or a member of the :py:class:`Color` class.
* *width* - The width to draw the feature in pixels. A value of -1 usually indicates a filled region.
* *autocolor* - If true a color is randomly selected for each feature.
**RETURNS**
Nada. Nothing. Zilch.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats.draw(color=Color.PUCE, width=3)
>>> img.show()
"""
for f in self:
if(autocolor):
color = Color().getRandom()
f.draw(color=color,width=width)
def show(self, color = Color.GREEN, autocolor = False,width=1):
"""
**EXAMPLE**
This function will automatically draw the features on the image and show it.
It is a basically a shortcut function for development and is the same as:
**PARAMETERS**
* *color* - The color to draw the object. Either an BGR tuple or a member of the :py:class:`Color` class.
* *width* - The width to draw the feature in pixels. A value of -1 usually indicates a filled region.
* *autocolor* - If true a color is randomly selected for each feature.
**RETURNS**
Nada. Nothing. Zilch.
**EXAMPLE**
>>> img = Image("logo")
>>> feat = img.findBlobs()
>>> if feat: feat.draw()
>>> img.show()
"""
self.draw(color, width, autocolor)
self[-1].image.show()
def reassignImage(self, newImg):
"""
**SUMMARY**
Return a new featureset where the features are assigned to a new image.
**PARAMETERS**
* *img* - the new image to which to assign the feature.
.. Warning::
THIS DOES NOT PERFORM A SIZE CHECK. IF YOUR NEW IMAGE IS NOT THE EXACT SAME SIZE YOU WILL CERTAINLY CAUSE ERRORS.
**EXAMPLE**
>>> img = Image("lenna")
>>> img2 = img.invert()
>>> l = img.findLines()
>>> l2 = img.reassignImage(img2)
>>> l2.show()
"""
retVal = FeatureSet()
for i in self:
retVal.append(i.reassign(newImg))
return retVal
def x(self):
"""
**SUMMARY**
Returns a numpy array of the x (horizontal) coordinate of each feature.
**RETURNS**
A numpy array.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.x()
>>> print xs
"""
return np.array([f.x for f in self])
def y(self):
"""
**SUMMARY**
Returns a numpy array of the y (vertical) coordinate of each feature.
**RETURNS**
A numpy array.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.y()
>>> print xs
"""
return np.array([f.y for f in self])
def coordinates(self):
"""
**SUMMARY**
Returns a 2d numpy array of the x,y coordinates of each feature. This
is particularly useful if you want to use Scipy's Spatial Distance module
**RETURNS**
A numpy array of all the positions in the featureset.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.coordinates()
>>> print xs
"""
return np.array([[f.x, f.y] for f in self])
def center(self):
return self.coordinates()
def area(self):
"""
**SUMMARY**
Returns a numpy array of the area of each feature in pixels.
**RETURNS**
A numpy array of all the positions in the featureset.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> xs = feats.area()
>>> print xs
"""
return np.array([f.area() for f in self])
def sortArea(self):
"""
**SUMMARY**
Returns a new FeatureSet, with the largest area features first.
**RETURNS**
A featureset sorted based on area.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats = feats.sortArea()
>>> print feats[-1] # biggest blob
>>> print feats[0] # smallest blob
"""
return FeatureSet(sorted(self, key = lambda f: f.area()))
def sortX(self):
"""
**SUMMARY**
Returns a new FeatureSet, with the smallest x coordinates features first.
**RETURNS**
A featureset sorted based on area.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats = feats.sortX()
>>> print feats[-1] # biggest blob
>>> print feats[0] # smallest blob
"""
return FeatureSet(sorted(self, key = lambda f: f.x))
def sortY(self):
"""
**SUMMARY**
Returns a new FeatureSet, with the smallest y coordinates features first.
**RETURNS**
A featureset sorted based on area.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> feats = feats.sortY()
>>> print feats[-1] # biggest blob
>>> print feats[0] # smallest blob
"""
return FeatureSet(sorted(self, key = lambda f: f.y))
def distanceFrom(self, point = (-1, -1)):
"""
**SUMMARY**
Returns a numpy array of the distance each Feature is from a given coordinate.
Default is the center of the image.
**PARAMETERS**
* *point* - A point on the image from which we will calculate distance.
**RETURNS**
A numpy array of distance values.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.distanceFrom()
>>> d[0] #show the 0th blobs distance to the center.
**TO DO**
Make this accept other features to measure from.
"""
if (point[0] == -1 or point[1] == -1 and len(self)):
point = self[0].image.size()
return spsd.cdist(self.coordinates(), [point])[:,0]
def sortDistance(self, point = (-1, -1)):
"""
**SUMMARY**
Returns a sorted FeatureSet with the features closest to a given coordinate first.
Default is from the center of the image.
**PARAMETERS**
* *point* - A point on the image from which we will calculate distance.
**RETURNS**
A numpy array of distance values.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.sortDistance()
>>> d[-1].show() #show the 0th blobs distance to the center.
"""
return FeatureSet(sorted(self, key = lambda f: f.distanceFrom(point)))
def distancePairs(self):
"""
**SUMMARY**
Returns the square-form of pairwise distances for the featureset.
The resulting N x N array can be used to quickly look up distances
between features.
**RETURNS**
A NxN np matrix of distance values.
**EXAMPLE**
>>> img = Image("lenna")
>>> feats = img.findBlobs()
>>> d = feats.distancePairs()
>>> print d
"""
return spsd.squareform(spsd.pdist(self.coordinates()))
def angle(self):
"""
**SUMMARY**
Return a numpy array of the angles (theta) of each feature.
Note that theta is given in degrees, with 0 being horizontal.
**RETURNS**
An array of angle values corresponding to the features.
**EXAMPLE**
>>> img = Image("lenna")
>>> l = img.findLines()
>>> angs = l.angle()
>>> print angs
"""
return np.array([f.angle() for f in self])
def sortAngle(self, theta = 0):
"""
Return a sorted FeatureSet with the features closest to a given angle first.
Note that theta is given in radians, with 0 being horizontal.
**RETURNS**
An array of angle values corresponding to the features.
**EXAMPLE**
>>> img = Image("lenna")
>>> l = img.findLines()
>>> l = l.sortAngle()
>>> print angs
"""
return FeatureSet(sorted(self, key = lambda f: abs(f.angle() - theta)))
def length(self):
"""
**SUMMARY**
Return a numpy array of the length (longest dimension) of each feature.
**RETURNS**
A numpy array of the length, in pixels, of eatch feature object.
**EXAMPLE**
>>> img = Image("Lenna")
>>> l = img.findLines()
>>> lengt = l.length()
>>> lengt[0] # length of the 0th element.
"""
return np.array([f.length() for f in self])
def sortLength(self):
"""
**SUMMARY**
Return a sorted FeatureSet with the longest features first.
**RETURNS**
A sorted FeatureSet.
**EXAMPLE**
>>> img = Image("Lenna")
>>> l = img.findLines().sortLength()
>>> lengt[-1] # length of the 0th element.
"""
return FeatureSet(sorted(self, key = lambda f: f.length()))
def meanColor(self):
"""
**SUMMARY**
Return a numpy array of the average color of the area covered by each Feature.
**RETURNS**
Returns an array of RGB triplets the correspond to the mean color of the feature.
**EXAMPLE**
>>> img = Image("lenna")
>>> kp = img.findKeypoints()
>>> c = kp.meanColor()
"""
return np.array([f.meanColor() for f in self])
def colorDistance(self, color = (0, 0, 0)):
"""
**SUMMARY**
Return a numpy array of the distance each features average color is from
a given color tuple (default black, so colorDistance() returns intensity)
**PARAMETERS**
* *color* - The color to calculate the distance from.
**RETURNS**
The distance of the average color for the feature from given color as a numpy array.
**EXAMPLE**
>>> img = Image("lenna")
>>> circs = img.findCircle()
>>> d = circs.colorDistance(color=Color.BLUE)
>>> print d
"""
return spsd.cdist(self.meanColor(), [color])[:,0]
def sortColorDistance(self, color = (0, 0, 0)):
"""
Return a sorted FeatureSet with features closest to a given color first.
Default is black, so sortColorDistance() will return darkest to brightest
"""
return FeatureSet(sorted(self, key = lambda f: f.colorDistance(color)))
def filter(self, filterarray):
"""
**SUMMARY**
Return a FeatureSet which is filtered on a numpy boolean array. This
will let you use the attribute functions to easily screen Features out
of return FeatureSets.
**PARAMETERS**
* *filterarray* - A numpy array, matching the size of the feature set,
made of Boolean values, we return the true values and reject the False value.
**RETURNS**
The revised feature set.
**EXAMPLE**
Return all lines < 200px
>>> my_lines.filter(my_lines.length() < 200) # returns all lines < 200px
>>> my_blobs.filter(my_blobs.area() > 0.9 * my_blobs.length**2) # returns blobs that are nearly square
>>> my_lines.filter(abs(my_lines.angle()) < numpy.pi / 4) #any lines within 45 degrees of horizontal
>>> my_corners.filter(my_corners.x() - my_corners.y() > 0) #only return corners in the upper diagonal of the image
"""
return FeatureSet(list(np.array(self)[np.array(filterarray)]))
def width(self):
"""
**SUMMARY**
Returns a nparray which is the width of all the objects in the FeatureSet.
**RETURNS**
A numpy array of width values.
**EXAMPLE**
>>> img = Image("NotLenna")
>>> l = img.findLines()
>>> l.width()
"""
return np.array([f.width() for f in self])
def height(self):
"""
Returns a nparray which is the height of all the objects in the FeatureSet
**RETURNS**
A numpy array of width values.
**EXAMPLE**
>>> img = Image("NotLenna")
>>> l = img.findLines()
>>> l.height()
"""
return np.array([f.height() for f in self])
def crop(self):
"""
**SUMMARY**
Returns a nparray with the cropped features as SimpleCV image.
**RETURNS**
A SimpleCV image cropped to each image.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> newImg = b.crop()
>>> newImg.show()
>>> time.sleep(1)
"""
return np.array([f.crop() for f in self])
def inside(self,region):
"""
**SUMMARY**
Return only the features inside the region. where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are inside the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> inside = lines.inside(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.isContainedWithin(region)):
fs.append(f)
return fs
def outside(self,region):
"""
**SUMMARY**
Return only the features outside the region. where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are outside the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.outside(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.isNotContainedWithin(region)):
fs.append(f)
return fs
def overlaps(self,region):
"""
**SUMMARY**
Return only the features that overlap or the region. Where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that overlap the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.overlaps(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if( f.overlaps(region) ):
fs.append(f)
return fs
def above(self,region):
"""
**SUMMARY**
Return only the features that are above a region. Where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are above the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> outside = lines.above(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.above(region)):
fs.append(f)
return fs
def below(self,region):
"""
**SUMMARY**
Return only the features below the region. where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are below the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> inside = lines.below(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.below(region)):
fs.append(f)
return fs
def left(self,region):
"""
**SUMMARY**
Return only the features left of the region. where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are left of the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> left = lines.left(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.left(region)):
fs.append(f)
return fs
def right(self,region):
"""
**SUMMARY**
Return only the features right of the region. where region can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *region*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a featureset of features that are right of the region.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[-1]
>>> lines = img.findLines()
>>> right = lines.right(b)
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
fs = FeatureSet()
for f in self:
if(f.right(region)):
fs.append(f)
return fs
def onImageEdge(self, tolerance=1):
"""
**SUMMARY**
The method returns a feature set of features that are on or "near" the edge of
the image. This is really helpful for removing features that are edge effects.
**PARAMETERS**
* *tolerance* - the distance in pixels from the edge at which a feature
qualifies as being "on" the edge of the image.
**RETURNS**
Returns a featureset of features that are on the edge of the image.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> es = blobs.onImageEdge()
>>> es.draw(color=Color.RED)
>>> img.show()
"""
fs = FeatureSet()
for f in self:
if(f.onImageEdge(tolerance)):
fs.append(f)
return fs
def notOnImageEdge(self, tolerance=1):
"""
**SUMMARY**
The method returns a feature set of features that are not on or "near" the edge of
the image. This is really helpful for removing features that are edge effects.
**PARAMETERS**
* *tolerance* - the distance in pixels from the edge at which a feature
qualifies as being "on" the edge of the image.
**RETURNS**
Returns a featureset of features that are not on the edge of the image.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> es = blobs.notOnImageEdge()
>>> es.draw(color=Color.RED)
>>> img.show()
"""
fs = FeatureSet()
for f in self:
if(f.notOnImageEdge(tolerance)):
fs.append(f)
return fs
def topLeftCorners(self):
"""
**SUMMARY**
This method returns the top left corner of each feature's bounding box.
**RETURNS**
A numpy array of x,y position values.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> tl = img.topLeftCorners()
>>> print tl[0]
"""
return np.array([f.topLeftCorner() for f in self])
def bottomLeftCorners(self):
"""
**SUMMARY**
This method returns the bottom left corner of each feature's bounding box.
**RETURNS**
A numpy array of x,y position values.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> bl = img.bottomLeftCorners()
>>> print bl[0]
"""
return np.array([f.bottomLeftCorner() for f in self])
def topLeftCorners(self):
"""
**SUMMARY**
This method returns the top left corner of each feature's bounding box.
**RETURNS**
A numpy array of x,y position values.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> tl = img.bottomLeftCorners()
>>> print tl[0]
"""
return np.array([f.topLeftCorner() for f in self])
def topRightCorners(self):
"""
**SUMMARY**
This method returns the top right corner of each feature's bounding box.
**RETURNS**
A numpy array of x,y position values.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> tr = img.topRightCorners()
>>> print tr[0]
"""
return np.array([f.topRightCorner() for f in self])
def bottomRightCorners(self):
"""
**SUMMARY**
This method returns the bottom right corner of each feature's bounding box.
**RETURNS**
A numpy array of x,y position values.
**EXAMPLE**
>>> img = Image("./sampleimages/EdgeTest1.png")
>>> blobs = img.findBlobs()
>>> br = img.bottomRightCorners()
>>> print br[0]
"""
return np.array([f.bottomRightCorner() for f in self])
def aspectRatios(self):
"""
**SUMMARY**
Return the aspect ratio of all the features in the feature set, For our purposes
aspect ration is max(width,height)/min(width,height).
**RETURNS**
A numpy array of the aspect ratio of the features in the featureset.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs.aspectRatio()
"""
return np.array([f.aspectRatio() for f in self])
def cluster(self,method="kmeans",properties=None,k=3):
"""
**SUMMARY**
This function clusters the blobs in the featureSet based on the properties. Properties can be "color", "shape" or "position" of blobs.
Clustering is done using K-Means or Hierarchical clustering(Ward) algorithm.
**PARAMETERS**
* *properties* - It should be a list with any combination of "color", "shape", "position". properties = ["color","position"]. properties = ["position","shape"]. properties = ["shape"]
* *method* - if method is "kmeans", it will cluster using K-Means algorithm, if the method is "hierarchical", no need to spicify the number of clusters
* *k* - The number of clusters(kmeans).
**RETURNS**
A list of featureset, each being a cluster itself.
**EXAMPLE**
>>> img = Image("lenna")
>>> blobs = img.findBlobs()
>>> clusters = blobs.cluster(method="kmeans",properties=["color"],k=5)
>>> for i in clusters:
>>> i.draw(color=Color.getRandom(),width=5)
>>> img.show()
"""
try :
from sklearn.cluster import KMeans, Ward
from sklearn import __version__
except :
logger.warning("install scikits-learning package")
return
X = [] #List of feature vector of each blob
if not properties:
properties = ['color','shape','position']
if k > len(self):
logger.warning("Number of clusters cannot be greater then the number of blobs in the featureset")
return
for i in self:
featureVector = []
if 'color' in properties:
featureVector.extend(i.mAvgColor)
if 'shape' in properties:
featureVector.extend(i.mHu)
if 'position' in properties:
featureVector.extend(i.extents())
if not featureVector :
logger.warning("properties parameter is not specified properly")
return
X.append(featureVector)
if method == "kmeans":
if (float(__version__) > 0.11):
k_means = KMeans(init='random', n_clusters=k, n_init=10).fit(X)
else:
k_means = KMeans(init='random', k=k, n_init=10).fit(X)
KClusters = [ FeatureSet([]) for i in range(k)]
for i in range(len(self)):
KClusters[k_means.labels_[i]].append(self[i])
return KClusters
if method == "hierarchical":
ward = Ward(n_clusters=int(sqrt(len(self)))).fit(X) #n_clusters = sqrt(n)
WClusters = [ FeatureSet([]) for i in range(int(sqrt(len(self))))]
for i in range(len(self)):
WClusters[ward.labels_[i]].append(self[i])
return WClusters
@property
def image(self):
if not len(self):
return None
return self[0].image
@image.setter
def image(self, i):
for f in self:
f.image = i
### ----------------------------------------------------------------------------
### ----------------------------------------------------------------------------
### ----------------------------FEATURE CLASS-----------------------------------
### ----------------------------------------------------------------------------
### ----------------------------------------------------------------------------
class Feature(object):
"""
**SUMMARY**
The Feature object is an abstract class which real features descend from.
Each feature object has:
* a draw() method,
* an image property, referencing the originating Image object
* x and y coordinates
* default functions for determining angle, area, meanColor, etc for FeatureSets
* in the Feature class, these functions assume the feature is 1px
"""
x = 0.00
y = 0.00
_mMaxX = None
_mMaxY = None
_mMinX = None
_mMinY = None
_mWidth = None
_mHeight = None
_mSrcImgW = None
_mSrcImgH = None
# This is 2.0 refactoring
mBoundingBox = None # THIS SHALT BE TOP LEFT (X,Y) THEN W H i.e. [X,Y,W,H]
mExtents = None # THIS SHALT BE [MAXX,MINX,MAXY,MINY]
points = None # THIS SHALT BE (x,y) tuples in the ORDER [(TopLeft),(TopRight),(BottomLeft),(BottomRight)]
image = "" #parent image
#points = []
#boundingBox = []
def __init__(self, i, at_x, at_y, points):
#THE COVENANT IS THAT YOU PROVIDE THE POINTS IN THE SPECIFIED FORMAT AND ALL OTHER VALUES SHALT FLOW
self.x = at_x
self.y = at_y
self.image = i
self.points = points
self._updateExtents()
def reassign(self, img):
"""
**SUMMARY**
Reassign the image of this feature and return an updated copy of the feature.
**PARAMETERS**
* *img* - the new image to which to assign the feature.
.. Warning::
THIS DOES NOT PERFORM A SIZE CHECK. IF YOUR NEW IMAGE IS NOT THE EXACT SAME SIZE YOU WILL CERTAINLY CAUSE ERRORS.
**EXAMPLE**
>>> img = Image("lenna")
>>> img2 = img.invert()
>>> l = img.findLines()
>>> l2 = img.reassignImage(img2)
>>> l2.show()
"""
retVal = copy.deepcopy(self)
if( self.image.width != img.width or
self.image.height != img.height ):
warnings.warn("DON'T REASSIGN IMAGES OF DIFFERENT SIZES")
retVal.image = img
return retVal
def corners(self):
self._updateExtents()
return self.points
def coordinates(self):
"""
**SUMMARY**
Returns the x,y position of the feature. This is usually the center coordinate.
**RETURNS**
Returns an (x,y) tuple of the position of the feature.
**EXAMPLE**
>>> img = Image("aerospace.png")
>>> blobs = img.findBlobs()
>>> for b in blobs:
>>> print b.coordinates()
"""
return np.array([self.x, self.y])
def draw(self, color = Color.GREEN):
"""
**SUMMARY**
This method will draw the feature on the source image.
**PARAMETERS**
* *color* - The color as an RGB tuple to render the image.
**RETURNS**
Nothing.
**EXAMPLE**
>>> img = Image("RedDog2.jpg")
>>> blobs = img.findBlobs()
>>> blobs[-1].draw()
>>> img.show()
"""
self.image[self.x, self.y] = color
def show(self, color = Color.GREEN):
"""
**SUMMARY**
This function will automatically draw the features on the image and show it.
**RETURNS**
Nothing.
**EXAMPLE**
>>> img = Image("logo")
>>> feat = img.findBlobs()
>>> feat[-1].show() #window pops up.
"""
self.draw(color)
self.image.show()
def distanceFrom(self, point = (-1, -1)):
"""
**SUMMARY**
Given a point (default to center of the image), return the euclidean distance of x,y from this point.
**PARAMETERS**
* *point* - The point, as an (x,y) tuple on the image to measure distance from.
**RETURNS**
The distance as a floating point value in pixels.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> blobs[-1].distanceFrom(blobs[-2].coordinates())
"""
if (point[0] == -1 or point[1] == -1):
point = np.array(self.image.size()) / 2
return spsd.euclidean(point, [self.x, self.y])
def meanColor(self):
"""
**SUMMARY**
Return the average color within the feature as a tuple.
**RETURNS**
An RGB color tuple.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if (b.meanColor() == color.WHITE):
>>> print "Found a white thing"
"""
return self.image[self.x, self.y]
def colorDistance(self, color = (0, 0, 0)):
"""
**SUMMARY**
Return the euclidean color distance of the color tuple at x,y from a given color (default black).
**PARAMETERS**
* *color* - An RGB triplet to calculate from which to calculate the color distance.
**RETURNS**
A floating point color distance value.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> print b.colorDistance(color.WHITE):
"""
return spsd.euclidean(np.array(color), np.array(self.meanColor()))
def angle(self):
"""
**SUMMARY**
Return the angle (theta) in degrees of the feature. The default is 0 (horizontal).
.. Warning::
This is not a valid operation for all features.
**RETURNS**
An angle value in degrees.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if b.angle() == 0:
>>> print "I AM HORIZONTAL."
**TODO**
Double check that values are being returned consistently.
"""
return 0
def length(self):
"""
**SUMMARY**
This method returns the longest dimension of the feature (i.e max(width,height)).
**RETURNS**
A floating point length value.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if b.length() > 200:
>>> print "OH MY! - WHAT A BIG FEATURE YOU HAVE!"
>>> print "---I bet you say that to all the features."
**TODO**
Should this be sqrt(x*x+y*y)?
"""
return float(np.max([self.width(),self.height()]))
def distanceToNearestEdge(self):
"""
**SUMMARY**
This method returns the distance, in pixels, from the nearest image edge.
**RETURNS**
The integer distance to the nearest edge.
**EXAMPLE**
>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> b[0].distanceToNearestEdge()
"""
w = self.image.width
h = self.image.height
return np.min([self._mMinX,self._mMinY, w-self._mMaxX,h-self._mMaxY])
def onImageEdge(self,tolerance=1):
"""
**SUMMARY**
This method returns True if the feature is less than `tolerance`
pixels away from the nearest edge.
**PARAMETERS**
* *tolerance* - the distance in pixels at which a feature qualifies
as being on the image edge.
**RETURNS**
True if the feature is on the edge, False otherwise.
**EXAMPLE**
>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> if(b[0].onImageEdge()):
>>> print "HELP! I AM ABOUT TO FALL OFF THE IMAGE"
"""
# this has to be one to deal with blob library weirdness that goes deep down to opencv
return ( self.distanceToNearestEdge() <= tolerance )
def notOnImageEdge(self,tolerance=1):
"""
**SUMMARY**
This method returns True if the feature is greate than `tolerance`
pixels away from the nearest edge.
**PARAMETERS**
* *tolerance* - the distance in pixels at which a feature qualifies
as not being on the image edge.
**RETURNS**
True if the feature is not on the edge of the image, False otherwise.
**EXAMPLE**
>>> img = Image("../sampleimages/EdgeTest1.png")
>>> b = img.findBlobs()
>>> if(b[0].notOnImageEdge()):
>>> print "I am safe and sound."
"""
# this has to be one to deal with blob library weirdness that goes deep down to opencv
return ( self.distanceToNearestEdge() > tolerance )
def aspectRatio(self):
"""
**SUMMARY**
Return the aspect ratio of the feature, which for our purposes
is max(width,height)/min(width,height).
**RETURNS**
A single floating point value of the aspect ration.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> b[0].aspectRatio()
"""
self._updateExtents()
return self.mAspectRatio
def area(self):
"""
**SUMMARY**
Returns the area (number of pixels) covered by the feature.
**RETURNS**
An integer area of the feature.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if b.area() > 200:
>>> print b.area()
"""
return self.width() * self.height()
def width(self):
"""
**SUMMARY**
Returns the height of the feature.
**RETURNS**
An integer value for the feature's width.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if b.width() > b.height():
>>> print "wider than tall"
>>> b.draw()
>>> img.show()
"""
self._updateExtents()
return self._mWidth
def height(self):
"""
**SUMMARY**
Returns the height of the feature.
**RETURNS**
An integer value of the feature's height.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> for b in blobs:
>>> if b.width() > b.height():
>>> print "wider than tall"
>>> b.draw()
>>> img.show()
"""
self._updateExtents()
return self._mHeight
def crop(self):
"""
**SUMMARY**
This function crops the source image to the location of the feature and returns
a new SimpleCV image.
**RETURNS**
A SimpleCV image that is cropped to the feature position and size.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> big = blobs[-1].crop()
>>> big.show()
"""
return self.image.crop(self.x, self.y, self.width(), self.height(), centered = True)
def __repr__(self):
return "%s.%s at (%d,%d)" % (self.__class__.__module__, self.__class__.__name__, self.x, self.y)
def _updateExtents(self):
# mBoundingBox = None # THIS SHALT BE TOP LEFT (X,Y) THEN W H i.e. [X,Y,W,H]
# mExtents = None # THIS SHALT BE [MAXX,MINX,MAXY,MINY]
# points = None # THIS SHALT BE (x,y) tuples in the ORDER [(TopLeft),(TopRight),(BottomLeft),(BottomRight)]
if( self._mMaxX is None or self._mMaxY is None or
self._mMinX is None or self._mMinY is None or
self._mWidth is None or self._mHeight is None or
self.mExtents is None or self.mBoundingBox is None
):
self._mMaxX = float("-infinity")
self._mMaxY = float("-infinity")
self._mMinX = float("infinity")
self._mMinY = float("infinity")
for p in self.points:
if( p[0] > self._mMaxX):
self._mMaxX = p[0]
if( p[0] < self._mMinX):
self._mMinX = p[0]
if( p[1] > self._mMaxY):
self._mMaxY = p[1]
if( p[1] < self._mMinY):
self._mMinY = p[1]
self._mWidth = self._mMaxX-self._mMinX
self._mHeight = self._mMaxY-self._mMinY
if( self._mWidth <= 0 ):
self._mWidth = 1
if( self._mHeight <= 0 ):
self._mHeight = 1
self.mBoundingBox = [self._mMinX,self._mMinY,self._mWidth,self._mHeight]
self.mExtents = [self._mMaxX,self._mMinX,self._mMaxY,self._mMinY]
self.mAspectRatio = float(np.max([self._mWidth,self._mHeight]))/float(np.min([self._mWidth,self._mHeight]))
def boundingBox(self):
"""
**SUMMARY**
This function returns a rectangle which bounds the blob.
**RETURNS**
A list of [x, y, w, h] where (x, y) are the top left point of the rectangle
and w, h are its width and height respectively.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].boundingBox()
"""
self._updateExtents()
return self.mBoundingBox
def extents(self):
"""
**SUMMARY**
This function returns the maximum and minimum x and y values for the feature and
returns them as a tuple.
**RETURNS**
A tuple of the extents of the feature. The order is (MaxX,MaxY,MinX,MinY).
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].extents()
"""
self._updateExtents()
return self.mExtents
def minY(self):
"""
**SUMMARY**
This method return the minimum y value of the bounding box of the
the feature.
**RETURNS**
An integer value of the minimum y value of the feature.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].minY()
"""
self._updateExtents()
return self._mMinY
def maxY(self):
"""
**SUMMARY**
This method return the maximum y value of the bounding box of the
the feature.
**RETURNS**
An integer value of the maximum y value of the feature.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].maxY()
"""
self._updateExtents()
return self._mMaxY
def minX(self):
"""
**SUMMARY**
This method return the minimum x value of the bounding box of the
the feature.
**RETURNS**
An integer value of the minimum x value of the feature.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].minX()
"""
self._updateExtents()
return self._mMinX
def maxX(self):
"""
**SUMMARY**
This method return the minimum x value of the bounding box of the
the feature.
**RETURNS**
An integer value of the maxium x value of the feature.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].maxX()
"""
self._updateExtents()
return self._mMaxX
def topLeftCorner(self):
"""
**SUMMARY**
This method returns the top left corner of the bounding box of
the blob as an (x,y) tuple.
**RESULT**
Returns a tupple of the top left corner.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].topLeftCorner()
"""
self._updateExtents()
return (self._mMinX,self._mMinY)
def bottomRightCorner(self):
"""
**SUMMARY**
This method returns the bottom right corner of the bounding box of
the blob as an (x,y) tuple.
**RESULT**
Returns a tupple of the bottom right corner.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].bottomRightCorner()
"""
self._updateExtents()
return (self._mMaxX,self._mMaxY)
def bottomLeftCorner(self):
"""
**SUMMARY**
This method returns the bottom left corner of the bounding box of
the blob as an (x,y) tuple.
**RESULT**
Returns a tupple of the bottom left corner.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].bottomLeftCorner()
"""
self._updateExtents()
return (self._mMinX,self._mMaxY)
def topRightCorner(self):
"""
**SUMMARY**
This method returns the top right corner of the bounding box of
the blob as an (x,y) tuple.
**RESULT**
Returns a tupple of the top right corner.
**EXAMPLE**
>>> img = Image("OWS.jpg")
>>> blobs = img.findBlobs(128)
>>> print blobs[-1].topRightCorner()
"""
self._updateExtents()
return (self._mMaxX,self._mMinY)
def above(self,object):
"""
**SUMMARY**
Return true if the feature is above the object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is above the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].above(b) ):
>>> print "above the biggest blob"
"""
if( isinstance(object,Feature) ):
return( self.maxY() < object.minY() )
elif( isinstance(object,tuple) or isinstance(object,np.ndarray) ):
return( self.maxY() < object[1] )
elif( isinstance(object,float) or isinstance(object,int) ):
return( self.maxY() < object )
else:
logger.warning("SimpleCV did not recognize the input type to feature.above(). This method only takes another feature, an (x,y) tuple, or a ndarray type.")
return None
def below(self,object):
"""
**SUMMARY**
Return true if the feature is below the object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is below the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].below(b) ):
>>> print "above the biggest blob"
"""
if( isinstance(object,Feature) ):
return( self.minY() > object.maxY() )
elif( isinstance(object,tuple) or isinstance(object,np.ndarray) ):
return( self.minY() > object[1] )
elif( isinstance(object,float) or isinstance(object,int) ):
return( self.minY() > object )
else:
logger.warning("SimpleCV did not recognize the input type to feature.below(). This method only takes another feature, an (x,y) tuple, or a ndarray type.")
return None
def right(self,object):
"""
**SUMMARY**
Return true if the feature is to the right object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is to the right object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].right(b) ):
>>> print "right of the the blob"
"""
if( isinstance(object,Feature) ):
return( self.minX() > object.maxX() )
elif( isinstance(object,tuple) or isinstance(object,np.ndarray) ):
return( self.minX() > object[0] )
elif( isinstance(object,float) or isinstance(object,int) ):
return( self.minX() > object )
else:
logger.warning("SimpleCV did not recognize the input type to feature.right(). This method only takes another feature, an (x,y) tuple, or a ndarray type.")
return None
def left(self,object):
"""
**SUMMARY**
Return true if the feature is to the left of the object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is to the left of the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].left(b) ):
>>> print "left of the biggest blob"
"""
if( isinstance(object,Feature) ):
return( self.maxX() < object.minX() )
elif( isinstance(object,tuple) or isinstance(object,np.ndarray) ):
return( self.maxX() < object[0] )
elif( isinstance(object,float) or isinstance(object,int) ):
return( self.maxX() < object )
else:
logger.warning("SimpleCV did not recognize the input type to feature.left(). This method only takes another feature, an (x,y) tuple, or a ndarray type.")
return None
def contains(self,other):
"""
**SUMMARY**
Return true if the feature contains the object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature contains the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].contains(b) ):
>>> print "this blob is contained in the biggest blob"
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
retVal = False
bounds = self.points
if( isinstance(other,Feature) ):# A feature
retVal = True
for p in other.points: # this isn't completely correct - only tests if points lie in poly, not edges.
p2 = (int(p[0]),int(p[1]))
retVal = self._pointInsidePolygon(p2,bounds)
if( not retVal ):
break
# a single point
elif( (isinstance(other,tuple) and len(other)==2) or ( isinstance(other,np.ndarray) and other.shape[0]==2) ):
retVal = self._pointInsidePolygon(other,bounds)
elif( isinstance(other,tuple) and len(other)==3 ): # A circle
#assume we are in x,y, r format
retVal = True
rr = other[2]*other[2]
x = other[0]
y = other[1]
for p in bounds:
test = ((x-p[0])*(x-p[0]))+((y-p[1])*(y-p[1]))
if( test < rr ):
retVal = False
break
elif( isinstance(other,tuple) and len(other)==4 and ( isinstance(other[0],float) or isinstance(other[0],int))):
retVal = ( self.maxX() <= other[0]+other[2] and
self.minX() >= other[0] and
self.maxY() <= other[1]+other[3] and
self.minY() >= other[1] )
elif(isinstance(other,list) and len(other) >= 4): # an arbitrary polygon
#everything else ....
retVal = True
for p in other:
test = self._pointInsidePolygon(p,bounds)
if(not test):
retVal = False
break
else:
logger.warning("SimpleCV did not recognize the input type to features.contains. This method only takes another blob, an (x,y) tuple, or a ndarray type.")
return False
return retVal
def overlaps(self, other):
"""
**SUMMARY**
Return true if the feature overlaps the object, where object can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *object*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature overlaps object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].overlaps(b) ):
>>> print "This blob overlaps the biggest blob"
Returns true if this blob contains at least one point, part of a collection
of points, or any part of a blob.
**NOTE**
This currently performs a bounding box test, not a full polygon test for speed.
"""
retVal = False
bounds = self.points
if( isinstance(other,Feature) ):# A feature
retVal = True
for p in other.points: # this isn't completely correct - only tests if points lie in poly, not edges.
retVal = self._pointInsidePolygon(p,bounds)
if( retVal ):
break
elif( (isinstance(other,tuple) and len(other)==2) or ( isinstance(other,np.ndarray) and other.shape[0]==2) ):
retVal = self._pointInsidePolygon(other,bounds)
elif( isinstance(other,tuple) and len(other)==3 and not isinstance(other[0],tuple)): # A circle
#assume we are in x,y, r format
retVal = False
rr = other[2]*other[2]
x = other[0]
y = other[1]
for p in bounds:
test = ((x-p[0])*(x-p[0]))+((y-p[1])*(y-p[1]))
if( test < rr ):
retVal = True
break
elif( isinstance(other,tuple) and len(other)==4 and ( isinstance(other[0],float) or isinstance(other[0],int))):
retVal = ( self.contains( (other[0],other[1] ) ) or # see if we contain any corner
self.contains( (other[0]+other[2],other[1] ) ) or
self.contains( (other[0],other[1]+other[3] ) ) or
self.contains( (other[0]+other[2],other[1]+other[3] ) ) )
elif(isinstance(other,list) and len(other) >= 3): # an arbitrary polygon
#everything else ....
retVal = False
for p in other:
test = self._pointInsidePolygon(p,bounds)
if(test):
retVal = True
break
else:
logger.warning("SimpleCV did not recognize the input type to features.overlaps. This method only takes another blob, an (x,y) tuple, or a ndarray type.")
return False
return retVal
def doesNotContain(self, other):
"""
**SUMMARY**
Return true if the feature does not contain the other object, where other can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *other*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature does not contain the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].doesNotContain(b) ):
>>> print "above the biggest blob"
Returns true if all of features points are inside this point.
"""
return not self.contains(other)
def doesNotOverlap( self, other):
"""
**SUMMARY**
Return true if the feature does not overlap the object other, where other can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *other*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature does not Overlap the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].doesNotOverlap(b) ):
>>> print "does not over overlap biggest blob"
"""
return not self.overlaps( other)
def isContainedWithin(self,other):
"""
**SUMMARY**
Return true if the feature is contained withing the object other, where other can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *other*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is above the object, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].isContainedWithin(b) ):
>>> print "inside the blob"
"""
retVal = True
bounds = self.points
if( isinstance(other,Feature) ): # another feature do the containment test
retVal = other.contains(self)
elif( isinstance(other,tuple) and len(other)==3 ): # a circle
#assume we are in x,y, r format
rr = other[2]*other[2] # radius squared
x = other[0]
y = other[1]
for p in bounds:
test = ((x-p[0])*(x-p[0]))+((y-p[1])*(y-p[1]))
if( test > rr ):
retVal = False
break
elif( isinstance(other,tuple) and len(other)==4 and # a bounding box
( isinstance(other[0],float) or isinstance(other[0],int))): # we assume a tuple of four is (x,y,w,h)
retVal = ( self.maxX() <= other[0]+other[2] and
self.minX() >= other[0] and
self.maxY() <= other[1]+other[3] and
self.minY() >= other[1] )
elif(isinstance(other,list) and len(other) > 2 ): # an arbitrary polygon
#everything else ....
retVal = True
for p in bounds:
test = self._pointInsidePolygon(p,other)
if(not test):
retVal = False
break
else:
logger.warning("SimpleCV did not recognize the input type to features.contains. This method only takes another blob, an (x,y) tuple, or a ndarray type.")
retVal = False
return retVal
def isNotContainedWithin(self,shape):
"""
**SUMMARY**
Return true if the feature is not contained within the shape, where shape can be a bounding box,
bounding circle, a list of tuples in a closed polygon, or any other featutres.
**PARAMETERS**
* *shape*
* A bounding box - of the form (x,y,w,h) where x,y is the upper left corner
* A bounding circle of the form (x,y,r)
* A list of x,y tuples defining a closed polygon e.g. ((x,y),(x,y),....)
* Any two dimensional feature (e.g. blobs, circle ...)
**RETURNS**
Returns a Boolean, True if the feature is not contained within the shape, False otherwise.
**EXAMPLE**
>>> img = Image("Lenna")
>>> blobs = img.findBlobs()
>>> b = blobs[0]
>>> if( blobs[-1].isNotContainedWithin(b) ):
>>> print "Not inside the biggest blob"
"""
return not self.isContainedWithin(shape)
def _pointInsidePolygon(self,point,polygon):
"""
returns true if tuple point (x,y) is inside polygon of the form ((a,b),(c,d),...,(a,b)) the polygon should be closed
Adapted for python from:
Http://paulbourke.net/geometry/insidepoly/
"""
if( len(polygon) < 3 ):
logger.warning("feature._pointInsidePolygon - this is not a valid polygon")
return False
if( not isinstance(polygon,list)):
logger.warning("feature._pointInsidePolygon - this is not a valid polygon")
return False
counter = 0
retVal = True
p1 = None
#print "point: " + str(point)
poly = copy.deepcopy(polygon)
poly.append(polygon[0])
#for p2 in poly:
N = len(poly)
p1 = poly[0]
for i in range(1,N+1):
p2 = poly[i%N]
if( point[1] > np.min((p1[1],p2[1])) ):
if( point[1] <= np.max((p1[1],p2[1])) ):
if( point[0] <= np.max((p1[0],p2[0])) ):
if( p1[1] != p2[1] ):
test = float((point[1]-p1[1])*(p2[0]-p1[0]))/float(((p2[1]-p1[1])+p1[0]))
if( p1[0] == p2[0] or point[0] <= test ):
counter = counter + 1
p1 = p2
if( counter % 2 == 0 ):
retVal = False
return retVal
def boundingCircle(self):
"""
**SUMMARY**
This function calculates the minimum bounding circle of the blob in the image
as an (x,y,r) tuple
**RETURNS**
An (x,y,r) tuple where (x,y) is the center of the circle and r is the radius
**EXAMPLE**
>>> img = Image("RatMask.png")
>>> blobs = img.findBlobs()
>>> print blobs[-1].boundingCircle()
"""
try:
import cv2
except:
logger.warning("Unable to import cv2")
return None
# contour of the blob in image
contour = self.contour()
points = []
# list of contour points converted to suitable format to pass into cv2.minEnclosingCircle()
for pair in contour:
points.append([[pair[0], pair[1]]])
points = np.array(points)
(cen, rad) = cv2.minEnclosingCircle(points);
return (cen[0], cen[1], rad)
#---------------------------------------------
|
const js = (el) => document.querySelector(el);
const jsAll = (el) => document.querySelectorAll(el);
const Netflix = {}
let primary = 0
Netflix.images =
{
"0": "avengers",
"1": "barracabeijo2",
"2": "billions",
"3": "blacklist",
"4": "blindspot",
"5": "freshprinceofbelair",
"6": "friends",
"7": "harrypotter",
"8": "hearth",
"9": "lastman",
"10": "mib",
"11": "mindhunter",
"12": "modernfamily",
"13": "parker",
"14": "peakyblinders",
"15": "suits",
"16": "thesinner",
"17": "visavis"
}
Netflix.slideMovies =
{
"again":
{
previous: {},
show: {},
next: {}
},
"high":
{
previous: {},
show: {},
next: {}
},
"favority":
{
previous: {},
show: {},
next: {}
},
"mylist":
{
previous: {},
show: {},
next: {}
}
}
jsAll("section.container-profiles section").forEach((element) =>
{
element.addEventListener("click", (e) =>
{
js(".a-profiles").style.opacity = 0
setTimeout(() =>
{
js(".a-profiles").style.display = "none"
}, 400);
js(".img-config img").setAttribute("src", element.children[0].getAttribute("src"))
})
})
jsAll("section.a-video section").forEach((element) =>
{
var classElement = element.getAttribute("class").split(" ")
for(images in Netflix.images)
{
if(parseInt(images) <= 5)
Netflix.slideMovies[classElement[1]].show[images] = Netflix.images[images]
else if (parseInt(images) <= 11)
Netflix.slideMovies[classElement[1]].next[images] = Netflix.images[images]
}
})
jsAll(".video-arrow-right").forEach((element) =>
{
element.addEventListener("click", (e) =>
{
let elementParentClass = element.parentNode.getAttribute("class").split(" ")[1]
Netflix.MovementSlide("right", elementParentClass)
})
})
jsAll(".video-arrow-left").forEach((element) =>
{
element.addEventListener("click", (e) =>
{
let elementParentClass = element.parentNode.getAttribute("class").split(" ")[1]
Netflix.MovementSlide("left", elementParentClass)
})
})
Netflix.CreateElementHtml = () =>
{
for(category in Netflix.slideMovies)
{
jsAll(`.a-video .${category} .video-animation-translate`).forEach((element, count = 0) =>
{
for(typeMovies in Netflix.slideMovies[category])
{
if(typeMovies == "show")
{
for(elements in Netflix.slideMovies[category][typeMovies])
{
var elementCreate = document.createElement("div")
elementCreate.classList.add(`video-item-${count}`)
elementCreate.style.cssText = `background: url(images/${Netflix.slideMovies[category][typeMovies][elements]}.png) center center no-repeat; background-size: contain;`
count++
element.append(elementCreate)
}
}
else if(typeMovies == "next")
{
for(elements in Netflix.slideMovies[category][typeMovies])
{
var elementCreate = document.createElement("div")
elementCreate.classList.add(`video-item-right`)
elementCreate.style.cssText = `background: url(images/${Netflix.slideMovies[category][typeMovies][elements]}.png) center center no-repeat; background-size: contain;`
element.append(elementCreate)
}
}
}
})
}
}
Netflix.CreateElementHtml()
Netflix.MovementSlide = (action, elementParentClass) =>
{
if(action == "right")
{
if(Netflix.slideMovies[elementParentClass] && Netflix.slideMovies[elementParentClass].next)
{
if(Netflix.slideMovies[elementParentClass].next && Object.keys(Netflix.slideMovies[elementParentClass].next).length > 0)
{
let lastElementNext = 0,
typeAnimation = 1,
breakWhile = false
Object.assign(Netflix.slideMovies[elementParentClass].previous = {}, Netflix.slideMovies[elementParentClass].show)
Netflix.slideMovies[elementParentClass].show = {}
for(count in Netflix.slideMovies[elementParentClass].next)
{
if (Object.keys(Netflix.slideMovies[elementParentClass].show).length <= 6)
{
Netflix.slideMovies[elementParentClass].show[count] = Netflix.slideMovies[elementParentClass].next[count]
delete Netflix.slideMovies[elementParentClass].next[count]
}
}
while(Object.keys(Netflix.slideMovies[elementParentClass].next).length <= 5 && !breakWhile)
{
if (lastElementNext == 0)
lastElementNext = Object.keys(Netflix.slideMovies[elementParentClass].show)[Object.keys(Netflix.slideMovies[elementParentClass].show).length - 1]
lastElementNext++
if (!lastElementNext)
typeAnimation = 0
if (Netflix.images[lastElementNext])
Netflix.slideMovies[elementParentClass].next[lastElementNext] = Netflix.images[lastElementNext]
else
breakWhile = true
}
Netflix.AlterElementAnimation(elementParentClass, "right", typeAnimation)
}
}
}
else if(action == "left")
{
if(Netflix.slideMovies[elementParentClass] && Netflix.slideMovies[elementParentClass].previous)
{
if(Netflix.slideMovies[elementParentClass].previous && Object.keys(Netflix.slideMovies[elementParentClass].previous).length > 0)
{
let typeAnimation = 1
Object.assign(Netflix.slideMovies[elementParentClass].next = {}, Netflix.slideMovies[elementParentClass].show)
Netflix.slideMovies[elementParentClass].show = {}
for (count in Netflix.slideMovies[elementParentClass].previous)
{
if (Object.keys(Netflix.slideMovies[elementParentClass].show).length <= 6)
{
Netflix.slideMovies[elementParentClass].show[count] = Netflix.slideMovies[elementParentClass].previous[count]
delete Netflix.slideMovies[elementParentClass].previous[count]
}
}
let FirstElementPrevious = Object.keys(Netflix.slideMovies[elementParentClass].show)[0],
breakWhile = false
while(Object.keys(Netflix.slideMovies[elementParentClass].previous).length <= 5 && !breakWhile)
{
FirstElementPrevious--
if(!FirstElementPrevious)
typeAnimation = 0
if (Netflix.images[FirstElementPrevious])
Netflix.slideMovies[elementParentClass].previous[FirstElementPrevious] = Netflix.images[FirstElementPrevious]
else
breakWhile = true
}
Netflix.AlterElementAnimation(elementParentClass, "left", typeAnimation)
}
}
}
}
Netflix.AlterElementAnimation = (category, side, typeAnimation) =>
{
let count = 0;
if(side == "right")
{
setTimeout(() =>{js(`.a-video .${category} .video-animation-translate`).style.cssText = "transition: none; transform: translate3d(0%, 0px, 0px);"}, 0);
setTimeout(() =>{js(`.a-video .${category} .video-animation-translate`).style.cssText = "transition: 0.4s ease all; transform: translate3d(-100.4%, 0px, 0px);"}, 50);
}
else if(side == "left")
{
if(typeAnimation == 1)
{
setTimeout(() => { js(`.a-video .${category} .video-animation-translate`).style.cssText = "transition: 0.4s ease all; transform: translate3d(0, 0px, 0px);" }, 50);
}
else
{
setTimeout(() => { js(`.a-video .${category} .video-animation-translate`).style.cssText = "transition: none; transform: translate3d(-200.4%, 0px, 0px);" }, 0);
setTimeout(() => { js(`.a-video .${category} .video-animation-translate`).style.cssText = "transition: 0.4s ease all; transform: translate3d(-100.4%, 0px, 0px);" }, 50);
}
}
jsAll(`.a-video .${category} .video-animation-translate div`).forEach((element) =>
{
element.remove()
})
for(typeMovies in Netflix.slideMovies[category])
{
if(typeMovies == "previous")
{
for(elements in Netflix.slideMovies[category][typeMovies])
{
var elementCreate = document.createElement("div")
elementCreate.classList.add(`video-item-left`)
elementCreate.style.cssText = `background: url(images/${Netflix.slideMovies[category][typeMovies][elements]}.png) center center no-repeat; background-size: contain;`
js(`.a-video .${category} .video-animation-translate`).appendChild(elementCreate)
}
}
else if(typeMovies == "show")
{
for(elements in Netflix.slideMovies[category][typeMovies])
{
var elementCreate = document.createElement("div")
elementCreate.classList.add(`video-item-${count}`)
elementCreate.style.cssText = `background: url(images/${Netflix.slideMovies[category][typeMovies][elements]}.png) center center no-repeat; background-size: contain;`
count++
js(`.a-video .${category} .video-animation-translate`).appendChild(elementCreate)
}
}
else if(typeMovies == "next")
{
for(elements in Netflix.slideMovies[category][typeMovies])
{
var elementCreate = document.createElement("div")
elementCreate.classList.add(`video-item-right`)
elementCreate.style.cssText = `background: url(images/${Netflix.slideMovies[category][typeMovies][elements]}.png) center center no-repeat; background-size: contain;`
js(`.a-video .${category} .video-animation-translate`).appendChild(elementCreate)
}
}
}
}
|
import { ValidatedMethod } from "meteor/mdg:validated-method";
import SimpleSchema from "simpl-schema";
import { Stages } from "./stages.js";
import shared from "../../shared.js";
export const updateStageData = new ValidatedMethod({
name: "Stages.methods.updateData",
validate: new SimpleSchema({
stageId: {
type: String,
regEx: SimpleSchema.RegEx.Id
},
key: {
type: String
},
value: {
type: String
},
append: {
type: Boolean,
optional: true
},
noCallback: {
type: Boolean,
optional: true
}
}).validator(),
run({ stageId, key, value, append, noCallback }) {
const stage = Stages.findOne(stageId);
if (!stage) {
throw new Error("stage not found");
}
// TODO check can update this record stage
const val = JSON.parse(value);
let update = { [`data.${key}`]: val };
const modifier = append ? { $push: update } : { $set: update };
Stages.update(stageId, modifier, {
autoConvert: false,
filter: false,
validate: false,
trimStrings: false,
removeEmptyStrings: false
});
if (Meteor.isServer && !noCallback) {
shared.callOnChange({
conn: this.connection,
stageId,
stage,
key,
value: val,
prevValue: stage.data && stage.data[key],
append
});
}
}
});
|
/**
@license
(C) Copyright Nuxeo Corp. (http://nuxeo.com/)
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.
*/
import { fixture, flush, focus, html, login, tap, waitForEvent } from '@nuxeo/testing-helpers';
import { dom } from '@polymer/polymer/lib/legacy/polymer.dom.js';
import '../widgets/nuxeo-directory-checkbox.js';
import '../widgets/nuxeo-directory-radio-group.js';
import '../widgets/nuxeo-directory-suggestion.js';
suite('nuxeo-directory-suggestion', () => {
let server;
let suggestionWidget;
setup(async () => {
server = await login();
});
const getSuggestedValue = (s2, timeout) => {
timeout = timeout || 2000;
const start = Date.now();
const waitForSuggestion = function(resolve, reject) {
const result = dom(s2.root).querySelector('.selectivity-result-item.highlight');
if (result) {
resolve(result.textContent);
} else if (timeout && Date.now() - start >= timeout) {
reject(new Error('timeout'));
} else {
setTimeout(waitForSuggestion.bind(this, resolve, reject), 30);
}
};
return new Promise(waitForSuggestion);
};
const assertSelectedValue = async (widget, input, value) => {
const s2 = dom(widget.root).querySelector('#s2');
const el = dom(s2.root).querySelector('#input');
tap(el);
dom(s2.root).querySelector(
widget.multiple ? '.selectivity-multiple-input' : '.selectivity-search-input',
).value = input;
const val = await getSuggestedValue(s2);
expect(val).to.be.equal(value);
};
suite('When I have a sigle-valued suggestion widget', () => {
setup(async () => {
// non-balanced hierarchical vocabulary
const response = [
{
absoluteLabel: 'Brittany',
computedId: 'breizh',
directoryName: 'l10ncoverage',
displayLabel: 'Brittany',
'entity-type': 'directoryEntry',
id: 'breizh',
label_en: 'Brittany',
label_fr: 'Bretagne',
obsolete: 0,
ordering: 10000000,
parent: '',
properties: {
id: 'breizh',
label_en: 'Brittany',
label_fr: 'Bretagne',
obsolete: 0,
ordering: 10000000,
parent: '',
},
},
{
children: [
{
absoluteLabel: 'South-america/Brazil',
computedId: 'south-america/Brazil',
directoryName: 'l10ncoverage',
displayLabel: 'Brazil',
'entity-type': 'directoryEntry',
id: 'Brazil',
label_en: 'Brazil',
label_fr: 'Br\u00e9sil',
obsolete: 0,
ordering: 10000000,
parent: 'south-america',
properties: {
id: 'Brazil',
label_en: 'Brazil',
label_fr: 'Br\u00e9sil',
obsolete: 0,
ordering: 10000000,
parent: 'south-america',
},
},
],
displayLabel: 'South-america',
},
];
server.respondWith('POST', '/api/v1/automation/Directory.SuggestEntries', [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
suggestionWidget = await fixture(html`
<nuxeo-directory-suggestion directory-name="l10coverage" min-chars="0"></nuxeo-directory-suggestion>
`);
});
test('Then I can select an entry', async () => {
await assertSelectedValue(suggestionWidget, 'Brittany', 'Brittany');
});
});
suite('When I have a multi-valued suggestion widget', () => {
const response = [
{
displayLabel: 'Art',
children: [
{
parent: 'art',
ordering: 10000000,
obsolete: 0,
id: 'architecture',
displayLabel: 'Architecture',
label_en: 'Architecture',
label_fr: 'Architecture',
directoryName: 'l10nsubjects',
properties: {
parent: 'art',
ordering: 10000000,
obsolete: 0,
id: 'architecture',
label_en: 'Architecture',
label_fr: 'Architecture',
},
'entity-type': 'directoryEntry',
computedId: 'art/architecture',
absoluteLabel: 'Art/Architecture',
},
{
parent: 'art',
ordering: 10000000,
obsolete: 0,
id: 'art history',
displayLabel: 'Art history',
label_en: 'Art history',
label_fr: "Histoire de l'art",
directoryName: 'l10nsubjects',
properties: {
parent: 'art',
ordering: 10000000,
obsolete: 0,
id: 'art history',
label_en: 'Art history',
label_fr: "Histoire de l'art",
},
'entity-type': 'directoryEntry',
computedId: 'art/art history',
absoluteLabel: 'Art/Art history',
},
],
},
];
setup(async () => {
server.respondWith('POST', '/api/v1/automation/Directory.SuggestEntries', [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
});
test('Then I can select an entry', async () => {
suggestionWidget = await fixture(html`
<nuxeo-directory-suggestion directory-name="l10nsubjects" multiple min-chars="0"></nuxeo-directory-suggestion>
`);
await assertSelectedValue(suggestionWidget, 'ar', 'Architecture');
});
test('Then I can select and re-select an entry', async () => {
suggestionWidget = await fixture(html`
<nuxeo-directory-suggestion directory-name="l10nsubjects" multiple min-chars="0"></nuxeo-directory-suggestion>
`);
await assertSelectedValue(suggestionWidget, 'ar', 'Architecture');
// click on the result
const s2 = dom(suggestionWidget.root).querySelector('#s2');
const results = s2.shadowRoot.querySelectorAll('.selectivity-result-item');
expect(results.length).to.equal(2);
tap(results[0]);
// assert it the label is propery presented
let selectedValues = s2.shadowRoot.querySelectorAll('.selectivity-multiple-selected-item');
expect(selectedValues.length).to.equal(1);
expect(selectedValues[0].innerText).to.equal('Art/Architecture');
// reset selection
const val = suggestionWidget.value;
suggestionWidget.value = [];
await flush();
selectedValues = s2.shadowRoot.querySelectorAll('.selectivity-multiple-selected-item');
expect(selectedValues.length).to.equal(0);
// re-set the value programatically and check that the label is properly displayed (tests entry caching)
suggestionWidget.value = val;
await flush();
selectedValues = s2.shadowRoot.querySelectorAll('.selectivity-multiple-selected-item');
expect(selectedValues.length).to.equal(1);
expect(selectedValues[0].innerText).to.equal('Art/Architecture');
});
test('Then I can select a second entry', async () => {
// this is how you get data from Directory.SuggestEntries
const selected = [response[0].children[0]];
suggestionWidget = await fixture(html`
<nuxeo-directory-suggestion
directory-name="l10nsubjects"
.value="${selected}"
multiple
min-chars="0"
></nuxeo-directory-suggestion>
`);
await assertSelectedValue(suggestionWidget, 'ar', 'Art history');
});
test("Then I can select a second entry if the first doesn't have a computedId", async () => {
// this is how you get data from a document, without the computedId
const selected = [
{
id: 'architecture',
directoryName: 'l10nsubjects',
properties: {
parent: 'art',
ordering: 10000000,
obsolete: 0,
id: 'architecture',
label_en: 'Architecture',
label_fr: 'Architecture',
},
'entity-type': 'directoryEntry',
},
];
suggestionWidget = await fixture(html`
<nuxeo-directory-suggestion
directory-name="l10nsubjects"
.value="${selected}"
multiple
min-chars="0"
></nuxeo-directory-suggestion>
`);
await assertSelectedValue(suggestionWidget, 'ar', 'Art history');
});
});
});
suite('nuxeo-directory-checkbox', () => {
let server;
setup(async () => {
server = await login();
const response = [
{
absoluteLabel: 'Arabic',
computedId: 'ar',
directoryName: 'language',
displayLabel: 'Arabic',
'entity-type': 'directoryEntry',
id: 'ar',
label: 'Arabic',
obsolete: 0,
ordering: 10000000,
properties: {
id: 'ar',
label: 'Arabic',
obsolete: 0,
ordering: 10000000,
},
},
{
absoluteLabel: 'Chinese',
computedId: 'zh',
directoryName: 'language',
displayLabel: 'Chinese',
'entity-type': 'directoryEntry',
id: 'zh',
label: 'Chinese',
obsolete: 0,
ordering: 10000000,
properties: {
id: 'zh',
label: 'Chinese',
obsolete: 0,
ordering: 10000000,
},
},
{
absoluteLabel: 'English',
computedId: 'en',
directoryName: 'language',
displayLabel: 'English',
'entity-type': 'directoryEntry',
id: 'en',
label: 'English',
obsolete: 0,
ordering: 10000000,
properties: {
id: 'en',
label: 'English',
obsolete: 0,
ordering: 10000000,
},
},
{
absoluteLabel: 'French',
computedId: 'fr',
directoryName: 'language',
displayLabel: 'French',
'entity-type': 'directoryEntry',
id: 'fr',
label: 'French',
obsolete: 0,
ordering: 10000000,
properties: {
id: 'fr',
label: 'French',
obsolete: 0,
ordering: 10000000,
},
},
];
server.respondWith('POST', '/api/v1/automation/Directory.SuggestEntries', [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
});
suite('When I have a checkbox widget initialized with English', () => {
test('Then I can deselect English and select French and Arabic instead', async () => {
const options = [
{
absoluteLabel: 'English',
computedId: 'en',
directoryName: 'language',
displayLabel: 'English',
'entity-type': 'directoryEntry',
id: 'en',
label: 'English',
obsolete: 0,
ordering: 3,
properties: {
id: 'en',
label: 'English',
obsolete: 0,
ordering: 10000000,
},
},
];
const checkboxes = await fixture(html`
<nuxeo-directory-checkbox directory-name="language" .selectedItems="${options}"></nuxeo-directory-checkbox>
`);
if (!checkboxes._entries || checkboxes._entries.length === 0) {
await waitForEvent(checkboxes, 'directory-entries-loaded');
}
await flush();
const choices = dom(checkboxes.root).querySelectorAll('paper-checkbox');
expect(choices.length).to.be.equal(4);
let selected = dom(checkboxes.root).querySelectorAll('paper-checkbox[checked]');
expect(selected.length).to.be.equal(1);
expect(selected[0].name).to.be.equal('en');
tap(selected[0]);
selected = dom(checkboxes.root).querySelectorAll('paper-checkbox[checked]');
expect(selected.length).to.be.equal(0);
tap(choices[3]);
tap(choices[0]);
selected = dom(checkboxes.root).querySelectorAll('paper-checkbox[checked]');
expect(selected.length).to.be.equal(2);
expect(selected[1].name).to.be.equal('fr');
expect(selected[0].name).to.be.equal('ar');
expect(checkboxes.value.length).to.be.equal(2);
expect(checkboxes.value[0]).to.be.equal('fr');
expect(checkboxes.value[1]).to.be.equal('ar');
expect(checkboxes.selectedItems.length).to.be.equal(2);
expect(checkboxes.selectedItems[0].id).to.be.equal('fr');
expect(checkboxes.selectedItems[1].id).to.be.equal('ar');
});
});
suite('When I have a radio group widget initialized with English', () => {
test('Then I can select French and it deselects English', async () => {
const option = {
absoluteLabel: 'English',
computedId: 'en',
directoryName: 'language',
displayLabel: 'English',
'entity-type': 'directoryEntry',
id: 'en',
label: 'English',
obsolete: 0,
ordering: 3,
properties: {
id: 'en',
label: 'English',
obsolete: 0,
ordering: 10000000,
},
};
const radioGroup = await fixture(html`
<nuxeo-directory-radio-group directory-name="language" .selectedItem="${option}"></nuxeo-directory-radio-group>
`);
if (!radioGroup._entries || radioGroup._entries.length === 0) {
await waitForEvent(radioGroup, 'directory-entries-loaded');
}
await flush();
const choices = dom(radioGroup.root).querySelectorAll('paper-radio-button');
expect(choices.length).to.be.equal(4);
let selected = dom(radioGroup.root).querySelectorAll('paper-radio-button[checked]');
expect(selected.length).to.be.equal(1);
expect(selected[0].name).to.be.equal('en');
focus(radioGroup);
tap(choices[3]);
selected = dom(radioGroup.root).querySelectorAll('paper-radio-button[checked]');
expect(selected.length).to.be.equal(1);
expect(selected[0].name).to.be.equal('fr');
expect(radioGroup.value).to.be.equal('fr');
expect(radioGroup.selectedItem.id).to.be.equal('fr');
});
});
});
|
"""
Wrap lambda handler and call main app
"""
from app import IngestAlert
def run_app(evt=None, ctx=None):
"""Parse event and run main app"""
resources = IngestAlert(event=evt).run()
return resources
def lambda_handler(event, context):
"""Lambda handler"""
try:
return run_app(event, context)
except Exception as err:
raise err
|
mycallback( {"ELECTION CODE": "P2012", "EXPENDITURE PURPOSE DESCRIP": "", "BENEFICIARY CANDIDATE OFFICE": "H", "PAYEE ZIP": "90026", "MEMO CODE": "", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Los Angeles", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "Becerra For Congress", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00343459", "EXPENDITURE AMOUNT (F3L Bundled)": "5000.00", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "Becerra", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "P.O. Box 261060", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "0.00", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "CCM", "BENEFICIARY CANDIDATE FEC ID": "H2CA30143", "BENEFICIARY COMMITTEE FEC ID": "C00264101", "BENEFICIARY CANDIDATE STATE": "CA", "BENEFICIARY CANDIDATE FIRST NAME": "Xavier", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727353.fec_1.yml", "CONDUIT STATE": "", "CATEGORY CODE": "011", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "31", "TRANSACTION ID NUMBER": "38486568", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20110129", "BENEFICIARY CANDIDATE PREFIX": "Rep.", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Becerra For Congress", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB23"});
mycallback( {"ELECTION CODE": "P2012", "EXPENDITURE PURPOSE DESCRIP": "", "BENEFICIARY CANDIDATE OFFICE": "H", "PAYEE ZIP": "90026", "MEMO CODE": "", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Los Angeles", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "Becerra For Congress", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00343459", "EXPENDITURE AMOUNT (F3L Bundled)": "5000.00", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "Becerra", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "P.O. Box 261060", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "0.00", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "CCM", "BENEFICIARY CANDIDATE FEC ID": "H2CA30143", "BENEFICIARY COMMITTEE FEC ID": "C00264101", "BENEFICIARY CANDIDATE STATE": "CA", "BENEFICIARY CANDIDATE FIRST NAME": "Xavier", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727353.fec_1.yml", "CONDUIT STATE": "", "CATEGORY CODE": "011", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "31", "TRANSACTION ID NUMBER": "38486568", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20110129", "BENEFICIARY CANDIDATE PREFIX": "Rep.", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Becerra For Congress", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB23"});
|
const defaultState = {
version: null,
cards: {},
validCards: [],
trends: {
data: [],
dt: null,
},
doodle: {
data: {},
dt: null,
},
backgroundLocal: {
filename: null,
dataUrl: '',
},
};
export default {
state: defaultState,
mutations: {
SET_VERSION(state, version) {
state.version = version;
},
SET_CARD_CACHE(state, { key, data }) {
if (!data || !Object.keys(data).length) return;
state.cards[key] = { ...data, ...{ CACHE_DT: Date.now() } };
},
DEL_CARD_CACHE(state, key) {
if (state.cards[key]) delete state.cards[key];
},
DEL_CARDS_CACHE(state) {
state.cards = {};
},
SET_TRENDS_CACHE(state, trends) {
state.trends.dt = trends && trends.length ? Date.now() : null;
state.trends.data = trends;
},
SET_DOODLE_CACHE(state, doodle) {
state.doodle.dt = doodle && doodle.url ? Date.now() : null;
state.doodle.data = doodle;
},
ADD_VALID_CARD(state, key) {
if (state.validCards.indexOf(key) > -1) return;
state.validCards.push(key);
},
DEL_VALID_CARD(state, key) {
state.validCards = state.validCards.filter(f => f !== key);
},
SET_BACKGROUND_LOCAL(state, data) {
state.backgroundLocal = data;
},
},
};
|
import React from 'react';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import renderWithRouter from './renderWithRouter';
import App from '../App';
import pokemons from '../data';
const nextPokemon = 'next-pokemon';
const pokemonName = 'pokemon-name';
describe('Testa informações do componente Pokedex.js', () => {
beforeEach(() => {
renderWithRouter(<App />);
});
it('Testa se página contém heading h2 com o texto Page requested not found', () => {
const heading = screen.getByRole('heading', { name: /Encountered pokémons/i });
expect(heading.localName).toBe('h2');
});
it('Testa se botão all inicia selecionado', () => {
const pokemonsNames = pokemons.map((pokemon) => pokemon.name);
const pokemonRotation = [...pokemonsNames, ...pokemonsNames];
const nextPokemonButton = screen.getByTestId(nextPokemon);
expect(nextPokemonButton).toHaveTextContent(/Próximo pokémon/i);
pokemonRotation.forEach((pokemon) => {
expect(screen.getByTestId(pokemonName)).toHaveTextContent(pokemon);
userEvent.click(nextPokemonButton);
});
});
it('Testa se existe um botão para cada tipo', () => {
expect(screen.getByRole('button', { name: /all/i })).toBeInTheDocument();
const pokemonsTypes = pokemons.map((pokemon) => pokemon.type)
.filter((type, index, array) => array.indexOf(type) === index);
const buttons = screen.getAllByTestId('pokemon-type-button');
pokemonsTypes.forEach((type, index) => {
expect(screen.getByRole('button', { name: type })).toBe(buttons[index]);
});
});
it('Testa se ao clicar no botão Fire, percorre pokémons daquele tipo', () => {
const firePokemons = pokemons.filter((pokemon) => pokemon.type === 'Fire')
.map((pokemon) => pokemon.name);
userEvent.click(screen.getByRole('button', { name: 'Fire' }));
const firePokemonsRotation = [...firePokemons, ...firePokemons];
const nextPokemonButton = screen.getByTestId(nextPokemon);
expect(nextPokemonButton).toHaveTextContent(/Próximo pokémon/i);
firePokemonsRotation.forEach((pokemon) => {
expect(screen.getByTestId(pokemonName)).toHaveTextContent(pokemon);
userEvent.click(nextPokemonButton);
});
});
it('Testa se botão all funciona', () => {
expect(screen.getByRole('button', { name: /all/i })).toBeInTheDocument();
userEvent.click(screen.getByRole('button', { name: /all/i }));
const pokemonsNames = pokemons.map((pokemon) => pokemon.name);
const newPokemonOrder = [...pokemonsNames.splice(1), 'Pikachu'];
const nextPokemonButton = screen.getByTestId(nextPokemon);
expect(nextPokemonButton).toHaveTextContent(/Próximo pokémon/i);
newPokemonOrder.forEach((pokemon) => {
userEvent.click(nextPokemonButton);
expect(screen.getByTestId(pokemonName)).toHaveTextContent(pokemon);
});
});
});
|
/*
Template Name: Stexo - Responsive Bootstrap 4 Admin Dashboard
Author: Themesdesign
Website: www.themesdesign.in
File: Nestable js
*/
!function($) {
"use strict";
var Nestable = function() {};
Nestable.prototype.updateOutput = function (e) {
var list = e.length ? e : $(e.target),
output = list.data('output');
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2));
} else {
output.val('JSON browser support required for this demo.');
}
},
//init
Nestable.prototype.init = function() {
// activate Nestable for list 1
$('#nestable_list_1').nestable({
group: 1
}).on('change', this.updateOutput);
// activate Nestable for list 2
$('#nestable_list_2').nestable({
group: 1
}).on('change', this.updateOutput);
// output initial serialised data
this.updateOutput($('#nestable_list_1').data('output', $('#nestable_list_1_output')));
this.updateOutput($('#nestable_list_2').data('output', $('#nestable_list_2_output')));
$('#nestable_list_menu').on('click', function (e) {
var target = $(e.target),
action = target.data('action');
if (action === 'expand-all') {
$('.dd').nestable('expandAll');
}
if (action === 'collapse-all') {
$('.dd').nestable('collapseAll');
}
});
$('#nestable_list_3').nestable();
},
//init
$.Nestable = new Nestable, $.Nestable.Constructor = Nestable
}(window.jQuery),
//initializing
function($) {
"use strict";
$.Nestable.init()
}(window.jQuery);
|
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const common = require("./common");
const app = express();
//Declare all Routes here
const authenticateRoutes = require("./routes/authenticate");
const infoRoutes = require("./routes/getInfo");
const channelsRoutes = require("./routes/channels");
const peersRoutes = require("./routes/peers");
const feesRoutes = require("./routes/fees");
const balanceRoutes = require("./routes/balance");
const walletRoutes = require("./routes/wallet");
const graphRoutes = require("./routes/graph");
const newAddressRoutes = require("./routes/newAddress");
const transactionsRoutes = require("./routes/transactions");
const payReqRoutes = require("./routes/payReq");
const paymentsRoutes = require("./routes/payments");
const RTLConfRoutes = require("./routes/RTLConf");
const invoiceRoutes = require("./routes/invoices");
const switchRoutes = require("./routes/switch");
const baseHref = "/rtl/";
const apiRoot = baseHref + "api/";
app.use(cookieParser(common.secret_key));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(baseHref, express.static(path.join(__dirname, "angular")));
// CORS fix, Only required for developement due to separate backend and frontend servers
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, filePath"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
// CORS fix, Only required for developement due to separate backend and frontend servers
// Use declared routes here
app.use(apiRoot + "authenticate", authenticateRoutes);
app.use(apiRoot + "getinfo", infoRoutes);
app.use(apiRoot + "channels", channelsRoutes);
app.use(apiRoot + "peers", peersRoutes);
app.use(apiRoot + "fees", feesRoutes);
app.use(apiRoot + "balance", balanceRoutes);
app.use(apiRoot + "wallet", walletRoutes);
app.use(apiRoot + "network", graphRoutes);
app.use(apiRoot + "newaddress", newAddressRoutes);
app.use(apiRoot + "transactions", transactionsRoutes);
app.use(apiRoot + "payreq", payReqRoutes);
app.use(apiRoot + "payments", paymentsRoutes);
app.use(apiRoot + "conf", RTLConfRoutes);
app.use(apiRoot + "invoices", invoiceRoutes);
app.use(apiRoot + "switch", switchRoutes);
// sending angular application when route doesn't match
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
module.exports = app;
|
const mongoose = require('mongoose')
const passportLocalMongoose = require('passport-local-mongoose')
const UserSchema = new mongoose.Schema ({
username: String,
password: String,
githubId: String,
notes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'note-app-note'
}
]
})
UserSchema.plugin(passportLocalMongoose)
module.exports = mongoose.model('note-app-user', UserSchema)
|
'use strict';
const CHARACTERS = [
{
id: 'card-0',
link: 'assets/catwoman.jpg',
title: 'Catwoman',
subtitle: 'Selina Kyle',
description:
'Is a fictional character created by Bill Finger and Bob Kane who appears in American comic books published by DC Comics, commonly in association with Batman.'
},
{
id: 'card-1',
link: 'assets/harley-quinn.jpg',
title: 'Harley Quinn',
subtitle: 'Dr. Harleen Frances Quinzel',
description:
'Is a fictional character appearing in media published by DC Entertainment. Created by Paul Dini and Bruce Timm to serve as a new supervillain and a romantic interest for the Joker.'
},
{
id: 'card-2',
link: 'assets/joker.jpg',
title: 'Joker',
subtitle: 'Unknown',
description:
'Is a supervillain created by Bill Finger, Bob Kane, and Jerry Robinson who first appeared in the debut issue of the comic book Batman (April 25, 1940), published by DC Comics.'
},
{
id: 'card-3',
link: 'assets/mr-freeze.png',
title: 'Mr. Freeze',
subtitle: 'Dr. Victor Fries',
description:
'Is a fictional supervillain appearing in American comic book published by DC Comics. Created by writer Dave Wood and artist Sheldon Moldoff, he first appeared in Batman #121.'
},
{
id: 'card-4',
link: 'assets/penguin.png',
title: 'Penguin',
subtitle: 'Oswald Chesterfield Cobblepot',
description:
'Is a fictional supervillain appearing in comic books published by DC Comics, commonly as an adversary of the superhero Batman.'
},
{
id: 'card-5',
link: 'assets/phantasm.jpg',
title: 'Phantasm',
subtitle: 'Andrea Beaumont',
description:
'Andrea Beaumont, also known as the Phantasm, is a fictional supervillain and antiheroine in the DC animated universe (DCAU) created by Alan Burnett and Paul Dini.'
},
{
id: 'card-6',
link: 'assets/poison-ivy.jpg',
title: 'Poison Ivy',
subtitle: 'Dr. Pamela Lillian Isley',
description:
'Is a fictional supervillain appearing in comic books published by DC Comics, commonly in Batman stories. Poison Ivy was created by Robert Kanigher and Sheldon Moldoff, and made her debut in Batman #181 (June 1966).'
},
{
id: 'card-7',
link: 'assets/ras-al-ghul.png',
title: "Ra's Al Ghul",
subtitle: 'The Head of the Demon',
description:
'Is a fictional supervillain appearing in American comic books published by DC Comics, commonly as an adversary of the crime-fighting vigilante Batman.'
},
{
id: 'card-8',
link: 'assets/riddler.png',
title: 'Riddler',
subtitle: 'Edward Nigma',
description:
'Is a fictional supervillain appearing in comic books published by DC Comics, created by Bill Finger and Dick Sprang.'
},
{
id: 'card-9',
link: 'assets/twoface.jpg',
title: 'Two Face',
subtitle: 'Harvey Dent',
description:
'Is a fictional supervillain appearing in comic books published by DC Comics, commonly as an adversary of the superhero Batman.'
}
];
class CardsListComponent extends HTMLElement {
lastCardIndex = 6;
constructor() {
super();
this.setupShadow();
}
connectedCallback() {
this.setupCards();
this.setupClickListener();
}
setupShadow() {
this.shadow = this.attachShadow({ mode: 'open' });
this.shadow.innerHTML = `
<link rel="stylesheet" href="normalize.css" />
<link rel="stylesheet" href="cards-list-component/cards-list-component.css" />
<main class="main-content"></main>
<button type="button" class="button" id="add-card-button">Add Card</button>
`;
}
setupCards() {
const container = this.shadow.querySelector('.main-content');
CHARACTERS.slice(0, this.lastCardIndex).map((character) =>
this.generateCard(character, container)
);
}
generateCard(character, container) {
const newElement = document.createElement('card-component');
newElement.setAttribute('image-link', character.link);
newElement.setAttribute('title', character.title);
newElement.setAttribute('subtitle', character.subtitle);
newElement.setAttribute('description', character.description);
newElement.id = character.id;
newElement.addEventListener('DeleteCard', () => this.removeCard(character.id));
container.appendChild(newElement);
}
setupClickListener() {
const button = this.shadow.getElementById('add-card-button');
button.addEventListener('click', (e) => this.addCard());
}
addCard() {
this.lastCardIndex++;
if (this.lastCardIndex <= CHARACTERS.length) {
this.generateCard(
CHARACTERS[this.lastCardIndex - 1],
this.shadow.querySelector('.main-content')
);
}
}
removeCard(id) {
this.shadow.getElementById(id).remove();
}
}
customElements.define('cards-list', CardsListComponent);
|
H5.define("System.Collections.Generic.SortedSetEqualityComparer$1", function (T) { return {
inherits: [System.Collections.Generic.IEqualityComparer$1(System.Collections.Generic.SortedSet$1(T))],
fields: {
comparer: null,
e_comparer: null
},
alias: [
"equals2", ["System$Collections$Generic$IEqualityComparer$1$System$Collections$Generic$SortedSet$1$" + H5.getTypeAlias(T) + "$equals2", "System$Collections$Generic$IEqualityComparer$1$equals2"],
"getHashCode2", ["System$Collections$Generic$IEqualityComparer$1$System$Collections$Generic$SortedSet$1$" + H5.getTypeAlias(T) + "$getHashCode2", "System$Collections$Generic$IEqualityComparer$1$getHashCode2"]
],
ctors: {
ctor: function () {
System.Collections.Generic.SortedSetEqualityComparer$1(T).$ctor2.call(this, null, null);
},
$ctor1: function (comparer) {
System.Collections.Generic.SortedSetEqualityComparer$1(T).$ctor2.call(this, comparer, null);
},
$ctor3: function (memberEqualityComparer) {
System.Collections.Generic.SortedSetEqualityComparer$1(T).$ctor2.call(this, null, memberEqualityComparer);
},
$ctor2: function (comparer, memberEqualityComparer) {
this.$initialize();
if (comparer == null) {
this.comparer = new (System.Collections.Generic.Comparer$1(T))(System.Collections.Generic.Comparer$1.$default.fn);
} else {
this.comparer = comparer;
}
if (memberEqualityComparer == null) {
this.e_comparer = System.Collections.Generic.EqualityComparer$1(T).def;
} else {
this.e_comparer = memberEqualityComparer;
}
}
},
methods: {
equals2: function (x, y) {
return System.Collections.Generic.SortedSet$1(T).SortedSetEquals(x, y, this.comparer);
},
equals: function (obj) {
var comparer;
if (!(((comparer = H5.as(obj, System.Collections.Generic.SortedSetEqualityComparer$1(T)))) != null)) {
return false;
}
return (H5.referenceEquals(this.comparer, comparer.comparer));
},
getHashCode2: function (obj) {
var $t;
var hashCode = 0;
if (obj != null) {
$t = H5.getEnumerator(obj);
try {
while ($t.moveNext()) {
var t = $t.Current;
hashCode = hashCode ^ (this.e_comparer[H5.geti(this.e_comparer, "System$Collections$Generic$IEqualityComparer$1$" + H5.getTypeAlias(T) + "$getHashCode2", "System$Collections$Generic$IEqualityComparer$1$getHashCode2")](t) & 2147483647);
}
} finally {
if (H5.is($t, System.IDisposable)) {
$t.System$IDisposable$Dispose();
}
}
}
return hashCode;
},
getHashCode: function () {
return H5.getHashCode(this.comparer) ^ H5.getHashCode(this.e_comparer);
}
}
}; });
|
/**
* DevExtreme (exporter/excel/excel.doc_comments.js)
* Version: 19.2.4
* Build date: Tue Nov 19 2019
*
* Copyright (c) 2012 - 2019 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
|
import hooks from 'feathers-hooks';
import { hooks as auth } from 'feathers-authentication';
import { validateHook as validate } from '../../hooks';
import { required } from '../../utils/validation';
import uuid from 'uuid';
import dashify from 'dashify';
const schemaValidator = {
name: [required],
email: [required],
address: [required],
comment: [required]
};
const options = {
service: 'guestbooks',
field: 'sentBy'
};
const guestbookHooks = {
before: {
all: [],
find: [],
get: [],
create: [
validate(schemaValidator),
hook => {
hook.data = {
_id: uuid.v4(),
name: hook.data.name,
slug: dashify(hook.data.name),
email: hook.data.email,
address: hook.data.address,
comment: hook.data.comment
};
},
hook => {
hook.data.createdAt = new Date();
}
],
update: [
validate(schemaValidator),
hook => {
hook.data = {
name: hook.data.name,
slug: dashify(hook.data.name),
email: hook.data.email,
address: hook.data.address,
comment: hook.data.comment
};
},
hook => {
hook.data.updatedAt = new Date();
}
],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
export default guestbookHooks;
|
module.exports={"type":"FeatureCollection","features":[{"type":"Feature","id":"310230","properties":{"name":"崇明县","cp":[121.5637,31.5383],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.9798,31.3522],[121.9537,31.219],[121.9276,31.1586],[121.9235,31.1668],[121.918,31.1771],[121.8631,31.2472],[121.6104,31.3859],[121.5816,31.3996],[121.5569,31.4044],[121.5349,31.4024],[121.5211,31.3907],[121.5349,31.4168],[121.5678,31.4779],[121.4951,31.4985],[121.4209,31.5218],[121.3866,31.5445],[121.322,31.5829],[121.2657,31.6461],[121.2273,31.6756],[121.1201,31.7471],[121.1009,31.7628],[121.1572,31.7965],[121.2039,31.8308],[121.2259,31.8432],[121.2547,31.8555],[121.2849,31.8665],[121.3138,31.8672],[121.3289,31.8624],[121.3522,31.8521],[121.3687,31.8411],[121.403,31.8116],[121.4195,31.7862],[121.4333,31.7704],[121.447,31.7622],[121.4731,31.7532],[121.5129,31.7477],[121.5651,31.7223],[121.5994,31.7155],[121.7285,31.6667],[121.7368,31.6653],[121.756,31.6564],[121.8672,31.6193],[121.8892,31.6187],[121.9043,31.6152],[121.9991,31.6138],[121.9991,31.5019],[121.9881,31.3934],[121.9798,31.3522]]]}},{"type":"Feature","id":"310119","properties":{"name":"南汇区","cp":[121.8755,30.954],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.9276,31.1586],[121.9427,31.1304],[121.9839,31.0316],[121.9908,30.8331],[121.9922,30.8064],[121.7972,30.7452],[121.7642,30.8187],[121.7697,30.8462],[121.7683,30.864],[121.7725,30.8791],[121.7766,30.8805],[121.7766,30.8867],[121.778,30.8956],[121.7793,30.8956],[121.778,30.9039],[121.7807,30.9155],[121.7793,30.9224],[121.778,30.9224],[121.778,30.9306],[121.7738,30.9313],[121.7683,30.9382],[121.7656,30.9361],[121.7628,30.9368],[121.7642,30.9375],[121.7615,30.9382],[121.7642,30.9416],[121.7615,30.9437],[121.7628,30.9457],[121.7532,30.9526],[121.7477,30.9519],[121.7368,30.9588],[121.7381,30.9608],[121.7313,30.9677],[121.7065,30.9856],[121.6928,30.9897],[121.675,30.9917],[121.6736,30.9897],[121.6557,30.9931],[121.6214,30.9924],[121.6187,30.9952],[121.6145,31.0014],[121.6118,31.002],[121.5953,31.0027],[121.5939,31.0007],[121.5706,30.9986],[121.5692,31.0007],[121.5706,31.002],[121.5706,31.0082],[121.5665,31.0123],[121.5692,31.0123],[121.5706,31.0172],[121.5733,31.0185],[121.5747,31.0226],[121.572,31.0247],[121.572,31.0261],[121.5678,31.0247],[121.5651,31.0213],[121.561,31.024],[121.5555,31.0192],[121.5514,31.0206],[121.5527,31.0233],[121.5582,31.024],[121.5569,31.0261],[121.5569,31.0288],[121.561,31.0295],[121.5582,31.0323],[121.5582,31.0412],[121.561,31.0439],[121.5541,31.0494],[121.5514,31.0494],[121.5417,31.0453],[121.5404,31.0522],[121.5431,31.0549],[121.5486,31.0563],[121.5472,31.0632],[121.5555,31.0666],[121.5555,31.0673],[121.5527,31.0666],[121.5555,31.0714],[121.5761,31.0803],[121.5706,31.0796],[121.5692,31.0817],[121.5623,31.0831],[121.5541,31.0803],[121.5486,31.0865],[121.5514,31.0879],[121.5514,31.0899],[121.5678,31.0927],[121.5665,31.0968],[121.5623,31.0975],[121.561,31.105],[121.561,31.1064],[121.5569,31.1098],[121.5596,31.1105],[121.5582,31.1119],[121.5541,31.114],[121.5527,31.1119],[121.5527,31.1133],[121.55,31.1126],[121.55,31.1105],[121.5472,31.1092],[121.5431,31.1126],[121.5431,31.1153],[121.5376,31.1133],[121.5349,31.1181],[121.5376,31.1222],[121.5335,31.1236],[121.5363,31.1256],[121.5321,31.1291],[121.5308,31.127],[121.528,31.1291],[121.5349,31.1339],[121.5363,31.1325],[121.5472,31.1353],[121.5486,31.1373],[121.5459,31.1462],[121.5404,31.1552],[121.5459,31.1572],[121.5527,31.1517],[121.5623,31.1524],[121.5623,31.151],[121.5829,31.1579],[121.5871,31.1524],[121.6022,31.1552],[121.6035,31.1524],[121.6214,31.16],[121.6324,31.1613],[121.6365,31.1634],[121.6393,31.1579],[121.6434,31.1565],[121.6461,31.1531],[121.6475,31.1476],[121.6434,31.1456],[121.6447,31.1339],[121.6461,31.1291],[121.6489,31.1291],[121.6489,31.1277],[121.6516,31.1263],[121.6722,31.1291],[121.6777,31.1359],[121.6818,31.1373],[121.6832,31.1407],[121.6846,31.1407],[121.6832,31.1462],[121.6832,31.1449],[121.6805,31.1476],[121.6846,31.1483],[121.6846,31.1497],[121.6887,31.1497],[121.6901,31.1531],[121.6914,31.151],[121.6983,31.1531],[121.6997,31.1462],[121.7024,31.1428],[121.6942,31.1394],[121.6956,31.1346],[121.6983,31.1325],[121.7052,31.1346],[121.7093,31.1298],[121.7175,31.1298],[121.7216,31.1311],[121.7203,31.1325],[121.723,31.1318],[121.7216,31.1325],[121.7258,31.1353],[121.7299,31.1325],[121.7313,31.1222],[121.7436,31.1208],[121.7436,31.1229],[121.7519,31.1222],[121.7519,31.1277],[121.7532,31.1284],[121.9276,31.1586]]]}},{"type":"Feature","id":"310120","properties":{"name":"奉贤区","cp":[121.5747,30.8475],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.3605,30.978],[121.3907,30.9876],[121.4209,30.9931],[121.4415,31.0055],[121.4594,31.0075],[121.4758,31.013],[121.4882,31.0151],[121.4937,31.013],[121.4951,30.9979],[121.4992,30.9979],[121.4992,31.0007],[121.5033,31.0034],[121.5157,31.0082],[121.5211,31.0034],[121.5198,30.9993],[121.5239,30.9993],[121.528,30.9959],[121.5363,30.9952],[121.5376,30.9931],[121.5445,30.9938],[121.55,30.9883],[121.5527,30.9883],[121.5527,30.9945],[121.5555,30.9931],[121.5569,30.9952],[121.5706,30.9986],[121.5939,31.0007],[121.5953,31.0027],[121.6118,31.002],[121.6145,31.0014],[121.6187,30.9952],[121.6214,30.9924],[121.6557,30.9931],[121.6736,30.9897],[121.675,30.9917],[121.6928,30.9897],[121.7065,30.9856],[121.7313,30.9677],[121.7381,30.9608],[121.7368,30.9588],[121.7477,30.9519],[121.7532,30.9526],[121.7628,30.9457],[121.7615,30.9437],[121.7642,30.9416],[121.7615,30.9382],[121.7642,30.9375],[121.7628,30.9368],[121.7656,30.9361],[121.7683,30.9382],[121.7738,30.9313],[121.778,30.9306],[121.778,30.9224],[121.7793,30.9224],[121.7807,30.9155],[121.778,30.9039],[121.7793,30.8956],[121.778,30.8956],[121.7766,30.8867],[121.7766,30.8805],[121.7725,30.8791],[121.7683,30.864],[121.7697,30.8462],[121.7642,30.8187],[121.7972,30.7452],[121.712,30.7205],[121.5417,30.68],[121.4607,30.7768],[121.4429,30.8022],[121.4374,30.8187],[121.4305,30.8201],[121.4209,30.8201],[121.4182,30.816],[121.4154,30.8167],[121.4127,30.8221],[121.4127,30.8215],[121.4058,30.8228],[121.4003,30.8283],[121.4003,30.8297],[121.4044,30.8304],[121.4044,30.8338],[121.4003,30.8345],[121.3962,30.829],[121.3934,30.8283],[121.3921,30.8297],[121.3879,30.8297],[121.3879,30.8324],[121.3811,30.8359],[121.3797,30.8434],[121.3852,30.8434],[121.3838,30.8633],[121.3824,30.8654],[121.3824,30.8784],[121.3742,30.8812],[121.3728,30.8867],[121.3673,30.8881],[121.3632,30.8867],[121.3577,30.9073],[121.3522,30.9128],[121.3564,30.9196],[121.3522,30.9245],[121.3509,30.9306],[121.355,30.9306],[121.355,30.9334],[121.3632,30.9354],[121.3605,30.9444],[121.366,30.9471],[121.3618,30.9492],[121.3632,30.956],[121.3605,30.978]]]}},{"type":"Feature","id":"310115","properties":{"name":"浦东新区","cp":[121.6928,31.2561],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.4676,31.1668],[121.4648,31.1737],[121.4648,31.1785],[121.469,31.184],[121.4758,31.1881],[121.4964,31.1936],[121.5019,31.2005],[121.5102,31.2156],[121.506,31.2238],[121.4937,31.2348],[121.4951,31.2417],[121.5074,31.2465],[121.5157,31.2472],[121.5266,31.2472],[121.5349,31.2492],[121.561,31.2664],[121.5665,31.2733],[121.5692,31.2794],[121.5692,31.2856],[121.5651,31.2925],[121.5623,31.3014],[121.5623,31.3234],[121.5596,31.3303],[121.5514,31.3378],[121.5253,31.3467],[121.5088,31.357],[121.5047,31.3673],[121.5074,31.3783],[121.5211,31.3907],[121.5349,31.4024],[121.5569,31.4044],[121.5816,31.3996],[121.6104,31.3859],[121.8631,31.2472],[121.918,31.1771],[121.9235,31.1668],[121.9276,31.1586],[121.7532,31.1284],[121.7519,31.1277],[121.7519,31.1222],[121.7436,31.1229],[121.7436,31.1208],[121.7313,31.1222],[121.7299,31.1325],[121.7258,31.1353],[121.7216,31.1325],[121.723,31.1318],[121.7203,31.1325],[121.7216,31.1311],[121.7175,31.1298],[121.7093,31.1298],[121.7052,31.1346],[121.6983,31.1325],[121.6956,31.1346],[121.6942,31.1394],[121.7024,31.1428],[121.6997,31.1462],[121.6983,31.1531],[121.6914,31.151],[121.6901,31.1531],[121.6887,31.1497],[121.6846,31.1497],[121.6846,31.1483],[121.6805,31.1476],[121.6832,31.1449],[121.6832,31.1462],[121.6846,31.1407],[121.6832,31.1407],[121.6818,31.1373],[121.6777,31.1359],[121.6722,31.1291],[121.6516,31.1263],[121.6489,31.1277],[121.6489,31.1291],[121.6461,31.1291],[121.6447,31.1339],[121.6434,31.1456],[121.6475,31.1476],[121.6461,31.1531],[121.6434,31.1565],[121.6393,31.1579],[121.6365,31.1634],[121.6324,31.1613],[121.6214,31.16],[121.6035,31.1524],[121.6022,31.1552],[121.5871,31.1524],[121.5829,31.1579],[121.5623,31.151],[121.5623,31.1524],[121.5527,31.1517],[121.5459,31.1572],[121.5404,31.1552],[121.5459,31.1462],[121.5486,31.1373],[121.5472,31.1353],[121.5363,31.1325],[121.5349,31.1339],[121.528,31.1291],[121.5308,31.127],[121.5321,31.1291],[121.5363,31.1256],[121.5335,31.1236],[121.5376,31.1222],[121.5349,31.1181],[121.5225,31.1153],[121.517,31.116],[121.5129,31.1215],[121.506,31.1201],[121.5047,31.1153],[121.5019,31.1147],[121.4992,31.1215],[121.4937,31.1195],[121.4909,31.1243],[121.4868,31.1243],[121.4799,31.1174],[121.4813,31.1105],[121.4786,31.1112],[121.4786,31.1092],[121.4745,31.114],[121.4635,31.1085],[121.4703,31.1188],[121.4703,31.1236],[121.469,31.1284],[121.4594,31.138],[121.4566,31.1456],[121.469,31.1586],[121.4676,31.1668]]]}},{"type":"Feature","id":"310116","properties":{"name":"金山区","cp":[121.2657,30.8112],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[120.9966,30.9512],[121.002,30.9512],[121.0034,30.9471],[121.0075,30.9499],[121.0144,30.9499],[121.0144,30.9471],[121.0117,30.9464],[121.0117,30.9437],[121.0144,30.9444],[121.0158,30.9409],[121.0185,30.9396],[121.0172,30.9416],[121.0281,30.9437],[121.0295,30.9437],[121.0295,30.9409],[121.0323,30.9409],[121.0309,30.9396],[121.0309,30.9348],[121.0254,30.9093],[121.035,30.9066],[121.035,30.9032],[121.0364,30.9018],[121.0391,30.9018],[121.0405,30.9045],[121.0405,30.9032],[121.0515,30.9025],[121.0803,30.9059],[121.0817,30.9039],[121.0858,30.9052],[121.0913,30.9032],[121.0982,30.9066],[121.0968,30.9093],[121.0954,30.9087],[121.0968,30.91],[121.0899,30.9114],[121.0886,30.9148],[121.1009,30.9265],[121.105,30.921],[121.1105,30.9224],[121.1215,30.9196],[121.1188,30.9107],[121.1174,30.9107],[121.1105,30.899],[121.1133,30.8977],[121.1229,30.9032],[121.127,30.9032],[121.1298,30.9004],[121.1407,30.9011],[121.1407,30.9107],[121.138,30.9135],[121.1394,30.9196],[121.1435,30.9183],[121.1421,30.9155],[121.1504,30.9128],[121.1504,30.9114],[121.1559,30.9107],[121.1572,30.9196],[121.1641,30.9203],[121.171,30.9148],[121.1847,30.9155],[121.2094,30.9203],[121.2231,30.9313],[121.2273,30.9272],[121.2341,30.9293],[121.2341,30.9272],[121.241,30.9258],[121.2424,30.9203],[121.2451,30.9196],[121.2465,30.9107],[121.2671,30.9066],[121.2657,30.9025],[121.2726,30.9004],[121.2726,30.897],[121.2781,30.897],[121.2808,30.8949],[121.2836,30.8977],[121.2877,30.8963],[121.2877,30.9004],[121.2904,30.9004],[121.2904,30.9183],[121.2959,30.919],[121.2987,30.91],[121.3014,30.9087],[121.3028,30.9128],[121.3138,30.9087],[121.3275,30.9107],[121.3371,30.908],[121.3454,30.9093],[121.3467,30.9135],[121.3522,30.9128],[121.3577,30.9073],[121.3632,30.8867],[121.3673,30.8881],[121.3728,30.8867],[121.3742,30.8812],[121.3824,30.8784],[121.3824,30.8654],[121.3838,30.8633],[121.3852,30.8434],[121.3797,30.8434],[121.3811,30.8359],[121.3879,30.8324],[121.3879,30.8297],[121.3921,30.8297],[121.3934,30.8283],[121.3962,30.829],[121.4003,30.8345],[121.4044,30.8338],[121.4044,30.8304],[121.4003,30.8297],[121.4003,30.8283],[121.4058,30.8228],[121.4127,30.8215],[121.4127,30.8221],[121.4154,30.8167],[121.4182,30.816],[121.4209,30.8201],[121.4305,30.8201],[121.4374,30.8187],[121.4429,30.8022],[121.4607,30.7768],[121.5417,30.68],[121.5129,30.6711],[121.5005,30.6711],[121.4676,30.6704],[121.4113,30.6725],[121.2822,30.6841],[121.2712,30.6951],[121.2657,30.7095],[121.2671,30.7123],[121.2671,30.715],[121.2698,30.7185],[121.2698,30.7226],[121.2712,30.7267],[121.2685,30.7294],[121.2712,30.7322],[121.2671,30.7349],[121.2643,30.7356],[121.2547,30.7446],[121.2328,30.7555],[121.23,30.7672],[121.2259,30.7713],[121.2286,30.772],[121.2218,30.7748],[121.2177,30.7858],[121.2053,30.7858],[121.2012,30.7844],[121.1984,30.7816],[121.2012,30.7741],[121.1971,30.7734],[121.1916,30.7803],[121.1861,30.7796],[121.1874,30.7755],[121.1751,30.7727],[121.1696,30.7755],[121.16,30.7741],[121.1504,30.7796],[121.1421,30.7803],[121.1325,30.7775],[121.127,30.7789],[121.1256,30.7926],[121.1284,30.8098],[121.1298,30.816],[121.138,30.8249],[121.138,30.8297],[121.1339,30.829],[121.1325,30.8318],[121.1339,30.8331],[121.1311,30.8366],[121.1311,30.8352],[121.1201,30.8366],[121.1201,30.8421],[121.1243,30.8475],[121.1119,30.8544],[121.1105,30.8551],[121.1119,30.8537],[121.1119,30.8524],[121.1009,30.8496],[121.0968,30.8572],[121.0803,30.8489],[121.0652,30.8482],[121.0597,30.8455],[121.0597,30.8379],[121.0474,30.8311],[121.0501,30.8263],[121.046,30.8256],[121.0432,30.8283],[121.0405,30.827],[121.0446,30.8173],[121.0432,30.816],[121.0378,30.8146],[121.0295,30.829],[121.0158,30.8338],[121.013,30.8352],[121.0144,30.8359],[121.0117,30.8352],[121.0048,30.8283],[121.0034,30.829],[121.0034,30.8276],[120.9993,30.829],[120.9938,30.8215],[120.9897,30.8235],[120.9924,30.827],[120.9911,30.8283],[120.9924,30.8311],[120.9897,30.8338],[120.9924,30.8379],[120.9952,30.8379],[121.002,30.8462],[121.0034,30.8455],[121.0062,30.851],[121.0103,30.8537],[121.0144,30.8544],[121.0117,30.8558],[121.013,30.8599],[121.0144,30.8592],[121.0158,30.8606],[121.0144,30.8613],[121.0158,30.8627],[121.0144,30.8647],[121.0185,30.8688],[121.0158,30.8709],[121.0185,30.8736],[121.0199,30.8723],[121.0213,30.8743],[121.0199,30.8764],[121.0199,30.8791],[121.0172,30.8826],[121.0089,30.8833],[121.0075,30.8881],[120.9938,30.8901],[120.9938,30.8936],[120.9911,30.8956],[120.9924,30.9025],[120.9979,30.9039],[120.9993,30.9059],[121.0034,30.9052],[121.0048,30.9093],[120.9993,30.9107],[121.0007,30.9375],[120.9966,30.943],[120.9979,30.9478],[120.9966,30.9512]]]}},{"type":"Feature","id":"310118","properties":{"name":"青浦区","cp":[121.1751,31.1909],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.1531,31.2767],[121.1613,31.2664],[121.1682,31.2602],[121.1861,31.252],[121.1888,31.2547],[121.1943,31.2527],[121.2108,31.2609],[121.2135,31.254],[121.219,31.2534],[121.2231,31.2616],[121.2286,31.263],[121.2355,31.263],[121.241,31.2595],[121.2465,31.2595],[121.2465,31.2582],[121.2547,31.2595],[121.2424,31.2465],[121.241,31.241],[121.2479,31.2403],[121.2575,31.23],[121.2575,31.2204],[121.2616,31.2163],[121.2589,31.2135],[121.2643,31.2087],[121.2657,31.2032],[121.2712,31.1977],[121.2822,31.1929],[121.2946,31.2032],[121.3014,31.1971],[121.3165,31.1765],[121.3234,31.1634],[121.3234,31.1613],[121.3193,31.1586],[121.3193,31.1572],[121.3179,31.1565],[121.3124,31.1579],[121.3042,31.1552],[121.3,31.1517],[121.2891,31.1552],[121.2877,31.1531],[121.2781,31.1517],[121.2794,31.149],[121.2753,31.1456],[121.2781,31.1442],[121.2794,31.1456],[121.2822,31.1414],[121.2836,31.1428],[121.2877,31.1407],[121.2877,31.1387],[121.2822,31.1339],[121.263,31.1366],[121.2616,31.1325],[121.2616,31.127],[121.2575,31.1277],[121.2589,31.1318],[121.2479,31.1339],[121.2451,31.1311],[121.241,31.1298],[121.2451,31.1298],[121.2451,31.1256],[121.2369,31.1256],[121.2369,31.1174],[121.2218,31.1153],[121.2286,31.1387],[121.2108,31.1366],[121.2012,31.138],[121.2025,31.1407],[121.1957,31.138],[121.1819,31.1428],[121.1806,31.1284],[121.1819,31.1243],[121.1847,31.1243],[121.1833,31.1188],[121.1751,31.1181],[121.1751,31.1085],[121.1655,31.1098],[121.1655,31.1064],[121.1668,31.1064],[121.1668,31.1016],[121.1545,31.1016],[121.1545,31.0989],[121.1572,31.0989],[121.1559,31.0899],[121.1504,31.0954],[121.1462,31.0941],[121.1449,31.0975],[121.1421,31.0968],[121.1421,31.0989],[121.1339,31.0989],[121.1325,31.1016],[121.127,31.1023],[121.1215,31.1092],[121.1174,31.1085],[121.116,31.1105],[121.1147,31.1092],[121.1133,31.1119],[121.1105,31.1078],[121.105,31.1037],[121.1064,31.1009],[121.1023,31.1016],[121.1037,31.1002],[121.1023,31.0989],[121.0968,31.1016],[121.0954,31.1002],[121.1009,31.0954],[121.0982,31.0934],[121.1009,31.0886],[121.1009,31.0817],[121.1023,31.0796],[121.1078,31.0817],[121.1119,31.0776],[121.1188,31.0762],[121.1229,31.0666],[121.1256,31.0666],[121.127,31.0597],[121.1284,31.0597],[121.1256,31.057],[121.1201,31.0583],[121.1188,31.0577],[121.1188,31.0563],[121.1037,31.0577],[121.1009,31.0535],[121.0995,31.0563],[121.0954,31.0563],[121.0941,31.0583],[121.0954,31.0618],[121.0913,31.0652],[121.0858,31.0632],[121.0872,31.0618],[121.0817,31.0563],[121.0858,31.0501],[121.0872,31.0501],[121.0872,31.0529],[121.0913,31.0494],[121.0899,31.048],[121.0968,31.0446],[121.0941,31.0412],[121.0968,31.0398],[121.1009,31.0336],[121.0995,31.0309],[121.0968,31.0316],[121.0954,31.0261],[121.0913,31.0261],[121.0899,31.0275],[121.0844,31.0254],[121.0913,31.0233],[121.105,31.0096],[121.1037,30.9952],[121.0995,30.9952],[121.0995,30.9732],[121.0954,30.9739],[121.0968,30.9657],[121.0886,30.9622],[121.0803,30.9622],[121.0817,30.9602],[121.0789,30.9602],[121.0776,30.956],[121.0638,30.9547],[121.057,30.9608],[121.057,30.965],[121.0529,30.9643],[121.0515,30.9698],[121.0432,30.9691],[121.046,30.9636],[121.0432,30.9567],[121.0364,30.9567],[121.0336,30.9478],[121.0281,30.9457],[121.0281,30.9437],[121.0172,30.9416],[121.0185,30.9396],[121.0158,30.9409],[121.0144,30.9444],[121.0117,30.9437],[121.0117,30.9464],[121.0144,30.9471],[121.0144,30.9499],[121.0075,30.9499],[121.0034,30.9471],[121.002,30.9512],[120.9966,30.9512],[120.9924,30.9581],[120.9952,30.9581],[120.9924,30.9705],[121.0007,30.9739],[121.0007,30.9766],[121.002,30.9773],[120.9952,30.9917],[120.9952,30.9952],[120.9911,30.9945],[120.9924,30.9993],[120.9911,31.002],[120.9924,31.0034],[120.9897,31.0123],[120.9897,31.0144],[120.9842,31.0144],[120.9842,31.0158],[120.9814,31.0165],[120.9787,31.0151],[120.9732,31.0178],[120.965,31.0165],[120.9636,31.0172],[120.965,31.0206],[120.9608,31.022],[120.9581,31.0288],[120.9485,31.0302],[120.9485,31.0254],[120.9512,31.024],[120.9512,31.0199],[120.943,31.0172],[120.9402,31.0096],[120.9279,31.0123],[120.9238,31.0103],[120.9196,31.0123],[120.9087,31.011],[120.9059,31.0165],[120.9004,31.0178],[120.9018,31.0275],[120.9004,31.0316],[120.9059,31.0357],[120.9032,31.0371],[120.9032,31.0384],[120.8977,31.0419],[120.8977,31.048],[120.8949,31.0487],[120.899,31.0776],[120.9032,31.0783],[120.9045,31.0796],[120.9018,31.0838],[120.9018,31.0851],[120.8963,31.0865],[120.8949,31.0906],[120.8922,31.0934],[120.8922,31.0975],[120.8894,31.0941],[120.8784,31.0954],[120.8784,31.0982],[120.8743,31.1009],[120.8702,31.0995],[120.8688,31.0975],[120.8661,31.0975],[120.8647,31.1009],[120.8565,31.1016],[120.8565,31.1085],[120.8606,31.1092],[120.8688,31.1174],[120.8743,31.1284],[120.8812,31.1353],[120.8839,31.1359],[120.8963,31.1366],[120.9045,31.1346],[120.9361,31.1421],[120.9526,31.1414],[120.9787,31.1346],[121.0048,31.1353],[121.0226,31.1387],[121.0226,31.1407],[121.0281,31.1442],[121.0281,31.1414],[121.0336,31.1421],[121.0364,31.1407],[121.0364,31.138],[121.0405,31.138],[121.0446,31.1449],[121.0419,31.1469],[121.0419,31.1497],[121.0446,31.151],[121.0446,31.1545],[121.0501,31.1524],[121.0501,31.151],[121.0556,31.151],[121.0556,31.1524],[121.0597,31.1531],[121.068,31.1483],[121.0762,31.1668],[121.0762,31.1703],[121.0735,31.1703],[121.0721,31.1737],[121.0748,31.1737],[121.0707,31.1813],[121.0748,31.1833],[121.0748,31.1847],[121.0693,31.1826],[121.0693,31.1847],[121.0721,31.1861],[121.0693,31.1888],[121.0721,31.1909],[121.0721,31.1929],[121.0693,31.1957],[121.0666,31.195],[121.0666,31.1971],[121.0693,31.1964],[121.0638,31.217],[121.0625,31.2259],[121.0652,31.2273],[121.0638,31.2307],[121.0666,31.2328],[121.0611,31.2348],[121.0611,31.2383],[121.0638,31.2389],[121.0638,31.2465],[121.057,31.2465],[121.0611,31.2465],[121.0625,31.2685],[121.0789,31.2698],[121.0831,31.2719],[121.0844,31.2746],[121.0817,31.2774],[121.0817,31.2794],[121.0872,31.2918],[121.0886,31.2918],[121.0927,31.2891],[121.0941,31.2897],[121.0941,31.2843],[121.0968,31.2829],[121.0982,31.2774],[121.1009,31.2753],[121.1064,31.2767],[121.1064,31.2794],[121.1078,31.2774],[121.1078,31.2808],[121.1092,31.2801],[121.1147,31.2856],[121.1174,31.2856],[121.1256,31.2843],[121.1243,31.2829],[121.1298,31.2801],[121.138,31.2788],[121.1366,31.2774],[121.1407,31.276],[121.1421,31.2774],[121.1421,31.2746],[121.1476,31.2746],[121.1531,31.2767]]]}},{"type":"Feature","id":"310117","properties":{"name":"松江区","cp":[121.1984,31.0268],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.0281,30.9437],[121.0281,30.9457],[121.0336,30.9478],[121.0364,30.9567],[121.0432,30.9567],[121.046,30.9636],[121.0432,30.9691],[121.0515,30.9698],[121.0529,30.9643],[121.057,30.965],[121.057,30.9608],[121.0638,30.9547],[121.0776,30.956],[121.0789,30.9602],[121.0817,30.9602],[121.0803,30.9622],[121.0886,30.9622],[121.0968,30.9657],[121.0954,30.9739],[121.0995,30.9732],[121.0995,30.9952],[121.1037,30.9952],[121.105,31.0096],[121.0913,31.0233],[121.0844,31.0254],[121.0899,31.0275],[121.0913,31.0261],[121.0954,31.0261],[121.0968,31.0316],[121.0995,31.0309],[121.1009,31.0336],[121.0968,31.0398],[121.0941,31.0412],[121.0968,31.0446],[121.0899,31.048],[121.0913,31.0494],[121.0872,31.0529],[121.0872,31.0501],[121.0858,31.0501],[121.0817,31.0563],[121.0872,31.0618],[121.0858,31.0632],[121.0913,31.0652],[121.0954,31.0618],[121.0941,31.0583],[121.0954,31.0563],[121.0995,31.0563],[121.1009,31.0535],[121.1037,31.0577],[121.1188,31.0563],[121.1188,31.0577],[121.1201,31.0583],[121.1256,31.057],[121.1284,31.0597],[121.127,31.0597],[121.1256,31.0666],[121.1229,31.0666],[121.1188,31.0762],[121.1119,31.0776],[121.1078,31.0817],[121.1023,31.0796],[121.1009,31.0817],[121.1009,31.0886],[121.0982,31.0934],[121.1009,31.0954],[121.0954,31.1002],[121.0968,31.1016],[121.1023,31.0989],[121.1037,31.1002],[121.1023,31.1016],[121.1064,31.1009],[121.105,31.1037],[121.1105,31.1078],[121.1133,31.1119],[121.1147,31.1092],[121.116,31.1105],[121.1174,31.1085],[121.1215,31.1092],[121.127,31.1023],[121.1325,31.1016],[121.1339,31.0989],[121.1421,31.0989],[121.1421,31.0968],[121.1449,31.0975],[121.1462,31.0941],[121.1504,31.0954],[121.1559,31.0899],[121.1572,31.0989],[121.1545,31.0989],[121.1545,31.1016],[121.1668,31.1016],[121.1668,31.1064],[121.1655,31.1064],[121.1655,31.1098],[121.1751,31.1085],[121.1751,31.1181],[121.1833,31.1188],[121.1847,31.1243],[121.1819,31.1243],[121.1806,31.1284],[121.1819,31.1428],[121.1957,31.138],[121.2025,31.1407],[121.2012,31.138],[121.2108,31.1366],[121.2286,31.1387],[121.2218,31.1153],[121.2369,31.1174],[121.2369,31.1256],[121.2451,31.1256],[121.2451,31.1298],[121.241,31.1298],[121.2451,31.1311],[121.2479,31.1339],[121.2589,31.1318],[121.2575,31.1277],[121.2616,31.127],[121.2616,31.1325],[121.263,31.1366],[121.2822,31.1339],[121.2877,31.1387],[121.2877,31.1407],[121.2836,31.1428],[121.2822,31.1414],[121.2794,31.1456],[121.2781,31.1442],[121.2753,31.1456],[121.2794,31.149],[121.2781,31.1517],[121.2877,31.1531],[121.2891,31.1552],[121.3,31.1517],[121.3042,31.1552],[121.3124,31.1579],[121.3179,31.1565],[121.3193,31.1572],[121.3261,31.1579],[121.3289,31.1559],[121.3316,31.1497],[121.3344,31.1483],[121.3344,31.1462],[121.3385,31.1414],[121.3371,31.1387],[121.344,31.1318],[121.3481,31.1201],[121.3522,31.1174],[121.3509,31.1167],[121.3536,31.1119],[121.3564,31.1133],[121.3564,31.1119],[121.3577,31.1105],[121.3536,31.1078],[121.3495,31.1078],[121.3481,31.1064],[121.3509,31.0995],[121.3536,31.0989],[121.3632,31.0995],[121.3715,31.0831],[121.3715,31.0796],[121.3632,31.0769],[121.3646,31.0762],[121.3618,31.0728],[121.3646,31.07],[121.3564,31.0666],[121.3577,31.0638],[121.3426,31.059],[121.3412,31.0632],[121.3358,31.0618],[121.333,31.0158],[121.344,31.0144],[121.3358,31.0034],[121.3275,30.9945],[121.3261,30.9835],[121.3275,30.9808],[121.3344,30.9808],[121.3467,30.976],[121.3605,30.978],[121.3632,30.956],[121.3618,30.9492],[121.366,30.9471],[121.3605,30.9444],[121.3632,30.9354],[121.355,30.9334],[121.355,30.9306],[121.3509,30.9306],[121.3522,30.9245],[121.3564,30.9196],[121.3522,30.9128],[121.3467,30.9135],[121.3454,30.9093],[121.3371,30.908],[121.3275,30.9107],[121.3138,30.9087],[121.3028,30.9128],[121.3014,30.9087],[121.2987,30.91],[121.2959,30.919],[121.2904,30.9183],[121.2904,30.9004],[121.2877,30.9004],[121.2877,30.8963],[121.2836,30.8977],[121.2808,30.8949],[121.2781,30.897],[121.2726,30.897],[121.2726,30.9004],[121.2657,30.9025],[121.2671,30.9066],[121.2465,30.9107],[121.2451,30.9196],[121.2424,30.9203],[121.241,30.9258],[121.2341,30.9272],[121.2341,30.9293],[121.2273,30.9272],[121.2231,30.9313],[121.2094,30.9203],[121.1847,30.9155],[121.171,30.9148],[121.1641,30.9203],[121.1572,30.9196],[121.1559,30.9107],[121.1504,30.9114],[121.1504,30.9128],[121.1421,30.9155],[121.1435,30.9183],[121.1394,30.9196],[121.138,30.9135],[121.1407,30.9107],[121.1407,30.9011],[121.1298,30.9004],[121.127,30.9032],[121.1229,30.9032],[121.1133,30.8977],[121.1105,30.899],[121.1174,30.9107],[121.1188,30.9107],[121.1215,30.9196],[121.1105,30.9224],[121.105,30.921],[121.1009,30.9265],[121.0886,30.9148],[121.0899,30.9114],[121.0968,30.91],[121.0954,30.9087],[121.0968,30.9093],[121.0982,30.9066],[121.0913,30.9032],[121.0858,30.9052],[121.0817,30.9039],[121.0803,30.9059],[121.0515,30.9025],[121.0405,30.9032],[121.0405,30.9045],[121.0391,30.9018],[121.0364,30.9018],[121.035,30.9032],[121.035,30.9066],[121.0254,30.9093],[121.0309,30.9348],[121.0309,30.9396],[121.0323,30.9409],[121.0295,30.9409],[121.0295,30.9437],[121.0281,30.9437]]]}},{"type":"Feature","id":"310114","properties":{"name":"嘉定区","cp":[121.2437,31.3625],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.3014,31.4971],[121.3042,31.4971],[121.3097,31.4923],[121.3097,31.4882],[121.3124,31.482],[121.3165,31.4806],[121.3193,31.4751],[121.3138,31.4724],[121.3193,31.4669],[121.3165,31.4662],[121.3193,31.4628],[121.3179,31.46],[121.3206,31.4573],[121.3193,31.4559],[121.3234,31.4552],[121.3275,31.4497],[121.3261,31.4484],[121.3289,31.4408],[121.333,31.4401],[121.3371,31.4346],[121.3371,31.4188],[121.3358,31.4195],[121.333,31.4168],[121.333,31.412],[121.3303,31.4106],[121.3275,31.412],[121.3138,31.4079],[121.3165,31.4037],[121.3152,31.3982],[121.3206,31.3976],[121.3234,31.3941],[121.3206,31.3893],[121.3234,31.3886],[121.3261,31.3818],[121.3316,31.3797],[121.3303,31.3763],[121.3358,31.3701],[121.3358,31.3667],[121.3412,31.3577],[121.3385,31.3557],[121.3358,31.3509],[121.3316,31.3515],[121.333,31.3481],[121.3467,31.3392],[121.3412,31.3337],[121.3467,31.3248],[121.3454,31.3241],[121.3454,31.3206],[121.3495,31.3213],[121.344,31.3179],[121.3358,31.3042],[121.3316,31.3014],[121.3358,31.2939],[121.3289,31.2897],[121.3248,31.2911],[121.3289,31.2856],[121.333,31.2856],[121.3371,31.2774],[121.3344,31.276],[121.3371,31.274],[121.3577,31.2719],[121.3591,31.2691],[121.3618,31.2712],[121.3687,31.2691],[121.3673,31.2671],[121.3605,31.2678],[121.3591,31.263],[121.3646,31.2589],[121.3742,31.2582],[121.3756,31.2602],[121.3811,31.2575],[121.3783,31.2499],[121.3756,31.2451],[121.3715,31.2444],[121.3673,31.2472],[121.3632,31.241],[121.3564,31.2403],[121.3536,31.2369],[121.3481,31.2396],[121.3495,31.2431],[121.3467,31.2444],[121.344,31.2444],[121.344,31.2403],[121.3412,31.2396],[121.3371,31.2369],[121.3344,31.2362],[121.333,31.2314],[121.3152,31.2273],[121.2987,31.2307],[121.2918,31.2334],[121.2863,31.2437],[121.2822,31.2479],[121.2836,31.254],[121.2698,31.2534],[121.2643,31.2568],[121.2643,31.2589],[121.2547,31.2595],[121.2465,31.2582],[121.2465,31.2595],[121.241,31.2595],[121.2355,31.263],[121.2286,31.263],[121.2231,31.2616],[121.219,31.2534],[121.2135,31.254],[121.2108,31.2609],[121.1943,31.2527],[121.1888,31.2547],[121.1861,31.252],[121.1682,31.2602],[121.1613,31.2664],[121.1531,31.2767],[121.1559,31.2808],[121.1586,31.2815],[121.1586,31.2829],[121.1613,31.2836],[121.1559,31.2897],[121.1517,31.2918],[121.1517,31.2946],[121.1504,31.2994],[121.1435,31.3097],[121.1394,31.3055],[121.138,31.3028],[121.1298,31.3035],[121.1284,31.3193],[121.1339,31.3268],[121.1325,31.3275],[121.1325,31.3323],[121.1298,31.3351],[121.1298,31.344],[121.1188,31.344],[121.1174,31.3515],[121.1078,31.3515],[121.1078,31.3598],[121.1064,31.366],[121.1201,31.3694],[121.1147,31.3728],[121.138,31.3818],[121.1394,31.3845],[121.1476,31.3852],[121.149,31.3873],[121.1435,31.3927],[121.149,31.3948],[121.1476,31.3969],[121.1531,31.3989],[121.149,31.3996],[121.1517,31.4017],[121.1504,31.4024],[121.1545,31.4037],[121.1517,31.4058],[121.1586,31.4085],[121.1586,31.4106],[121.1545,31.412],[121.1559,31.4127],[121.1545,31.4147],[121.149,31.4168],[121.1476,31.4202],[121.1462,31.4202],[121.16,31.425],[121.1641,31.4278],[121.1655,31.4298],[121.1627,31.4339],[121.149,31.436],[121.1462,31.4388],[121.1476,31.4429],[121.1613,31.4491],[121.1737,31.4491],[121.1847,31.4545],[121.1861,31.4607],[121.2025,31.4703],[121.2025,31.4717],[121.2094,31.4772],[121.2149,31.4793],[121.2135,31.4765],[121.219,31.4758],[121.23,31.4813],[121.2286,31.482],[121.2341,31.4889],[121.2355,31.493],[121.2369,31.4923],[121.241,31.4937],[121.2451,31.4813],[121.2479,31.482],[121.2465,31.4813],[121.2465,31.4772],[121.2534,31.4799],[121.2547,31.4799],[121.2547,31.4786],[121.2575,31.4799],[121.2575,31.4786],[121.2602,31.4779],[121.2616,31.4813],[121.2671,31.4841],[121.2685,31.4875],[121.2712,31.4854],[121.2767,31.4854],[121.2808,31.4909],[121.2822,31.4896],[121.2849,31.4909],[121.2904,31.4889],[121.2904,31.4909],[121.2973,31.4909],[121.3014,31.4971]]]}},{"type":"Feature","id":"310113","properties":{"name":"宝山区","cp":[121.4346,31.4051],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.3866,31.5445],[121.4209,31.5218],[121.4951,31.4985],[121.5678,31.4779],[121.5349,31.4168],[121.5211,31.3907],[121.5074,31.3783],[121.5047,31.3673],[121.5088,31.357],[121.5253,31.3467],[121.5225,31.3419],[121.5198,31.3433],[121.5184,31.3412],[121.506,31.3461],[121.4937,31.3303],[121.4992,31.3255],[121.4951,31.3234],[121.4964,31.3117],[121.4854,31.3117],[121.4854,31.3145],[121.469,31.3158],[121.4676,31.3206],[121.4621,31.3213],[121.4484,31.3172],[121.447,31.3206],[121.4333,31.3206],[121.4333,31.3186],[121.4346,31.3131],[121.4319,31.3097],[121.4319,31.3035],[121.4264,31.3035],[121.4264,31.2987],[121.4195,31.2966],[121.4182,31.2932],[121.4195,31.2911],[121.4236,31.2911],[121.4223,31.2843],[121.425,31.2794],[121.425,31.2705],[121.4182,31.2657],[121.4154,31.2691],[121.4113,31.2705],[121.4113,31.2733],[121.4058,31.2733],[121.4072,31.2767],[121.4044,31.276],[121.4003,31.2788],[121.4044,31.2856],[121.3962,31.2877],[121.3962,31.2904],[121.3934,31.2911],[121.3948,31.2946],[121.3879,31.2952],[121.3824,31.2918],[121.3811,31.2891],[121.377,31.2897],[121.3742,31.2877],[121.3632,31.2911],[121.3632,31.2918],[121.3605,31.2932],[121.3632,31.3028],[121.355,31.3],[121.3522,31.3014],[121.3481,31.2987],[121.3426,31.2987],[121.3385,31.2966],[121.3385,31.2939],[121.3358,31.2939],[121.3316,31.3014],[121.3358,31.3042],[121.344,31.3179],[121.3495,31.3213],[121.3454,31.3206],[121.3454,31.3241],[121.3467,31.3248],[121.3412,31.3337],[121.3467,31.3392],[121.333,31.3481],[121.3316,31.3515],[121.3358,31.3509],[121.3385,31.3557],[121.3412,31.3577],[121.3358,31.3667],[121.3358,31.3701],[121.3303,31.3763],[121.3316,31.3797],[121.3261,31.3818],[121.3234,31.3886],[121.3206,31.3893],[121.3234,31.3941],[121.3206,31.3976],[121.3152,31.3982],[121.3165,31.4037],[121.3138,31.4079],[121.3275,31.412],[121.3303,31.4106],[121.333,31.412],[121.333,31.4168],[121.3358,31.4195],[121.3371,31.4188],[121.3371,31.4346],[121.333,31.4401],[121.3289,31.4408],[121.3261,31.4484],[121.3275,31.4497],[121.3234,31.4552],[121.3193,31.4559],[121.3206,31.4573],[121.3179,31.46],[121.3193,31.4628],[121.3165,31.4662],[121.3193,31.4669],[121.3138,31.4724],[121.3193,31.4751],[121.3165,31.4806],[121.3124,31.482],[121.3097,31.4882],[121.3097,31.4923],[121.3042,31.4971],[121.3014,31.4971],[121.3,31.4999],[121.3042,31.5019],[121.3055,31.5054],[121.3097,31.5054],[121.3138,31.5005],[121.3152,31.5012],[121.3165,31.5047],[121.3206,31.5054],[121.322,31.504],[121.3193,31.4999],[121.3234,31.4992],[121.3248,31.504],[121.3275,31.5033],[121.3385,31.5088],[121.3866,31.5445]]]}},{"type":"Feature","id":"310112","properties":{"name":"闵行区","cp":[121.4992,31.0838],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.2547,31.2595],[121.2643,31.2589],[121.2643,31.2568],[121.2698,31.2534],[121.2836,31.254],[121.2822,31.2479],[121.2863,31.2437],[121.2918,31.2334],[121.2987,31.2307],[121.3152,31.2273],[121.333,31.2314],[121.3344,31.2362],[121.3371,31.2369],[121.3426,31.2355],[121.3454,31.2307],[121.3426,31.2259],[121.3454,31.2238],[121.3426,31.2122],[121.3385,31.2122],[121.3385,31.1929],[121.3316,31.1895],[121.3385,31.1799],[121.3412,31.1785],[121.3522,31.1833],[121.355,31.1819],[121.3824,31.1909],[121.4127,31.1916],[121.4127,31.1874],[121.4168,31.1874],[121.4154,31.1819],[121.3948,31.1771],[121.3948,31.173],[121.3921,31.173],[121.3948,31.1696],[121.3921,31.1689],[121.3948,31.16],[121.403,31.162],[121.4113,31.1407],[121.4223,31.127],[121.436,31.1291],[121.4388,31.1195],[121.4346,31.1126],[121.4388,31.1119],[121.4511,31.1153],[121.4525,31.1078],[121.4456,31.1064],[121.4511,31.1037],[121.4525,31.1009],[121.4621,31.1023],[121.4635,31.1085],[121.4745,31.114],[121.4786,31.1092],[121.4786,31.1112],[121.4813,31.1105],[121.4799,31.1174],[121.4868,31.1243],[121.4909,31.1243],[121.4937,31.1195],[121.4992,31.1215],[121.5019,31.1147],[121.5047,31.1153],[121.506,31.1201],[121.5129,31.1215],[121.517,31.116],[121.5225,31.1153],[121.5349,31.1181],[121.5376,31.1133],[121.5431,31.1153],[121.5431,31.1126],[121.5472,31.1092],[121.55,31.1105],[121.55,31.1126],[121.5527,31.1133],[121.5527,31.1119],[121.5541,31.114],[121.5582,31.1119],[121.5596,31.1105],[121.5569,31.1098],[121.561,31.1064],[121.561,31.105],[121.5623,31.0975],[121.5665,31.0968],[121.5678,31.0927],[121.5514,31.0899],[121.5514,31.0879],[121.5486,31.0865],[121.5541,31.0803],[121.5623,31.0831],[121.5692,31.0817],[121.5706,31.0796],[121.5761,31.0803],[121.5555,31.0714],[121.5527,31.0666],[121.5555,31.0673],[121.5555,31.0666],[121.5472,31.0632],[121.5486,31.0563],[121.5431,31.0549],[121.5404,31.0522],[121.5417,31.0453],[121.5514,31.0494],[121.5541,31.0494],[121.561,31.0439],[121.5582,31.0412],[121.5582,31.0323],[121.561,31.0295],[121.5569,31.0288],[121.5569,31.0261],[121.5582,31.024],[121.5527,31.0233],[121.5514,31.0206],[121.5555,31.0192],[121.561,31.024],[121.5651,31.0213],[121.5678,31.0247],[121.572,31.0261],[121.572,31.0247],[121.5747,31.0226],[121.5733,31.0185],[121.5706,31.0172],[121.5692,31.0123],[121.5665,31.0123],[121.5706,31.0082],[121.5706,31.002],[121.5692,31.0007],[121.5706,30.9986],[121.5569,30.9952],[121.5555,30.9931],[121.5527,30.9945],[121.5527,30.9883],[121.55,30.9883],[121.5445,30.9938],[121.5376,30.9931],[121.5363,30.9952],[121.528,30.9959],[121.5239,30.9993],[121.5198,30.9993],[121.5211,31.0034],[121.5157,31.0082],[121.5033,31.0034],[121.4992,31.0007],[121.4992,30.9979],[121.4951,30.9979],[121.4937,31.013],[121.4882,31.0151],[121.4758,31.013],[121.4594,31.0075],[121.4415,31.0055],[121.4209,30.9931],[121.3907,30.9876],[121.3605,30.978],[121.3467,30.976],[121.3344,30.9808],[121.3275,30.9808],[121.3261,30.9835],[121.3275,30.9945],[121.3358,31.0034],[121.344,31.0144],[121.333,31.0158],[121.3358,31.0618],[121.3412,31.0632],[121.3426,31.059],[121.3577,31.0638],[121.3564,31.0666],[121.3646,31.07],[121.3618,31.0728],[121.3646,31.0762],[121.3632,31.0769],[121.3715,31.0796],[121.3715,31.0831],[121.3632,31.0995],[121.3536,31.0989],[121.3509,31.0995],[121.3481,31.1064],[121.3495,31.1078],[121.3536,31.1078],[121.3577,31.1105],[121.3564,31.1119],[121.3564,31.1133],[121.3536,31.1119],[121.3509,31.1167],[121.3522,31.1174],[121.3481,31.1201],[121.344,31.1318],[121.3371,31.1387],[121.3385,31.1414],[121.3344,31.1462],[121.3344,31.1483],[121.3316,31.1497],[121.3289,31.1559],[121.3261,31.1579],[121.3193,31.1572],[121.3193,31.1586],[121.3234,31.1613],[121.3234,31.1634],[121.3165,31.1765],[121.3014,31.1971],[121.2946,31.2032],[121.2822,31.1929],[121.2712,31.1977],[121.2657,31.2032],[121.2643,31.2087],[121.2589,31.2135],[121.2616,31.2163],[121.2575,31.2204],[121.2575,31.23],[121.2479,31.2403],[121.241,31.241],[121.2424,31.2465],[121.2547,31.2595]]]}},{"type":"Feature","id":"310110","properties":{"name":"杨浦区","cp":[121.528,31.2966],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.4854,31.3117],[121.4964,31.3117],[121.4951,31.3234],[121.4992,31.3255],[121.4937,31.3303],[121.506,31.3461],[121.5184,31.3412],[121.5198,31.3433],[121.5225,31.3419],[121.5253,31.3467],[121.5514,31.3378],[121.5596,31.3303],[121.5623,31.3234],[121.5623,31.3014],[121.5651,31.2925],[121.5692,31.2856],[121.5692,31.2794],[121.5665,31.2733],[121.561,31.2664],[121.5349,31.2492],[121.5266,31.2472],[121.5157,31.2472],[121.517,31.2499],[121.5157,31.254],[121.506,31.2657],[121.506,31.2705],[121.5005,31.2753],[121.4964,31.2767],[121.4964,31.2843],[121.5033,31.2897],[121.5019,31.2946],[121.4896,31.2932],[121.4854,31.3035],[121.4854,31.3117]]]}},{"type":"Feature","id":"310107","properties":{"name":"普陀区","cp":[121.3879,31.2602],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.3358,31.2939],[121.3385,31.2939],[121.3385,31.2966],[121.3426,31.2987],[121.3481,31.2987],[121.3522,31.3014],[121.355,31.3],[121.3632,31.3028],[121.3605,31.2932],[121.3632,31.2918],[121.3632,31.2911],[121.3742,31.2877],[121.377,31.2897],[121.3811,31.2891],[121.3824,31.2918],[121.3879,31.2952],[121.3948,31.2946],[121.3934,31.2911],[121.3962,31.2904],[121.3962,31.2877],[121.4044,31.2856],[121.4003,31.2788],[121.4044,31.276],[121.4072,31.2767],[121.4058,31.2733],[121.4113,31.2733],[121.4113,31.2705],[121.4154,31.2691],[121.4182,31.2657],[121.425,31.2705],[121.4291,31.2746],[121.4429,31.2671],[121.4497,31.2582],[121.4511,31.2499],[121.4484,31.2444],[121.4497,31.2431],[121.436,31.2355],[121.4305,31.2348],[121.4278,31.2293],[121.4236,31.2293],[121.4195,31.2252],[121.4154,31.2286],[121.4154,31.2238],[121.4003,31.2204],[121.4003,31.2183],[121.3879,31.2183],[121.3742,31.2204],[121.3673,31.2238],[121.366,31.2259],[121.3605,31.2266],[121.3536,31.2369],[121.3564,31.2403],[121.3632,31.241],[121.3673,31.2472],[121.3715,31.2444],[121.3756,31.2451],[121.3783,31.2499],[121.3811,31.2575],[121.3756,31.2602],[121.3742,31.2582],[121.3646,31.2589],[121.3591,31.263],[121.3605,31.2678],[121.3673,31.2671],[121.3687,31.2691],[121.3618,31.2712],[121.3591,31.2691],[121.3577,31.2719],[121.3371,31.274],[121.3344,31.276],[121.3371,31.2774],[121.333,31.2856],[121.3289,31.2856],[121.3248,31.2911],[121.3289,31.2897],[121.3358,31.2939]]]}},{"type":"Feature","id":"310104","properties":{"name":"徐汇区","cp":[121.4333,31.1607],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.4127,31.1916],[121.4209,31.1909],[121.4236,31.1971],[121.4374,31.2032],[121.4346,31.2115],[121.4388,31.2142],[121.458,31.2204],[121.4621,31.2039],[121.4676,31.2039],[121.4703,31.1916],[121.4758,31.1881],[121.469,31.184],[121.4648,31.1785],[121.4648,31.1737],[121.4676,31.1668],[121.469,31.1586],[121.4566,31.1456],[121.4594,31.138],[121.469,31.1284],[121.4703,31.1236],[121.4703,31.1188],[121.4635,31.1085],[121.4621,31.1023],[121.4525,31.1009],[121.4511,31.1037],[121.4456,31.1064],[121.4525,31.1078],[121.4511,31.1153],[121.4388,31.1119],[121.4346,31.1126],[121.4388,31.1195],[121.436,31.1291],[121.4223,31.127],[121.4113,31.1407],[121.403,31.162],[121.3948,31.16],[121.3921,31.1689],[121.3948,31.1696],[121.3921,31.173],[121.3948,31.173],[121.3948,31.1771],[121.4154,31.1819],[121.4168,31.1874],[121.4127,31.1874],[121.4127,31.1916]]]}},{"type":"Feature","id":"310105","properties":{"name":"长宁区","cp":[121.3852,31.2115],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.3371,31.2369],[121.3412,31.2396],[121.344,31.2403],[121.344,31.2444],[121.3467,31.2444],[121.3495,31.2431],[121.3481,31.2396],[121.3536,31.2369],[121.3605,31.2266],[121.366,31.2259],[121.3673,31.2238],[121.3742,31.2204],[121.3879,31.2183],[121.4003,31.2183],[121.4003,31.2204],[121.4154,31.2238],[121.4154,31.2286],[121.4195,31.2252],[121.4236,31.2293],[121.4278,31.2293],[121.4291,31.2238],[121.436,31.2252],[121.4388,31.2142],[121.4346,31.2115],[121.4374,31.2032],[121.4236,31.1971],[121.4209,31.1909],[121.4127,31.1916],[121.3824,31.1909],[121.355,31.1819],[121.3522,31.1833],[121.3412,31.1785],[121.3385,31.1799],[121.3316,31.1895],[121.3385,31.1929],[121.3385,31.2122],[121.3426,31.2122],[121.3454,31.2238],[121.3426,31.2259],[121.3454,31.2307],[121.3426,31.2355],[121.3371,31.2369]]]}},{"type":"Feature","id":"310108","properties":{"name":"闸北区","cp":[121.4511,31.2794],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.469,31.3158],[121.4676,31.3062],[121.4635,31.3062],[121.4648,31.2973],[121.4607,31.2897],[121.4621,31.2788],[121.4703,31.2671],[121.4799,31.2589],[121.4813,31.2506],[121.4799,31.2499],[121.4827,31.2424],[121.4799,31.2403],[121.4745,31.2417],[121.4703,31.2389],[121.4635,31.2417],[121.458,31.2383],[121.4497,31.2431],[121.4484,31.2444],[121.4511,31.2499],[121.4497,31.2582],[121.4429,31.2671],[121.4291,31.2746],[121.425,31.2705],[121.425,31.2794],[121.4223,31.2843],[121.4236,31.2911],[121.4195,31.2911],[121.4182,31.2932],[121.4195,31.2966],[121.4264,31.2987],[121.4264,31.3035],[121.4319,31.3035],[121.4319,31.3097],[121.4346,31.3131],[121.4333,31.3186],[121.4333,31.3206],[121.447,31.3206],[121.4484,31.3172],[121.4621,31.3213],[121.4676,31.3206],[121.469,31.3158]]]}},{"type":"Feature","id":"310109","properties":{"name":"虹口区","cp":[121.4882,31.2788],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.469,31.3158],[121.4854,31.3145],[121.4854,31.3117],[121.4854,31.3035],[121.4896,31.2932],[121.5019,31.2946],[121.5033,31.2897],[121.4964,31.2843],[121.4964,31.2767],[121.5005,31.2753],[121.506,31.2705],[121.506,31.2657],[121.5157,31.254],[121.517,31.2499],[121.5157,31.2472],[121.5074,31.2465],[121.4951,31.2417],[121.4868,31.2444],[121.4827,31.2424],[121.4799,31.2499],[121.4813,31.2506],[121.4799,31.2589],[121.4703,31.2671],[121.4621,31.2788],[121.4607,31.2897],[121.4648,31.2973],[121.4635,31.3062],[121.4676,31.3062],[121.469,31.3158]]]}},{"type":"Feature","id":"310101","properties":{"name":"黄浦区","cp":[121.4868,31.219],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.4635,31.2417],[121.4703,31.2389],[121.4745,31.2417],[121.4799,31.2403],[121.4827,31.2424],[121.4868,31.2444],[121.4951,31.2417],[121.4937,31.2348],[121.506,31.2238],[121.5102,31.2156],[121.5019,31.2005],[121.4964,31.1936],[121.4909,31.1991],[121.4868,31.1984],[121.4841,31.2067],[121.4813,31.2149],[121.4799,31.2163],[121.4841,31.2177],[121.4799,31.2259],[121.469,31.2245],[121.4676,31.2307],[121.4635,31.2417]]]}},{"type":"Feature","id":"310103","properties":{"name":"卢湾区","cp":[121.4758,31.2074],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.469,31.2245],[121.4799,31.2259],[121.4841,31.2177],[121.4799,31.2163],[121.4813,31.2149],[121.4841,31.2067],[121.4868,31.1984],[121.4909,31.1991],[121.4964,31.1936],[121.4758,31.1881],[121.4703,31.1916],[121.4676,31.2039],[121.4621,31.2039],[121.458,31.2204],[121.4566,31.2231],[121.469,31.2245]]]}},{"type":"Feature","id":"310106","properties":{"name":"静安区","cp":[121.4484,31.2286],"childNum":1},"geometry":{"type":"Polygon","coordinates":[[[121.4278,31.2293],[121.4305,31.2348],[121.436,31.2355],[121.4497,31.2431],[121.458,31.2383],[121.4635,31.2417],[121.4676,31.2307],[121.469,31.2245],[121.4566,31.2231],[121.458,31.2204],[121.4388,31.2142],[121.436,31.2252],[121.4291,31.2238],[121.4278,31.2293]]]}}]} |
/**
* JsonLD source for a repository.
*/
((definition) => {
if (typeof define === "function" && define.amd) {
define(["./jsonld-to-json", "./http"], definition);
} else if (typeof module !== "undefined") {
const jsonLdToJson = require("./jsonld-to-json");
const http = require("./http");
module.exports = definition(jsonLdToJson, http);
}
})((jsonLdToJson, http) => {
"use strict";
const TOMBSTONE_TEMPLATE = {
"id": {
"$resource": null
}
};
const METADATA_TEMPLATE = {
"timestamp": {
"$property": "http://etl.linkedpipes.com/ontology/serverTime",
"$type": "plain-string"
}
};
const METADATA_TYPE = "http://etl.linkedpipes.com/ontology/Metadata";
function createJsonLdSource(config) {
if (config.incrementalUpdateSupport) {
return createWithIncrementalUpdateSupport(config);
} else {
return create(config);
}
}
function createWithIncrementalUpdateSupport(config) {
return {
"fetch": (changedSince) => fetchChangedSince(changedSince, config),
"deleteById": deleteById,
"incrementalUpdateSupport": true
};
}
function fetchChangedSince(changedSince, config) {
let url = config.url;
if (changedSince !== undefined) {
url += "?changedSince=" + changedSince;
}
return fetchItems(
url,
config.itemType,
config.tombstoneType,
config.itemTemplate);
}
function fetchItems(url, itemType, tombstoneType, itemTemplate) {
return http.getJsonLd(url).then((response) => {
const payload = response.payload;
return {
"data": jsonLdToJson(payload, itemType, itemTemplate),
"tombstones": getTombstonesIds(payload, tombstoneType),
"timeStamp": getTimeStamp(payload)
}
})
}
function getTimeStamp(payload) {
const metadata = jsonLdToJson(
payload, METADATA_TYPE, METADATA_TEMPLATE);
if (metadata.length === 0) {
return undefined;
} else {
return metadata[0].timestamp;
}
}
function getTombstonesIds(payload, type) {
const tombstones = jsonLdToJson(payload, type, TOMBSTONE_TEMPLATE);
return tombstones.map(item => item.id);
}
function create(config) {
return {
"fetch": () => fetch(config),
"deleteById": deleteById,
"incrementalUpdateSupport": false
};
}
function fetch(config) {
return fetchItems(
config.url,
config.itemType,
config.tombstoneType,
config.itemTemplate);
}
function deleteById(id) {
const url = id;
return http.delete(url);
}
const createBuilder = () => {
const config = {
"incrementalUpdateSupport": false
};
const builder = {};
builder["url"] =
(url) => config["url"] = url;
builder["itemType"] =
(type) => config["itemType"] = type;
builder["tombstoneType"] =
(type) => config["tombstoneType"] = type;
builder["itemTemplate"] =
(template) => config["itemTemplate"] = template;
builder["supportIncrementalUpdate"] =
() => config["incrementalUpdateSupport"] = true;
builder["build"] = () => createJsonLdSource(config);
return builder;
};
return {
"create": createJsonLdSource,
"createBuilder": createBuilder
}
});
|
"""`librabbitmq`_ transport.
.. _`librabbitmq`: https://pypi.python.org/librabbitmq/
"""
from __future__ import absolute_import, unicode_literals
import os
import socket
import warnings
import librabbitmq as amqp
from librabbitmq import ChannelError, ConnectionError
from kombu.five import items, values
from kombu.utils.amq_manager import get_manager
from kombu.utils.text import version_string_as_tuple
from . import base
from .base import to_rabbitmq_queue_arguments
W_VERSION = """
librabbitmq version too old to detect RabbitMQ version information
so make sure you are using librabbitmq 1.5 when using rabbitmq > 3.3
"""
DEFAULT_PORT = 5672
DEFAULT_SSL_PORT = 5671
NO_SSL_ERROR = """\
ssl not supported by librabbitmq, please use pyamqp:// or stunnel\
"""
class Message(base.Message):
"""AMQP Message (librabbitmq)."""
def __init__(self, channel, props, info, body):
super(Message, self).__init__(
channel=channel,
body=body,
delivery_info=info,
properties=props,
delivery_tag=info.get('delivery_tag'),
content_type=props.get('content_type'),
content_encoding=props.get('content_encoding'),
headers=props.get('headers'))
class Channel(amqp.Channel, base.StdChannel):
"""AMQP Channel (librabbitmq)."""
Message = Message
def prepare_message(self, body, priority=None,
content_type=None, content_encoding=None,
headers=None, properties=None):
"""Encapsulate data into a AMQP message."""
properties = properties if properties is not None else {}
properties.update({'content_type': content_type,
'content_encoding': content_encoding,
'headers': headers,
'priority': priority})
return body, properties
def prepare_queue_arguments(self, arguments, **kwargs):
arguments = to_rabbitmq_queue_arguments(arguments, **kwargs)
return {k.encode('utf8'): v for k, v in items(arguments)}
class Connection(amqp.Connection):
"""AMQP Connection (librabbitmq)."""
Channel = Channel
Message = Message
class Transport(base.Transport):
"""AMQP Transport (librabbitmq)."""
Connection = Connection
default_port = DEFAULT_PORT
default_ssl_port = DEFAULT_SSL_PORT
connection_errors = (
base.Transport.connection_errors + (
ConnectionError, socket.error, IOError, OSError)
)
channel_errors = (
base.Transport.channel_errors + (ChannelError,)
)
driver_type = 'amqp'
driver_name = 'librabbitmq'
implements = base.Transport.implements.extend(
async=True,
heartbeats=False,
)
def __init__(self, client, **kwargs):
self.client = client
self.default_port = kwargs.get('default_port') or self.default_port
self.default_ssl_port = (kwargs.get('default_ssl_port') or
self.default_ssl_port)
self.__reader = None
def driver_version(self):
return amqp.__version__
def create_channel(self, connection):
return connection.channel()
def drain_events(self, connection, **kwargs):
return connection.drain_events(**kwargs)
def establish_connection(self):
"""Establish connection to the AMQP broker."""
conninfo = self.client
for name, default_value in items(self.default_connection_params):
if not getattr(conninfo, name, None):
setattr(conninfo, name, default_value)
if conninfo.ssl:
raise NotImplementedError(NO_SSL_ERROR)
opts = dict({
'host': conninfo.host,
'userid': conninfo.userid,
'password': conninfo.password,
'virtual_host': conninfo.virtual_host,
'login_method': conninfo.login_method,
'insist': conninfo.insist,
'ssl': conninfo.ssl,
'connect_timeout': conninfo.connect_timeout,
}, **conninfo.transport_options or {})
conn = self.Connection(**opts)
conn.client = self.client
self.client.drain_events = conn.drain_events
return conn
def close_connection(self, connection):
"""Close the AMQP broker connection."""
self.client.drain_events = None
connection.close()
def _collect(self, connection):
if connection is not None:
for channel in values(connection.channels):
channel.connection = None
try:
os.close(connection.fileno())
except OSError:
pass
connection.channels.clear()
connection.callbacks.clear()
self.client.drain_events = None
self.client = None
def verify_connection(self, connection):
return connection.connected
def register_with_event_loop(self, connection, loop):
loop.add_reader(
connection.fileno(), self.on_readable, connection, loop,
)
def get_manager(self, *args, **kwargs):
return get_manager(self.client, *args, **kwargs)
def qos_semantics_matches_spec(self, connection):
try:
props = connection.server_properties
except AttributeError:
warnings.warn(UserWarning(W_VERSION))
else:
if props.get('product') == 'RabbitMQ':
return version_string_as_tuple(props['version']) < (3, 3)
return True
@property
def default_connection_params(self):
return {
'userid': 'guest',
'password': 'guest',
'port': (self.default_ssl_port if self.client.ssl
else self.default_port),
'hostname': 'localhost',
'login_method': 'AMQPLAIN',
}
|
import React from "react"
export default function Loading(){
return(
<img className="loading" src="./images/pikachu.gif" />
);
} |
import numpy as np
import h5py as py
import matplotlib.pyplot as plt
depth = []
s22 = []
hdf5_file = py.File("..\\Build\\TestsWithGL\\t2d_mpm_chm_t_bar_conference_restart.hdf5", "r")
frame_id = 100
frame_dset = hdf5_file['TimeHistory']['penetration']['frame_%d' % frame_id]['ParticleData']
pcl_num = frame_dset.attrs['pcl_num']
for i in range(pcl_num):
depth.append(-frame_dset[i]['y'])
s22.append(-frame_dset[i]['n'])
#print(frame_dset[i][12])
hdf5_file.close()
fig = plt.figure()
plot1 = fig.subplots(1, 1)
plot1.set_xlabel("s22")
plot1.set_ylabel("depth")
plot1.scatter(s22, depth)
plt.show() |
// valid.js http://github.com/bronson/valid.js
//
// A simple, chainable validation library under the MIT license.
// Works in Node, the browser, and anywhere JavaScript should run.
var Valid = function Valid() { };
module.exports = Valid;
// Internals
// ---------
Valid.GetChain = function GetChain() {
if(this === Valid) {
// we're the first item in a chain so create a Chain object
var chain = function Chain() {};
chain.prototype = this;
return new chain();
}
return this;
};
// Adds the given validation to the current Chain.
// Data is optional but can help identify the validation when debugging.
Valid.AddValidation = function AddValidation(validation, data) {
var self = this.GetChain();
if(self._queue === undefined) self._queue = [];
if(data) validation.data = data;
self._queue.push(validation);
return self;
};
// Supply a function that that returns undefined on success or an error message on failure, produces a full, chainable validation.
// The first arg passed to your your function is the value to test, the rest are the args passed when declaring the validation.
// i.e. Valid.t = SimpleValidation(fn(){...}); Valid.t(4,2).check(9) would call your function with arguments 9, 4, 2.
Valid.SimpleValidation = function SimpleValidation(fn) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
return this.AddValidation( function SimpleValidation(value) {
return fn.apply(this, [value].concat(args));
}, args);
};
};
// Run all the validations in the given queue
Valid.ValidateQueue = function ValidateQueue(queue, value) {
if(!queue || queue.length < 1) return "no validations!";
for(var i=0; i<queue.length; i++) {
var error = queue[i].call(this, value);
if(error === Valid) return; // indicates early success, used by optional()
if(error) return error;
}
};
// converts value into a string that can be printed
Valid.Escape = function Escape(value) {
if(typeof value === 'string') {
return '"' + value.replace(/[\\"]/g, '\\$&').replace(/\u0000/g, '\\0').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') + '"';
}
return '' + value;
};
// Turns a Chain object into a callable Validation.
// Valid.isFour = Valid.equal(4).define(); // define the isFour validation
// Valid.integer().isFour().isValid(4); // true!
// If you get this error then you forgot to call define() on your chain:
// Property 'myfunc' of object function Valid() { } is not a function
// It's really shameful that this function needs to exist.
// In an ideal world you could just do this: Valid.null() = Valid.equal(null);
// In our world, that only works if you don't call it: Valid.null.check(1); Ugh.
// Since Valid.equal(null) returns the chain object, if you call null:
// Valid.null().check(1) JS complains "Property null is not a function"
// For this to work, JS needs to a callable object with a prototype chain.
// And, without using nonstandard __proto__, I don't think that's possible...?
Valid.define = function define() {
var queue = this._queue;
return function() {
var self = this.GetChain();
for(var i=0; i<queue.length; i++) {
self.AddValidation(queue[i]);
}
return self;
};
};
// User-facing API
// ---------------
// results
// returns the error string or undefined if there were no validation errors
Valid.check = function check(value) {
var self = this.GetChain();
return self.GetChain().ValidateQueue(self._queue, value);
};
// returns true if the validation succeeded, false if there were errors
Valid.isValid = function isValid(value) {
return !this.check(value);
};
// core validations
Valid.nop = Valid.SimpleValidation(function Nop(val) { });
Valid.fail = Valid.SimpleValidation(function Fail(val,msg) { return msg || "failed"; });
Valid.mod = Valid.SimpleValidation(function mod(val,by,rem) { if(val%by !== (rem||0)) return "mod "+by+" must be "+rem+" not "+val%by; });
Valid.optional = Valid.SimpleValidation(function Optional(value) { if(value === null || value === undefined) return Valid; });
Valid.equal = Valid.SimpleValidation(function Equal(value) {
// Here is the old equal, not sure supporting multiple values is worth the additional complexity...
// Valid.equal = Valid.SimpleValidation(function Equal(val,want) { if(val !== want) return "is not equal to "+Valid.Escape(want); });
if(arguments.length === 1) return "equal needs at least one argument";
var opts = [];
for(var i=1; i<arguments.length; i++) {
if(value === arguments[i]) return;
opts.push(this.Escape(arguments[i]));
}
if(arguments.length === 2) return "must equal " + opts[0];
var lastopt = opts.pop();
return "must be " + opts.join(", ") + " or " + lastopt;
});
Valid.oneOf = Valid.SimpleValidation(function OneOf(value,collection) {
if(collection === null || collection === undefined) return "oneOf needs a collection";
if(value in collection) return;
return "is not an option";
});
Valid.type = Valid.SimpleValidation(function Type(value,type) {
if(typeof type !== 'string') return "type requires a string argument, not "+(typeof type);
if(typeof value !== type) return "must be of type " + type + " not " + (typeof value);
});
Valid.array = Valid.SimpleValidation(function Arry(value, validation) {
if(!Array.isArray(value)) return "must be an array";
if(validation !== undefined) {
for(var i=0; i<value.length; i++) {
var error = this.ValidateQueue(validation._queue, value[i]);
if(error) return "item " + i + " " + error; // TODO: this sucks
}
}
});
Valid.date = Valid.SimpleValidation(function(value) {
if(isNaN(Date.parse(value))) return "must be a date";
});
Valid.before = Valid.SimpleValidation(function Before(value,when) {
if(when === undefined) when = new Date();
if(Date.parse(value) > when) return "must be before " + when;
});
Valid.after = Valid.SimpleValidation(function After(value,when) {
if(when === undefined) when = new Date();
if(Date.parse(value) < when) return "must be after " + when;
});
Valid.len = Valid.SimpleValidation(function Len(value,min,max) {
var items = typeof value === 'string' ? 'character' : 'element';
if(typeof value === 'null' || typeof value === 'undefined' || typeof value.length === 'undefined') return "must have a length field";
if(typeof value.length !== 'number') return "must have a numeric length field, not " + (typeof value.length);
// now we can read the property without risking throwing an exception
if(value.length < min) return "is too short (minimum is " + min + " " + items + (min === 1 ? '' : 's') + ")";
if(typeof max !== undefined) {
if(value.length > max) return "is too long (maximum is " + max + " " + items + (max === 1 ? '' : 's') + ")";
}
});
Valid.message = function message(msg) {
var validation = this.GetChain();
return Valid.AddValidation(function Message(value) {
var error = this.ValidateQueue(validation._queue, value);
if(error) return validation._queue ? msg : error;
}, msg);
};
Valid.not = Valid.SimpleValidation(function Not(value, validation, message) {
var error = this.ValidateQueue(validation._queue, value);
if(!error) return message || "validation must fail";
});
// seems somewhat useless since V.a().b() is the same as V.and(V.a(),V.b())
Valid.and = function and() {
var chains = arguments;
return this.AddValidation( function And(value) {
for(var i=0; i<chains.length; i++) {
var error = this.ValidateQueue(chains[i]._queue, value);
if(error) return error;
}
}, chains);
};
Valid.or = function or() {
var chains = arguments;
return this.AddValidation(function Or(value) {
var errors = [];
for(var i=0; i<chains.length; i++) {
var error = this.ValidateQueue(chains[i]._queue, value);
if(!error) return; // short circuit
errors.push(error);
}
return errors.length > 0 ? errors.join(" or ") : undefined;
}, chains);
};
Valid.match = function match(pattern, modifiers) {
if(typeof pattern !== 'function') pattern = new RegExp(pattern, modifiers);
return this.string().AddValidation( function Match(value) {
if(!value.match(pattern)) return "must match " + pattern;
}, pattern);
};
// composite validations
Valid.undef = Valid.equal(undefined).message("must be undefined").define();
Valid.defined = Valid.not(Valid.undef(), "can't be undefined").define();
Valid.nil = Valid.equal(null).message("must be null").define();
Valid.notNull = Valid.not(Valid.nil(), "can't be null").define();
Valid.noexisty = Valid.equal(undefined, null).message("must not exist").define();
Valid.exists = Valid.not(Valid.noexisty(), "must exist").define();
Valid.empty = Valid.len(0,0).message("must be empty").define();
Valid.number = Valid.type('number').message("must be a number").define();
Valid.integer = Valid.number().mod(1).message("must be an integer").define();
Valid.even = Valid.number().mod(2).message("must be even").define();
Valid.odd = Valid.number().mod(2,1).message("must be odd").define();
Valid.string = Valid.type('string').message("must be a string").define();
Valid.blank = Valid.optional().match(/^\s*$/).message("must be blank").define();
Valid.notBlank = Valid.not(Valid.blank(), "can't be blank").define();
// reserved words, calling them with dot notation may cause problems with crappy JS implementations
Valid['undefined'] = Valid.undef;
Valid['null'] = Valid.nil;
Valid['in'] = Valid.oneOf;
// composites that take arguments
Valid.todo = function(name) { return this.fail((name ? name : "validation") + " is still todo"); };
Valid.notEqual = function(arg) { return this.not(this.equal(arg), "can't equal " + this.Escape(arg)); };
Valid.nomatch = function(pat,mods) { var match = this.match(pat,mods); return this.not(match, "can't match " + match._queue[1].data); };
// comparisons
Valid.eq = Valid.equal;
Valid.ne = Valid.notEqual;
Valid.lt = Valid.SimpleValidation(function lt(val,than) { if(val >= than) return "must be less than " + Valid.Escape(than); });
Valid.le = Valid.SimpleValidation(function le(val,than) { if(val > than) return "must be less than or equal to " + Valid.Escape(than); });
Valid.gt = Valid.SimpleValidation(function gt(val,than) { if(val <= than) return "must be greater than " + Valid.Escape(than); });
Valid.ge = Valid.SimpleValidation(function ge(val,than) { if(val < than) return "must be greater than or equal to " + Valid.Escape(than); });
Valid.min = Valid.ge;
Valid.max = Valid.le;
// JSON Schema
Valid.JsonError = function(path, message) {
var error = this._errors;
var last = path.length - 1;
var key = path.length === 0 ? '.' : path[last];
for(var i=0; i<last; i++) {
if(!error[path[i]]) error[path[i]] = {};
error = error[path[i]];
}
error[key] = message;
this._errorCount += 1;
};
Valid.JsonObject = function(path, value, schema, strict) {
// if strict is true, all keys in value must be named in schema.
if(typeof value !== 'object') {
this.JsonError(path, "must be an object");
return;
}
for(var key in schema) {
if(!schema.hasOwnProperty(key)) continue;
if(key in value) {
this.JsonField(path.concat(key), value[key], schema[key]);
} else {
this.JsonError(path, "must include " + key);
}
if(this._errorCount > this._maxErrors) break;
}
if(strict) for(key in value) {
if(!value.hasOwnProperty(key)) continue;
if(!(key in schema)) this.JsonError(path, "can't include " + key);
if(this._errorCount > this._maxErrors) break;
}
};
Valid.JsonField = function(path, value, schema) {
// need to duck type RegExps because instanceof isn't working reliably
var isRegExp = function(o) { return o && o.test && o.exec && o.source && (o.global === true || o.global === false) && (o.ignoreCase === true || o.ignoreCase === false) && (o.multiline === true || o.multiline === false); };
switch(typeof schema) {
case 'string':
case 'number':
case 'boolean':
case 'undefined':
if(value !== schema) this.JsonError(path, "must equal " + this.Escape(schema));
break;
case 'null': // usually typeof null === 'object'
case 'object':
case 'function': // seems random what impls return for built-in objects
if(schema === null) {
if(value !== null) this.JsonError(path, "must be null");
} else if(schema._queue && typeof schema.GetChain === 'function') { // try to detect a Valid chain
var vresult = schema.check(value);
if(vresult) this.JsonError(path, vresult);
} else if(value === null) {
this.JsonError(path, "can't be null");
} else if(isRegExp(schema)) {
var reresult = Valid.match(schema).check(value);
if(reresult) this.JsonError(path, reresult);
} else if(schema instanceof Array) {
if(value instanceof Array) {
if(value.length !== schema.length) this.JsonError(path, " must have " + value.length + " items, not " + schema.length);
for(var i=0; i < schema.length; i++) {
this.JsonField(path.concat(i), value[i], schema[i]);
if(this._errorCount > this._maxErrors) break;
}
} else {
this.JsonError(path, "must be an array");
}
} else if(typeof schema === 'function') {
var fresult = schema.call(this, value);
if(fresult) this.JsonError(path, fresult);
} else {
this.JsonObject(path, value, schema, false);
}
break;
default:
this.JsonError(path, "Error in template: what is " + (typeof schema) + "?");
}
};
Valid.json = function json(schema) {
return this.AddValidation(function Json(value, maxErrors) {
this._errors = {};
this._errorCount = 0;
this._maxErrors = maxErrors || 20;
this.JsonField([], value, schema, {});
if(this._errorCount > 0) return this._errors;
}, schema);
};
|
import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import Link from 'umi/link';
import router from 'umi/router';
import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd';
import styles from './Register.less';
const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;
const passwordStatusMap = {
ok: (
<div className={styles.success}>
<FormattedMessage id="validation.password.strength.strong" />
</div>
),
pass: (
<div className={styles.warning}>
<FormattedMessage id="validation.password.strength.medium" />
</div>
),
poor: (
<div className={styles.error}>
<FormattedMessage id="validation.password.strength.short" />
</div>
),
};
const passwordProgressMap = {
ok: 'success',
pass: 'normal',
poor: 'exception',
};
@connect(({ register, loading }) => ({
register,
submitting: loading.effects['register/submit'],
}))
@Form.create()
class Register extends Component {
state = {
count: 0,
confirmDirty: false,
visible: false,
help: '',
prefix: '86',
};
componentDidUpdate() {
const { form, register } = this.props;
const account = form.getFieldValue('name');
if (register.status === '200') {
router.push({
pathname: '/user/register-result',
state: {
account,
},
});
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
onGetCaptcha = () => {
let count = 59;
this.setState({ count });
this.interval = setInterval(() => {
count -= 1;
this.setState({ count });
if (count === 0) {
clearInterval(this.interval);
}
}, 1000);
};
getPasswordStatus = () => {
const { form } = this.props;
const value = form.getFieldValue('password');
if (value && value.length > 9) {
return 'ok';
}
if (value && value.length > 5) {
return 'pass';
}
return 'poor';
};
handleSubmit = e => {
e.preventDefault();
const { form, dispatch } = this.props;
form.validateFields({ force: true }, (err, values) => {
if (!err) {
const { prefix } = this.state;
dispatch({
type: 'register/submit',
payload: {
...values
}
});
}
});
};
handleConfirmBlur = e => {
const { value } = e.target;
const { confirmDirty } = this.state;
this.setState({ confirmDirty: confirmDirty || !!value });
};
checkConfirm = (rule, value, callback) => {
const { form } = this.props;
if (value && value !== form.getFieldValue('password')) {
callback(formatMessage({ id: 'validation.password.twice' }));
} else {
callback();
}
};
checkPassword = (rule, value, callback) => {
const { visible, confirmDirty } = this.state;
if (!value) {
this.setState({
help: formatMessage({ id: 'validation.password.required' }),
visible: !!value,
});
callback('error');
} else {
this.setState({
help: '',
});
if (!visible) {
this.setState({
visible: !!value,
});
}
if (value.length < 6) {
callback('error');
} else {
const { form } = this.props;
if (value && confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
}
}
};
changePrefix = value => {
this.setState({
prefix: value,
});
};
renderPasswordProgress = () => {
const { form } = this.props;
const value = form.getFieldValue('password');
const passwordStatus = this.getPasswordStatus();
return value && value.length ? (
<div className={styles[`progress-${passwordStatus}`]}>
<Progress
status={passwordProgressMap[passwordStatus]}
className={styles.progress}
strokeWidth={6}
percent={value.length * 10 > 100 ? 100 : value.length * 10}
showInfo={false}
/>
</div>
) : null;
};
render() {
const { form, submitting } = this.props;
const { getFieldDecorator } = form;
const { count, prefix, help, visible } = this.state;
return (
<div className={styles.main}>
<h3>
<FormattedMessage id="app.register.register" />
</h3>
<Form onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator('id', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.userId.required' }),
},
],
})(
<Input size="large" placeholder={formatMessage({ id: 'form.userId.placeholder' })} />
)}
</FormItem>
<FormItem>
{getFieldDecorator('name', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.userName.required' }),
},
],
})(
<Input size="large" placeholder={formatMessage({ id: 'form.userName.placeholder' })} />
)}
</FormItem>
<FormItem>
<InputGroup compact>
<Select
size="large"
value={prefix}
onChange={this.changePrefix}
style={{ width: '20%' }}
>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
{getFieldDecorator('telNo', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.phone-number.required' }),
},
{
pattern: /^\d{11}$/,
message: formatMessage({ id: 'validation.phone-number.wrong-format' }),
},
],
})(
<Input
size="large"
style={{ width: '80%' }}
placeholder={formatMessage({ id: 'form.phone-number.placeholder' })}
/>
)}
</InputGroup>
</FormItem>
<FormItem help={help}>
<Popover
getPopupContainer={node => node.parentNode}
content={
<div style={{ padding: '4px 0' }}>
{passwordStatusMap[this.getPasswordStatus()]}
{this.renderPasswordProgress()}
<div style={{ marginTop: 10 }}>
<FormattedMessage id="validation.password.strength.msg" />
</div>
</div>
}
overlayStyle={{ width: 240 }}
placement="right"
visible={visible}
>
{getFieldDecorator('password', {
rules: [
{
validator: this.checkPassword,
},
],
})(
<Input
size="large"
type="password"
placeholder={formatMessage({ id: 'form.password.placeholder' })}
/>
)}
</Popover>
</FormItem>
<FormItem>
{getFieldDecorator('confirm', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.confirm-password.required' }),
},
{
validator: this.checkConfirm,
},
],
})(
<Input
size="large"
type="password"
placeholder={formatMessage({ id: 'form.confirm-password.placeholder' })}
/>
)}
</FormItem>
<FormItem>
<Button
size="large"
loading={submitting}
className={styles.submit}
type="primary"
htmlType="submit"
>
<FormattedMessage id="app.register.register" />
</Button>
<Link className={styles.login} to="/User/Login">
<FormattedMessage id="app.register.sign-in" />
</Link>
</FormItem>
</Form>
</div>
);
}
}
export default Register;
|
"""
ASGI config for azureproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'azureproject.settings')
application = get_asgi_application()
|
const Heart = props => (
<svg
width={24}
height={24}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className="feather feather-heart"
{...props}
>
<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" />
</svg>
);
export default Heart;
|
import nodemailer from 'nodemailer';
import exphbs from 'express-handlebars';
import nodemailerhbs from 'nodemailer-express-handlebars';
import { resolve } from 'path';
import mailConfig from '../config/mail';
class Mail {
constructor() {
const { host, port, secure, auth } = mailConfig;
this.transporter = nodemailer.createTransport({
host,
port,
secure,
auth: auth.user ? auth : null,
});
this.configureTemplates();
}
configureTemplates() {
const viewPath = resolve(__dirname, '..', 'app', 'views', 'emails');
this.transporter.use(
'compile',
nodemailerhbs({
viewEngine: exphbs.create({
layoutsDir: resolve(viewPath, 'layouts'),
partialsDir: resolve(viewPath, 'partials'),
defaultLayout: 'default',
extname: '.hbs',
}),
viewPath,
extName: '.hbs',
})
);
}
sendMail(message) {
return this.transporter.sendMail({
...mailConfig.default,
...message,
});
}
}
export default new Mail();
|
// Useful imports
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
// HTML import
import './management.html';
// JS import
import './modals/confirmDelete.js';
// Initializing Session variable
Session.set('commentsManagement', []);
FlowRouter.route('/dashboard/comments', {
name: 'dashboardComments',
action(){
// We will render the comments management template using Blaze, but we need the user's role to check if access is allowed
Meteor.call('getCurrentUserRole', function(error, role){
if(error){
// There was an error
Session.set('message', {type:"header", headerContent:error.reason, style:"is-danger"});
// Sending user back to home page to avoid a blank page displayed
FlowRouter.go('/');
} else if(role === 'author' || role === 'admin'){
// User is allowed to access comments management, rendering it
BlazeLayout.render('main', {currentPage: 'commentsManagement'});
// Scrolling the window back to the top
window.scrollTo(0, 0);
// Calling the method to refresh the list of comments to manage (in case we just deleted or edited one)
Template.commentsManagement.__helpers.get('displayComments').call();
} else{
// User doesn't have the correct role to access this page, sending him back to home page
FlowRouter.go('/');
}
});
}
});
Template.commentsManagement.helpers({
displayComments: function(){
// Return the comments that the current user can manage
Meteor.call('getCommentsForManagement', function(error, comments){
if(error){
// There was an error
Session.set('message', {type:"header", headerContent:error.reason, style:"is-danger"});
} else{
// Comments were successfully retrieved, saving them in a Session variable
Session.set('commentsManagement', comments);
}
});
return Session.get('commentsManagement');
}
});
|
import * as React from 'react';
import { View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Profile"
onPress={() =>
navigation.navigate('Profile', { name: 'Custom profile header' })
}
/>
</View>
);
}
function ProfileScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Profile screen</Text>
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My home' }}
/>
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={({ route }) => ({ title: route.params.name })}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
|
# -*- coding: utf-8 -*-
"""Unit test package for chaostoolkit-k6."""
|
/*
BOM, DOM
브라우저 정보, 해상도, 사용자 정보 등 확인
브라우저 기능지원 여부: http://modernizr.com/download/
@date (버전관리) MAJOR.MINOR.BUGFIX
2015.04.09
@copyright
Copyright (c) Sung-min Yu.
@license
Dual licensed under the MIT and GPL licenses.
http://www.opensource.org/licenses/MIT
@browser compatibility
IE7 이상(IE7, IE8 부분지원하며, 트랜지션, 애니메이션 등의 사용은 IE10 이상)
querySelectorAll: Chrome 1, Firefox 3.5, Internet Explorer 8, Opera 10, Safari 3.2 - IE8의 경우 CSS 2.1 Selector (https://www.w3.org/TR/CSS2/selector.html) 제한적으로 지원
element.classList: Chrome 8.0, Firefox 3.6, Internet Explorer 10, Opera 11.50, Safari 5.1
box-sizing: border-box; IE8 이상 (boder 효과가 화면상에 안보일 수 있으니 주의한다.)
localStorage, sessionStorage: IE8 이상
@webapi 참고
https://developer.mozilla.org/en-US/docs/Web/API
http://www.quirksmode.org/js/detect.html
*/
;(function(factory, global) {
'use strict'; // ES5
if(typeof global === 'undefined' || global !== window) {
return false;
}else if(!global.api) {
global.api = {};
}
// 일반적인 고유키 생성 (id="" 속성의 경우 첫글자가 문자로 시작해야 한다.)
var getKey = function() {
/*
-
ES6
심볼(Symbol)은 프로그램이 이름 충돌의 위험 없이 속성(property)의 키(key)로 쓰기 위해 생성하고 사용할 수 있는 값입니다.
Symbol()을 호출하면 새로운 심볼 값이 생성됩니다. 이 값은 다른 어떤 값과도 다릅니다.
-
랜덤, 날짜 결합
var arr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var date = new Date();
return [arr[Math.floor(Math.random() * arr.length)], Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1), date.getFullYear(), (Number(date.getMonth()) + 1), date.getDate(), date.getHours(), date.getMinutes()].join('');
-
페이스북 참고
1. 'f' + : 'f' 문자열에 뒤의 것을 더할 건데, // f
2. Math.random() : 0~1 사이의 랜덤한 수 생성에 // 0.13190673617646098
3. * (1 << 30) : 2의 30승을 곱하고, // 0.13190673617646098 * 1073741824 = 141633779.5
4. .toString(16) : 16진수로 문자열로 표현한 후에, // Number(141633779.9).toString(16) = 87128f3.8
5. .replace('.', '') : 문자열에서 닷(소수점)을 제거한다. // 'f' + 87128f38 = f87128f38
return 'f' + (Math.random() * (1 << 30)).toString(16).replace('.', '');
*/
return ['api', new Date().getTime(), (Math.random() * (1 << 30)).toString(16).replace('.', '')].join('').substr(0, 24); // MongoDB _id 24자 길이
};
// 클라이언트 브라우저 환경
var agent = (global.navigator.userAgent || global.navigator.vendor || global.opera).toLowerCase();
var div = document.createElement('div');
var environment = {
//"zindex": 100, // z-index 최대값: 2147483647 (대부분 브라우저 32 비트 값 -2147483648 ~ +2147483647으로 제한)
//"support": {
"check": { // true, false
"mobile": (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i.test(agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(agent.substr(0, 4))),
"touch": ('ontouchstart' in global || global.navigator.MaxTouchPoints > 0 || global.navigator.msMaxTouchPoints > 0 || (global.DocumentTouch && global.document instanceof DocumentTouch)),
//"orientationchange": 'onorientationchange' in window, // 모바일기기 회전
"transform": false,
"transform3d": false,
"transition": false/*('transition' in div.style || 'WebkitTransition' in div.style || 'MozTransition' in div.style || 'OTransition' in div.style || 'msTransition' in div.style)*/,
"animation": false/*('animationName' in div.style || 'WebkitAnimationName' in div.style || 'MozAnimationName' in div.style || 'OAnimationName' in div.style || 'msAnimationName' in div.style || 'KhtmlAnimationName' in div.style)*/,
"fullscreen": (document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled)
},
"os": { // android | ios | mac | window
"name": ""
},
"monitor": '', // pc | mobile | tablet (해상도에 따라 설정가능) - check['mobile'] 가 있음에도 따로 구분한 이유는 기기기준과 해상도(모니터) 기준의 영역을 나누어 관리하기 위함
"screen": { // browser 사이즈가 아닌 해상도 값
"width": global.screen.availWidth/*Windows Taskbar 제외*/ || global.screen.width || Math.round(global.innerWidth),
"height": global.screen.availHeight/*Windows Taskbar 제외*/ || global.screen.height || Math.round(global.innerHeight)
},
"browser": {
"name": '', // chrome | safari | opera | firefox | explorer (브라우저 구분)
"version": '',
"scrollbar": (function() { // 브라우저별 스크롤바 폭 (모바일브라우저 주의)
var div = document.createElement("div");
var scrollbar = 0;
div.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
document.documentElement.appendChild(div);
scrollbar = div.offsetWidth - div.clientWidth;
document.documentElement.removeChild(div);
return scrollbar;
})()
},
"event": {
// 마우스 또는 터치
"down": "mousedown",
"move": "mousemove",
"up": "mouseup",
//"click": ('ontouchstart' in window) ? 'touchstart' : (global.DocumentTouch && document instanceof DocumentTouch) ? 'tap' : 'click', // touchstart 를 사용할 경우 click 이벤트보다 먼저 작동하여, 예상과 다른 실행순서가 발생할 수 있다.
"click": "click",
"wheel": (function() {
if(agent.indexOf('webkit') >= 0) { // Chrome / Safari
return 'mousewheel';
}else if(div.attachEvent) { // IE
return 'mousewheel';
}else if(div.addEventListener) { // Mozilla
return 'DOMMouseScroll';
}
/*
// 마우스휠 스크롤 코드 참고
var scroll;
if(event.wheelDelta) {
scroll = event.wheelDelta / 3600; // Chrome / Safari
}else if(event.detail) {
scroll = event.detail / -90; // Mozilla
}else {
return false;
}
scroll = 1 + scroll; // Zoom factor: 0.9 / 1.1
if(scroll > 1) {
// top
}else if(scroll < 1) {
// bottom
}else {
return false;
}
*/
return false;
})(),
// 트랜지션, 애니메이션
"transitionend": "transitionend",
"animationstart": "animationstart",
"animationiteration": "animationiteration",
"animationend": "animationend"
}/*,
"css": {
"prefix": '', // 벤더 프리픽스
"transform": '',
"transform3d": ''
}*/
};
// transform, transition, animation
(function() {
var transforms = ["transform", "WebkitTransform", "MozTransform", "OTransform", "msTransform"]; // css check (IE9 벤더프리픽스로 사용가능, IE10이상 공식지원)
var transforms3d = ["perspective", "WebkitPerspective", "MozPerspective", "OPerspective", "msPerspective"]; // 3D지원여부 판단자료
var transitions = { // event check (IE10이상 공식지원)
"transition": "transitionend",
"WebkitTransition": "webkitTransitionEnd",
"MozTransition": "transitionend",
"OTransition": "oTransitionEnd",
"msTransition": "MSTransitionEnd"
};
var animations = { // event check (IE10이상 공식지원)
"animation": ['animationstart', 'animationiteration', 'animationend'],
"WebkitAnimation": ['webkitAnimationStart', 'webkitAnimationIteration', 'webkitAnimationEnd'],
"MozAnimation": ['animationstart', 'animationiteration', 'animationend'],
"OAnimation": ['oanimationstart', 'oanimationiteration', 'oanimationend'],
"msAnimation": ['MSAnimationStart', 'MSAnimationIteration', 'MSAnimationEnd']
};
var key;
// 트랜스폼
for(key in transforms) {
if(div.style[transforms[key]] !== undefined) {
environment['check']['transform'] = true;
//environment['css']['transform'] = transforms[key];
break;
}
}
for(key in transforms3d) {
if(div.style[transforms3d[key]] !== undefined) {
environment['check']['transform3d'] = true;
//environment['css']['transform3d'] = transforms3d[key];
break;
}
}
// 트랜지션
for(key in transitions) {
if(div.style[key] !== undefined) {
environment['check']['transition'] = true;
environment['event']['transitionend'] = transitions[key];
break;
}
}
// 애니메이션
for(key in animations) {
if(div.style[key] !== undefined) {
environment['check']['animation'] = true;
environment['event']['animationstart'] = animations[key][0];
environment['event']['animationiteration'] = animations[key][1];
environment['event']['animationend'] = animations[key][2];
break;
}
}
})();
// os, monitor
(function() {
var platform = global.navigator.platform;
if(/android/i.test(agent)) { // 안드로이드
environment['os']['name'] = 'android';
// mobile 없으면 태블릿임
if(/mobile/i.test(agent)) {
environment['monitor'] = 'mobile';
}else {
environment['monitor'] = 'tablet';
}
}else if(/(iphone|ipad|ipod)/i.test(agent)) { // 애플
environment['os']['name'] = 'ios';
if(/ipad/i.test(agent)) {
environment['monitor'] = 'tablet';
}else {
environment['monitor'] = 'mobile';
}
}else if(environment.check.mobile) {
environment['monitor'] = 'mobile';
}else if(/(MacIntel|MacPPC)/i.test(platform)) {
environment['os']['name'] = 'mac';
environment['monitor'] = 'pc';
}else if(/(win32|win64)/i.test(platform)) {
environment['os']['name'] = 'window';
environment['monitor'] = 'pc';
}
// agent 값보다 스크린 크기를 우선 적용하여 태블릿인지 모바일인지 여부를 결정한다.
// 테블렛인데 가로 길이가 미달이면 모바일로 인식하게 함
/*if((environment['monitor'] = 'tablet') && environment['screen']['width'] && environment['screen']['height'] && (Math.min(environment['screen']['width'], environment['screen']['height']) < 768)) {
environment['monitor'] = 'mobile';
}*/
// 모바일인데 가로 길이가 넘어가면 테블렛으로 인식하게 함
/*if((environment['monitor'] = 'mobile') && environment['screen']['width'] && environment['screen']['height'] && (Math.min(environment['screen']['width'], environment['screen']['height']) >= 768)) {
environment['monitor'] = 'tablet';
}*/
})();
// browser
(function() {
var app_name = global.navigator.appName;
var app_version = global.navigator.appVersion;
var offset_name, offset_version;
// if문 순서 중요함
environment['browser']['name'] = app_name;
environment['browser']['version'] = String(parseFloat(app_version));
if((offset_version = agent.indexOf("opr/")) !== -1) {
environment['browser']['name'] = "opera";
environment['browser']['version'] = agent.substring(offset_version + 4);
}else if((offset_version = agent.indexOf("opera")) !== -1) {
environment['browser']['name'] = "opera";
environment['browser']['version'] = agent.substring(offset_version + 6);
if((offset_version = agent.indexOf("version")) !== -1) {
environment['browser']['version'] = agent.substring(offset_version + 8);
}
}else if((offset_version = agent.indexOf("msie")) !== -1) {
environment['browser']['name'] = "explorer";
environment['browser']['version'] = agent.substring(offset_version + 5);
}else if((offset_version = agent.indexOf("chrome")) !== -1) {
environment['browser']['name'] = "chrome";
environment['browser']['version'] = agent.substring(offset_version + 7);
}else if((offset_version = agent.indexOf("safari")) !== -1) {
environment['browser']['name'] = "safari";
environment['browser']['version'] = agent.substring(offset_version + 7);
if((offset_version = agent.indexOf("version")) !== -1) {
environment['browser']['version'] = agent.substring(offset_version + 8);
}
}else if((offset_version = agent.indexOf("firefox")) !== -1) {
environment['browser']['name'] = "firefox";
environment['browser']['version'] = agent.substring(offset_version + 8);
}else if((offset_name = agent.lastIndexOf(' ') + 1) < (offset_version = agent.lastIndexOf('/'))) {
environment['browser']['name'] = agent.substring(offset_name, offset_version);
environment['browser']['version'] = agent.substring(offset_version + 1);
if(environment['browser']['name'].toLowerCase() === environment['browser']['name'].toUpperCase()) {
environment['browser']['name'] = app_name;
}
}
if((offset_version = environment['browser']['version'].indexOf(';')) !== -1) {
environment['browser']['version'] = environment['browser']['version'].substring(0, offset_version);
}
if((offset_version = environment['browser']['version'].indexOf(' ')) !== -1) {
environment['browser']['version'] = environment['browser']['version'].substring(0, offset_version);
}
})();
// event
if(environment['check']['touch'] === true) {
environment['event']['down'] = 'touchstart';
environment['event']['move'] = 'touchmove';
environment['event']['up'] = 'touchend';
/*if(/(iphone|ipad|ipod)/i.test(agent)) { // touchend와 click 이벤트 실행 우선순위 문제발생
environment['event']['click'] = 'touchend';
}*/
}
// public return
global.api.key = getKey;
global.api.env = environment;
if(environment['browser']['name'] !== 'explorer' || (environment['browser']['name'] === 'explorer' && environment['browser']['version'] > 6)) {
// 브라우저 버전에 따라 추가 기능제공
factory(global);
}
})(function(global, undefined) {
'use strict'; // ES5
// 정규식
var regexp = {
pixel_unit_list: /width$|height$|top|right|bottom|left|fontSize|letterSpacing|lineHeight|^margin*|^padding*/i, // 단위 px 해당되는 것
time_unit_list: /.+(-duration|-delay)$/i, // seconds (s) or milliseconds (ms)
position_list: /^(top|right|bottom|left)$/,
display_list: /^(display|visibility|opacity|)$/i,
text: /^(\D+)$/i, // 텍스트
num_unit: /^([0-9]+)(\D+)$/i, // 단위
num: /^[+-]?\d+(\.\d+)?$/, // 숫자
source_num: /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // +=, -= 숫자와 연산자 분리
trim: /(^\s*)|(\s*$)/g // 양쪽 여백
};
// element 의 window
var getWindow = function(element) {
return element !== null && element === element.window ? element : element.nodeType === 9 ? element.defaultView || element.parentWindow : global;
};
// element 의 docuemnt
var getDocument = function(element) {
// document.documentElement; // <html> element //표준
return element && element.ownerDocument || global.document;
};
// event name 브라우저에 따른 자동 변경
var setEventTypeChange = function(events) {
if(typeof events === 'string' && /transitionend|animationstart|animationiteration|animationend/i.test(events.toLowerCase())) {
events = events.toLowerCase(); // 주의! 이벤트명을 모두 소문자로 변경했을 때 작동하지 않는 이벤트가 있다. (DOMMouseScroll)
if(/transitionend/i.test(events) && global.api.env['event']['transitionend']) {
events = global.api.env['event']['transitionend'];
}else if(/animationstart/i.test(events) && global.api.env['event']['animationstart']) {
events = global.api.env['event']['animationstart'];
}else if(/animationiteration/i.test(events) && global.api.env['event']['animationiteration']) {
events = global.api.env['event']['animationiteration'];
}else if(/animationend/i.test(events) && global.api.env['event']['animationend']) {
events = global.api.env['event']['animationend'];
}
}
return events;
};
// 숫자여부
var isNumeric = function(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
};
// 숫자 분리
var getNumber = function(value) {
return isNumeric(value) ? value : String(value).replace(/[^+-\.\d]|,/g, '') || 0;
};
// 숫자/단위 분리 (예: 10px -> [0]=>10px, [1]=>10, [2]=>'px')
var getNumberUnit = function(value) {
//var regexp_source_num = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
var regexp_number = new RegExp("^(" + regexp.source_num + ")(.*)$", "i");
var matches = regexp_number.exec(value);
if(matches) {
return matches;
}else {
return [value];
}
};
// inner, outer 관련
var getAugmentWidthHeight = function(elements, property) {
var value = {
'padding': 0,
'border': 0,
'margin': 0
};
var arr = [], i, max, tmp;
//
if(!elements || !elements instanceof DOM || !property || !(/^(width|height)$/i.test(property))) {
return value;
}
// 소문자 변환
property = property.toLowerCase();
// width, height 에 따라 분기 (paddingLeft, paddingRight, paddingTop, paddingBottom, ...)
if(property === 'width') {
arr = ["Left", "Right"];
}else if(property === 'height') {
arr = ["Top", "Bottom"];
}
for(i=0, max=arr.length; i<max; i++) {
// padding
tmp = getNumberUnit(elements.css('padding' + arr[i]));
value['padding'] += (tmp && tmp[1] && isNumeric(tmp[1])) ? Number(tmp[1]) : 0;
// border
tmp = getNumberUnit(elements.css('border' + arr[i] + 'Width'));
value['border'] += (tmp && tmp[1] && isNumeric(tmp[1])) ? Number(tmp[1]) : 0;
// margin
tmp = getNumberUnit(elements.css('margin' + arr[i]));
value['margin'] += (tmp && tmp[1] && isNumeric(tmp[1])) ? Number(tmp[1]) : 0;
}
return value;
};
// width, height 등 사이즈 정보 반환
// property: width, height
// extra: inner(padding), outer(border) 값 포함구분
// is: margin 값 포함여부
var getElementWidthHeight = function(element, property, extra, is) {
if(!element || !element instanceof DOM || !property || !(/^(width|height)$/i.test(property)) || (extra && !/^(inner|outer)$/i.test(extra))) {
return 0;
}
var is_border_box = (element.css('boxSizing') === 'border-box') ? true : false; // IE와 웹킷간의 박스모델 스팩이 다르므로 구분해야 한다.
var is_display = (element.css('display') === 'none') ? true : false;
var queue = {
/*
css property 기본값
position: static
visibility: visible
display: inline | block
*/
'position': /^(static)$/i,
'visibility': /^(visible)$/i,
'display': /^(inline|block)$/i
};
var value = 0;
var rect = {};
var key, tmp;
// 소문자 변환
property = property.toLowerCase();
// display가 none 경우 width, height 추출에 오차가 발생한다.
if(is_display === true) {
// 현재 설정된 css 값 확인
for(key in queue) {
if(tmp = element.css(key)) {
if(queue[key].test(tmp)) {
// 현재 element에 설정된 style의 값이 queue 목록에 지정된 기본값(style property default value)과 동일하거나 없으므로
// 작업 후 해당 property 초기화(삭제)
queue[key] = null;
}else {
// 현재 element에 설정된 style의 값이 queue 목록에 지정된 기본값(style property default value)이 아니므로
// 현재 설정된 값을 저장(종료 후 현재값으로 재설정)
queue[key] = tmp;
}
}
}
// display가 none 상태의 element 의 크기를 정확하게 추출하기 위한 임시 css 설정
element.css({'position': 'absolute', 'visibility': 'hidden', 'display': 'block'});
}
// 해당 property 값
value = element.get(0)['offset' + (property.substring(0, 1).toUpperCase() + property.substring(1))]; // offsetWidth, offsetHeight (border + padding + width 값, display: none 의 경우는 0 반환)
if(typeof element.get(0).getBoundingClientRect === 'function') { // chrome 에서는 정수가 아닌 실수단위로 정확한 값을 요구하므로 getBoundingClientRect 사용
rect = element.get(0).getBoundingClientRect(); // width/height: IE9 이상 지원
if(property in rect) {
value = rect[property];
}/*else if(property === 'width') {
value = rect.right - rect.left;
}else if(property === 'height') {
value = rect.bottom - rect.top;
}*/
}
if(value <= 0 || value === null) {
// 방법1: css로 값을 구한다.
tmp = getNumberUnit(element.css(property));
value = (tmp && tmp[1] && isNumeric(tmp[1])) ? Number(tmp[1]) : 0;
if(extra) {
// inner, outer 추가
tmp = getAugmentWidthHeight(element, property);
value += tmp['padding'];
if(extra === 'outer') {
value += tmp['border'];
if(is === true) {
value += tmp['margin'];
}
}
}
}else {
// 방법2: offset 값 가공 (margin, border, padding)
tmp = getAugmentWidthHeight(element, property);
if(extra) {
if(extra === 'inner') {
value -= tmp['border'];
}else if(extra === 'outer' && is === true) {
value += tmp['margin'];
}
}else {
value -= tmp['border'];
value -= tmp['padding'];
}
}
// 값 반환을 위해 임시 수정했던 style 복구
if(is_display === true) {
// queue
element.css(queue);
}
return value;
};
// DOM (event, style, attr, data, scroll 등)
// var element = api.dom('<div>').css({'': '', '': ''}).attr({'': ''}).data({'': ''}).on('', function() { ... }).get();
function DOM(selector, context) {
// return instance
if(!(this instanceof DOM)) {
return new DOM(selector, context);
}
var match1, match2, elements, i, max;
this.elements = [];
this.length = 0;
if(selector) {
if(typeof selector === 'object') {
/*
nodeType
1 : Element 노드를 의미
2 : Attribute 노드를 의미
3 : Text 노드를 의미
4 : CDATASection 노드를 의미
5 : EntityReference 노드를 의미
6 : Entity 노드를 의미
7 : ProcessingInstruction 노드를 의미
8 : Comment 노드를 의미
9 : Document 노드를 의미
10 : DocumentType 노드를 의미
11 : DocumentFragment 노드를 의미
12 : Notation 노드를 의미
*/
if('elements' in selector) {
return selector;
}else if(selector.nodeType || selector === window) { // DOMElement, window (querySelectorAll 반환값 nodeType 은 undefined)
this.elements[0] = selector;
}else if(Object.prototype.toString.call(selector) === '[object Array]'/*Array.isArray(selector)*/) { // array list (api.dom 으로 리턴된 것)
this.elements = selector;
}else if(Object.keys(selector).length > 0) { // object list (querySelectorAll 으로 리턴된 것)
max = 0;
for(i in selector) {
if(selector.hasOwnProperty(i) && selector[i].nodeType) {
this.elements[max] = selector[i];
max++;
}
}
}else {
//console.log('[오류] dom search error');
}
}else if(typeof selector === 'string') {
match1 = /<(\w+:\w+|\w+)[^>]*/.exec(selector); // tag create 확인 정규식 (<svg:g> 또는 <div> 형식)
//match1 = /<(\w+)[^>]*/.exec(selector); // tag create 확인 정규식 (createElementNS 사용안할경우)
if(match1 && match1[1]) { // create element
match2 = /(\w+):(\w+)/.exec(selector);
switch(match2 && match2[1] && match2[2] && match2[1].toLowerCase()) {
case 'xhtml':
// api.dom('<xhtml:값>')
this.elements[0] = document.createElementNS("http://www.w3.org/1999/xhtml", match2[2]);
break;
case 'math':
// api.dom('<math:값>')
this.elements[0] = document.createElementNS("http://www.w3.org/1998/Math/MathML", match2[2]);
break;
case 'svg':
// api.dom('<svg:값>')
this.elements[0] = document.createElementNS("http://www.w3.org/2000/svg", match2[2]);
break;
case 'text':
// text node
// api.dom('<text:텍스트값>')
// http://www.mediaevent.de/javascript/DOM-Neue-Knoten.html
this.elements[0] = document.createTextNode(match2[2]);
break;
default:
// element node
this.elements[0] = document.createElement(match1[1]);
break;
}
}else { // search element
try {
// document.querySelectorAll(x); // IE8의 경우 CSS 2.1 Selector (https://www.w3.org/TR/CSS2/selector.html) 제한적으로 지원
elements = (context || document).querySelectorAll(selector); // querySelectorAll: length 있음, querySelector: length 없음
if(elements instanceof NodeList || elements instanceof HTMLCollection) {
for(i=0, max=elements.length; i<max; i++) {
this.elements[i] = elements[i];
}
}
}catch(e) {
// IE7, 8 대응시 아래 코드 사용
if(selector.charAt(0) === '#') { // id
elements = document.getElementById(selector.slice(1)); // getElementById context 하위 검색 불가능
try {
if(elements && elements.nodeType) {
this.elements[0] = elements;
}
}catch(e) {}
}else { // tag
// element.getElementsByTagName(x);
// element.getElementsByTagName("*"); // IE6이상 사용가능
// element.getElementsByClassName(x); // IE9이상 사용가능
elements = (context || document).getElementsByTagName(selector);
try {
if(elements && (elements.length || elements instanceof NodeList || elements instanceof HTMLCollection)) { // IE7 문제: NodeList, HTMLCollection
for(i=0, max=elements.length; i<max; i++) {
this.elements[i] = elements[i];
}
}
}catch(e) {}
}
}
}
}
}
// this.elements -> this 연관배열
for(i=0, max=this.elements.length; i<max; i++) {
this[i] = this.elements[i];
}
this.length = this.elements.length;
return this;
}
// DOM prototype
DOM.fn = DOM.prototype = {
constructor: DOM, // constructor 를 Object 가 아닌 DOM 으로 변경 - instanceof 활용이 가능
// document ready
ready: (function() {
if(document.readyState === "interactive" || document.readyState === "complete") {
// IE8 등에서 global.setTimeout 파라미터로 바로 함수값을 넣으면 오류가 난다.
// 그러므로 function() {} 무명함수로 해당 함수를 실행시킨다.
return function(callback) {
global.setTimeout(function() {
callback();
});
};
}else if(document.addEventListener) { // Mozilla, Opera, Webkit
return function(callback) {
document.addEventListener("DOMContentLoaded", callback, false);
};
}else if(document.attachEvent) { // IE
return function(callback) {
// https://developer.mozilla.org/ko/docs/Web/API/Document/readyState
document.attachEvent("onreadystatechange", function(e) {
if(document.readyState === "complete") {
callback.call(this, e);
}
});
};
}
})(),
// element return
get: function(index) {
if(this.elements && this.elements.length > 0) {
if(typeof index === 'number' && this.elements[index]) {
return this.elements[index];
}else {
return this.elements;
}
}
return false;
},
// child node search
find: function(selector) {
if(this.elements && this.elements.length > 0) {
return DOM(selector, this.elements[0] || document);
}
return this;
},
// loop elements
each: function(callback) {
var i, max;
if(this.elements && this.elements.length > 0 && typeof callback === 'function') {
for(i=0, max=this.elements.length; i<max; i++) {
// i:key, this.elements[i]:element
if(callback.apply(this.elements[i], [i, this.elements[i]]) === false) { // return false 경우 break
break;
}
}
}
},
// parent node search
closest: function(selector, context) {
// document.querySelector(x); // IE8이상 사용가능 ('.testClass + p' selector 형태는 IE9이상 사용가능)
// x.parentNode; // 표준
var i, max = (this.elements && this.elements.length) || 0;
var context = context || document.documentElement; // documentElement: <html />
var element, search;
if(!max) {
return this;
//return false;
}else if(typeof selector === 'string') {
for(i=0; i<max; i++) { // this.elements[] 연관배열
for(search = this.elements[i].parentNode; search && search !== context; search = search.parentNode) {
// 현재 element 부터 검사하기 위해
// 현재 노드의 parentNode 를 search 초기값으로 바인딩하고
// search.querySelector() 로 확인 한다.
element = search.querySelector(selector);
if(element) {
this.elements[0] = element;
return this;
}
}
}
}
return this;
},
// 자식요소 리스트
children: function() {
// x.hasChildNodes(); // 표준
// x.childNodes[1]; // IE9이상 사용가능 (IE8이하 부분지원), TextNode 까지 검색
// x.children[1]; // IE9이상 사용가능 (IE8이하 부분지원)
// getElementsByTagName('*'); // 폴리필
if(this.elements && this.elements.length > 0 && this.elements[0].hasChildNodes()) { // true | false
return this.elements[0].children;
}
},
//
/*getClass: (function() {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
if('classList' in document.createElement('div')) {
return function() {
if(this.elements && this.elements.length > 0) {
return this.elements[0].classList;
}
};
}else {
return function() {
if(this.elements && this.elements.length > 0 && this.elements[0].className) {
return this.elements[0].className.split(/\s+/);
}
};
}
})(),*/
getClass: function() {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
if(this.elements && this.elements.length > 0) {
// 초기화 시점분기 패턴을 사용하지 않고, if문으로 확인하는 이유는 $(selector) 리스트에 svg 등이 들어있을 가능성 때문이다.
if('classList' in this.elements[0]) {
return this.elements[0].classList;
}else if('className' in this.elements[0]) {
return this.elements[0].className.split(/\s+/);
}
}
},
hasClass: function(name) {
// x.className; // 표준
var regexp;
if(this.elements && this.elements.length > 0 && typeof name === 'string' && this.elements[0].className) {
regexp = new RegExp('(\\s|^)' + name + '(\\s|$)'); // new로 만들때에는 이스케이프문자 \는 \\로 해주어야 한다.
return regexp.test(this.elements[0].className);
}
return false;
},
/*addClass: (function() {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
if('classList' in document.createElement('div')) {
return function(name) {
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
this.elements[i].classList.add(arr[key]); // add(): 한번에 하나의 클래스만 입력 가능하다. 즉, 띄어쓰기로 여러 클래스 입력 불가능
}
}
}
return this;
};
}else {
return function(name) {
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
if(!(!!this.elements[i].className.match(new RegExp('(\\s|^)' + arr[key] + '(\\s|$)')))) { // new로 만들때에는 이스케이프문자 \는 \\로 해주어야 한다.
this.elements[i].className += " " + arr[key];
}
}
}
}
return this;
};
}
})(),*/
addClass: function(name) {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
// 초기화 시점분기 패턴을 사용하지 않고, if문으로 확인하는 이유는 $(selector) 리스트에 svg 등이 들어있을 가능성 때문이다.
if('classList' in this.elements[i]) {
this.elements[i].classList.add(arr[key]); // add(): 한번에 하나의 클래스만 입력 가능하다. 즉, 띄어쓰기로 여러 클래스 입력 불가능
}else if('className' in this.elements[i] && !(!!this.elements[i].className.match(new RegExp('(\\s|^)' + arr[key] + '(\\s|$)')))) { // new로 만들때에는 이스케이프문자 \는 \\로 해주어야 한다.
this.elements[i].className += " " + arr[key];
}
}
}
}
return this;
},
/*removeClass: (function() {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
if('classList' in document.createElement('div')) {
return function(name) {
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
this.elements[i].classList.remove(arr[key]); // remove(): 한번에 하나의 클래스만 삭제 가능하다. 즉, 띄어쓰기로 여러 클래스 삭제 불가능
}
}
}
return this;
};
}else {
return function(name) {
var regexp;
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
regexp = new RegExp('(\\s|^)' + arr[key] + '(\\s|$)'); // new로 만들때에는 이스케이프문자 \는 \\로 해주어야 한다.
this.elements[i].className = this.elements[i].className.replace(regexp, ' ');
}
}
}
return this;
};
}
})(),*/
removeClass: function(name) {
// x.classList; // IE10이상 사용가능
// x.className; // 표준
var regexp;
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
// 초기화 시점분기 패턴을 사용하지 않고, if문으로 확인하는 이유는 $(selector) 리스트에 svg 등이 들어있을 가능성 때문이다.
if('classList' in this.elements[i]) {
this.elements[i].classList.remove(arr[key]); // remove(): 한번에 하나의 클래스만 삭제 가능하다. 즉, 띄어쓰기로 여러 클래스 삭제 불가능
}else if('className' in this.elements[i]) {
regexp = new RegExp('(\\s|^)' + arr[key] + '(\\s|$)'); // new로 만들때에는 이스케이프문자 \는 \\로 해주어야 한다.
this.elements[i].className = this.elements[i].className.replace(regexp, ' ');
}
}
}
}
return this;
},
/*toggleClass: (function() {
// x.classList; // IE10이상 사용가능
if('classList' in document.createElement('div')) {
return function(name) {
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
this.elements[i].classList.toggle(arr[key]);
}
}
}
return this;
};
}else {
return function(name) {
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
this.hasClass.call(this, arr[key]) ? this.removeClass.call(this, arr[key]) : this.addClass.call(this, arr[key]);
}
}
}
return this;
};
}
})(),*/
toggleClass: function(name) {
// x.classList; // IE10이상 사용가능
var i, key, max = (this.elements && this.elements.length) || 0;
var arr;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
arr = name.split(/\s+/); // 띄어쓰기로 구분된 여러 클래스 분리
for(i=0; i<max; i++) {
for(key in arr) {
// 초기화 시점분기 패턴을 사용하지 않고, if문으로 확인하는 이유는 $(selector) 리스트에 svg 등이 들어있을 가능성 때문이다.
if('classList' in this.elements[i]) {
this.elements[i].classList.toggle(arr[key]);
}else {
this.hasClass.call(this, arr[key]) ? this.removeClass.call(this, arr[key]) : this.addClass.call(this, arr[key]);
}
}
}
}
return this;
},
//
html: function(value) {
// x.outerHTML; // IE4이상 사용가능, IE외 다른 브라우저 사용가능여부 체크필요
// x.innerHTML; // 표준
var i, max = (this.elements && this.elements.length) || 0;
var dummy;
if(!max) {
return this;
//return false;
}else if(typeof value === 'undefined') { // get
//return this[i].outerHTML;
//return this[0].innerHTML;
if(this.elements[0].outerHTML) {
return this.elements[0].outerHTML;
}else {
dummy = document.createElement("div");
dummy.appendChild(this.elements[0].cloneNode(true));
return dummy.innerHTML;
}
}else if(typeof value === 'string' || typeof value === 'number') { // set
for(i=0; i<max; i++) {
this.elements[i].innerHTML = value;
}
}
return this;
},
text: function(value) {
// x.textContent; // 표준
// x.innerText; // IE
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof value === 'undefined') { // get
return this.elements[0].textContent || this.elements[0].innerText;
}else if(typeof value === 'string' || typeof value === 'number') { // set
for(i=0; i<max; i++) {
this.elements[i].textContent = this.elements[i].innerText = value;
}
}
return this;
},
val: function(value) {
// x.value; // IE8이상 공식지원 (IE6, IE7 부분적 사용가능)
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof value === 'undefined') { // get
return this.elements[0].value;
}else if(typeof value === 'string' || typeof value === 'number') { // set
for(i=0; i<max; i++) {
this.elements[i].value = value;
}
}
return this;
},
// stylesheet
css: function(parameter) {
// x.style.cssText; // 표준
// x.currentStyle[styleProp];
// document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
var i, key, max = (this.elements && this.elements.length) || 0;
var value;
var property, current, unit;
var tmp1, tmp2;
var getStyleProperty = function(style, property) {
var i, max;
var converted = '';
if(style === 'js') {
// HTML DOM Style Object (CSS 속성방식이 아닌 Jvascript style property 방식)
// (예: background-color -> backgroundColor)
for(i=0, max=property.length; i<max; ++i) {
if(property.charAt(i) === '-' && property.charAt(i+1)) {
converted = converted + property.charAt(++i).toUpperCase();
}else {
converted = converted + property.charAt(i);
}
}
}else if(style === 'css') {
// CSS 속성명으로 값을 구한다.
// CSS style property 의 경우 대문자를 소문자로 변환하고 그 앞에 '-'를 붙인다.
// (예: backgroundColor -> background-color, zIndex -> z-index, fontSize -> font-size)
for(i=0, max=property.length; i<max; ++i) {
if(property.charAt(i) === property.charAt(i).toUpperCase()) {
converted = converted + '-' + property.charAt(i).toLowerCase();
}else {
converted = converted + property.charAt(i);
}
}
}else {
converted = property;
}
return converted;
};
/*
// transition, animation 처리 방법
element.style.webkitTransitionDuration = element.style.MozTransitionDuration = element.style.msTransitionDuration = element.style.OTransitionDuration = element.style.transitionDuration = '1s';
element.style.webkitAnimationDelay = element.style.MozAnimationDelay = element.style.msAnimationDelay = element.style.OAnimationDelay = element.style.animationDelay = '1s';
*/
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string' && this.elements[0].nodeType && this.elements[0].nodeType !== 3 && this.elements[0].nodeType !== 8) { // get
// return this[0].style[property]; // CSS 속성과 JS 에서의 CSS 속성형식이 다르므로 사용불가능
// return this[0].style.getPropertyValue(property); // CSS 속성명을 사용하여 정상적 출력가능
if(this.elements[0].style[getStyleProperty('js', parameter)]) { // style로 값을 구할 수 있는 경우
value = this.elements[0].style[getStyleProperty('js', parameter)];
}else if(this.elements[0].currentStyle && this.elements[0].currentStyle[getStyleProperty('js', parameter)]) { // IE의 경우
value = this.elements[0].currentStyle[getStyleProperty('js', parameter)];
}else if(document.defaultView && document.defaultView.getComputedStyle) {
if(document.defaultView.getComputedStyle(this.elements[0], null).getPropertyValue(getStyleProperty('css', parameter))) {
value = document.defaultView.getComputedStyle(this.elements[0], null).getPropertyValue(getStyleProperty('css', parameter));
}
}
// css 는 단위까지 명확하게 알기위한 성격이 강하므로, 단위/숫자 분리는 하지않고 값 그대로 반환
return value;
}else if(typeof parameter === 'object') { // set
for(i=0; i<max; i++) {
for(property in parameter) {
// 속성, 값 검사
if(!parameter.hasOwnProperty(property) || !this.elements[i].nodeType || this.elements[i].nodeType === 3 || this.elements[i].nodeType === 8) {
continue;
}
// +=, -= 연산자 분리
if(tmp1 = new RegExp("^([+-])=(" + regexp.source_num + ")", "i").exec(parameter[property])) {
// tmp1[1]: 연산자
// tmp1[2]: 값
current = DOM(this.elements[i]).css(property);
unit = '';
// 단위값 존재 확인
if(regexp.text.test(current)) { // 기존 설정값이 단어로 되어 있는 것 (예: auto, none 등)
unit = 0;
}else if(tmp2 = regexp.num_unit.exec(current)) { // 단위 분리
// tmp2[1]: 값
// tmp2[2]: 단위 (예: px, em, %, s)
current = tmp2[1];
unit = tmp2[2];
}
parameter[property] = ((tmp1[1] + 1) * tmp1[2] + parseFloat(current)) + unit; // ( '연산자' + 1 ) * 값 + 현재css속성값
}
// trim
/*if(typeof parameter[property] === 'string') {
parameter[property].replace(regexp.trim, '');
}*/
// 단위값이 없을 경우 설정
if(regexp.num.test(parameter[property]) && !regexp.num_unit.test(parameter[property])) {
// property default value 단위가 px 에 해당하는 것
if(regexp.pixel_unit_list.test(property)) {
parameter[property] = parameter[property] + 'px';
}else if(regexp.time_unit_list.test(property)) { // animation, transition
parameter[property] = parameter[property] + 's';
}
}
// window, document
if(this.elements[i].nodeType === 9 || this.elements[i] === window) {
this.elements[i] = global.document.documentElement; // html
//this.elements[i] = global.document.body;
}
// css 값 설정
if(parameter[property] === '' || parameter[property] === null) { // 해당 css 프로퍼티 초기화여부 확인
// 초기화시 css default value 를 설정해 주는 것이 가장 정확함
if(this.elements[i].style.removeProperty) {
this.elements[i].style.removeProperty(getStyleProperty('css', property));
}else if(this.elements[i].style.removeAttribute) { // IE9 이상
this.elements[i].style.removeAttribute(getStyleProperty('js', property));
}else if(getStyleProperty('js', property) in this.elements[i].style) {
this.elements[i].style[getStyleProperty('js', property)] = null;
}
}else if(getStyleProperty('js', property) in this.elements[i].style) {
// 방법1
// 단위(예:px)까지 명확하게 입력해줘야 한다.
this.elements[i].style[getStyleProperty('js', property)] = parameter[property];
}else if(typeof this.elements[i].style.setProperty !== 'undefined') {
// 방법2 (Internet Explorer version 9)
this.elements[i].style.setProperty(getStyleProperty('css', property), parameter[property]);
}
}
}
}
return this;
},
show: function() {
// x.setAttribute(y, z); // IE8이상 사용가능
var i, key, max = (this.elements && this.elements.length) || 0;
var dummy;
var display;
var iframe, doc;
if(!max) {
return this;
//return false;
}else {
for(i=0; i<max; i++) {
if(!this.elements[i].tagName || !this.elements[i].nodeType || this.elements[i].nodeType === 3 || this.elements[i].nodeType === 8) {
continue;
}
// default value
dummy = document.createElement(this.elements[i].tagName);
document.body.appendChild(dummy);
display = DOM(dummy).css('display');
dummy.parentNode.removeChild(dummy);
if(!display || display === 'none') {
iframe = document.createElement('iframe');
iframe.setAttribute('frameborder', 0);
iframe.setAttribute('width', 0);
iframe.setAttribute('height', 0);
iframe.style.cssText = 'display:block !important';
document.body.appendChild(iframe);
doc = (iframe.contentWindow || iframe.contentDocument).document;
doc.write("<!doctype html><html><body>");
doc.close();
dummy = doc.createElement(this.elements[i].tagName);
doc.body.appendChild(dummy);
display = DOM(dummy).css('display');
iframe.parentNode.removeChild(iframe);
}
// css 값 설정
this.elements[i].style.display = display;
}
}
return this;
},
hide: function() {
var i, key, max = (this.elements && this.elements.length) || 0;
if(!max || !this.elements[0].nodeType || this.elements[0].nodeType === 3 || this.elements[0].nodeType === 8) {
return this;
//return false;
}else {
for(i=0; i<max; i++) {
if(!this.elements[i].tagName || !this.elements[i].nodeType || this.elements[i].nodeType === 3 || this.elements[i].nodeType === 8) {
continue;
}
// css 값 설정
this.elements[i].style.display = 'none';
}
}
return this;
},
// 절대좌표 (jQuery 와 다르게 값 설정은 하지 않는다.)
offset: function() {
var max = (this.elements && this.elements.length) || 0;
var win, doc;
var offset = {}, box = {'top': 0, 'left': 0};
if(!max) {
return this;
}else {
win = getWindow(this.elements[0]);
doc = getDocument(this.elements[0]);
// getBoundingClientRect
if(typeof this.elements[0].getBoundingClientRect === 'function') {
box = this.elements[0].getBoundingClientRect();
}
// scroll 값 포함
offset.top = box.top + (win.pageYOffset || doc.documentElement.scrollTop) - (doc.documentElement.clientTop || 0);
offset.left = box.left + (win.pageXOffset || doc.documentElement.scrollLeft) - (doc.documentElement.clientLeft || 0);
return offset;
}
},
offsetParent: function() {
// x.offsetParent; // IE8 이상 사용가능
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
return this.elements[0].offsetParent;
}
},
// 상대좌표 (부모 element 기준)
position: function() {
var position, offset;
var offsetParent, parentOffset = {'top': 0, 'left': 0};
var getOffsetParent = function(element) {
// document.documentElement; //<html> element //표준
var offsetParent = element.offsetParent || document.documentElement;
while(offsetParent && (!(offsetParent.nodeName && offsetParent.nodeName.toLowerCase() === 'html') && DOM(offsetParent).css('position') === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
};
if(!this.elements || !this.elements.length) {
return this;
//return false;
}else { // get
position = this.css.call(this, 'position');
if(position === 'fixed') {
offset = this.elements[0].getBoundingClientRect();
}else {
offsetParent = DOM(getOffsetParent(this.elements[0]));
offset = this.offset();
if(!(offsetParent[0].nodeName && offsetParent[0].nodeName.toLowerCase() === 'html')) {
parentOffset = offsetParent.offset();
}
parentOffset.top += getNumber(offsetParent.css('borderTopWidth'));
parentOffset.left += getNumber(offsetParent.css('borderLeftWidth'));
}
return {
'top': offset.top - parentOffset.top - getNumber(this.css('marginTop')),
'left': offset.left - parentOffset.left - getNumber(this.css('marginLeft'))
};
}
},
// 너비
width: function(value) {
var i, key, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof value === 'undefined') { // get
if(this.elements[0] === window) { // window (브라우저)
return global.innerWidth || document.documentElement.clientWidth;
}else if(this.elements[0].nodeType === 9) { // document
return Math.max(
document.body.scrollWidth, document.documentElement.scrollWidth,
document.body.offsetWidth, document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
}else {
return getElementWidthHeight(this, 'width');
}
}else if(typeof value === 'string' || typeof value === 'number') { // set
for(i=0; i<max; i++) {
if(!this.elements[i].nodeType || !this.elements[i].style) {
continue;
}
// 단위(예:px)까지 명확하게 입력해줘야 한다.
this.elements[i].style.width = value;
}
}
return this;
},
innerWidth: function() { // border 안쪽 크기 (padding 포함)
if(!this.elements || !this.elements.length) {
return this;
//return false;
}else if(this.elements[0] === window || this.elements[0].nodeType === 9) { // window, document
return this.width();
}else {
return getElementWidthHeight(this, 'width', 'inner');
}
},
outerWidth: function(is) { // border 포함 크기 (padding + border 포함, 파라미터가 true 경우 margin 값까지 포함)
if(!this.elements || !this.elements.length) {
return this;
//return false;
}else if(this.elements[0] === window || this.elements[0].nodeType === 9) { // window, document
return this.width();
}else {
return getElementWidthHeight(this, 'width', 'outer', is);
}
},
scrollWidth: function() {
// element overflow auto/scroll 값에서 보이지 않는 부분까지 포함한 값
// https://developer.mozilla.org/ko/docs/Web/API/Element/scrollWidth
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
return this.elements[0].scrollWidth;
}
},
// 높이
height: function(value) {
var i, key, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof value === 'undefined') { // get
if(this.elements[0] === window) { // window (브라우저)
return global.innerHeight || document.documentElement.clientHeight;
}else if(this.elements[0].nodeType === 9) { // document
return Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}else {
return getElementWidthHeight(this, 'height');
}
}else if(typeof value === 'string' || typeof value === 'number') { // set
for(i=0; i<max; i++) {
if(!this.elements[i].nodeType || !this.elements[i].style) {
continue;
}
// 단위(예:px)까지 명확하게 입력해줘야 한다.
this.elements[i].style.height = value;
}
}
return this;
},
innerHeight: function() { // border 안쪽 크기 (padding 포함)
if(!this.elements || !this.elements.length) {
return this;
//return false;
}else if(this.elements[0] === window || this.elements[0].nodeType === 9) { // window, document
return this.height();
}else {
return getElementWidthHeight(this, 'height', 'inner');
}
},
outerHeight: function(is) { // border 포함 크기 (padding + border 포함, 파라미터가 true 경우 margin 값까지 포함)
if(!this.elements || !this.elements.length) {
return this;
//return false;
}else if(this.elements[0] === window || this.elements[0].nodeType === 9) { // window, document
return this.height();
}else {
return getElementWidthHeight(this, 'height', 'outer', is);
}
},
scrollHeight: function() {
// element overflow auto/scroll 값에서 보이지 않는 부분까지 포함한 값
// https://developer.mozilla.org/ko/docs/Web/API/Element/scrollHeight
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
return this.elements[0].scrollHeight;
}
},
// attribute
attr: function(parameter) {
// x.attributes[y]; //
// x.getAttribute(y); // IE8이상 사용가능
// x.setAttribute(y, z); // IE8이상 사용가능
var i, key, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string') { // get
return this.elements[0].getAttribute(parameter);
}else if(typeof parameter === 'object') { // set
for(i=0; i<max; i++) {
for(key in parameter) {
this.elements[i].setAttribute(key, parameter[key]);
}
}
}
return this;
},
removeAttr: function(name) {
// x.removeAttribute(y); // 표준
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
for(i=0; i<max; i++) {
this.elements[i].removeAttribute(name);
}
}
return this;
},
hasAttr: function(name) {
// x.hasAttribute(y); // IE8이상 사용가능
if(this.elements && this.elements.length > 0 && typeof name === 'string') {
return this.elements[0].hasAttribute(name);
}
},
// property
prop: function(parameter) {
var i, key, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string') { // get
return this.elements[0][parameter];
}else if(typeof parameter === 'object') { // set
for(i=0; i<max; i++) {
for(key in parameter) {
this.elements[i][key] = parameter[key];
}
}
}
return this;
},
removeProp: function(name) {
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof name === 'string') {
for(i=0; i<max; i++) {
this.elements[i][name] = undefined;
delete this.elements[i][name];
}
}
return this;
},
// 제거
empty: function() {
// x.hasChildNodes(); // 표준
// x.removeChild(y); // 표준
// x.parentNode; //표준
// x.childNodes[1]; // IE9이상 사용가능 (IE8이하 부분지원), TextNode 까지 검색
// x.children[1]; // IE9이상 사용가능 (IE8이하 부분지원)
// x.lastChild; // IE9이상 사용가능
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else {
for(i=0; i<max; i++) {
// element
while(this.elements[i].hasChildNodes()) { // TextNode 포함 내부 element 전체 제거
this.elements[i].removeChild(this.elements[i].lastChild);
}
// select box
if(this.elements[i].options && this.elements[i].nodeName.toLowerCase() === 'select') {
this.elements[i].options.length = 0;
}
}
}
return this;
},
remove: function() {
// x.removeChild(y); // 표준
// x.parentNode; // 표준
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else {
// 이벤트 제거
// (element에 이벤트가 설정되었을 경우 이벤트 리스너도 같이 삭제해야 이벤트 메모리 누적 방지)
//this.off();
// element remove
for(i=0; i<max; i++) {
if(this.elements[i].parentNode) {
this.elements[i].parentNode.removeChild(this.elements[i]);
}
}
}
},
detach: function() {
// remove() 와 다른점은 제거한 element를 반환하므로, 재사용이 가능하도록 만든다.
},
// 복제
clone: function(is) { // jQuery 처럼 이벤트 복사는 api.dom 을 통해 설정된 이벤트 리스트(storage)에 한해 설계가능하다
// x = y.cloneNode(true | false); // 표준
// is : 자식 노드들도 모두 복제할지 여부(true:복사, false:해당없음)
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
// id를 가진 node를 복사할 때 주의하자(페이지내 중복 id를 가진 노드가 만들어 지는 가능성이 있다)
return this.elements[0].cloneNode(is || true);
}
return this;
},
// 삽입
prepend: function(parameter) {
// x.insertBefore(y,z); // 표준
// x.firstChild; // IE9이상 사용가능 (TextNode 포함)
// x.firstElementChild // TextNode 제외
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(this.elements[i].nodeType === 1 || this.elements[i].nodeType === 9 || this.elements[i].nodeType === 11) {
if(element.nodeType === 11) { // FRAGMENT NODE
this.elements[i].insertBefore(element.cloneNode(true), this.elements[i].firstChild);
}else {
this.elements[i].insertBefore(element, this.elements[i].firstChild);
}
}
}
}
return this;
},
append: function(parameter) {
// x.appendChild(y); // 표준
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(this.elements[i].nodeType === 1 || this.elements[i].nodeType === 9 || this.elements[i].nodeType === 11) {
if(element.nodeType === 11) { // FRAGMENT NODE
this.elements[i].appendChild(element.cloneNode(true));
}else {
this.elements[i].appendChild(element);
}
}
}
}
return this;
},
// 어떤 요소의 위치에 노드를 삽입
after: function(parameter) {
// x.insertBefore(y,z); // 표준
// x.parentNode; // 표준
// x.nextSibling; // IE9이상 사용가능
// api.dom(기준 요소).before(이동할 요소);
// 이동(또는 삽입)시킬 element 가 기준 element 바로 뒤로 이동(또는 삽입)한다.
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(this.elements[i].parentNode) {
this.elements[i].parentNode.insertBefore(element, this.elements[i].nextSibling);
}
}
}
return this;
},
before: function(parameter) {
// x.insertBefore(y,z); // 표준
// x.parentNode; // 표준
// api.dom(기준 요소).before(이동할 요소);
// 이동(또는 삽입)시킬 element 가 기준 element 바로 전으로 이동(또는 삽입)한다.
// querySelectorAll 또는 api.dom() length 가 있으나, querySelector 는 length 가 없다.
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(this.elements[i].parentNode) {
this.elements[i].parentNode.insertBefore(element, this.elements[i]);
}
}
}
return this;
},
insertBefore: function(parameter) {
// x.insertBefore(y,z); // 표준
// x.parentNode; // 표준
// api.dom(이동할 요소).insertBefore(기준 요소);
// 이동(또는 삽입)시킬 element 가 기준 element 바로 전으로 이동(또는 삽입)한다.
// querySelectorAll 또는 api.dom() length 가 있으나, querySelector 는 length 가 없다.
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(element.parentNode) {
element.parentNode.insertBefore(this.elements[i], element);
}
}
}
return this;
},
// 지정한 콘텐츠로 대체
replaceWith: function(parameter) {
// x.replaceChild(y,z); // 표준
// x.parentNode; // 표준
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return this;
//return false;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
if(this.elements[i].parentNode) {
this.elements[i].parentNode.replaceChild(element, this.elements[i]);
}
}
}
return this;
},
// next
next: function() {
// x.nextElementSibling; // IE9이상 사용가능
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
return this.elements[0].nextElementSibling;
}
},
// prev
prev: function() {
// x.previousElementSibling; // IE9이상 사용가능
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
return this.elements[0].previousElementSibling;
}
},
// event
on: function(events, handler, capture) {
var events = events || ''; // 띄어쓰기 기준 여러개의 이벤트를 설정할 수 있다.
var handler = handler || function() {};
var capture = typeof capture !== 'boolean' && typeof capture !== 'object' ? false : capture; // IE의 경우 캡쳐 미지원 (기본값: false 버블링으로 함) - Chrome 에서는 기본이벤트 방지를 위해 {passive: false} 값 등이 올 수 있다.
var list = events.split(/\s+/);
/*
.on('click.EVENT_CLICK_TEST mousedown.EVENT_MOUSEDOWN_TEST');
.on('click.EVENT_CLICK_TEST');
.on('click');
*/
this.each(function(index, element) {
var arr = [];
var type, key;
var i, max;
var callback;
var result = {};
if(typeof element.storage !== 'object') {
element.storage = {};
}
if(typeof element.storage.events !== 'object') {
element.storage.events = {};
}
for(i=0, max=list.length; i<max; i++) {
// 이벤트 type.key 분리
arr = list[i].split('.');
type = arr.shift();
if(0 < arr.length) {
// key 존재함
key = arr.join('');
}
if(type) {
// 이벤트 바인딩
if(typeof element.addEventListener === 'function') {
callback = handler.bind(element);
element.addEventListener(type, callback, capture); // IE9이상 사용가능
}else if(element.attachEvent) { // IE (typeof 검사시 IE8에서는 function 이 아닌 object 반환)
callback = function(e) { // IE this 바인딩 문제
handler(e, element);
};
/*
// 아래 같이 선언했을 경우 IE에서 스택풀 발생
handler = function(e) { // IE this 바인딩 문제
handler(e, element);
};
*/
element.attachEvent('on' + type, callback);
}
// 이벤트 정보 저장
result = {
"key": key, // 사용자가 지정한 이벤트키
"event": type,
"handler": callback,
"capture": capture
};
// event array (이벤트 종류별로 저장)
if(typeof element.storage.events[type] !== 'object') {
element.storage.events[type] = [];
}
element.storage.events[type].push(result);
// event key (이벤트 key/type 별로 저장)
if(key) {
if(typeof element.storage[key] !== 'object') {
element.storage[key] = {};
}
element.storage[key][type] = result;
}
}
}
});
return this;
},
off: function(events) {
var that = this;
var events = events || ''; // 띄어쓰기 기준 여러개의 이벤트를 해제할 수 있다.
var list = events.split(/\s+/);
var i, max;
var setListener = function(element, event, handler, capture) { // 이벤트 해제
if(typeof element.removeEventListener === 'function') {
element.removeEventListener(event, handler, capture);
}else if(element.detachEvent) { // IE
element.detachEvent('on' + event, handler);
}
};
/*
.off('click.EVENT_CLICK_TEST mousedown.EVENT_MOUSEDOWN_TEST');
.off('click.EVENT_CLICK_TEST');
.off('click');
.off('.EVENT_CLICK_TEST');
.off();
*/
for(i=0, max=list.length; i<max; i++) {
(function(factor) {
var arr = [];
var type, key;
var setRemove = function() {};
// 이벤트 type.key 분리
arr = factor.split('.');
if(1 < arr.length) {
// key 존재함
type = arr.shift();
key = arr.join('');
}else {
type = arr.shift();
}
if(key) {
// key 기반 이벤트 해제
if(type) {
// type.key 해제
setRemove = function(element) {
var result = {};
if(element.storage[key]) {
result = element.storage[key][type];
if(result) {
setListener(element, result.event, result.handler, result.capture);
}
delete element.storage[key][type];
}
};
}else {
// .key 해당 전체 해제
setRemove = function(element) {
var event;
var result = {};
if(element.storage[key]) {
for(event in element.storage[key]) {
if(element.storage[key].hasOwnProperty(event)) {
result = element.storage[key][event];
if(result) {
setListener(element, result.event, result.handler, result.capture);
}
delete element.storage[key][event];
}
}
delete element.storage[key];
}
};
}
}else if(type) {
// type 해당 전체 해제
setRemove = function(element) {
var result = {};
if(element.storage.events[type]) {
while(element.storage.events[type].length) {
result = element.storage.events[type].shift();
if(result) {
setListener(element, result.event, result.handler, result.capture);
if(result.key && element.storage.events[result.key]) {
delete element.storage.events[result.key][type];
}
}
}
delete element.storage.events[type];
}
};
}else {
// 전체 해제
setRemove = function(element) {
var event;
var result = {};
for(event in element.storage.events) {
while(element.storage.events[event].length) {
result = element.storage.events[event].shift();
if(result) {
setListener(element, result.event, result.handler, result.capture);
if(result.key && element.storage.events[result.key]) {
delete element.storage.events[result.key][event];
}
}
}
delete element.storage.events[event];
}
};
}
that.each(function(i, element) {
if(typeof element.storage === 'object') {
setRemove(element);
}
});
})(list[i]);
}
return this;
},
one: function(events, handler, capture) {
var that = this;
var key = global.api.key();
var callback = function() {
// off
that.off('.' + key);
// handler
handler.apply(this, Array.prototype.slice.call(arguments));
};
// on
that.on(events + '.' + key, callback, capture);
return this;
},
trigger: (function() {
if(document.createEvent) {
return function(events) {
var obj = document.createEvent('MouseEvents');
obj.initEvent(events, true, false);
this.each(function() {
this.dispatchEvent(obj);
});
};
}else if(document.createEventObject) { // IE
return function(events) {
var obj = document.createEventObject();
this.each(function() {
this.fireEvent('on' + events, obj);
});
};
}
})(),
// data
data: (function() {
// x.dataset; // IE11이상 사용가능
/*
! 주의
data-* 속성값에서 -(hyphen) 다음의 첫글자는 무조건 대문자로 들어가야 한다.
http://www.sitepoint.com/managing-custom-data-html5-dataset-api/
*/
var setTheFirstLetter = function(value) {
if(typeof value === 'string') {
return value.replace(/-([a-z])/g, function(value) {
return value[1].toUpperCase();
});
}
};
/*function hyphenToCamelCase(string) {
return string.replace(/-([a-z])/g, function(string) {
return string[1].toUpperCase();
});
}
function camelCaseToHyphen(string) {
return string.replace(/([A-Z])/g, function(string) {
return '-' + string.toLowerCase();
});
}*/
/*
if('dataset' in document.createElement('div')) { // IE11 이상
return function(parameter) {
var key;
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string') { // get
return this.elements[0].dataset[setTheFirstLetter(parameter)];
}else if(typeof parameter === 'object') { // set
for(i=0; i<max; i++) {
for(key in parameter) {
this.elements[i].dataset[setTheFirstLetter(key)] = parameter[key];
}
}
}
return this;
};
}else { // attr
return function(parameter) {
var key, convert = {};
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string') { // get
return this.attr('data-' + parameter);
}else if(typeof parameter === 'object') { // set
for(key in parameter) {
convert['data-' + key] = parameter[key];
}
this.attr(convert);
}
return this;
};
}
*/
// svg 대응
return function(parameter) {
// x.setAttribute(y, z); // IE8이상 사용가능
var key;
var i, max = (this.elements && this.elements.length) || 0;
if(!max) {
return this;
//return false;
}else if(typeof parameter === 'string') { // get
if('dataset' in this.elements[0]) {
return this.elements[0].dataset[setTheFirstLetter(parameter)];
}else {
return this.attr('data-' + parameter);
}
}else if(typeof parameter === 'object') { // set
for(i=0; i<max; i++) {
for(key in parameter) {
// 초기화 시점분기 패턴을 사용하지 않고, if문으로 확인하는 이유는 $(selector) 리스트에 svg 등이 들어있을 가능성 때문이다.
if('dataset' in this.elements[i]) {
this.elements[i].dataset[setTheFirstLetter(key)] = parameter[key];
}else if('setAttribute' in this.elements[i]) {
this.elements[i].setAttribute('data-' + key, parameter[key]);
}
}
}
}
return this;
};
})(),
// scroll 정보 / 설정
scroll: function(parameter) {
var parameter = parameter || {};
var key, property;
var i, max = (this.elements && this.elements.length) || 0;
var scroll;
var getBrowserScroll = function() {
if('pageXOffset' in window && 'pageYOffset' in window) {
return {'left': global.pageXOffset, 'top': global.pageYOffset};
}else if(document.body && ('scrollLeft' in document.body && 'scrollTop' in document.body)) {
return {'left': document.body.scrollLeft, 'top': document.body.scrollTop};
}else if(document.documentElement && ('scrollLeft' in document.documentElement && 'scrollTop' in document.documentElement)) {
return {'left': document.documentElement.scrollLeft, 'top': document.documentElement.scrollTop};
}else {
return {'left': 0, 'top': 0};
}
};
if(max) {
if(this.elements[0] === window || this.elements[0].nodeType === 9) {
// window, document
scroll = getBrowserScroll();
if('left' in parameter || 'top' in parameter) {
global.scrollTo((typeof parameter.left !== 'undefined' ? parameter.left : (scroll.left || 0)), (typeof parameter.top !== 'undefined' ? parameter.top : (scroll.top || 0)));
}else {
return {'left': scroll.left, 'top': scroll.top};
}
}else {
// element
if('left' in parameter || 'top' in parameter) {
for(i=0; i<max; i++) {
for(key in parameter) {
property = 'scroll' + key.substring(0, 1).toUpperCase() + key.substring(1, key.length).toLowerCase(); // 첫글자 대문자
if(property in this.elements[i]) {
this.elements[i][property] = parameter[key];
}
}
}
}else {
return {'left': this.elements[0].scrollLeft, 'top': this.elements[0].scrollTop};
}
}
}
},
// 특정 노드가 다른 노드 내에 포함되었는지 여부
// 사용예: api.dom('#test').contains(event.target)
contains: function(parameter) {
// x.contains(y); // 표준
var i, max = (this.elements && this.elements.length) || 0;
var element;
// parameter 검사
if(!max || !parameter) {
return is;
}else if(typeof parameter === 'object') {
if(parameter.elements) {
element = parameter.elements[0];
}else if(parameter.nodeType) {
element = parameter;
}
}
if(element) {
for(i=0; i<max; i++) {
// this.elements[i] 내부에 element 가 포함되어 있는지 확인
if(this.elements[i] && this.elements[i].contains(element)) {
return true;
}
}
}
return false;
},
// 조건 반환
// $(element).is('.my-class');
is: function(selector) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
// x.matches() // IE9이상 사용가능
var matches;
if(this.elements && this.elements.length > 0 && this.elements[0].nodeType) {
matches = this.elements[0].matches || this.elements[0].matchesSelector || this.elements[0].msMatchesSelector || this.elements[0].mozMatchesSelector || this.elements[0].webkitMatchesSelector || this.elements[0].oMatchesSelector;
}
if(matches) {
return matches.call(this.elements[0], selector);
}
return this;
}
};
// one, two, delay touch
/*
마우스 또는 터치 up 이 발생하고, 특정시간 이후까지 down이 발생하지 않았을 때, 클릭이 몇번발생했는지 카운트를 시작한다.
-
사용예
api.touch.on('#ysm',
{
'one': function(e) {
console.log('one touch');
},
'two': function(e) {
console.log('two touch');
},
'delay': function(e) {
console.log('delay touch');
}
}
);
api.touch.off('#ysm', 'one'); // one 해제
또는
api.touch.on('#ysm', function() {
...
});
api.touch.off('#ysm', 'all'); // 전체 해제
*/
var setTouchHandler = function(e, element) {
var event = e || global.event;
var touch = event.touches; // touchstart
var that = element || this;
var radius = 0; // 유효한 터치영역
var checkout = {
'delay': 1000, // 길게누르고 있는지 여부 검사시작 시간
'count': 250, // 몇번을 클릭했는지 검사시작 시간
'interval': 180 // 터지 down, up 이 발생한 간격 검사에 사용되는 시간
};
// 기본 이벤트를 중단시키면 스크롤이 작동을 안한다.
// 버블링(stopPropagation) 중지시키면, 상위 이벤트(예: document 에 적용된 이벤트)이 작동을 안한다.
if(!that['storage']) { // 유효성 검사
return;
}else if(touch && touch.length && 1 < touch.length) { // 멀티터치 방지
return;
}
// 이벤트 종료
DOM(document).off('.EVENT_MOUSEMOVE_DOM_TOUCH');
DOM(document).off('.EVENT_MOUSEUP_DOM_TOUCH');
// 필수 정보
that.touchCount = that.touchCount || 0; // 터치 횟수
that.touchTimeDelay = that.touchTimeDelay || null; // delay check 관련 setTimeout
that.touchTimeCount = that.touchTimeCount || null; // 터치 횟수 카운트 시작 관련 setTimeout
that.touchCheck = that.touchCheck || {};
radius = (event.target !== undefined && event.target.offsetWidth !== undefined && event.target.offsetWidth !== 'undefined') ? Math.max(event.target.offsetWidth, event.target.offsetHeight) : 0; // IE문제: 7에서 offsetWidth null 오류
radius = Math.max(radius, 30); // 이벤트 작동 타겟 영역
if(touch) {
that.touchCheck[that.touchCount] = {
'start': {
'top': touch[0].screenY,
'left': touch[0].screenX
},
'end': {
'top': touch[0].screenY,
'left': touch[0].screenX
}
};
}else {
that.touchCheck[that.touchCount] = {
'start': {
'top': event.screenY,
'left': event.screenX
},
'end': {
'top': event.screenY,
'left': event.screenX
}
};
}
that.touchCheck['time'] = {};
that.touchCheck['time']['start'] = new Date().getTime();
// delay
global.clearTimeout(that.touchTimeCount);
that.touchTimeDelay = global.setTimeout(function() {
if(that['storage']['EVENT_DOM_TOUCH_DELAY'] && typeof that['storage']['EVENT_DOM_TOUCH_DELAY'] === 'function') {
that['storage']['EVENT_DOM_TOUCH_DELAY'].call(that, e);
}
}, checkout.delay);
DOM(document).on(global.api.env['event']['move'] + '.EVENT_MOUSEMOVE_DOM_TOUCH', function(e) {
var event = e || global.event;
var touch = event.touches || event.changedTouches;
if(touch) {
that.touchCheck[that.touchCount]['end']['top'] = touch[0].screenY;
that.touchCheck[that.touchCount]['end']['left'] = touch[0].screenX;
}else {
that.touchCheck[that.touchCount]['end']['top'] = event.screenY;
that.touchCheck[that.touchCount]['end']['left'] = event.screenX;
}
// delay 정지
if(Math.abs(that.touchCheck[0]['start']['top'] - that.touchCheck[that.touchCount]['end']['top']) > radius || Math.abs(that.touchCheck[0]['start']['left'] - that.touchCheck[that.touchCount]['end']['left']) > radius) {
global.clearTimeout(that.touchTimeDelay);
}
});
DOM(document).on(global.api.env['event']['up'] + '.EVENT_MOUSEUP_DOM_TOUCH', function(e) { // IE7문제: window 가 아닌 document 에 할당해야 한다.
var event = e || global.event;
var touch = event.changedTouches; // touchend
// 현재 이벤트의 기본 동작을 중단한다. (모바일에서 스크롤 하단이동 기본기능)
if(event.preventDefault) {
event.preventDefault();
}else {
event.returnValue = false;
}
// 이벤트 종료
DOM(document).off('.EVENT_MOUSEMOVE_DOM_TOUCH');
DOM(document).off('.EVENT_MOUSEUP_DOM_TOUCH');
//
that.touchCount += 1;
that.touchCheck['time']['end'] = new Date().getTime();
// click check: 지정된 시간까지 다음 클릭이 발생하지 않는다면, count 값을 확인하여 해당 콜백을 실행한다.
global.clearTimeout(that.touchTimeDelay);
if(typeof that.touchCheck === 'object' && that.touchCheck[that.touchCount-1]) {
that.touchTimeCount = global.setTimeout(function() {
var start = that.touchCheck[0]['start'];
var end = that.touchCheck[that.touchCount-1]['end'];
var time = Number(that.touchCheck['time']['end']) - Number(that.touchCheck['time']['start']);
// handler(callback) 실행
if(time <= checkout.interval/* 클릭된 상태가 지속될 수 있으므로 시간검사 */ && Math.abs(start['top'] - end['top']) <= radius && Math.abs(start['left'] - end['left']) <= radius) {
if(that.touchCount === 1 && that['storage']['EVENT_DOM_TOUCH_ONE'] && typeof that['storage']['EVENT_DOM_TOUCH_ONE'] === 'function') {
that['storage']['EVENT_DOM_TOUCH_ONE'].call(that, e);
}else if(that.touchCount === 2 && that['storage']['EVENT_DOM_TOUCH_TWO'] && typeof that['storage']['EVENT_DOM_TOUCH_TWO'] === 'function') {
that['storage']['EVENT_DOM_TOUCH_TWO'].call(that, e);
}
}
that.touchCount = 0;
that.touchCheck = {};
}, checkout.count); // 검사 시작시간
}
});
};
DOM.touch = {
on: function(selector, handler) {
if(selector && (typeof handler === 'object' || typeof handler === 'function')) {
DOM(selector).each(function(i, element) {
var key;
if(element && element.nodeType) {
if(typeof element['storage'] !== 'object') {
element['storage'] = {};
}
if(typeof handler === 'object') {
for(key in handler) {
if(handler.hasOwnProperty(key) && /^(one|two|delay)$/i.test(key) && typeof handler[key] === 'function') {
element['storage']['EVENT_DOM_TOUCH_' + key.toUpperCase()] = handler[key];
}
}
}else {
element['storage']['EVENT_DOM_TOUCH_ONE'] = handler;
}
if(!element['storage']['EVENT_DOM_TOUCH']) {
DOM(element).on(global.api.env['event']['down'] + '.EVENT_DOM_TOUCH', setTouchHandler);
}
}
});
}
},
off: function(selector, eventkey) { // eventkey: one, two, delay, all
if(selector) {
DOM(selector).each(function(i, element) {
var key = (typeof eventkey === 'string' && eventkey) || 'all';
if(element && element.nodeType && element['storage']) {
switch(key.toLowerCase()) {
case 'one':
case 'two':
case 'delay':
delete element['storage']['EVENT_DOM_TOUCH_' + key.toUpperCase()];
break;
case 'all':
DOM(element).off('.EVENT_DOM_TOUCH');
break;
}
}
});
}
}
};
// DOM extend
DOM.extend = DOM.fn.extend = function(parameter) {
var value = typeof parameter === 'object' ? parameter : {};
var key;
for(key in value) {
if(this.hasOwnProperty(key)) {
// 동일한 함수(또는 메소드)가 있으면 건너뛴다
continue;
}
// this : DOM.extend( ... ), DOM.fn.extend( ... ) 분리
// api.dom.test = function() { ... } <- 같은 기능 -> api.dom.extend({'test': function() { ... }})
// api.dom.fn.test = function() { ... } <- 같은 기능 -> api.dom.fn.extend({'test': function() { ... }})
this[key] = value[key];
}
};
// BOM localStorage, sessionStorage (IE8 이상)
var browserStorage = global.localStorage && global.sessionStorage && (function() {
return {
clear: function(type) {
// No return value.
switch(type) {
case 'local':
global.localStorage.clear();
break;
case 'session':
global.sessionStorage.clear();
break;
}
},
length: function(type) {
var count = 0;
switch(type) {
case 'local':
count = global.localStorage.length;
break;
case 'session':
count = global.sessionStorage.length;
break;
}
return count;
},
get: function(type, key) {
var item = '';
if(this.length(type) > 0) {
switch(type) {
case 'local':
item = global.localStorage.getItem(key); // return type string
break;
case 'session':
item = global.sessionStorage.getItem(key); // return type string
break;
}
item = (/^{.*}$|^\[.*\]$/.test(item)) ? JSON.parse(item) : item;
}
return item;
},
set: function(type, key, item) {
// No return value.
item = (item && typeof item === 'object' && Object.keys(item).length > 0) ? JSON.stringify(item) : (item || '');
switch(type) {
case 'local':
global.localStorage.setItem(key, item);
break;
case 'session':
global.sessionStorage.setItem(key, item);
break;
}
},
del: function(type, key) {
// No return value.
switch(type) {
case 'local':
global.localStorage.removeItem(key);
break;
case 'session':
global.sessionStorage.removeItem(key);
break;
}
}
};
})() || {};
// public return
global.api.dom = DOM;
global.api.storage = browserStorage;
}, this);
|
import logging
import os
def setup_logging():
logfile = 'logfile.txt'
if os.path.exists(logfile):
os.remove(logfile)
logging.basicConfig(filename=logfile,
level=logging.DEBUG,
format='%(message)s')
|
import getScrollRtlBehavior from "../../../core/utils/scroll_rtl_behavior";
import { titleize } from "../../../core/utils/inflector";
import { DIRECTION_VERTICAL, DIRECTION_HORIZONTAL, DIRECTION_BOTH } from "./common/consts";
import { ScrollDirection } from "./utils/scroll_direction";
function isScrollInverted(rtlEnabled) {
var {
decreasing,
positive
} = getScrollRtlBehavior();
return rtlEnabled && !!(decreasing ^ positive);
}
export function getScrollSign(rtlEnabled) {
return isScrollInverted(rtlEnabled) && getScrollRtlBehavior().positive ? -1 : 1;
}
function getElementLocationInternal(element, offset, direction, containerElement) {
var prop = direction === DIRECTION_VERTICAL ? "top" : "left";
var dimension = direction === DIRECTION_VERTICAL ? "Height" : "Width";
var relativeLocation = containerElement["scroll".concat(titleize(prop))] + element.getBoundingClientRect()[prop] - containerElement.getBoundingClientRect()[prop];
var containerLocation = containerElement["scroll".concat(titleize(prop))];
var scrollBarSize = containerElement["offset".concat(dimension)] - containerElement["client".concat(dimension)];
var containerSize = containerElement["offset".concat(dimension)];
var elementOffset = element["offset".concat(dimension)];
var offsetStart = offset[prop];
var offsetEnd = offset[direction === DIRECTION_VERTICAL ? "bottom" : "right"] || 0;
if (relativeLocation < containerLocation + offsetStart) {
if (elementOffset < containerSize - offsetStart - offsetEnd) {
return relativeLocation - offsetStart;
}
return relativeLocation + elementOffset - containerSize + offsetEnd + scrollBarSize;
}
if (relativeLocation + elementOffset >= containerLocation + containerSize - offsetEnd - scrollBarSize) {
if (elementOffset < containerSize - offsetStart - offsetEnd) {
return relativeLocation + elementOffset + scrollBarSize - containerSize + offsetEnd;
}
return relativeLocation - offsetStart;
}
return containerLocation;
}
export function normalizeOffsetLeft(scrollLeft, maxLeftOffset, rtlEnabled) {
if (isScrollInverted(rtlEnabled)) {
if (getScrollRtlBehavior().positive) {
return maxLeftOffset - scrollLeft;
}
return maxLeftOffset + scrollLeft;
}
return scrollLeft;
}
export function getLocation(element, offset, direction, containerElement) {
var location = getElementLocationInternal(element, offset, direction, containerElement);
return location;
}
export function updateAllowedDirection(allowedDirections, direction) {
var {
isBoth,
isHorizontal,
isVertical
} = new ScrollDirection(direction);
if (isBoth && allowedDirections.vertical && allowedDirections.horizontal) {
return DIRECTION_BOTH;
}
if (isHorizontal && allowedDirections.horizontal) {
return DIRECTION_HORIZONTAL;
}
if (isVertical && allowedDirections.vertical) {
return DIRECTION_VERTICAL;
}
return undefined;
} |
'use strict';
let Options = {};
let gConfig = null;
// Text in the butter bar, to prompt the user to reload after a config change.
let kReloadText = {
en: 'To apply configuration changes, reload cactbot overlays.',
de: 'Um die Änderungen zu aktivieren, aktualisiere bitte die Cacbot Overlays.',
fr: 'Afin d\'appliquer les modifications, il faut recharger l\'overlay cacbot.',
cn: '要应用配置更改,请重新加载cactbot悬浮窗。',
ko: '변경사항을 적용하려면, 오버레이를 새로고침 하십시오.',
};
// Text in the butter bar reload button.
let kReloadButtonText = {
en: 'Reload',
de: 'Aktualisieren',
fr: 'Recharger',
cn: '重新加载',
ko: '새로고침',
};
// Text on the directory choosing button.
let kDirectoryChooseButtonText = {
en: 'Choose Directory',
de: 'Wähle ein Verzeichnis',
fr: 'Choix du répertoire',
cn: '选择目录',
ko: '디렉터리 선택',
};
// What to show when a directory hasn't been chosen.
let kDirectoryDefaultText = {
en: '(Default)',
de: '(Standard)',
fr: '(Défaut)',
cn: '(默认)',
ko: '(기본)',
};
class CactbotConfigurator {
constructor(configFiles, configOptions, savedConfig) {
// Predefined, only for ordering purposes.
this.contents = {
// top level
'general': [],
// things most people care about
'raidboss': [],
'jobs': [],
};
this.configOptions = configOptions;
this.lang = configOptions.Language || 'en';
this.savedConfig = savedConfig || {};
this.developerOptions = this.getOption('general', 'ShowDeveloperOptions', false);
for (let filename in configFiles) {
try {
eval(configFiles[filename]);
} catch (exception) {
console.error('Error parsing JSON from ' + filename + ': ' + exception);
continue;
}
}
let templates = UserConfig.optionTemplates;
for (let group in templates) {
this.contents[group] = this.contents[group] || [];
this.contents[group].push(templates[group]);
}
this.buildButterBar();
let container = document.getElementById('container');
this.buildUI(container, this.contents);
}
async saveConfigData() {
// TODO: rate limit this?
await callOverlayHandler({
call: 'cactbotSaveData',
overlay: 'options',
data: this.savedConfig,
});
document.getElementById('butter-margin').classList.remove('hidden');
}
// Helper translate function. Takes in an object with locale keys
// and returns a single entry based on available translations.
translate(textObj) {
if (textObj === null || typeof textObj !== 'object' || !textObj['en'])
return textObj;
let t = textObj[this.lang];
if (t)
return t;
return textObj['en'];
}
// takes variable args, with the last value being the default value if
// any key is missing.
// e.g. (foo, bar, baz, 5) with {foo: { bar: { baz: 3 } } } will return
// the value 3. Requires at least two args.
getOption() {
let num = arguments.length;
if (num < 2) {
console.error('getOption requires at least two args');
return;
}
let defaultValue = arguments[num - 1];
let objOrValue = this.savedConfig;
for (let i = 0; i < num - 1; ++i) {
objOrValue = objOrValue[arguments[i]];
if (typeof objOrValue === 'undefined')
return defaultValue;
}
return objOrValue;
}
// takes variable args, with the last value being the 'value' to set it to
// e.g. (foo, bar, baz, 3) will set {foo: { bar: { baz: 3 } } }.
// requires at least two args.
setOption() {
let num = arguments.length;
if (num < 2) {
console.error('setOption requires at least two args');
return;
}
// Set keys and create default {} if it doesn't exist.
let obj = this.savedConfig;
for (let i = 0; i < num - 2; ++i) {
let arg = arguments[i];
obj[arg] = obj[arg] || {};
obj = obj[arg];
}
// Set the last key to have the final argument's value.
obj[arguments[num - 2]] = arguments[num - 1];
this.saveConfigData();
}
buildButterBar() {
let container = document.getElementById('butter-bar');
let textDiv = document.createElement('div');
textDiv.classList.add('reload-text');
textDiv.innerText = this.translate(kReloadText);
container.appendChild(textDiv);
let buttonInput = document.createElement('input');
buttonInput.classList.add('reload-button');
buttonInput.type = 'button';
buttonInput.onclick = () => {
callOverlayHandler({ call: 'cactbotReloadOverlays' });
};
buttonInput.value = this.translate(kReloadButtonText);
container.appendChild(buttonInput);
}
// Top level UI builder, builds everything.
buildUI(container, contents) {
for (let group in contents) {
let content = contents[group];
if (content.length == 0)
continue;
// For each overlay options template, build a section for it.
// Then iterate through all of its options and build ui for those options.
// Give each options template a chance to build special ui.
let groupDiv = this.buildOverlayGroup(container, group);
for (let i = 0; i < content.length; ++i) {
let options = content[i].options || [];
for (let j = 0; j < options.length; ++j) {
let opt = options[j];
if (!this.developerOptions && opt.debugOnly)
continue;
let buildFunc = {
checkbox: this.buildCheckbox,
select: this.buildSelect,
float: this.buildFloat,
integer: this.buildInteger,
directory: this.buildDirectory,
}[opt.type];
if (!buildFunc) {
console.error('unknown type: ' + JSON.stringify(opt));
continue;
}
buildFunc.bind(this)(groupDiv, opt, group);
}
let builder = content[i].buildExtraUI;
if (builder)
builder(this, groupDiv);
}
}
}
// Overlay builder for each overlay type (e.g. raidboss, jobs).
buildOverlayGroup(container, group) {
let collapser = document.createElement('div');
collapser.classList.add('overlay-container');
container.appendChild(collapser);
let a = document.createElement('a');
a.name = group;
collapser.appendChild(a);
let header = document.createElement('div');
header.classList.add('overlay-header');
header.innerText = group;
a.appendChild(header);
let groupDiv = document.createElement('div');
groupDiv.classList.add('overlay-options');
collapser.appendChild(groupDiv);
a.onclick = (e) => {
a.parentNode.classList.toggle('collapsed');
};
return groupDiv;
}
buildNameDiv(opt) {
let div = document.createElement('div');
div.innerHTML = this.translate(opt.name);
div.classList.add('option-name');
return div;
}
buildCheckbox(parent, opt, group) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('input');
div.appendChild(input);
input.type = 'checkbox';
input.checked = this.getOption(group, opt.id, opt.default);
input.onchange = () => this.setOption(group, opt.id, input.checked);
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
buildDirectory(parent, opt, group) {
let div = document.createElement('div');
div.classList.add('option-input-container');
div.classList.add('input-dir-container');
let input = document.createElement('input');
input.type = 'submit';
input.value = this.translate(kDirectoryChooseButtonText);
input.classList.add('input-dir-submit');
div.appendChild(input);
let label = document.createElement('div');
label.classList.add('input-dir-label');
div.appendChild(label);
let setLabel = (str) => {
if (str)
label.innerText = str;
else
label.innerText = this.translate(kDirectoryDefaultText);
};
setLabel(this.getOption(group, opt.id, opt.default));
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
input.onclick = async () => {
// Prevent repeated clicks on the folder chooser.
// callOverlayHandler is not synchronous.
// FIXME: do we need some clearer UI here (like pretending to be modal?)
input.disabled = true;
let prevValue = label.innerText;
label.innerText = '';
let result = await callOverlayHandler({
call: 'cactbotChooseDirectory',
});
input.disabled = false;
let dir = result.data ? result.data : '';
if (dir !== prevValue)
this.setOption(group, opt.id, dir);
setLabel(dir);
};
}
buildSelect(parent, opt, group) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('select');
div.appendChild(input);
let defaultValue = this.getOption(group, opt.id, opt.default);
input.onchange = () => this.setOption(group, opt.id, input.value);
let innerOptions = this.translate(opt.options);
for (let key in innerOptions) {
let elem = document.createElement('option');
elem.value = innerOptions[key];
elem.innerHTML = key;
if (innerOptions[key] == defaultValue)
elem.selected = true;
input.appendChild(elem);
}
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
// FIXME: this could use some data validation if a user inputs non-floats.
buildFloat(parent, opt, group) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('input');
div.appendChild(input);
input.type = 'text';
input.step = 'any';
input.value = this.getOption(group, opt.id, opt.default);
let setFunc = () => this.setOption(group, opt.id, input.value);
input.onchange = setFunc;
input.oninput = setFunc;
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
// FIXME: this could use some data validation if a user inputs non-integers.
buildInteger(parent, opt, group) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('input');
div.appendChild(input);
input.type = 'text';
input.step = 1;
input.value = this.getOption(group, opt.id, opt.default);
let setFunc = () => this.setOption(group, opt.id, input.value);
input.onchange = setFunc;
input.oninput = setFunc;
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
}
UserConfig.getUserConfigLocation('config', async function(e) {
let readConfigFiles = callOverlayHandler({
call: 'cactbotReadDataFiles',
source: location.href,
});
gConfig = new CactbotConfigurator(
(await readConfigFiles).detail.files,
Options,
UserConfig.savedConfig);
});
|
/**
* Copyright (c) Microsoft 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.
*/
// @ts-check
/** @typedef {{
* type: 'text' | 'li' | 'code' | 'properties' | 'h0' | 'h1' | 'h2' | 'h3' | 'h4' | 'note',
* text?: string,
* codeLang?: string,
* noteType?: string,
* lines?: string[],
* liType?: 'default' | 'bullet' | 'ordinal',
* children?: MarkdownNode[]
* }} MarkdownNode */
function flattenWrappedLines(content) {
const inLines = content.replace(/\r\n/g, '\n').split('\n');
let inCodeBlock = false;
const outLines = [];
let outLineTokens = [];
for (const line of inLines) {
const trimmedLine = line.trim();
let singleLineExpression = line.startsWith('#');
let flushLastParagraph = !trimmedLine
|| trimmedLine.startsWith('1.')
|| trimmedLine.startsWith('<')
|| trimmedLine.startsWith('>')
|| trimmedLine.startsWith('|')
|| trimmedLine.startsWith('-')
|| trimmedLine.startsWith('*')
|| line.match(/\[[^\]]+\]:.*/)
|| singleLineExpression;
if (trimmedLine.startsWith('```') || trimmedLine.startsWith('---') || trimmedLine.startsWith(':::')) {
inCodeBlock = !inCodeBlock;
flushLastParagraph = true;
}
if (flushLastParagraph && outLineTokens.length) {
outLines.push(outLineTokens.join(' '));
outLineTokens = [];
}
if (inCodeBlock || singleLineExpression)
outLines.push(line);
else if (trimmedLine)
outLineTokens.push(outLineTokens.length ? line.trim() : line);
}
if (outLineTokens.length)
outLines.push(outLineTokens.join(' '));
return outLines;
}
/**
* @param {string[]} lines
*/
function buildTree(lines) {
/** @type {MarkdownNode} */
const root = {
type: 'h0',
text: '<root>',
children: []
};
/** @type {MarkdownNode[]} */
const headerStack = [root];
/** @type {{ indent: string, node: MarkdownNode }[]} */
let sectionStack = [];
/**
* @param {string} indent
* @param {MarkdownNode} node
*/
const appendNode = (indent, node) => {
while (sectionStack.length && sectionStack[0].indent.length >= indent.length)
sectionStack.shift();
const parentNode = sectionStack.length ? sectionStack[0].node :headerStack[0];
if (!parentNode.children)
parentNode.children = [];
parentNode.children.push(node);
if (node.type === 'li')
sectionStack.unshift({ indent, node });
};
for (let i = 0; i < lines.length; ++i) {
let line = lines[i];
// Headers form hierarchy.
const header = line.match(/^(#+)/);
if (header) {
const h = header[1].length;
const node = /** @type {MarkdownNode} */({ type: 'h' + h, text: line.substring(h + 1), children: [] });
while (true) {
const lastH = +headerStack[0].type.substring(1);
if (h <= lastH)
headerStack.shift();
else
break;
}
headerStack[0].children.push(node);
headerStack.unshift(node);
continue;
}
// Remaining items respect indent-based nesting.
const [, indent, content] = line.match('^([ ]*)(.*)');
if (content.startsWith('```')) {
/** @type {MarkdownNode} */
const node = {
type: 'code',
lines: [],
codeLang: content.substring(3)
};
line = lines[++i];
while (!line.trim().startsWith('```')) {
if (line && !line.startsWith(indent)) {
const from = Math.max(0, i - 5)
const to = Math.min(lines.length, from + 10);
const snippet = lines.slice(from, to);
throw new Error(`Bad code block: ${snippet.join('\n')}`);
}
if (line)
line = line.substring(indent.length);
node.lines.push(line);
line = lines[++i];
}
appendNode(indent, node);
continue;
}
if (content.startsWith(':::')) {
/** @type {MarkdownNode} */
const node = {
type: 'note',
noteType: content.substring(3)
};
line = lines[++i];
const tokens = [];
while (!line.trim().startsWith(':::')) {
if (!line.startsWith(indent)) {
const from = Math.max(0, i - 5)
const to = Math.min(lines.length, from + 10);
const snippet = lines.slice(from, to);
throw new Error(`Bad comment block: ${snippet.join('\n')}`);
}
tokens.push(line.substring(indent.length));
line = lines[++i];
}
node.text = tokens.join(' ');
appendNode(indent, node);
continue;
}
if (content.startsWith('---')) {
/** @type {MarkdownNode} */
const node = {
type: 'properties',
lines: [],
};
line = lines[++i];
while (!line.trim().startsWith('---')) {
if (!line.startsWith(indent))
throw new Error('Bad header block ' + line);
node.lines.push(line.substring(indent.length));
line = lines[++i];
}
appendNode(indent, node);
continue;
}
const liType = content.match(/^(-|1.|\*) /);
const node = /** @type {MarkdownNode} */({ type: 'text', text: content });
if (liType) {
node.type = 'li';
node.text = content.substring(liType[0].length);
if (content.startsWith('1.'))
node.liType = 'ordinal';
else if (content.startsWith('*'))
node.liType = 'bullet';
else
node.liType = 'default';
}
appendNode(indent, node);
}
return root.children;
}
/**
* @param {string} content
*/
function parse(content) {
return buildTree(flattenWrappedLines(content));
}
/**
* @param {MarkdownNode[]} nodes
* @param {number=} maxColumns
*/
function render(nodes, maxColumns) {
const result = [];
let lastNode;
for (let node of nodes) {
innerRenderMdNode('', node, lastNode, result, maxColumns);
lastNode = node;
}
return result.join('\n');
}
/**
* @param {string} indent
* @param {MarkdownNode} node
* @param {MarkdownNode} lastNode
* @param {number=} maxColumns
* @param {string[]} result
*/
function innerRenderMdNode(indent, node, lastNode, result, maxColumns) {
const newLine = () => {
if (result[result.length - 1] !== '')
result.push('');
};
if (node.type.startsWith('h')) {
newLine();
const depth = +node.type.substring(1);
result.push(`${'#'.repeat(depth)} ${node.text}`);
let lastNode = node;
for (const child of node.children || []) {
innerRenderMdNode('', child, lastNode, result, maxColumns);
lastNode = child;
}
}
if (node.type === 'text') {
const bothTables = node.text.startsWith('|') && lastNode && lastNode.type === 'text' && lastNode.text.startsWith('|');
const bothGen = node.text.startsWith('<!--') && lastNode && lastNode.type === 'text' && lastNode.text.startsWith('<!--');
const bothComments = node.text.startsWith('>') && lastNode && lastNode.type === 'text' && lastNode.text.startsWith('>');
const bothLinks = node.text.match(/\[[^\]]+\]:/) && lastNode && lastNode.type === 'text' && lastNode.text.match(/\[[^\]]+\]:/);
if (!bothTables && !bothGen && !bothComments && !bothLinks && lastNode && lastNode.text)
newLine();
for (const line of node.text.split('\n'))
result.push(wrapText(line, maxColumns, indent));
return;
}
if (node.type === 'code') {
newLine();
result.push(`${indent}\`\`\`${node.codeLang}`);
for (const line of node.lines)
result.push(indent + line);
result.push(`${indent}\`\`\``);
newLine();
return;
}
if (node.type === 'note') {
newLine();
result.push(`${indent}:::${node.noteType}`);
result.push(`${wrapText(node.text, maxColumns, indent)}`);
result.push(`${indent}:::`);
newLine();
return;
}
if (node.type === 'properties') {
result.push(`${indent}---`);
for (const line of node.lines)
result.push(indent + line);
result.push(`${indent}---`);
newLine();
return;
}
if (node.type === 'li') {
let char;
switch (node.liType) {
case 'bullet': char = '*'; break;
case 'default': char = '-'; break;
case 'ordinal': char = '1.'; break;
}
result.push(`${wrapText(node.text, maxColumns, `${indent}${char} `)}`);
const newIndent = indent + ' '.repeat(char.length + 1);
for (const child of node.children || []) {
innerRenderMdNode(newIndent, child, lastNode, result, maxColumns);
lastNode = child;
}
}
}
/**
* @param {string} text
*/
function tokenizeNoBreakLinks(text) {
const links = [];
// Don't wrap simple links with spaces.
text = text.replace(/\[[^\]]+\]/g, match => {
links.push(match);
return `[${links.length - 1}]`;
});
return text.split(' ').map(c => c.replace(/\[(\d+)\]/g, (_, p1) => links[+p1]));
}
/**
* @param {string} text
* @param {number=} maxColumns
* @param {string=} prefix
*/
function wrapText(text, maxColumns = 0, prefix = '') {
if (!maxColumns)
return prefix + text;
if (text.trim().startsWith('|'))
return prefix + text;
const indent = ' '.repeat(prefix.length);
const lines = [];
maxColumns -= indent.length;
const words = tokenizeNoBreakLinks(text);
let line = '';
for (const word of words) {
if (line.length && line.length + word.length < maxColumns) {
line += ' ' + word;
} else {
if (line)
lines.push(line);
line = (lines.length ? indent : prefix) + word;
}
}
if (line)
lines.push(line);
return lines.join('\n');
}
/**
* @param {MarkdownNode} node
*/
function clone(node) {
const copy = { ...node };
copy.children = copy.children ? copy.children.map(c => clone(c)) : undefined;
return copy;
}
/**
* @param {MarkdownNode[]} nodes
* @param {function(MarkdownNode, number): void} visitor
*/
function visitAll(nodes, visitor) {
for (const node of nodes)
visit(node, visitor);
}
/**
* @param {MarkdownNode} node
* @param {function(MarkdownNode, number): void} visitor
*/
function visit(node, visitor, depth = 0) {
visitor(node, depth);
for (const n of node.children || [])
visit(n, visitor, depth + 1);
}
/**
* @param {MarkdownNode[]} nodes
* @param {boolean=} h3
* @returns {string}
*/
function generateToc(nodes, h3) {
const result = [];
visitAll(nodes, (node, depth) => {
if (node.type === 'h1' || node.type === 'h2' || (h3 && node.type === 'h3')) {
let link = node.text.toLowerCase();
link = link.replace(/[ ]+/g, '-');
link = link.replace(/[^\w-_]/g, '');
result.push(`${' '.repeat(depth * 2)}- [${node.text}](#${link})`);
}
});
return result.join('\n');
}
/**
* @param {MarkdownNode[]} nodes
* @param {string} language
* @return {MarkdownNode[]}
*/
function filterNodesForLanguage(nodes, language) {
const result = nodes.filter(node => {
if (!node.children)
return true;
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if (child.type !== 'li' || child.liType !== 'bullet' || !child.text.startsWith('langs:'))
continue;
const only = child.text.substring('langs:'.length).split(',').map(l => l.trim());
node.children.splice(i, 1);
return only.includes(language);
}
return true;
});
result.forEach(n => {
if (!n.children)
return;
n.children = filterNodesForLanguage(n.children, language);
});
return result;
}
module.exports = { parse, render, clone, visitAll, visit, generateToc, filterNodesForLanguage };
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
const fs = require('fs');
const path = require('path');
const map = require('lodash/map');
const reduce = require('lodash/reduce');
const zipObject = require('lodash/zipObject');
const ruleNames = map(fs.readdirSync(path.resolve(__dirname, 'rules')), (f) => f.replace(/\.js$/, ''));
const allRules = zipObject(
ruleNames,
map(ruleNames, (r) => require(`./rules/${r}`))
);
module.exports = {
rules: allRules,
configs: {
recommended: {
plugins: ['@bfc/eslint-plugin-bfcomposer'],
rules: reduce(
ruleNames,
(all, rule) => ({
...all,
[`@bfc/bfcomposer/${rule}`]: 'error',
}),
{}
),
},
},
};
|
import express from 'express'
import { Nuxt, Builder } from 'nuxt'
import api from './api'
const bodyParser = require('body-parser')
const app = express()
const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 3000
process.env.TZ = 'Europe/London'
app.set('port', port)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// Import API Routes
app.use('/api', api)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
// Init Nuxt.js
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
console.log('Enviroment variables: ' + process.env.BASE_URL + ' ' + process.env.AUTH_USER + ' ' + process.env.AUTH_PASS)
|
/* ========================================================================
* Bootstrap: iconset-glyphicon.js by @recktoner
* https://victor-valencia.github.com/bootstrap-iconpicker
*
* Iconset: Glyphicons
* ========================================================================
* Copyright 2013-2014 Victor Valencia Rico.
*
* 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.
* ======================================================================== */
!function(e){e.iconset_glyphicon={iconClass:"glyphicon",iconClassFix:"glyphicon-",icons:["adjust","align-center","align-justify","align-left","align-right","arrow-down","arrow-left","arrow-right","arrow-up","asterisk","backward","ban-circle","barcode","bell","bold","book","bookmark","briefcase","bullhorn","calendar","camera","certificate","check","chevron-down","chevron-left","chevron-right","chevron-up","circle-arrow-down","circle-arrow-left","circle-arrow-right","circle-arrow-up","cloud","cloud-download","cloud-upload","cog","collapse-down","collapse-up","comment","compressed","copyright-mark","credit-card","cutlery","dashboard","download","download-alt","earphone","edit","eject","envelope","euro","exclamation-sign","expand","export","eye-close","eye-open","facetime-video","fast-backward","fast-forward","file","film","filter","fire","flag","flash","floppy-disk","floppy-open","floppy-remove","floppy-save","floppy-saved","folder-close","folder-open","font","forward","fullscreen","gbp","gift","glass","globe","hand-down","hand-left","hand-right","hand-up","hd-video","hdd","header","headphones","heart","heart-empty","home","import","inbox","indent-left","indent-right","info-sign","italic","leaf","link","list","list-alt","lock","log-in","log-out","magnet","map-marker","minus","minus-sign","move","music","new-window","off","ok","ok-circle","ok-sign","open","paperclip","pause","pencil","phone","phone-alt","picture","plane","play","play-circle","plus","plus-sign","print","pushpin","qrcode","question-sign","random","record","refresh","registration-mark","remove","remove-circle","remove-sign","repeat","resize-full","resize-horizontal","resize-small","resize-vertical","retweet","road","save","saved","screenshot","sd-video","search","send","share","share-alt","shopping-cart","signal","sort","sort-by-alphabet","sort-by-alphabet-alt","sort-by-attributes","sort-by-attributes-alt","sort-by-order","sort-by-order-alt","sound-5-1","sound-6-1","sound-7-1","sound-dolby","sound-stereo","star","star-empty","stats","step-backward","step-forward","stop","subtitles","tag","tags","tasks","text-height","text-width","th","th-large","th-list","thumbs-down","thumbs-up","time","tint","tower","transfer","trash","tree-conifer","tree-deciduous","unchecked","upload","usd","user","volume-down","volume-off","volume-up","warning-sign","wrench","zoom-in","zoom-out"]}}(jQuery); |
$(function() {
mui('.mui-scroll-wrapper').scroll();
$('body').on('tap', '#submit1', function() {
if($('#thisForm').find('input.dasmust').val() != ''){
$.ajax({
type : 'post',
url : 'courseApplySave',
data : $('#thisForm').serialize(),
dataType : 'html',
success : function(data) {
if (data > 0) {
mui.alert('申请成功,后续会有工作人员联系您','逸品生活',function(){$("#thisForm")[0].reset();location.href='wxParentChildCourseDetail?courseId='+$("#courseId").val()})
} else {
mui.alert('定制失败,手机号码为必填项','逸品生活')
}
}
});
}else{
mui.alert('定制失败,手机号码为必填项','逸品生活')
}
});
}) |
(self.webpackChunkRemoteClient=self.webpackChunkRemoteClient||[]).push([[8206],{17253:(e,i,t)=>{"use strict";function a(e){}t.d(i,{Bg:()=>a}),t(77645)},80108:(e,i,t)=>{"use strict";t.d(i,{Y:()=>c});var a=t(14983),n=t(45851),r=t(67380),s=t(84066),l=(t(77645),t(38215),t(74184)),o=t(29444);const c=e=>{let i=class extends e{get title(){if(this._get("title")&&"defaults"!==this.originOf("title"))return this._get("title");if(this.url){const e=(0,o.Qc)(this.url);if((0,r.pC)(e)&&e.title)return e.title}return this._get("title")||""}set title(e){this._set("title",e)}set url(e){this._set("url",(0,o.Nm)(e,n.Z.getLogger(this.declaredClass)))}};return(0,a._)([(0,s.Cb)()],i.prototype,"title",null),(0,a._)([(0,s.Cb)({type:String})],i.prototype,"url",null),i=(0,a._)([(0,l.j)("esri.layers.mixins.ArcGISService")],i),i}},13567:(e,i,t)=>{"use strict";t.d(i,{a:()=>r});var a=t(30817),n=t(13834);const r={inches:(0,a.En)(1,"meters","inches"),feet:(0,a.En)(1,"meters","feet"),"us-feet":(0,a.En)(1,"meters","us-feet"),yards:(0,a.En)(1,"meters","yards"),miles:(0,a.En)(1,"meters","miles"),"nautical-miles":(0,a.En)(1,"meters","nautical-miles"),millimeters:(0,a.En)(1,"meters","millimeters"),centimeters:(0,a.En)(1,"meters","centimeters"),decimeters:(0,a.En)(1,"meters","decimeters"),meters:(0,a.En)(1,"meters","meters"),kilometers:(0,a.En)(1,"meters","kilometers"),"decimal-degrees":1/(0,a.ty)(1,"meters",n.sv.radius)}},97684:(e,i,t)=>{"use strict";function a(e){return e&&"esri.renderers.visualVariables.SizeVariable"===e.declaredClass}function n(e){return null!=e&&!isNaN(e)&&isFinite(e)}function r(e){return e.valueExpression?"expression":e.field&&"string"==typeof e.field?"field":"unknown"}function s(e,i){const t=i||r(e),a=e.valueUnit||"unknown";return"unknown"===t?"constant":e.stops?"stops":null!=e.minSize&&null!=e.maxSize&&null!=e.minDataValue&&null!=e.maxDataValue?"clamped-linear":"unknown"===a?null!=e.minSize&&null!=e.minDataValue?e.minSize&&e.minDataValue?"proportional":"additive":"identity":"real-world-size"}t.d(i,{PS:()=>r,QW:()=>s,iY:()=>a,qh:()=>n})},73225:(e,i,t)=>{"use strict";t.d(i,{PR:()=>w,Lq:()=>m,Km:()=>v,cM:()=>h,ap:()=>b,V3:()=>y,B3:()=>p});var a=t(98540),n=t(42885),r=t(17253),s=t(45851),l=t(67380),o=t(13567),c=t(97684);const u=s.Z.getLogger("esri.renderers.visualVariables.support.visualVariableUtils"),d=new n.Z,f=Math.PI,p=/^\s*(return\s+)?\$view\.scale\s*(;)?\s*$/i;function m(e,i,t){const n="visualVariables"in e&&e.visualVariables?e.visualVariables.filter((e=>"color"===e.type))[0]:e;if(!n)return;if("esri.renderers.visualVariables.ColorVariable"!==n.declaredClass)return void u.warn("The visualVariable should be an instance of esri.renderers.visualVariables.ColorVariable");const r="number"==typeof i,s=r?null:i,o=s&&s.attributes;let c=r?i:null;const d=n.field,{ipData:f,hasExpression:p}=n.cache;let m=n.cache.compiledFunc;if(!d&&!p){const e=n.stops;return e&&e[0]&&e[0].color}if("number"!=typeof c)if(p){if(!(0,l.pC)(t)||!(0,l.pC)(t.arcade))return void u.error("Use of arcade expressions requires an arcade context");const e={viewingMode:t.viewingMode,scale:t.scale,spatialReference:t.spatialReference},i=t.arcade.arcadeUtils,a=i.getViewInfo(e),r=i.createExecContext(s,a);if(!m){const e=i.createSyntaxTree(n.valueExpression);m=i.createFunction(e),n.cache.compiledFunc=m}c=i.executeFunction(m,r)}else o&&(c=o[d]);const v=n.normalizationField,h=o?parseFloat(o[v]):void 0;if(null!=c&&(!v||r||!isNaN(h)&&0!==h)){isNaN(h)||r||(c/=h);const e=g(c,f);if(e){const i=e[0],r=e[1],s=i===r?n.stops[i].color:a.Z.blendColors(n.stops[i].color,n.stops[r].color,e[2],(0,l.pC)(t)?t.color:void 0);return new a.Z(s)}}}function v(e,i,t){const a="visualVariables"in e&&e.visualVariables?e.visualVariables.filter((e=>"opacity"===e.type))[0]:e;if(!a)return;if("esri.renderers.visualVariables.OpacityVariable"!==a.declaredClass)return void u.warn("The visualVariable should be an instance of esri.renderers.visualVariables.OpacityVariable");const n="number"==typeof i,r=n?null:i,s=r&&r.attributes;let o=n?i:null;const c=a.field,{ipData:d,hasExpression:f}=a.cache;let p=a.cache.compiledFunc;if(!c&&!f){const e=a.stops;return e&&e[0]&&e[0].opacity}if("number"!=typeof o)if(f){if((0,l.Wi)(t)||(0,l.Wi)(t.arcade))return void u.error("Use of arcade expressions requires an arcade context");const e={viewingMode:t.viewingMode,scale:t.scale,spatialReference:t.spatialReference},i=t.arcade.arcadeUtils,n=i.getViewInfo(e),s=i.createExecContext(r,n);if(!p){const e=i.createSyntaxTree(a.valueExpression);p=i.createFunction(e),a.cache.compiledFunc=p}o=i.executeFunction(p,s)}else s&&(o=s[c]);const m=a.normalizationField,v=s?parseFloat(s[m]):void 0;if(null!=o&&(!m||n||!isNaN(v)&&0!==v)){isNaN(v)||n||(o/=v);const e=g(o,d);if(e){const i=e[0],t=e[1];if(i===t)return a.stops[i].opacity;{const n=a.stops[i].opacity;return n+(a.stops[t].opacity-n)*e[2]}}}}function h(e,i,t){const a="visualVariables"in e&&e.visualVariables?e.visualVariables.filter((e=>"rotation"===e.type))[0]:e;if(!a)return;if("esri.renderers.visualVariables.RotationVariable"!==a.declaredClass)return void u.warn("The visualVariable should be an instance of esri.renderers.visualVariables.RotationVariable");const n=a.axis||"heading",r="heading"===n&&"arithmetic"===a.rotationType?90:0,s="heading"===n&&"arithmetic"===a.rotationType?-1:1,o="number"==typeof i?null:i,c=o&&o.attributes,d=a.field,{hasExpression:f}=a.cache;let p=a.cache.compiledFunc,m=0;if(!d&&!f)return m;if(f){if((0,l.Wi)(t)||(0,l.Wi)(t.arcade))return void u.error("Use of arcade expressions requires an arcade context");const e={viewingMode:t.viewingMode,scale:t.scale,spatialReference:t.spatialReference},i=t.arcade.arcadeUtils,n=i.getViewInfo(e),r=i.createExecContext(o,n);if(!p){const e=i.createSyntaxTree(a.valueExpression);p=i.createFunction(e),a.cache.compiledFunc=p}m=i.executeFunction(p,r)}else c&&(m=c[d]||0);return m="number"!=typeof m||isNaN(m)?null:r+s*m,m}function b(e,i,t){const a="visualVariables"in e&&e.visualVariables?e.visualVariables.filter((e=>"size"===e.type))[0]:e;if(!a)return;if("esri.renderers.visualVariables.SizeVariable"!==a.declaredClass)return void u.warn("The visualVariable should be an instance of esri.renderers.visualVariables.SizeVariable");const n=function(e,i,t,a,n){switch(i.transformationType){case"additive":return function(e,i,t,a){return e+(V(i.minSize,t,a)||i.minDataValue)}(e,i,t,a);case"constant":return function(e,i,t){const a=e.stops;let n=a&&a.length&&a[0].size;return null==n&&(n=e.minSize),V(n,i,t)}(i,t,a);case"clamped-linear":return function(e,i,t,a){const n=(e-i.minDataValue)/(i.maxDataValue-i.minDataValue),r=V(i.minSize,t,a),s=V(i.maxSize,t,a),o=(0,l.pC)(a)?a.shape:void 0;if(e<=i.minDataValue)return r;if(e>=i.maxDataValue)return s;if("area"===i.scaleBy&&o){const e="circle"===o,i=e?f*(r/2)**2:r*r,t=i+n*((e?f*(s/2)**2:s*s)-i);return e?2*Math.sqrt(t/f):Math.sqrt(t)}return r+n*(s-r)}(e,i,t,a);case"proportional":return function(e,i,t,a){const n=(0,l.pC)(a)?a.shape:void 0,r=e/i.minDataValue,s=V(i.minSize,t,a),o=V(i.maxSize,t,a);let c=null;return c="circle"===n?2*Math.sqrt(r*(s/2)**2):"square"===n||"diamond"===n||"image"===n?Math.sqrt(r*s**2):r*s,x(c,s,o)}(e,i,t,a);case"stops":return function(e,i,t,a,n){const[r,s,l]=g(e,n);if(r===s)return V(i.stops[r].size,t,a);{const e=V(i.stops[r].size,t,a);return e+(V(i.stops[s].size,t,a)-e)*l}}(e,i,t,a,n);case"real-world-size":return function(e,i,t,a){const n=((0,l.pC)(a)&&a.resolution?a.resolution:1)*o.a[i.valueUnit],r=V(i.minSize,t,a),s=V(i.maxSize,t,a),{valueRepresentation:c}=i;let u=null;return u="area"===c?2*Math.sqrt(e/f)/n:"radius"===c||"distance"===c?2*e/n:e/n,x(u,r,s)}(e,i,t,a);case"identity":return e;case"unknown":return null}}(function(e,i,t){const a="number"==typeof i,n=a?null:i,r=n&&n.attributes;let s=a?i:null;const{isScaleDriven:o}=e.cache;let d=e.cache.compiledFunc;if(o){const i=(0,l.pC)(t)?t.scale:void 0,a=(0,l.pC)(t)?t.view:void 0;s=null==i||"3d"===a?function(e){let i=null,t=null;const a=e.stops;return a?(i=a[0].value,t=a[a.length-1].value):(i=e.minDataValue||0,t=e.maxDataValue||0),(i+t)/2}(e):i}else if(!a)switch(e.inputValueType){case"expression":{if((0,l.Wi)(t)||(0,l.Wi)(t.arcade))return void u.error("Use of arcade expressions requires an arcade context");const i={viewingMode:t.viewingMode,scale:t.scale,spatialReference:t.spatialReference},a=t.arcade.arcadeUtils,r=a.getViewInfo(i),o=a.createExecContext(n,r);if(!d){const i=a.createSyntaxTree(e.valueExpression);d=a.createFunction(i),e.cache.compiledFunc=d}s=a.executeFunction(d,o);break}case"field":r&&(s=r[e.field]);break;case"unknown":s=null}if(!(0,c.qh)(s))return null;if(a||!e.normalizationField)return s;const f=r?parseFloat(r[e.normalizationField]):null;return(0,c.qh)(f)&&0!==f?s/f:null}(a,i,t),a,i,t,a.cache.ipData);return null==n||isNaN(n)?0:n}function V(e,i,t){return null==e?null:(0,c.iY)(e)?b(e,i,t):(0,c.qh)(e)?e:null}function x(e,i,t){return(0,c.qh)(t)&&e>t?t:(0,c.qh)(i)&&e<i?i:e}function y(e,i,t){const{isScaleDriven:a}=e.cache;if(!(a&&"3d"===t||i))return null;const n={scale:i,view:t};let r=V(e.minSize,d,n),s=V(e.maxSize,d,n);if(null!=r||null!=s){if(r>s){const e=s;s=r,r=e}return{minSize:r,maxSize:s}}}function g(e,i){if(!i)return;let t=0,a=i.length-1;return i.some(((i,n)=>e<i?(a=n,!0):(t=n,!1))),[t,a,(e-i[t])/(i[a]-i[t])]}function w(e,i,t){const a=["proportional","proportional","proportional"];for(const n of e){const e=n.useSymbolValue?"symbol-value":b(n,i,t);switch(n.axis){case"width":a[0]=e;break;case"depth":a[1]=e;break;case"height":a[2]=e;break;case"width-and-depth":a[0]=e,a[1]=e;break;case"all":case void 0:case null:a[0]=e,a[1]=e,a[2]=e;break;default:(0,r.Bg)(n.axis)}}return a}}}]); |
import { Chemistry16 } from '..';
export default Chemistry16;
|
const Discord = require('discord.js');
const fetch = require('node-fetch');
require('dotenv').config();
const WolframAlphaAPI = require('wolfram-alpha-api');
const waApi = WolframAlphaAPI(process.env.WOLFRAMALPHA_API_KEY);
module.exports = {
name: 'wolfram',
category: 'Search',
description: '울프럼 알파 검색 결과의 짧은 버전을 보여줍니다. 베타 기능이므로 불안정할 수 있습니다.',
aliases: ['wolframalpha', 'wolf', '울프럼', '울프럼알파', '울프'],
args: true,
usage: ['[검색 내용]'],
cooldowns: 5,
async execute(message, args) {
const question = args.join(' ');
const embed = new Discord.MessageEmbed()
.setColor('ORANGE')
.setTitle('울프럼 알파 검색 중...')
.setTimestamp();
const msg = await message.channel.send(embed);
let answer = '';
try {
answer = await waApi.getShort(question);
}
catch (error) {
if (error == 'Error: Wolfram|Alpha did not understand your input') {
embed
.setTitle('울프럼 알파 검색 결과')
.setThumbnail('https://www.wolframalpha.com/static/share_3G6HuGr6.png')
.setDescription(`**검색 내용을 해석하지 못했습니다.**`)
.setFooter(`Wolfram Alpha API | ${message.author.tag} 에 의해 요청됨`, 'https://cpb-ap-se2.wpmucdn.com/global2.vic.edu.au/dist/e/29837/files/2016/10/Wolfram-Alpha-pqskmm.png');
return msg.edit(embed);
}
else if (error == 'Error: No short answer available') {
embed
.setTitle('울프럼 알파 검색 결과')
.setThumbnail('https://www.wolframalpha.com/static/share_3G6HuGr6.png')
.setDescription(`**검색 결과가 없습니다.**`)
.setFooter(`Wolfram Alpha API | ${message.author.tag} 에 의해 요청됨`, 'https://cpb-ap-se2.wpmucdn.com/global2.vic.edu.au/dist/e/29837/files/2016/10/Wolfram-Alpha-pqskmm.png');
return msg.edit(embed);
}
else return message.channel.send(`예상치 못한 오류가 발생하였습니다: \`\`\`${error}\`\`\``);
}
embed
.setTitle('울프럼 알파 검색 결과')
.setThumbnail('https://www.wolframalpha.com/static/share_3G6HuGr6.png')
.setDescription(`
**검색 내용**
\`\`\`${question}\`\`\`
**검색 결과**
\`\`\`${answer}\`\`\``)
.setFooter(`Wolfram Alpha API | ${message.author.tag} 에 의해 요청됨`, 'https://cpb-ap-se2.wpmucdn.com/global2.vic.edu.au/dist/e/29837/files/2016/10/Wolfram-Alpha-pqskmm.png');
msg.edit(embed);
},
}; |
const baseUrl = "http://localhost:3000/";
const scenarios = [
{
label: 'home',
url: baseUrl,
misMatchThreshold: 1e-10,
requireSameDimensions: false,
}
];
const projectId = "dark";
module.exports = {
id: projectId,
scenarios,
paths: {
bitmaps_reference: `backstop_data/snapshots/${projectId}`,
bitmaps_test: `backstop_data/bitmaps_test/${projectId}`,
ci_report: "backstop_data/ci_report",
engine_scripts: "backstop_data/engine_scripts",
html_report: `backstop_data/html_report/${projectId}`,
},
report: ["browser"],
engine: "puppeteer",
engineOptions: {
args: ["--no-sandbox"],
},
asyncCaptureLimit: 10,
asyncCompareLimit: 100,
viewports: [
{
height: 768,
label: "PC",
width: 1920,
},
],
};
|
window.API_URL = PROJECT.apiUrl || window.location.protocol + '//' + window.location.hostname;
if (window.location.port && !PROJECT.apiUrl) window.API_URL += ':' + window.location.port
window.DEBUG = true;
window.app = {
models: {},
collections: {},
views: {},
routers: {},
initialize: function(){
// init auth
var auth_provider_paths = _.object(_.map(PROJECT.authProviders, function(provider) { return [provider.name, provider.path]; }));
// Force a hard refresh after sign in/out
PubSub.subscribe('auth.oAuthSignIn.success', function(ev, msg) {
window.location.reload(true);
});
PubSub.subscribe('auth.signOut.success', function(ev, msg) {
window.location.reload(true);
});
// load the main router
var mainRouter = new app.routers.DefaultRouter();
// Enable pushState for compatible browsers
var enablePushState = true;
var pushState = !!(enablePushState && window.history && window.history.pushState);
// Start backbone history
Backbone.history = Backbone.history || new Backbone.History({});
Backbone.history.start({
pushState:pushState
});
// Backbone.history.start();
}
};
/**
* Configurable page title.
*
* @TODO: Move this to a view or something.
*/
window.app.pageTitle = function(pagename) {
if (!pagename) {
pagename = '';
}
var titleElems = document.getElementsByTagName('title');
if (!titleElems.length) {
return '';
}
var titleElem = titleElems[0];
var sitename = (
!!titleElem.getAttribute('data-title-sitename') ?
titleElem.getAttribute('data-title-sitename') :
titleElem.textContent
);
var template = (
!!titleElem.getAttribute('data-title-template') ?
titleElem.getAttribute('data-title-template') :
''
);
if (!pagename.length || !template.length) {
return titleElem.textContent;
}
return template.replace('{{sitename}}', sitename)
.replace('{{pagename}}', pagename);
};
// Init backbone app
$(function(){
app.initialize();
});
|
import { govPoolABI } from '../abi';
export const avalancheStakePools = [
{
id: 'bifi-avax',
name: 'BIFI',
logo: 'single-assets/BIFI.png',
token: 'BIFI',
tokenDecimals: 18,
tokenAddress: '0xd6070ae98b8069de6B494332d1A1a81B6179D960',
tokenOracle: 'tokens',
tokenOracleId: 'BIFI',
earnedToken: 'AVAX',
earnedTokenDecimals: 18,
earnedTokenAddress: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7',
earnContractAddress: '0x86d38c6b6313c5a3021d68d1f57cf5e69197592a',
earnContractAbi: govPoolABI,
earnedOracle: 'tokens',
earnedOracleId: 'WAVAX',
partnership: false,
status: 'active',
hideCountdown: true,
partners: [
{
logo: 'stake/beefy/beefyfinance.png',
background: 'stake/beefy/background.png',
text: "You probably already knew that Beefy is the most trusted Yield optimizer for the Binance Smart Chain. But did you know that Beefy has its own token? $BIFI has a maximum supply of 80000 tokens and there is no way to mint more. Everyone who holds our own $BIFI token can not only do cool stuff like create and vote on proposals, they also get a share of all harvests done, every hour, every day on all our Avalanche vaults. That's a lot of AVAX that goes straight to our $BIFI holders. All you have to do is stake your $BIFI in this vault, it’s that simple, come back and harvest your AVAX whenever you need it!",
website: 'https://app.robo-vault.com',
social: {
telegram: 'https://t.me/robovault',
twitter: 'https://twitter.com/robo-vault',
},
},
],
},
];
|
import React from 'react';
export default class Tile extends React.Component {
render() {
return (
<div className="fl ma2 bg-white bg-gray0-d overflow-hidden"
style={{ height: '126px', width: '126px' }}>
{this.props.children}
</div>
);
}
}
|
var Axes;
import {
vis
} from '../../../lib/pub/draw/Vis.js';
Axes = class Axes {
constructor(svgMgr) {
this.svgMgr = svgMgr;
this.d3 = this.svgMgr.d3;
this.svg = this.svgMgr.svg;
this.g = this.svgMgr.g;
this.ready();
}
ready() {
var sz;
sz = this.svgMgr.size;
this.margin = {
left: 40,
top: 40,
right: 40,
bottom: 40
};
this.width = Math.min(sz.w, sz.h) - this.margin.left - this.margin.right;
this.height = Math.min(sz.w, sz.h) - this.margin.top - this.margin.bottom;
this.xObj = {
x1: 0,
x2: 100,
xtick1: 10,
xtick2: 1,
stroke1: '#AAAAAA',
stroke2: '#666666'
};
this.yObj = {
y1: 0,
y2: 100,
ytick1: 10,
ytick2: 1,
stroke1: '#AAAAAA',
stroke2: '#666666'
};
this.xScale = this.createXScale(this.xObj, this.width);
this.yScale = this.createYScale(this.yObj, this.height);
this.axes(this.g, this.xObj, this.yObj);
return this.grid(this.g, this.xObj, this.yObj);
}
axes(g, xObj, yObj) {
this.attrG(g);
this.bAxis = this.createBAxis(g, xObj);
this.tAxis = this.createTAxis(g, xObj);
this.lAxis = this.createLAxis(g, yObj);
this.rAxis = this.createRAxis(g, yObj);
if (this.bAxis === false && this.tAxis === false && this.lAxis === false && this.rAxis === false) {
return {};
}
}
createXScale(xObj, width) {
return this.d3.scaleLinear().domain([xObj.x1, xObj.x2]).range([0, width]).clamp(true);
}
createYScale(yObj, height) {
return this.d3.scaleLinear().domain([yObj.y1, yObj.y2]).range([height, 0]).clamp(true);
}
attrG(g) {
return g.attr("style", "overflow:visible;").attr("transform", `translate(${this.margin.left},${this.margin.top})`).attr("style", "overflow:visible;");
}
createBAxis(g, xObj) {
var axisBottom, ntick1;
ntick1 = (xObj.x2 - xObj.x1) / xObj.xtick1; // ntick2 = xObj.xtick1/xObj.xtick2
axisBottom = this.d3.axisBottom().scale(this.xScale).ticks(ntick1).tickSize(12).tickPadding(1);
g.append("svg:g").attr("class", "axis-bottom axis").attr("stroke", '#FFFFFF').attr("transform", `translate(0,${this.height})`).call(axisBottom).selectAll('.tick line').attr("stroke", '#FFFFFF');
return axisBottom;
}
createTAxis(g, xObj) {
var axisTop, ntick1;
ntick1 = (xObj.x2 - xObj.x1) / xObj.xtick1; //ntick2 = xObj.xtick1/xObj.xtick2
axisTop = this.d3.axisTop().scale(this.xScale).ticks(ntick1).tickSize(12).tickPadding(1);
g.append("svg:g").attr("class", "axis-top axis").attr("stroke", '#FFFFFF').call(axisTop).selectAll('.tick line').attr("stroke", '#FFFFFF');
return axisTop;
}
createLAxis(g, yObj) {
var axisLeft, ntick1;
ntick1 = (yObj.y2 - yObj.y1) / yObj.ytick1; // ntick2 = ytick1/yObj.ytick2
axisLeft = this.d3.axisLeft().scale(this.yScale).ticks(ntick1).tickSize(12).tickPadding(1);
g.append("svg:g").attr("class", "axis-left axis").attr("stroke", '#FFFFFF').call(axisLeft).selectAll('.tick line').attr("stroke", '#FFFFFF');
return axisLeft;
}
createRAxis(g, yObj) {
var axisRight, ntick1;
ntick1 = (yObj.y2 - yObj.y1) / yObj.ytick1; //ntick2 = ytick1/yObj.ytick2
axisRight = this.d3.axisRight().scale(this.yScale).ticks(ntick1).tickSize(12).tickPadding(1);
g.append("svg:g").attr("class", "axis-right axis").attr("stroke", '#FFFFFF').attr("transform", `translate(${this.width},0)`).call(axisRight).selectAll('.tick line').attr("stroke", '#FFFFFF');
return axisRight;
}
grid(g, xObj, yObj) {
var elem;
elem = g.append("g:g");
this.xLines(elem, xObj.x1, xObj.x2, xObj.xtick2, yObj.y1, yObj.y2, xObj.stroke2, 1);
this.yLines(elem, yObj.y1, yObj.y2, yObj.ytick2, xObj.x1, xObj.x2, yObj.stroke2, 1);
this.xLines(elem, xObj.x1, xObj.x2, xObj.xtick1, yObj.y1, yObj.y2, xObj.stroke1, 1);
return this.yLines(elem, yObj.y1, yObj.y2, yObj.ytick1, xObj.x1, xObj.x2, yObj.stroke1, 1);
}
line(elem, x1, y1, x2, y2, stroke = "white", thick = 1, xScale = this.xScale, yScale = this.yScale) {
return elem.append("svg:line").attr("x1", xScale(x1)).attr("y1", yScale(y1)).attr("x2", xScale(x2)).attr("y2", yScale(y2)).attr("stroke", stroke).attr("stroke-width", thick); //attr("x1",x1).attr("y1",y1).attr("x2",x2).attr("y2",y2)
}
xLines(elem, xb, xe, dx, y1, y2, stroke, thick) {
var i, results, x, x1, x2;
i = 1;
x1 = vis.floor(xb, dx);
x2 = vis.ceil(xe, dx);
x = x1;
results = [];
while (x <= x2) {
this.line(elem, x, y1, x, y2, stroke, thick);
results.push(x = x1 + dx * i++);
}
return results;
}
yLines(elem, yb, ye, dy, x1, x2, stroke, thick) {
var i, results, y, y1, y2;
i = 1;
y1 = vis.floor(yb, dy);
y2 = vis.ceil(ye, dy);
y = y1;
results = [];
while (y <= y2) {
this.line(elem, x1, y, x2, y, stroke, thick);
results.push(y = y1 + dy * i++);
}
return results;
}
};
export default Axes;
//# sourceMappingURL=Axes.js.map
|
var casper = require('casper').create({
// verbose: true,
// logLevel: "debug",
pageSettings: {
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
}
});
var xpath = require('casper').selectXPath;
var symbolList = [
'CNX AUTO','CNX BANK','CNX ENERGY','CNX FINANCE','CNX FMCG','CNX IT','CNX MEDIA','CNX METAL','CNX PHARMA','CNX PSU BANK','CNX REALTY'
];
var fromDate = '10-03-2014';
var toDate = '14-03-2014';
var urlPre='http://www.nseindia.com/products/dynaContent/equities/indices/historicalindices.jsp?indexType=';
function getLink() {
var links = document.querySelectorAll('a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href');
});
}
casper.start();
var j=0;
casper.then(function() {
for (var i = 0 ; i < symbolList.length ; i++) {
casper.thenOpen(urlPre+symbolList[i]+'&fromDate='+fromDate+'&toDate='+toDate, function() {
casper.download('http://www.nseindia.com/'+this.evaluate(getLink),symbolList[j]+'.csv');
j++;
});
}
});
casper.then(function() {
casper.echo('Done');
});
casper.run(); |
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:.2f}, {:.2f})'.format(self.x, self.y)
def distanceTo(self, point):
return math.sqrt((self.x - point.x)**2 + (self.y - point.y)**2)
p = Point(2.34, 5.67)
print ("%.2f" % p.x)
print ("%.2f" % p.y)
point = Point(-18.5, 13.5)
print(point)
print(p.distanceTo(point))
|
#!/usr/bin/python
# -*- coding=utf-8 -*-
# Project: catchcore
# Class: TailorTen
# The tailorable tensor class to manage the tensor data
#
# tailorten.py
# Version: 1.0
# Goal: Class script
# Created by @wenchieh on <10/23/2018>
#
# Copyright:
# This software is free of charge under research purposes.
# For commercial purposes, please contact the author.
#
# Created by @wenchieh on <10/23/2018>
#
__author__ = 'wenchieh'
# third-party lib
import numpy as np
from sktensor import sptensor
class TailorTen(object):
# input para.
data = None # the input tensor in dictionary format.
ndim = None # the dimension of input tensor
shape = None # input tensor shape
nnz = 0
vals = 0
_dimsmin_ = None
_dimsmap_ = None
_invdimsmap_ = None
def __init__(self, subs, vals, shape=None, dtype=int, accumfun=sum.__call__):
if len(vals) <= 0:
ValueError("the input tensor is ZERO!")
subs = np.asarray(subs)
ns, ndims = subs.shape
self._dimsmin_ = np.min(subs, 0)
self._dimsmap_ = list()
for d in range(ndims):
undim = np.unique(subs[:, d])
self._dimsmap_.append(dict(zip(undim, range(len(undim)))))
nwsubs = list()
for k in range(ns):
term = list()
for d in range(ndims):
term.append(self._dimsmap_[d][subs[k, d]])
nwsubs.append(np.asarray(term))
tensor = sptensor(tuple(np.asarray(nwsubs).T), np.asarray(vals),
shape, dtype, accumfun=accumfun)
self.data = dict(zip(map(tuple, np.asarray(tensor.subs).T), tensor.vals))
self.shape = tensor.shape
self.ndim = tensor.ndim
self.nnz = len(tensor.vals)
self.vals = np.sum(self.data.values())
def update(self, subs, vals):
subs = np.asarray(subs)
ns, ndim = subs.shape
if ndim != self.ndim:
ValueError('input update data is invalid, the dimension is not match')
# nwsubs = list()
# for k in range(ns):
# term = list()
# for d in range(ndim):
# term.append(self._dimsmap_[d][subs[k, d]])
# nwsubs.append(tuple(term))
# self.data.update(dict(zip(nwsubs, vals)))
self.data.update(dict(zip(map(tuple, subs.T), vals)))
print("update: nnzs ({} --> {}), vals ({} --> {})".format(self.nnz, len(self.data),
self.vals, np.sum(self.data.values())))
self.nnz = len(self.data)
self.vals = np.sum(self.data.values())
def _getinvdimsmap_(self):
if self._invdimsmap_ is None:
self._invdimsmap_ = [dict(zip(self._dimsmap_[dm].values(), self._dimsmap_[dm].keys()))
for dm in range(self.ndim)]
def get_entities(self, subs=None, update=False):
if subs is None:
ValueError("input parameter is [None]!")
self._getinvdimsmap_()
res = list()
if subs is not None:
for term in subs:
orgterm = [self._invdimsmap_[dm][term[dm]] for dm in range(self.ndim)]
res.append(orgterm + [self.data[tuple(term)]])
if update:
del self.data[tuple(term)]
self.nnz = len(self.data)
self.vals = np.sum(self.data.values())
res = np.asarray(res)
# res[:, :-1] += self._dimsmin_
return res
def shave(self, sub=None):
self.get_entities(sub, True)
def tosptensor(self):
return sptensor(tuple(np.asarray(list(self.data.keys())).T), np.asarray(list(self.data.values())), self.shape)
def nnz_validsubs(self, candidates=None):
if candidates is None:
ValueError("input data is [None]!")
return set(self.data.keys()).intersection(map(tuple, candidates))
def dimension_select(self, selector):
assert (len(selector) == self.ndim)
res_dat = np.vstack([np.asarray(self.data.keys()).T, np.asarray(self.data.values()).T]).T
for dm in range(self.ndim):
res_dat = res_dat[np.isin(res_dat[:, dm], selector[dm])]
# return map(tuple, res_dat[:, :-1]), res_dat[:, -1]
return res_dat
def selectormap(self, selector, direct=1):
res = list()
self._getinvdimsmap_()
for h in range(len(selector)):
hidx = list()
for dm in range(self.ndim):
hidx.append([self._invdimsmap_[dm][s] for s in selector[h][dm]])
res.append(tuple(hidx))
return res
def info(self):
print("dimension: {}, shape:{}, #nnz:{}".format(self.ndim, self.shape, self.nnz))
print("initial density: {}".format(1.0 * self.nnz / np.prod(np.asarray(self.shape, float))))
def serialize(self, outs, header=None, valtype=int, delim=',', comment='%'):
self._getinvdimsmap_()
with open(outs, 'w') as ofp:
if header is not None:
ofp.writelines(comment + header + '\n')
for pos, v in self.data.items():
term = [self._invdimsmap_[dm][pos[dm]] for dm in range(self.ndim)]
ofp.writelines(delim.join(map(str, term + [valtype(v)])) + '\n')
ofp.flush()
ofp.close()
print('done!')
|
import { mat4, quat, vec3 } from 'gl-matrix';
import macro from 'vtk.js/Sources/macros';
import vtkBufferObject from 'vtk.js/Sources/Rendering/OpenGL/BufferObject';
import { ObjectType } from 'vtk.js/Sources/Rendering/OpenGL/BufferObject/Constants';
import { Representation } from 'vtk.js/Sources/Rendering/Core/Property/Constants';
const { vtkErrorMacro } = macro;
// ----------------------------------------------------------------------------
// Static functions
// ----------------------------------------------------------------------------
function computeInverseShiftAndScaleMatrix(coordShift, coordScale) {
const inverseScale = new Float64Array(3);
vec3.inverse(inverseScale, coordScale);
const matrix = new Float64Array(16);
mat4.fromRotationTranslationScale(
matrix,
quat.create(),
coordShift,
inverseScale
);
return matrix;
}
function shouldApplyCoordShiftAndScale(coordShift, coordScale) {
if (coordShift === null || coordScale === null) {
return false;
}
return !(
vec3.exactEquals(coordShift, [0, 0, 0]) &&
vec3.exactEquals(coordScale, [1, 1, 1])
);
}
// ----------------------------------------------------------------------------
// vtkOpenGLCellArrayBufferObject methods
// ----------------------------------------------------------------------------
function vtkOpenGLCellArrayBufferObject(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkOpenGLCellArrayBufferObject');
publicAPI.setType(ObjectType.ARRAY_BUFFER);
publicAPI.createVBO = (
cellArray,
inRep,
outRep,
options,
selectionMaps = null
) => {
if (!cellArray.getData() || !cellArray.getData().length) {
model.elementCount = 0;
return 0;
}
// Figure out how big each block will be, currently 6 or 7 floats.
model.blockSize = 3;
model.vertexOffset = 0;
model.normalOffset = 0;
model.tCoordOffset = 0;
model.tCoordComponents = 0;
model.colorComponents = 0;
model.colorOffset = 0;
model.customData = [];
const pointData = options.points.getData();
let normalData = null;
let tcoordData = null;
let colorData = null;
const colorComponents = options.colors
? options.colors.getNumberOfComponents()
: 0;
const textureComponents = options.tcoords
? options.tcoords.getNumberOfComponents()
: 0;
// the values of 4 below are because floats are 4 bytes
if (options.normals) {
model.normalOffset = 4 * model.blockSize;
model.blockSize += 3;
normalData = options.normals.getData();
}
if (options.customAttributes) {
options.customAttributes.forEach((a) => {
if (a) {
model.customData.push({
data: a.getData(),
offset: 4 * model.blockSize,
components: a.getNumberOfComponents(),
name: a.getName(),
});
model.blockSize += a.getNumberOfComponents();
}
});
}
if (options.tcoords) {
model.tCoordOffset = 4 * model.blockSize;
model.tCoordComponents = textureComponents;
model.blockSize += textureComponents;
tcoordData = options.tcoords.getData();
}
if (options.colors) {
model.colorComponents = options.colors.getNumberOfComponents();
model.colorOffset = 0;
colorData = options.colors.getData();
if (!model.colorBO) {
model.colorBO = vtkBufferObject.newInstance();
}
model.colorBO.setOpenGLRenderWindow(model._openGLRenderWindow);
} else {
model.colorBO = null;
}
model.stride = 4 * model.blockSize;
let pointIdx = 0;
let normalIdx = 0;
let tcoordIdx = 0;
let colorIdx = 0;
let custIdx = 0;
let cellCount = 0;
let addAPoint;
const cellBuilders = {
// easy, every input point becomes an output point
anythingToPoints(numPoints, cellPts, offset) {
for (let i = 0; i < numPoints; ++i) {
addAPoint(cellPts[offset + i]);
}
},
linesToWireframe(numPoints, cellPts, offset) {
// for lines we add a bunch of segments
for (let i = 0; i < numPoints - 1; ++i) {
addAPoint(cellPts[offset + i]);
addAPoint(cellPts[offset + i + 1]);
}
},
polysToWireframe(numPoints, cellPts, offset) {
// for polys we add a bunch of segments and close it
if (numPoints > 2) {
for (let i = 0; i < numPoints; ++i) {
addAPoint(cellPts[offset + i]);
addAPoint(cellPts[offset + ((i + 1) % numPoints)]);
}
}
},
stripsToWireframe(numPoints, cellPts, offset) {
if (numPoints > 2) {
// for strips we add a bunch of segments and close it
for (let i = 0; i < numPoints - 1; ++i) {
addAPoint(cellPts[offset + i]);
addAPoint(cellPts[offset + i + 1]);
}
for (let i = 0; i < numPoints - 2; i++) {
addAPoint(cellPts[offset + i]);
addAPoint(cellPts[offset + i + 2]);
}
}
},
polysToSurface(npts, cellPts, offset) {
for (let i = 0; i < npts - 2; i++) {
addAPoint(cellPts[offset + 0]);
addAPoint(cellPts[offset + i + 1]);
addAPoint(cellPts[offset + i + 2]);
}
},
stripsToSurface(npts, cellPts, offset) {
for (let i = 0; i < npts - 2; i++) {
addAPoint(cellPts[offset + i]);
addAPoint(cellPts[offset + i + 1 + (i % 2)]);
addAPoint(cellPts[offset + i + 1 + ((i + 1) % 2)]);
}
},
};
const cellCounters = {
// easy, every input point becomes an output point
anythingToPoints(numPoints, cellPts) {
return numPoints;
},
linesToWireframe(numPoints, cellPts) {
if (numPoints > 1) {
return (numPoints - 1) * 2;
}
return 0;
},
polysToWireframe(numPoints, cellPts) {
if (numPoints > 2) {
return numPoints * 2;
}
return 0;
},
stripsToWireframe(numPoints, cellPts) {
if (numPoints > 2) {
return numPoints * 4 - 6;
}
return 0;
},
polysToSurface(npts, cellPts) {
if (npts > 2) {
return (npts - 2) * 3;
}
return 0;
},
stripsToSurface(npts, cellPts, offset) {
if (npts > 2) {
return (npts - 2) * 3;
}
return 0;
},
};
let func = null;
let countFunc = null;
if (outRep === Representation.POINTS || inRep === 'verts') {
func = cellBuilders.anythingToPoints;
countFunc = cellCounters.anythingToPoints;
} else if (outRep === Representation.WIREFRAME || inRep === 'lines') {
func = cellBuilders[`${inRep}ToWireframe`];
countFunc = cellCounters[`${inRep}ToWireframe`];
} else {
func = cellBuilders[`${inRep}ToSurface`];
countFunc = cellCounters[`${inRep}ToSurface`];
}
const array = cellArray.getData();
const size = array.length;
let caboCount = 0;
for (let index = 0; index < size; ) {
caboCount += countFunc(array[index], array);
index += array[index] + 1;
}
let packedUCVBO = null;
const packedVBO = new Float32Array(caboCount * model.blockSize);
if (colorData) {
packedUCVBO = new Uint8Array(caboCount * 4);
}
let vboidx = 0;
let ucidx = 0;
// Find out if shift scale should be used
// Compute squares of diagonal size and distance from the origin
let diagSq = 0.0;
let distSq = 0.0;
for (let i = 0; i < 3; ++i) {
const range = options.points.getRange(i);
const delta = range[1] - range[0];
diagSq += delta * delta;
const distShift = 0.5 * (range[1] + range[0]);
distSq += distShift * distShift;
}
const useShiftAndScale =
diagSq > 0 &&
(Math.abs(distSq) / diagSq > 1.0e6 || // If data is far from the origin relative to its size
Math.abs(Math.log10(diagSq)) > 3.0 || // If the size is huge when not far from the origin
(diagSq === 0 && distSq > 1.0e6)); // If data is a point, but far from the origin
if (useShiftAndScale) {
// Compute shift and scale vectors
const coordShift = new Float64Array(3);
const coordScale = new Float64Array(3);
for (let i = 0; i < 3; ++i) {
const range = options.points.getRange(i);
const delta = range[1] - range[0];
coordShift[i] = 0.5 * (range[1] + range[0]);
coordScale[i] = delta > 0 ? 1.0 / delta : 1.0;
}
publicAPI.setCoordShiftAndScale(coordShift, coordScale);
} else if (model.coordShiftAndScaleEnabled === true) {
// Make sure to reset
publicAPI.setCoordShiftAndScale(null, null);
}
// Initialize the structures used to keep track of point ids and cell ids for selectors
if (selectionMaps) {
if (!selectionMaps.points && !selectionMaps.cells) {
selectionMaps.points = new Int32Array(caboCount);
selectionMaps.cells = new Int32Array(caboCount);
} else {
const newPoints = new Int32Array(
caboCount + selectionMaps.points.length
);
newPoints.set(selectionMaps.points);
selectionMaps.points = newPoints;
const newCells = new Int32Array(
caboCount + selectionMaps.points.length
);
newCells.set(selectionMaps.cells);
selectionMaps.cells = newCells;
}
}
let pointCount = options.vertexOffset;
addAPoint = function addAPointFunc(i) {
// Keep track of original point and cell ids, for selection
if (selectionMaps) {
selectionMaps.points[pointCount] = i;
selectionMaps.cells[pointCount] = cellCount;
}
++pointCount;
// Vertices
pointIdx = i * 3;
if (!model.coordShiftAndScaleEnabled) {
packedVBO[vboidx++] = pointData[pointIdx++];
packedVBO[vboidx++] = pointData[pointIdx++];
packedVBO[vboidx++] = pointData[pointIdx++];
} else {
// Apply shift and scale
packedVBO[vboidx++] =
(pointData[pointIdx++] - model.coordShift[0]) * model.coordScale[0];
packedVBO[vboidx++] =
(pointData[pointIdx++] - model.coordShift[1]) * model.coordScale[1];
packedVBO[vboidx++] =
(pointData[pointIdx++] - model.coordShift[2]) * model.coordScale[2];
}
if (normalData !== null) {
if (options.haveCellNormals) {
normalIdx = (cellCount + options.cellOffset) * 3;
} else {
normalIdx = i * 3;
}
packedVBO[vboidx++] = normalData[normalIdx++];
packedVBO[vboidx++] = normalData[normalIdx++];
packedVBO[vboidx++] = normalData[normalIdx++];
}
model.customData.forEach((attr) => {
custIdx = i * attr.components;
for (let j = 0; j < attr.components; ++j) {
packedVBO[vboidx++] = attr.data[custIdx++];
}
});
if (tcoordData !== null) {
tcoordIdx = i * textureComponents;
for (let j = 0; j < textureComponents; ++j) {
packedVBO[vboidx++] = tcoordData[tcoordIdx++];
}
}
if (colorData !== null) {
if (options.haveCellScalars) {
colorIdx = (cellCount + options.cellOffset) * colorComponents;
} else {
colorIdx = i * colorComponents;
}
packedUCVBO[ucidx++] = colorData[colorIdx++];
packedUCVBO[ucidx++] = colorData[colorIdx++];
packedUCVBO[ucidx++] = colorData[colorIdx++];
packedUCVBO[ucidx++] =
colorComponents === 4 ? colorData[colorIdx++] : 255;
}
};
for (let index = 0; index < size; ) {
func(array[index], array, index + 1);
index += array[index] + 1;
cellCount++;
}
model.elementCount = caboCount;
publicAPI.upload(packedVBO, ObjectType.ARRAY_BUFFER);
if (model.colorBO) {
model.colorBOStride = 4;
model.colorBO.upload(packedUCVBO, ObjectType.ARRAY_BUFFER);
}
return cellCount;
};
publicAPI.setCoordShiftAndScale = (coordShift, coordScale) => {
if (
coordShift !== null &&
(coordShift.constructor !== Float64Array || coordShift.length !== 3)
) {
vtkErrorMacro('Wrong type for coordShift, expected vec3 or null');
return;
}
if (
coordScale !== null &&
(coordScale.constructor !== Float64Array || coordScale.length !== 3)
) {
vtkErrorMacro('Wrong type for coordScale, expected vec3 or null');
return;
}
if (
model.coordShift === null ||
coordShift === null ||
!vec3.equals(coordShift, model.coordShift)
) {
model.coordShift = coordShift;
}
if (
model.coordScale === null ||
coordScale === null ||
!vec3.equals(coordScale, model.coordScale)
) {
model.coordScale = coordScale;
}
model.coordShiftAndScaleEnabled = shouldApplyCoordShiftAndScale(
model.coordShift,
model.coordScale
);
if (model.coordShiftAndScaleEnabled) {
model.inverseShiftAndScaleMatrix = computeInverseShiftAndScaleMatrix(
model.coordShift,
model.coordScale
);
} else {
model.inverseShiftAndScaleMatrix = null;
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
elementCount: 0,
stride: 0,
colorBOStride: 0,
vertexOffset: 0,
normalOffset: 0,
tCoordOffset: 0,
tCoordComponents: 0,
colorOffset: 0,
colorComponents: 0,
tcoordBO: null,
customData: [],
coordShift: null,
coordScale: null,
coordShiftAndScaleEnabled: false,
inverseShiftAndScaleMatrix: null,
};
// ----------------------------------------------------------------------------
export function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
// Inheritance
vtkBufferObject.extend(publicAPI, model, initialValues);
macro.setGet(publicAPI, model, [
'colorBO',
'elementCount',
'stride',
'colorBOStride',
'vertexOffset',
'normalOffset',
'tCoordOffset',
'tCoordComponents',
'colorOffset',
'colorComponents',
'customData',
]);
macro.get(publicAPI, model, [
'coordShift',
'coordScale',
'coordShiftAndScaleEnabled',
'inverseShiftAndScaleMatrix',
]);
// Object specific methods
vtkOpenGLCellArrayBufferObject(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = macro.newInstance(extend);
// ----------------------------------------------------------------------------
export default { newInstance, extend };
|
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./content.css";
/**
* CONCEPTS :-
* (1) Functional Component
* (2) Using hooks for the Life-cycle management
* (3) Using state for setting the value of the props
* (4) Using react Children API to clone the react element and append the Props dynamically
* (5) @todo Manual rendering of the component forceUpdate() ?
* (6) String refs are not usable in the function component
* (7) ReactDOM.findDomNode() API for accessing the DOM element.
* (8) Inline Style {} that you want to assign
* @param {*} props
*/
//create your forceUpdate hook
// function useForceUpdate() {
// const [value, setValue] = useState(0); // integer state
// return () => setValue((value) => ++value); // update the state to force render
// }
const Content = (props) => {
/**
* Example of using the state in the functional component.
* Here we are trying to use the Hooks
*/
const [className, setClassName] = useState("");
// call your hook here
// const forceUpdate = useForceUpdate();
/**
* Will be called on component DidMount / DiDUpdate as well
*/
useEffect(() => {
console.log("UseEffect called for Content...");
setClassName("content");
/**
* Using reactDom API to make changes in DOM
*/
var myDiv = document.getElementById("myDiv");
ReactDOM.findDOMNode(myDiv).style.color = "green";
return () => {
// cleanup
};
}, [""]);
/**
* Runtime assign the property to the element which is className
* using "className" property in the state
*/
return (
<React.Fragment>
{React.Children.map(props.children, function (child) {
return React.cloneElement(child, { className: className });
})}
{/* <input type="text" ref="myInput"></input> */}
<div
id="myDiv"
style={{ padding: 10, backgroundColor: "lightblue", marginBottom: 10 }}>
this will be updated on the component did mount / update using
findDOMNode() API.
</div>
</React.Fragment>
);
};
export default Content;
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Problem 1.6
compress a string by having subsequent identical characters transformed like so
hhhhh -> h5. If the string is no shorter, keep it unchanged
>>> compress(qqqwwwwweerty)
q3w5e2t1y1
Trivia: oddly enough, there are English words with three consecutive
identical letters but none for which this compression would yield a shorted
result (closest to succeed is 'aaaaba', some sort of bee)
(https://en.wikipedia.org/wiki/List_of_words_in_English_with_tripled_letters)_
>>> compress(aaaaba)
aaaaba
"""
import re
def compress(string):
"""
compresses a string as described in the above
"""
if string == '':
return ''
compressed_string = ''
previous_letter, count = string[0], 0
for letter in string:
if letter == previous_letter:
count += 1
else:
compressed_string += previous_letter + str(count)
previous_letter = letter
count = 1
compressed_string += letter + str(count)
if len(compressed_string) >= len(string):
return string
else:
return compressed_string
def uncompress(string):
"""
from a 'compressed' string, returns its original form
"""
# We capture with a regex all the blocks (letter number of duplicates)
compressed_string_regex = re.compile("([a-zA-Z])(\d+)+")
matches = compressed_string_regex.finditer(string)
uncompressed_string = ''
for match in matches:
letter, repetitions = match.groups()[0], int(match.groups()[1])
uncompressed_string += letter * repetitions
# if the regex didn't match, the string wasn't compressed so we return it
if not uncompressed_string:
return string
return uncompressed_string
|
const pathModule = require('path');
/* global describe, it */
const expect = require('../unexpected-with-plugins');
const AssetGraph = require('../../lib/AssetGraph');
describe('relations/HtmlShortcutIcon', function() {
it('should handle a test case with an existing <link rel="shortcut icon" href="..."> elements in different variants', async function() {
const assetGraph = new AssetGraph({
root: pathModule.resolve(
__dirname,
'../../testdata/relations/HtmlShortcutIcon/'
)
});
await assetGraph.loadAssets('index.html').populate();
expect(assetGraph, 'to contain assets', 2);
expect(assetGraph, 'to contain relations', 'HtmlShortcutIcon', 7);
const htmlAsset = assetGraph.findAssets({ type: 'Html' })[0];
const pngAsset = assetGraph.findAssets({ type: 'Png' })[0];
const firstExistingHtmlShortcutIconRelation = assetGraph.findRelations({
type: 'HtmlShortcutIcon'
})[0];
htmlAsset.addRelation(
{
type: 'HtmlShortcutIcon',
to: pngAsset
},
'after',
firstExistingHtmlShortcutIconRelation
);
htmlAsset.addRelation(
{
type: 'HtmlShortcutIcon',
to: pngAsset
},
'before',
firstExistingHtmlShortcutIconRelation
);
expect(assetGraph, 'to contain relations', 'HtmlShortcutIcon', 9);
const matches = assetGraph
.findAssets({ type: 'Html' })[0]
.text.match(/<link rel="shortcut icon" href="foo.png">/g);
expect(matches, 'not to be null').and('to have length', 3);
});
});
|
import alertIfConfigIncomplete from '../../alert-if-config-incomplete';
jest.mock('../../config', () => ({
get: (key) => {
switch (key) {
case 'codeshipApiKey':
return 'secret squirrel';
case 'githubUsername':
return 'cbovis';
default:
return undefined;
}
},
}));
describe('alert-if-config-incomplete', () => {
afterAll(() => {
global.atom = undefined;
});
beforeAll(() => {
global.atom = {
notifications: {
addWarning: jest.fn(),
},
};
});
it('displays a warning when Codeship API Key empty', () => {
alertIfConfigIncomplete();
expect(atom.notifications.addWarning).toHaveBeenCalledTimes(0);
});
});
|
;(function(){
// ga
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-113904149-2', 'auto');
ga('require', 'displayfeatures');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
})(); |
# -*- coding: utf-8 -*-
"""
wechatpy._compat
~~~~~~~~~~~~~~~~~
This module makes it easy for wechatpy to run on both Python 2 and 3.
:copyright: (c) 2014 by messense.
:license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import sys
import six
import warnings
warnings.warn("Module `wechatpy._compat` is deprecated, will be removed in 2.0"
"use `wechatpy.utils` instead",
DeprecationWarning, stacklevel=2)
from wechatpy.utils import get_querystring
from wechatpy.utils import json
|
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {baseURL,token} from "@/api/globaldata.js"
const state = {
token: getToken(),
name: '',
avatar: '',
introduction: '',
roles: []
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_INTRODUCTION: (state, introduction) => {
state.introduction = introduction
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
}
}
const actions = {
// user login
login({ commit }, userInfo) {
const { username, password } = userInfo
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password,client_id:'web',client_secret:'secret',grant_type:'password',scope:'all' }).then(response => {
const { data } = response
commit('SET_TOKEN', data.access_token)
// setToken(data.access_token)
setToken(data.access_token);
console.log("baseURL"+baseURL+"token"+"+++++++++++++"+data.access_token)
console.log("测试是否拿到token++++++++++++"+getToken())
localStorage.setItem('accessToken', data.access_token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// get userA info
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const { data } = response
if (!data) {
reject('Verification failed, please Login again.')
}
const { roles, name, avatar, introduction } = data
// roles must be a non-empty array
if (!roles || roles.length <= 0) {
reject('getInfo: roles must be a non-null array!')
}
commit('SET_ROLES', roles)
// commit('SET_ROLES', ['admin'])
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
commit('SET_INTRODUCTION', introduction)
resolve(data)
}).catch(error => {
reject(error)
})
})
},
getInfo1({ commit, state }) {
return new Promise((resolve, reject) => {
const data = {};
data.roles = ['admin']
data.name = "123"
data.avatar = "123"
data.introduction = "123"
const { roles, name, avatar, introduction } = data
// roles must be a non-empty array
if (!roles || roles.length <= 0) {
reject('getInfo: roles must be a non-null array!')
}
commit('SET_ROLES', roles)
// commit('SET_ROLES', ['admin'])
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
commit('SET_INTRODUCTION', introduction)
resolve(data)
})
},
// user logout
logout({ commit, state, dispatch }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resetRouter()
// reset visited views and cached views
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
dispatch('tagsView/delAllViews', null, { root: true })
resolve()
}).catch(error => {
reject(error)
})
})
},
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resolve()
})
},
// dynamically modify permissions
async changeRoles({ commit, dispatch }, role) {
const token = role + '-token'
commit('SET_TOKEN', token)
setToken(token)
// const { roles } = await dispatch('getInfo')
resetRouter()
// generate accessible routes map based on roles
// const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
// dynamically add accessible routes
// router.addRoutes(accessRoutes)
// reset visited views and cached views
dispatch('tagsView/delAllViews', null, { root: true })
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
|
# encoding: UTF-8
# AUTHOR:李来佳
# WeChat/QQ: 28888502
from datetime import datetime
import talib as ta
import numpy
import copy,csv
from pykalman import KalmanFilter
from vnpy.trader.app.ctaStrategy.ctaBase import *
from vnpy.trader.vtConstant import *
DEBUGCTALOG = True
PERIOD_SECOND = 'second' # 秒级别周期
PERIOD_MINUTE = 'minute' # 分钟级别周期
PERIOD_HOUR = 'hour' # 小时级别周期
PERIOD_DAY = 'day' # 日级别周期
class CtaLineBar(object):
"""CTA K线"""
""" 使用方法:
1、在策略构造函数__init()中初始化
self.lineM = None # 1分钟K线
lineMSetting = {}
lineMSetting['name'] = u'M1'
lineMSetting['barTimeInterval'] = 60 # 1分钟对应60秒
lineMSetting['inputEma1Len'] = 7 # EMA线1的周期
lineMSetting['inputEma2Len'] = 21 # EMA线2的周期
lineMSetting['inputBollLen'] = 20 # 布林特线周期
lineMSetting['inputBollStdRate'] = 2 # 布林特线标准差
lineMSetting['minDiff'] = self.minDiff # 最小条
lineMSetting['shortSymbol'] = self.shortSymbol #商品短号
self.lineM = CtaLineBar(self, self.onBar, lineMSetting)
2、在onTick()中,需要导入tick数据
self.lineM.onTick(tick)
self.lineM5.onTick(tick) # 如果你使用2个周期
3、在onBar事件中,按照k线结束使用;其他任何情况下bar内使用,通过对象使用即可,self.lineM.lineBar[-1].close
"""
# 区别:
# -使用tick模式时,当tick到达后,最新一个lineBar[-1]是当前的正在拟合的bar,不断累积tick,传统按照OnBar来计算的话,是使用LineBar[-2]。
# -使用bar模式时,当一个bar到达时,lineBar[-1]是当前生成出来的Bar,不再更新
TICK_MODE = 'tick'
BAR_MODE = 'bar'
# 参数列表,保存了参数的名称
paramList = ['vtSymbol']
def __init__(self, strategy, onBarFunc, setting=None,):
# OnBar事件回调函数
self.onBarFunc = onBarFunc
# 参数列表
self.paramList.append('barTimeInterval')
self.paramList.append('period')
self.paramList.append('inputPreLen')
self.paramList.append('inputEma1Len')
self.paramList.append('inputEma2Len')
self.paramList.append('inputMa1Len')
self.paramList.append('inputMa2Len')
self.paramList.append('inputMa3Len')
self.paramList.append('inputDmiLen')
self.paramList.append('inputDmiMax')
self.paramList.append('inputAtr1Len')
self.paramList.append('inputAtr2Len')
self.paramList.append('inputAtr3Len')
self.paramList.append('inputVolLen')
self.paramList.append('inputRsi1Len')
self.paramList.append('inputRsi2Len')
self.paramList.append('inputCmiLen')
self.paramList.append('inputBollLen')
self.paramList.append('inputBollStdRate')
self.paramList.append('inputKdjLen')
self.paramList.append('inputCciLen')
self.paramList.append('inputMacdFastPeriodLen')
self.paramList.append('inputMacdSlowPeriodLen')
self.paramList.append('inputMacdSignalPeriodLen')
self.paramList.append('inputKF')
self.paramList.append('minDiff')
self.paramList.append('shortSymbol')
self.paramList.append('activeDayJump')
self.paramList.append('name')
# 输入参数
self.name = u'LineBar'
self.mode = self.TICK_MODE # 缺省为tick模式
self.period = PERIOD_SECOND # 缺省为分钟级别周期
self.barTimeInterval = 300
self.barMinuteInterval = self.barTimeInterval / 60
self.inputPreLen = EMPTY_INT #1
self.inputMa1Len = EMPTY_INT # 10
self.inputMa2Len = EMPTY_INT # 20
self.inputMa3Len = EMPTY_INT # 120
self.inputEma1Len = EMPTY_INT # 13
self.inputEma2Len = EMPTY_INT # 21
self.inputDmiLen = EMPTY_INT # 14 # DMI的计算周期
self.inputDmiMax = EMPTY_FLOAT # 30 # Dpi和Mdi的突破阈值
self.inputAtr1Len = EMPTY_INT # 10 # ATR波动率的计算周期(近端)
self.inputAtr2Len = EMPTY_INT # 26 # ATR波动率的计算周期(常用)
self.inputAtr3Len = EMPTY_INT # 50 # ATR波动率的计算周期(远端)
self.inputVolLen = EMPTY_INT # 14 # 平均交易量的计算周期
self.inputRsi1Len = EMPTY_INT # 7 # RSI 相对强弱指数(快曲线)
self.inputRsi2Len = EMPTY_INT # 14 # RSI 相对强弱指数(慢曲线)
self.shortSymbol = EMPTY_STRING # 商品的短代码
self.minDiff = 1 # 商品的最小价格单位
self.round_n = 4 # round() 小数点的截断数量
self.activeDayJump = False # 隔夜跳空
# 当前的Tick
self.curTick = None
self.lastTick = None
self.curTradingDay = EMPTY_STRING
# K 线服务的策略
self.strategy = strategy
# K线保存数据
self.bar = None # K线数据对象
self.lineBar = [] # K线缓存数据队列
self.barFirstTick =False # K线的第一条Tick数据
# K 线的相关计算结果数据
self.preHigh = [] # K线的前inputPreLen的的最高
self.preLow = [] # K线的前inputPreLen的的最低
self.lineMa1 = [] # K线的MA1均线,周期是InputMaLen1,不包含当前bar
self.lineMa2 = [] # K线的MA2均线,周期是InputMaLen2,不包含当前bar
self.lineMa3 = [] # K线的MA2均线,周期是InputMaLen2,不包含当前bar
self.lineEma1 = [] # K线的EMA1均线,周期是InputEmaLen1,不包含当前bar
self.lineEma1MtmRate = [] # K线的EMA1均线 的momentum(3) 动能
self.lineEma2 = [] # K线的EMA2均线,周期是InputEmaLen2,不包含当前bar
self.lineEma2MtmRate = [] # K线的EMA2均线 的momentum(3) 动能
# K线的DMI( Pdi,Mdi,ADX,Adxr) 计算数据
self.barPdi = EMPTY_FLOAT # bar内的升动向指标,即做多的比率
self.barMdi = EMPTY_FLOAT # bar内的下降动向指标,即做空的比率
self.linePdi = [] # 升动向指标,即做多的比率
self.lineMdi = [] # 下降动向指标,即做空的比率
self.lineDx = [] # 趋向指标列表,最大长度为inputM*2
self.barAdx = EMPTY_FLOAT # Bar内计算的平均趋向指标
self.lineAdx = [] # 平均趋向指标
self.barAdxr = EMPTY_FLOAT # 趋向平均值,为当日ADX值与M日前的ADX值的均值
self.lineAdxr = [] # 平均趋向变化指标
# K线的基于DMI、ADX计算的结果
self.barAdxTrend = EMPTY_FLOAT # ADX值持续高于前一周期时,市场行情将维持原趋势
self.barAdxrTrend = EMPTY_FLOAT # ADXR值持续高于前一周期时,波动率比上一周期高
self.buyFilterCond = False # 多过滤器条件,做多趋势的判断,ADX高于前一天,上升动向> inputMM
self.sellFilterCond = False # 空过滤器条件,做空趋势的判断,ADXR高于前一天,下降动向> inputMM
# K线的ATR技术数据
self.lineAtr1 = [] # K线的ATR1,周期为inputAtr1Len
self.lineAtr2 = [] # K线的ATR2,周期为inputAtr2Len
self.lineAtr3 = [] # K线的ATR3,周期为inputAtr3Len
self.barAtr1 = EMPTY_FLOAT
self.barAtr2 = EMPTY_FLOAT
self.barAtr3 = EMPTY_FLOAT
# K线的交易量平均
self.lineAvgVol = [] # K 线的交易量平均
# K线的RSI计算数据
self.lineRsi1 = [] # 记录K线对应的RSI数值,只保留inputRsi1Len*8
self.lineRsi2 = [] # 记录K线对应的RSI数值,只保留inputRsi2Len*8
self.lowRsi = 30 # RSI的最低线
self.highRsi = 70 # RSI的最高线
self.lineRsiTop = [] # 记录RSI的最高峰,只保留 inputRsiLen个
self.lineRsiButtom = [] # 记录RSI的最低谷,只保留 inputRsiLen个
self.lastRsiTopButtom = {} # 最近的一个波峰/波谷
# K线的CMI计算数据
self.inputCmiLen = EMPTY_INT
self.lineCmi = [] # 记录K线对应的Cmi数值,只保留inputCmiLen*8
# K线的布林特计算数据
self.inputBollLen = EMPTY_INT # K线周期
self.inputBollStdRate = 1.5 # 两倍标准差
self.lineBollClose = [] # 用于运算的close价格列表
self.lineUpperBand = [] # 上轨
self.lineMiddleBand = [] # 中线
self.lineLowerBand = [] # 下轨
self.lineBollStd = [] # 标准差
self.lastBollUpper = EMPTY_FLOAT # 最后一根K的Boll上轨数值(与MinDiff取整)
self.lastBollMiddle = EMPTY_FLOAT # 最后一根K的Boll中轨数值(与MinDiff取整)
self.lastBollLower = EMPTY_FLOAT # 最后一根K的Boll下轨数值(与MinDiff取整+1)
# K线的KDJ指标计算数据
self.inputKdjLen = EMPTY_INT # KDJ指标的长度,缺省是9
self.lineK = [] # K为快速指标
self.lineD = [] # D为慢速指标
self.lineJ = [] #
self.lineKdjTop = [] # 记录KDJ最高峰,只保留 inputKdjLen个
self.lineKdjButtom = [] # 记录KDJ的最低谷,只保留 inputKdjLen个
self.lastKdjTopButtom = {} # 最近的一个波峰/波谷
self.lastK = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时K值
self.lastD = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时值
self.lastJ = EMPTY_FLOAT # bar内计算时,最后一个未关闭的bar的实时J值
# K线的MACD计算数据
self.inputMacdFastPeriodLen = EMPTY_INT
self.inputMacdSlowPeriodLen = EMPTY_INT
self.inputMacdSignalPeriodLen = EMPTY_INT
self.lineDif = [] # DIF = EMA12 - EMA26,即为talib-MACD返回值macd
self.lineDea = [] # DEA = (前一日DEA X 8/10 + 今日DIF X 2/10),即为talib-MACD返回值
self.lineMacd = [] # (dif-dea)*2,但是talib中MACD的计算是bar = (dif-dea)*1,国内一般是乘以2
# K 线的CCI计算数据
self.inputCciLen = EMPTY_INT
self.lineCci = []
# 卡尔曼过滤器
self.inputKF = False
self.kf = None
self.lineStateMean = []
self.lineStateCovar = []
if setting:
self.setParam(setting)
# 修正精度
if self.minDiff < 1:
self.round_n = 7
## 导入卡尔曼过滤器
if self.inputKF:
try:
self.kf = KalmanFilter(transition_matrices=[1],
observation_matrices=[1],
initial_state_mean=0,
initial_state_covariance=1,
observation_covariance=1,
transition_covariance=0.01)
except :
self.writeCtaLog(u'导入卡尔曼过滤器失败,需先安装 pip install pykalman')
self.inputKF = False
def setParam(self, setting):
"""设置参数"""
d = self.__dict__
for key in self.paramList:
if key in setting:
d[key] = setting[key]
def setMode(self,mode):
"""Tick/Bar模式"""
self.mode = mode
def onTick(self, tick):
"""行情更新
:type tick: object
"""
# Tick 有效性检查
#if (tick.datetime- datetime.now()).seconds > 10:
# self.writeCtaLog(u'无效的tick时间:{0}'.format(tick.datetime))
# return
if tick.datetime.hour == 8 or tick.datetime.hour == 20:
self.writeCtaLog(u'竞价排名tick时间:{0}'.format(tick.datetime))
return
if self.lastTick is None:
self.lastTick = tick
self.curTick = tick
# 3.生成x K线,若形成新Bar,则触发OnBar事件
self.__drawLineBar(tick)
self.lastTick = tick
# 4.执行 bar内计算
self.__recountKdj(countInBar=True)
def addBar(self,bar):
"""予以外部初始化程序增加bar"""
l1 = len(self.lineBar)
if l1 == 0:
self.lineBar.append(bar)
self.curTradingDay = bar.date
self.onBar(bar)
return
# 与最后一个BAR的时间比对,判断是否超过K线的周期
lastBar = self.lineBar[-1]
self.curTradingDay = bar.tradingDay
is_new_bar = False
if self.period == PERIOD_SECOND and (bar.datetime-lastBar.datetime).seconds >= self.barTimeInterval:
is_new_bar = True
elif self.period == PERIOD_MINUTE and (bar.datetime - lastBar.datetime).seconds >= self.barTimeInterval*60:
is_new_bar = True
elif self.period == PERIOD_HOUR:
if self.barTimeInterval == 1 and bar.datetime.hour != lastBar.datetime.hour :
is_new_bar = True
elif self.barTimeInterval == 2 and bar.datetime.hour != lastBar.datetime.hour \
and bar.datetime.hour in {1, 9, 11, 13, 15, 21, 23}:
is_new_bar = True
elif self.barTimeInterval == 4 and bar.datetime.hour != lastBar.datetime.hour \
and bar.datetime.hour in {1, 9, 13, 21}:
is_new_bar = True
elif self.period == PERIOD_DAY and bar.datetime.date != lastBar.datetime.date :
is_new_bar = True
if is_new_bar:
# 添加新的bar
self.lineBar.append(bar)
# 将上一个Bar推送至OnBar事件
self.onBar(lastBar)
return
# 更新最后一个bar
# 此段代码,针对一部分短周期生成长周期的k线更新,如3根5分钟k线,合并成1根15分钟k线。
lastBar.close = bar.close
lastBar.high = max(lastBar.high, bar.high)
lastBar.low = min(lastBar.low, bar.low)
lastBar.volume = lastBar.volume + bar.volume
lastBar.dayVolume = bar.dayVolume
lastBar.mid4 = round((2*lastBar.close + lastBar.high + lastBar.low)/4, self.round_n)
lastBar.mid5 = round((2*lastBar.close + lastBar.open + lastBar.high + lastBar.low)/5, self.round_n)
def onBar(self, bar):
"""OnBar事件"""
# 计算相关数据
bar.mid4 = round((2*bar.close + bar.high + bar.low)/4, self.round_n)
bar.mid5 = round((2*bar.close + bar.open + bar.high + bar.low)/5, self.round_n)
self.__recountPreHighLow()
self.__recountMa()
self.__recountEma()
self.__recountDmi()
self.__recountAtr()
self.__recoundAvgVol()
self.__recountRsi()
self.__recountCmi()
self.__recountKdj()
self.__recountBoll()
self.__recountMacd()
self.__recountCci()
self.__recountKF()
# 回调上层调用者
self.onBarFunc(bar)
def displayLastBar(self):
"""显示最后一个Bar的信息"""
msg = u'['+self.name+u']'
if len(self.lineBar) < 2:
return msg
if self.mode == self.TICK_MODE:
displayBar = self.lineBar[-2]
else:
displayBar = self.lineBar[-1]
msg = msg + u'{0} o:{1};h{2};l:{3};c:{4},v:{5}'.\
format(displayBar.date+' '+displayBar.time, displayBar.open, displayBar.high,
displayBar.low, displayBar.close, displayBar.volume)
if self.inputMa1Len > 0 and len(self.lineMa1) > 0:
msg = msg + u',MA({0}):{1}'.format(self.inputMa1Len, self.lineMa1[-1])
if self.inputMa2Len > 0 and len(self.lineMa2) > 0:
msg = msg + u',MA({0}):{1}'.format(self.inputMa2Len, self.lineMa2[-1])
if self.inputMa3Len > 0 and len(self.lineMa3) > 0:
msg = msg + u',MA({0}):{1}'.format(self.inputMa3Len, self.lineMa3[-1])
if self.inputEma1Len > 0 and len(self.lineEma1) > 0:
msg = msg + u',EMA({0}):{1}'.format(self.inputEma1Len, self.lineEma1[-1])
if self.inputEma2Len > 0 and len(self.lineEma2) > 0:
msg = msg + u',EMA({0}):{1}'.format(self.inputEma2Len, self.lineEma2[-1])
if self.inputDmiLen > 0 and len(self.linePdi) > 0:
msg = msg + u',Pdi:{1};Mdi:{1};Adx:{2}'.format(self.linePdi[-1], self.lineMdi[-1], self.lineAdx[-1])
if self.inputAtr1Len > 0 and len(self.lineAtr1) > 0:
msg = msg + u',Atr({0}):{1}'.format(self.inputAtr1Len, self.lineAtr1[-1])
if self.inputAtr2Len > 0 and len(self.lineAtr2) > 0:
msg = msg + u',Atr({0}):{1}'.format(self.inputAtr2Len, self.lineAtr2[-1])
if self.inputAtr3Len > 0 and len(self.lineAtr3) > 0:
msg = msg + u',Atr({0}):{1}'.format(self.inputAtr3Len, self.lineAtr3[-1])
if self.inputVolLen > 0 and len(self.lineAvgVol) > 0:
msg = msg + u',AvgVol({0}):{1}'.format(self.inputVolLen, self.lineAvgVol[-1])
if self.inputRsi1Len > 0 and len(self.lineRsi1) > 0:
msg = msg + u',Rsi({0}):{1}'.format(self.inputRsi1Len, self.lineRsi1[-1])
if self.inputRsi2Len > 0 and len(self.lineRsi2) > 0:
msg = msg + u',Rsi({0}):{1}'.format(self.inputRsi2Len, self.lineRsi2[-1])
if self.inputKdjLen > 0 and len(self.lineK) > 0:
msg = msg + u',KDJ({0}):{1},{2},{3}'.format(self.inputKdjLen,
round(self.lineK[-1], self.round_n),
round(self.lineD[-1], self.round_n),
round(self.lineJ[-1], self.round_n))
if self.inputCciLen > 0 and len(self.lineCci) > 0:
msg = msg + u',Cci({0}):{1}'.format(self.inputCciLen, self.lineCci[-1])
if self.inputBollLen > 0 and len(self.lineUpperBand)>0:
msg = msg + u',Boll({0}):u:{1},m:{2},l:{3}'.\
format(self.inputBollLen, round(self.lineUpperBand[-1], self.round_n),
round(self.lineMiddleBand[-1], self.round_n), round(self.lineLowerBand[-1]), self.round_n)
if self.inputMacdFastPeriodLen >0 and len(self.lineDif)>0:
msg = msg + u',MACD({0},{1},{2}):Dif:{3},Dea{4},Macd:{5}'.\
format(self.inputMacdFastPeriodLen, self.inputMacdSlowPeriodLen, self.inputMacdSignalPeriodLen,
round(self.lineDif[-1], self.round_n),
round(self.lineDea[-1], self.round_n),
round(self.lineMacd[-1], self.round_n))
if self.inputKF and len(self.lineKfMa) > 0:
msg = msg + u',Kalman:{0}'.format( self.lineKfMa[-1])
return msg
def __firstTick(self, tick):
""" K线的第一个Tick数据"""
self.bar = CtaBarData() # 创建新的K线
# 计算K线的整点分钟周期,这里周期最小是1分钟。如果你是采用非整点分钟,例如1.5分钟,请把这段注解掉
if self.barMinuteInterval and self.period == PERIOD_SECOND:
self.barMinuteInterval = int(self.barTimeInterval / 60)
if self.barMinuteInterval < 1:
self.barMinuteInterval = 1
fixedMin = int( tick.datetime.minute /self.barMinuteInterval) * self.barMinuteInterval
tick.datetime = tick.datetime.replace(minute=fixedMin)
self.bar.vtSymbol = tick.vtSymbol
self.bar.symbol = tick.symbol
self.bar.exchange = tick.exchange
self.bar.openInterest = tick.openInterest
self.bar.open = tick.lastPrice # O L H C
self.bar.high = tick.lastPrice
self.bar.low = tick.lastPrice
self.bar.close = tick.lastPrice
self.bar.mid4 = tick.lastPrice # 4价均价
self.bar.mid5 = tick.lastPrice # 5价均价
# K线的日期时间
self.bar.tradingDay = tick.tradingDay # K线所在的交易日期
self.bar.date = tick.date # K线的日期,(夜盘的话,与交易日期不同哦)
self.bar.datetime = tick.datetime
# K线的日期时间(去除秒)设为第一个Tick的时间
self.bar.datetime = self.bar.datetime.replace(second=0, microsecond=0)
self.bar.time = self.bar.datetime.strftime('%H:%M:%S')
# K线的日总交易量,k线内交易量
self.bar.dayVolume = tick.volume
if self.curTradingDay != self.bar.tradingDay or not self.lineBar:
# bar的交易日与记录的当前交易日不一致:即该bar为新的交易日,bar的交易量为当前的tick.volume
self.bar.volume = tick.volume
self.curTradingDay = self.bar.tradingDay
else:
# bar的交易日与记录的当前交易日一致, 交易量为tick的volume,减去上一根bar的日总交易量
self.bar.volume = tick.volume - self.lineBar[-1].dayVolume
self.barFirstTick = True # 标识该Tick属于该Bar的第一个tick数据
self.lineBar.append(self.bar) # 推入到lineBar队列
# ----------------------------------------------------------------------
def __drawLineBar(self, tick):
"""生成 line Bar """
l1 = len(self.lineBar)
# 保存第一个K线数据
if l1 == 0:
self.__firstTick(tick)
return
# 清除480周期前的数据,
if l1 > 60 * 8:
del self.lineBar[0]
# 与最后一个BAR的时间比对,判断是否超过5分钟
lastBar = self.lineBar[-1]
# 处理日内的间隔时段最后一个tick,如10:15分,11:30分,15:00 和 2:30分
endtick = False
if (tick.datetime.hour == 10 and tick.datetime.minute == 15) \
or (tick.datetime.hour == 11 and tick.datetime.minute == 30) \
or (tick.datetime.hour == 15 and tick.datetime.minute == 00) \
or (tick.datetime.hour == 2 and tick.datetime.minute == 30):
endtick = True
# 夜盘1:30收盘
if self.shortSymbol in NIGHT_MARKET_SQ2 and tick.datetime.hour == 1 and tick.datetime.minute == 00:
endtick = True
# 夜盘23:00收盘
if self.shortSymbol in NIGHT_MARKET_SQ3 and tick.datetime.hour == 23 and tick.datetime.minute == 00:
endtick = True
# 夜盘23:30收盘
if self.shortSymbol in NIGHT_MARKET_ZZ or self.shortSymbol in NIGHT_MARKET_DL:
if tick.datetime.hour == 23 and tick.datetime.minute == 30:
endtick = True
# 满足时间要求
# 1,秒周期,tick的时间,距离最后一个bar的开始时间,已经超出bar的时间周期(barTimeInterval)
# 2,分钟、小时周期,取整=0
# 3、日周期,开盘时间
# 4、不是最后一个结束tick
is_new_bar = False
if ((self.period == PERIOD_SECOND and (tick.datetime-lastBar.datetime).seconds >= self.barTimeInterval) \
or
(self.period == PERIOD_MINUTE and tick.datetime.minute % self.barTimeInterval == 0
and tick.datetime.minute != self.lastTick.datetime.minute)
or
(self.period == PERIOD_HOUR and self.barTimeInterval == 1 and tick.datetime
and tick.datetime.hour != self.lastTick.datetime.hour)
or
(self.period == PERIOD_HOUR and self.barTimeInterval == 2 and tick.datetime
and tick.datetime.hour != self.lastTick.datetime.hour
and tick.datetime.hour in {1, 9, 11, 13, 21, 23})
or
(self.period == PERIOD_HOUR and self.barTimeInterval == 4 and tick.datetime
and tick.datetime.hour != self.lastTick.datetime.hour
and tick.datetime.hour in {1, 9, 13, 21})
or (self.period == PERIOD_DAY and tick.datetime
and (tick.datetime.hour == 21 or tick.datetime.hour == 9)
and 14 <= self.lastTick.datetime.hour <= 15)
) and not endtick:
# 创建并推入新的Bar
self.__firstTick(tick)
# 触发OnBar事件
self.onBar(lastBar)
else:
# 更新当前最后一个bar
self.barFirstTick = False
# 更新最高价、最低价、收盘价、成交量
lastBar.high = max(lastBar.high, tick.lastPrice)
lastBar.low = min(lastBar.low, tick.lastPrice)
lastBar.close = tick.lastPrice
# 更新日内总交易量,和bar内交易量
lastBar.dayVolume = tick.volume
if l1 == 1:
# 针对第一个bar的tick volume更新
lastBar.volume = tick.volume
else:
# 针对新交易日的第一个bar:于上一个bar的时间在14,当前bar的时间不在14点,初始化为tick.volume
if self.lineBar[-2].datetime.hour == 14 and tick.datetime.hour != 14 and not endtick:
lastBar.volume = tick.volume
else:
# 其他情况,bar为同一交易日,将tick的volume,减去上一bar的dayVolume
lastBar.volume = tick.volume - self.lineBar[-2].dayVolume
# 更新Bar的颜色
if lastBar.close > lastBar.open:
lastBar.color = COLOR_RED
elif lastBar.close < lastBar.open:
lastBar.color = COLOR_BLUE
else:
lastBar.color = COLOR_EQUAL
# ----------------------------------------------------------------------
def __recountPreHighLow(self):
"""计算 K线的前周期最高和最低"""
if self.inputPreLen <= 0: # 不计算
return
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < self.inputPreLen:
self.writeCtaLog(u'数据未充分,当前Bar数据数量:{0},计算High、Low需要:{1}'.
format(len(self.lineBar), self.inputPreLen))
return
# 2.计算前inputPreLen周期内(不包含当前周期)的Bar高点和低点
preHigh = EMPTY_FLOAT
preLow = EMPTY_FLOAT
if self.mode == self.TICK_MODE:
idx = 2
else:
idx = 1
for i in range(len(self.lineBar)-idx, len(self.lineBar)-idx-self.inputPreLen, -1):
if self.lineBar[i].high > preHigh or preHigh == EMPTY_FLOAT:
preHigh = self.lineBar[i].high # 前InputPreLen周期高点
if self.lineBar[i].low < preLow or preLow == EMPTY_FLOAT:
preLow = self.lineBar[i].low # 前InputPreLen周期低点
# 保存
if len(self.preHigh) > self.inputPreLen * 8:
del self.preHigh[0]
self.preHigh.append(preHigh)
# 保存
if len(self.preLow)> self.inputPreLen * 8:
del self.preLow[0]
self.preLow.append(preLow)
#----------------------------------------------------------------------
def __recountMa(self):
"""计算K线的MA1 和MA2"""
l = len(self.lineBar)
if not (self.inputMa1Len > 0 or self.inputMa2Len > 0 or self.inputMa3Len > 0): # 不计算
return
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < max(7, self.inputMa1Len, self.inputMa2Len, self.inputMa3Len)+2:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算MA需要:{1}'.
format(len(self.lineBar), max(7, self.inputMa1Len, self.inputMa2Len, self.inputMa3Len)+2))
return
# 计算第一条MA均线
if self.inputMa1Len > 0:
if self.inputMa1Len > l:
ma1Len = l
else:
ma1Len = self.inputMa1Len
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-ma1Len - 1:-1]]
else:
listClose=[x.close for x in self.lineBar[-ma1Len:]]
barMa1 = ta.MA(numpy.array(listClose, dtype=float), ma1Len)[-1]
barMa1 = round(float(barMa1), self.round_n)
if len(self.lineMa1) > self.inputMa1Len*8:
del self.lineMa1[0]
self.lineMa1.append(barMa1)
# 计算第二条MA均线
if self.inputMa2Len > 0:
if self.inputMa2Len > l:
ma2Len = l
else:
ma2Len = self.inputMa2Len
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-ma2Len - 1:-1]]
else:
listClose=[x.close for x in self.lineBar[-ma2Len:]]
barMa2 = ta.MA(numpy.array(listClose, dtype=float), ma2Len)[-1]
barMa2 = round(float(barMa2), self.round_n)
if len(self.lineMa2) > self.inputMa2Len*8:
del self.lineMa2[0]
self.lineMa2.append(barMa2)
# 计算第三条MA均线
if self.inputMa3Len > 0:
if self.inputMa3Len > l:
ma3Len = l
else:
ma3Len = self.inputMa3Len
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
listClose = [x.close for x in self.lineBar[-ma3Len - 1:-1]]
else:
listClose = [x.close for x in self.lineBar[-ma3Len:]]
barMa3 = ta.MA(numpy.array(listClose, dtype=float), ma3Len)[-1]
barMa3 = round(float(barMa3), self.round_n)
if len(self.lineMa3) > self.inputMa3Len * 8:
del self.lineMa3[0]
self.lineMa3.append(barMa3)
#----------------------------------------------------------------------
def __recountEma(self):
"""计算K线的EMA1 和EMA2"""
if not (self.inputEma1Len > 0 or self.inputEma2Len >0): # 不计算
return
l = len(self.lineBar)
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < max(7, self.inputEma1Len, self.inputEma2Len)+2:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算EMA需要:{1}'.
format(len(self.lineBar), max(7, self.inputEma1Len, self.inputEma2Len)+2))
return
# 计算第一条EMA均线
if self.inputEma1Len > 0:
if self.inputEma1Len > l:
ema1Len = l
else:
ema1Len = self.inputEma1Len
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-ema1Len - 1:-1]]
else:
listClose=[x.close for x in self.lineBar[-ema1Len:]]
barEma1 = ta.EMA(numpy.array(listClose, dtype=float), ema1Len)[-1]
barEma1 = round(float(barEma1), self.round_n)
if len(self.lineEma1) > self.inputEma1Len*8:
del self.lineEma1[0]
self.lineEma1.append(barEma1)
# 计算第二条EMA均线
if self.inputEma2Len > 0:
if self.inputEma2Len > l:
ema2Len = l
else:
ema2Len = self.inputEma2Len
# 3、获取前InputN周期(不包含当前周期)的自适应均线
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-ema2Len - 1:-1]]
else:
listClose=[x.close for x in self.lineBar[-ema2Len:]]
barEma2 = ta.EMA(numpy.array(listClose, dtype=float), ema2Len)[-1]
barEma2 = round(float(barEma2), self.round_n)
if len(self.lineEma2) > self.inputEma1Len*8:
del self.lineEma2[0]
self.lineEma2.append(barEma2)
def __recountDmi(self):
"""计算K线的DMI数据和条件"""
if self.inputDmiLen <= 0: # 不计算
return
# 1、lineMx满足长度才执行计算
if len(self.lineBar) < self.inputDmiLen+1:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算DMI需要:{1}'.format(len(self.lineBar), self.inputDmiLen+1))
return
# 2、根据当前High,Low,(不包含当前周期)重新计算TR1,PDM,MDM和ATR
barTr1 = EMPTY_FLOAT # 获取InputP周期内的价差最大值之和
barPdm = EMPTY_FLOAT # InputP周期内的做多价差之和
barMdm = EMPTY_FLOAT # InputP周期内的做空价差之和
if self.mode == self.TICK_MODE:
idx = 2
else:
idx = 1
for i in range(len(self.lineBar)-idx, len(self.lineBar)-idx-self.inputDmiLen, -1): # 周期 inputDmiLen
# 3.1、计算TR1
# 当前周期最高与最低的价差
high_low_spread = self.lineBar[i].high - self.lineBar[i].low
# 当前周期最高与昨收价的价差
high_preclose_spread = abs(self.lineBar[i].high - self.lineBar[i - 1].close)
# 当前周期最低与昨收价的价差
low_preclose_spread = abs(self.lineBar[i].low - self.lineBar[i - 1].close)
# 最大价差
max_spread = max(high_low_spread, high_preclose_spread, low_preclose_spread)
barTr1 = barTr1 + float(max_spread)
# 今高与昨高的价差
high_prehigh_spread = self.lineBar[i].high - self.lineBar[i - 1].high
# 昨低与今低的价差
low_prelow_spread = self.lineBar[i - 1].low - self.lineBar[i].low
# 3.2、计算周期内的做多价差之和
if high_prehigh_spread > 0 and high_prehigh_spread > low_prelow_spread:
barPdm = barPdm + high_prehigh_spread
# 3.3、计算周期内的做空价差之和
if low_prelow_spread > 0 and low_prelow_spread > high_prehigh_spread:
barMdm = barMdm + low_prelow_spread
# 6、计算上升动向指标,即做多的比率
if barTr1 == 0:
self.barPdi = 0
else:
self.barPdi = barPdm * 100 / barTr1
if len(self.linePdi) > self.inputDmiLen+1:
del self.linePdi[0]
self.linePdi.append(self.barPdi)
# 7、计算下降动向指标,即做空的比率
if barTr1 == 0:
self.barMdi = 0
else:
self.barMdi = barMdm * 100 / barTr1
# 8、计算平均趋向指标 Adx,Adxr
if self.barMdi + self.barPdi == 0:
dx = 0
else:
dx = 100 * abs(self.barMdi - self.barPdi) / (self.barMdi + self.barPdi)
if len(self.lineMdi) > self.inputDmiLen+1:
del self.lineMdi[0]
self.lineMdi.append(self.barMdi)
if len(self.lineDx) > self.inputDmiLen+1:
del self.lineDx[0]
self.lineDx.append(dx)
# 平均趋向指标,MA计算
if len(self.lineDx) < self.inputDmiLen+1:
self.barAdx = dx
else:
self.barAdx = ta.EMA(numpy.array(self.lineDx, dtype=float), self.inputDmiLen)[-1]
# 保存Adx值
if len(self.lineAdx) > self.inputDmiLen+1:
del self.lineAdx[0]
self.lineAdx.append(self.barAdx)
# 趋向平均值,为当日ADX值与1周期前的ADX值的均值
if len(self.lineAdx) == 1:
self.barAdxr = self.lineAdx[-1]
else:
self.barAdxr = (self.lineAdx[-1] + self.lineAdx[-2]) / 2
# 保存Adxr值
if len(self.lineAdxr) > self.inputDmiLen+1:
del self.lineAdxr[0]
self.lineAdxr.append(self.barAdxr)
# 7、计算A,ADX值持续高于前一周期时,市场行情将维持原趋势
if len(self.lineAdx) < 2:
self.barAdxTrend = False
elif self.lineAdx[-1] > self.lineAdx[-2]:
self.barAdxTrend = True
else:
self.barAdxTrend = False
# ADXR值持续高于前一周期时,波动率比上一周期高
if len(self.lineAdxr) < 2:
self.barAdxrTrend = False
elif self.lineAdxr[-1] > self.lineAdxr[-2]:
self.barAdxrTrend = True
else:
self.barAdxrTrend = False
# 多过滤器条件,做多趋势,ADX高于前一天,上升动向> inputDmiMax
if self.barPdi > self.barMdi and self.barAdxTrend and self.barAdxrTrend and self.barPdi >= self.inputDmiMax:
self.buyFilterCond = True
self.writeCtaLog(u'{0}[DEBUG]Buy Signal On Bar,Pdi:{1}>Mdi:{2},adx[-1]:{3}>Adx[-2]:{4}'
.format(self.curTick.datetime, self.barPdi, self.barMdi, self.lineAdx[-1], self.lineAdx[-2]))
else:
self.buyFilterCond = False
# 空过滤器条件 做空趋势,ADXR高于前一天,下降动向> inputMM
if self.barPdi < self.barMdi and self.barAdxTrend and self.barAdxrTrend and self.barMdi >= self.inputDmiMax:
self.sellFilterCond = True
self.writeCtaLog(u'{0}[DEBUG]Short Signal On Bar,Pdi:{1}<Mdi:{2},adx[-1]:{3}>Adx[-2]:{4}'
.format(self.curTick.datetime, self.barPdi, self.barMdi, self.lineAdx[-1], self.lineAdx[-2]))
else:
self.sellFilterCond = False
def __recountAtr(self):
"""计算Mx K线的各类数据和条件"""
# 1、lineMx满足长度才执行计算
maxAtrLen = max(self.inputAtr1Len, self.inputAtr2Len, self.inputAtr3Len)
if maxAtrLen <= 0: # 不计算
return
if len(self.lineBar) < maxAtrLen+1:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算ATR需要:{1}'.
format(len(self.lineBar), maxAtrLen+1))
return
if self.mode == self.TICK_MODE:
idx = 2
else:
idx = 1
# 首次计算
if (self.inputAtr1Len > 0 and len(self.lineAtr1) < 1) \
or (self.inputAtr2Len > 0 and len(self.lineAtr2) < 1) \
or (self.inputAtr3Len > 0 and len(self.lineAtr3) < 1):
# 根据当前High,Low,(不包含当前周期)重新计算TR1和ATR
barTr1 = EMPTY_FLOAT # 获取inputAtr1Len周期内的价差最大值之和
barTr2 = EMPTY_FLOAT # 获取inputAtr2Len周期内的价差最大值之和
barTr3 = EMPTY_FLOAT # 获取inputAtr3Len周期内的价差最大值之和
j = 0
for i in range(len(self.lineBar)-idx, len(self.lineBar)-idx-maxAtrLen, -1): # 周期 inputP
# 3.1、计算TR
# 当前周期最高与最低的价差
high_low_spread = self.lineBar[i].high - self.lineBar[i].low
# 当前周期最高与昨收价的价差
high_preclose_spread = abs(self.lineBar[i].high - self.lineBar[i - 1].close)
# 当前周期最低与昨收价的价差
low_preclose_spread = abs(self.lineBar[i].low - self.lineBar[i - 1].close)
# 最大价差
max_spread = max(high_low_spread, high_preclose_spread, low_preclose_spread)
if j < self.inputAtr1Len:
barTr1 = barTr1 + float(max_spread)
if j < self.inputAtr2Len:
barTr2 = barTr2 + float(max_spread)
if j < self.inputAtr3Len:
barTr3 = barTr3 + float(max_spread)
j = j + 1
else: # 只计算一个
# 当前周期最高与最低的价差
high_low_spread = self.lineBar[0-idx].high - self.lineBar[0-idx].low
# 当前周期最高与昨收价的价差
high_preclose_spread = abs(self.lineBar[0-idx].high - self.lineBar[-1-idx].close)
# 当前周期最低与昨收价的价差
low_preclose_spread = abs(self.lineBar[0-idx].low - self.lineBar[-1-idx].close)
# 最大价差
barTr1 = max(high_low_spread, high_preclose_spread, low_preclose_spread)
barTr2 = barTr1
barTr3 = barTr1
# 计算 ATR
if self.inputAtr1Len > 0:
if len(self.lineAtr1) < 1:
self.barAtr1 = round(barTr1 / self.inputAtr1Len, self.round_n)
else:
self.barAtr1 = round((self.lineAtr1[-1]*(self.inputAtr1Len -1) + barTr1) / self.inputAtr1Len, self.round_n)
if len(self.lineAtr1) > self. inputAtr1Len+1 :
del self.lineAtr1[0]
self.lineAtr1.append(self.barAtr1)
if self.inputAtr2Len > 0:
if len(self.lineAtr2) < 1:
self.barAtr2 = round(barTr2 / self.inputAtr2Len, self.round_n)
else:
self.barAtr2 = round((self.lineAtr2[-1]*(self.inputAtr2Len -1) + barTr2) / self.inputAtr2Len, self.round_n)
if len(self.lineAtr2) > self. inputAtr2Len+1:
del self.lineAtr2[0]
self.lineAtr2.append(self.barAtr2)
if self.inputAtr3Len > 0:
if len(self.lineAtr3) < 1:
self.barAtr3 = round(barTr3 / self.inputAtr3Len, self.round_n)
else:
self.barAtr3 = round((self.lineAtr3[-1]*(self.inputAtr3Len -1) + barTr3) / self.inputAtr3Len, self.round_n)
if len(self.lineAtr3) > self. inputAtr3Len+1:
del self.lineAtr3[0]
self.lineAtr3.append(self.barAtr3)
#----------------------------------------------------------------------
def __recoundAvgVol(self):
"""计算平均成交量"""
# 1、lineBar满足长度才执行计算
if self.inputVolLen <= 0: # 不计算
return
if len(self.lineBar) < self.inputVolLen+1:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算Avg Vol需要:{1}'.
format(len(self.lineBar), self.inputVolLen+1))
return
if self.mode == self.TICK_MODE:
listVol = [x.volume for x in self.lineBar[-self.inputVolLen-1: -1]]
else:
listVol = [x.volume for x in self.lineBar[-self.inputVolLen:]]
sumVol = ta.SUM(numpy.array(listVol, dtype=float), timeperiod=self.inputVolLen)[-1]
avgVol = round(sumVol/self.inputVolLen, 0)
self.lineAvgVol.append(avgVol)
# ----------------------------------------------------------------------
def __recountRsi(self):
"""计算K线的RSI"""
if self.inputRsi1Len <= 0 and self.inputRsi2Len <= 0:
return
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < self.inputRsi1Len+2:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算RSI需要:{1}'.
format(len(self.lineBar), self.inputRsi1Len + 2))
return
# 计算第1根RSI曲线
# 3、inputRsi1Len(包含当前周期)的相对强弱
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-self.inputRsi1Len - 2:-1]]
idx = 2
else:
listClose=[x.close for x in self.lineBar[-self.inputRsi1Len-1:]]
idx = 1
barRsi = ta.RSI(numpy.array(listClose, dtype=float), self.inputRsi1Len)[-1]
barRsi = round(float(barRsi), self.round_n)
l = len(self.lineRsi1)
if l > self.inputRsi1Len*8:
del self.lineRsi1[0]
self.lineRsi1.append(barRsi)
if l > 3:
# 峰
if self.lineRsi1[-1] < self.lineRsi1[-2] and self.lineRsi1[-3] < self.lineRsi1[-2]:
t={}
t["Type"] = u'T'
t["RSI"] = self.lineRsi1[-2]
t["Close"] = self.lineBar[-1-idx].close
if len(self.lineRsiTop) > self.inputRsi1Len:
del self.lineRsiTop[0]
self.lineRsiTop.append( t )
self.lastRsiTopButtom = self.lineRsiTop[-1]
# 谷
elif self.lineRsi1[-1] > self.lineRsi1[-2] and self.lineRsi1[-3] > self.lineRsi1[-2]:
b={}
b["Type"] = u'B'
b["RSI"] = self.lineRsi1[-2]
b["Close"] = self.lineBar[-1-idx].close
if len(self.lineRsiButtom) > self.inputRsi1Len:
del self.lineRsiButtom[0]
self.lineRsiButtom.append(b)
self.lastRsiTopButtom = self.lineRsiButtom[-1]
# 计算第二根RSI曲线
if self.inputRsi2Len > 0:
if len(self.lineBar) < self.inputRsi2Len+2:
return
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-self.inputRsi2Len - 2:-1]]
else:
listClose=[x.close for x in self.lineBar[-self.inputRsi2Len - 1:]]
barRsi = ta.RSI(numpy.array(listClose, dtype=float), self.inputRsi2Len)[-1]
barRsi = round(float(barRsi), self.round_n)
l = len(self.lineRsi2)
if l > self.inputRsi2Len*8:
del self.lineRsi2[0]
self.lineRsi2.append(barRsi)
def __recountCmi(self):
"""市场波动指数(Choppy Market Index,CMI)是一个用来判断市场走势类型的技术分析指标。
它通过计算当前收盘价与一定周期前的收盘价的差值与这段时间内价格波动的范围的比值,来判断目前的股价走势是趋势还是盘整。
市场波动指数CMI的计算公式:
CMI=(Abs(Close-ref(close,(n-1)))*100/(HHV(high,n)-LLV(low,n))
其中,Abs是绝对值。
n是周期数,例如30。
市场波动指数CMI的使用方法:
这个指标的重要用途是来区分目前的股价走势类型:盘整,趋势。当CMI指标小于20时,市场走势是盘整;当CMI指标大于20时,市场在趋势期。
CMI指标还可以用于预测股价走势类型的转变。因为物极必反,当CMI长期处于0附近,此时,股价走势很可能从盘整转为趋势;当CMI长期处于100附近,此时,股价趋势很可能变弱,形成盘整。
"""
if self.inputCmiLen <= EMPTY_INT: return
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < self.inputCmiLen:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算CMI需要:{1}'.
format(len(self.lineBar), self.inputCmiLen))
return
if self.mode == self.TICK_MODE:
listClose =[x.close for x in self.lineBar[-self.inputCmiLen-1:-1]]
idx = 2
else:
listClose =[x.close for x in self.lineBar[-self.inputCmiLen:]]
idx = 1
hhv = max(listClose)
llv = min(listClose)
if hhv==llv:
cmi = 100
else:
cmi = abs(self.lineBar[0-idx].close-self.lineBar[-1-idx].close)*100/(hhv-llv)
cmi = round(cmi, self.round_n)
if len(self.lineCmi) > self.inputCmiLen:
del self.lineCmi[0]
self.lineCmi.append(cmi)
def __recountBoll(self):
"""布林特线"""
if self.inputBollLen <= EMPTY_INT: return
l = len(self.lineBar)
if l < min(14, self.inputBollLen)+1:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算Boll需要:{1}'.
format(len(self.lineBar), min(14, self.inputBollLen)+1))
return
if l < self.inputBollLen+2:
bollLen = l-1
else:
bollLen = self.inputBollLen
# 不包含当前最新的Bar
if self.mode == self.TICK_MODE:
listClose=[x.close for x in self.lineBar[-bollLen - 1:-1]]
else:
listClose=[x.close for x in self.lineBar[-bollLen :]]
#
upper, middle, lower = ta.BBANDS(numpy.array(listClose, dtype=float),
timeperiod=bollLen, nbdevup=self.inputBollStdRate,
nbdevdn=self.inputBollStdRate, matype=0)
if len(self.lineUpperBand) > self.inputBollLen*8:
del self.lineUpperBand[0]
if len(self.lineMiddleBand) > self.inputBollLen*8:
del self.lineMiddleBand[0]
if len(self.lineLowerBand) > self.inputBollLen*8:
del self.lineLowerBand[0]
if len(self.lineBollStd) > self.inputBollLen * 8:
del self.lineBollStd[0]
# 1标准差
std = (upper[-1] - lower[-1]) / (self.inputBollStdRate*2)
self.lineBollStd.append(std)
u = round(upper[-1], self.round_n)
self.lineUpperBand.append(u) # 上轨
self.lastBollUpper = u - u % self.minDiff # 上轨取整
m = round(middle[-1], self.round_n)
self.lineMiddleBand.append(m) # 中轨
self.lastBollMiddle = m - m % self.minDiff # 中轨取整
l = round(lower[-1], self.round_n)
self.lineLowerBand.append(l) # 下轨
self.lastBollLower = l - l % self.minDiff # 下轨取整
def __recountKdj(self, countInBar = False):
"""KDJ指标"""
"""
KDJ指标的中文名称又叫随机指标,是一个超买超卖指标,最早起源于期货市场,由乔治·莱恩(George Lane)首创。
随机指标KDJ最早是以KD指标的形式出现,而KD指标是在威廉指标的基础上发展起来的。
不过KD指标只判断股票的超买超卖的现象,在KDJ指标中则融合了移动平均线速度上的观念,形成比较准确的买卖信号依据。在实践中,K线与D线配合J线组成KDJ指标来使用。
KDJ指标在设计过程中主要是研究最高价、最低价和收盘价之间的关系,同时也融合了动量观念、强弱指标和移动平均线的一些优点。
因此,能够比较迅速、快捷、直观地研判行情,被广泛用于股市的中短期趋势分析,是期货和股票市场上最常用的技术分析工具。
第一步 计算RSV:即未成熟随机值(Raw Stochastic Value)。
RSV 指标主要用来分析市场是处于“超买”还是“超卖”状态:
- RSV高于80%时候市场即为超买状况,行情即将见顶,应当考虑出仓;
- RSV低于20%时候,市场为超卖状况,行情即将见底,此时可以考虑加仓。
N日RSV=(N日收盘价-N日内最低价)÷(N日内最高价-N日内最低价)×100%
第二步 计算K值:当日K值 = 2/3前1日K值 + 1/3当日RSV ;
第三步 计算D值:当日D值 = 2/3前1日D值 + 1/3当日K值;
第四步 计算J值:当日J值 = 3当日K值 - 2当日D值.
"""
if self.inputKdjLen <= EMPTY_INT: return
if len(self.lineBar) < self.inputKdjLen+1:
if not countInBar:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算KDJ需要:{1}'.format(len(self.lineBar), self.inputKdjLen+1))
return
# 数据是Tick模式,非bar内计算
if self.mode == self.TICK_MODE and not countInBar:
listClose =[x.close for x in self.lineBar[-self.inputKdjLen-1:-1]]
listHigh = [x.high for x in self.lineBar[-self.inputKdjLen - 1:-1]]
listLow = [x.low for x in self.lineBar[-self.inputKdjLen - 1:-1]]
idx = 2
else:
listClose =[x.close for x in self.lineBar[-self.inputKdjLen:]]
listHigh = [x.high for x in self.lineBar[-self.inputKdjLen :]]
listLow = [x.low for x in self.lineBar[-self.inputKdjLen :]]
idx = 1
hhv = max(listHigh)
llv = min(listLow)
if len(self.lineK) > 0:
lastK = self.lineK[-1]
else:
lastK = 0
if len(self.lineD) > 0:
lastD = self.lineD[-1]
else:
lastD = 0
if hhv == llv:
rsv = 50
else:
rsv = (self.lineBar[-1].close - llv)/(hhv - llv) * 100
k = 2*lastK/3 + rsv/3
if k < 0: k = 0
if k > 100: k = 100
d = 2*lastD/3 + k/3
if d < 0: d = 0
if d > 100: d = 100
j = 3*k - 2*d
if countInBar:
self.lastD = d
self.lastK = k
self.lastJ = j
return
if len(self.lineK) > self.inputKdjLen * 8:
del self.lineK[0]
self.lineK.append(k)
if len(self.lineD) > self.inputKdjLen * 8:
del self.lineD[0]
self.lineD.append(d)
l = len(self.lineJ)
if l > self.inputKdjLen * 8:
del self.lineJ[0]
self.lineJ.append(j)
#增加KDJ的J谷顶和波底
if l > 3:
# 峰
if self.lineJ[-1] < self.lineJ[-2] and self.lineJ[-3] <= self.lineJ[-2]:
t={}
t["Type"] = u'T'
t["J"] = self.lineJ[-2]
t["Close"] = self.lineBar[-1-idx].close
if len(self.lineKdjTop) > self.inputKdjLen:
del self.lineKdjTop[0]
self.lineKdjTop.append( t )
self.lastKdjTopButtom = self.lineKdjTop[-1]
# 谷
elif self.lineJ[-1] > self.lineJ[-2] and self.lineJ[-3] >= self.lineJ[-2]:
b={}
b["Type"] = u'B'
b["J"] = self.lineJ[-2]
b["Close"] = self.lineBar[-1-idx].close
if len(self.lineKdjButtom) > self.inputKdjLen:
del self.lineKdjButtom[0]
self.lineKdjButtom.append(b)
self.lastKdjTopButtom = self.lineKdjButtom[-1]
def __recountMacd(self):
"""
Macd计算方法:
12日EMA的计算:EMA12 = 前一日EMA12 X 11/13 + 今日收盘 X 2/13
26日EMA的计算:EMA26 = 前一日EMA26 X 25/27 + 今日收盘 X 2/27
差离值(DIF)的计算: DIF = EMA12 - EMA26,即为talib-MACD返回值macd
根据差离值计算其9日的EMA,即离差平均值,是所求的DEA值。
今日DEA = (前一日DEA X 8/10 + 今日DIF X 2/10),即为talib-MACD返回值signal
DIF与它自己的移动平均之间差距的大小一般BAR=(DIF-DEA)*2,即为MACD柱状图。
但是talib中MACD的计算是bar = (dif-dea)*1
"""
if self.inputMacdFastPeriodLen <= EMPTY_INT: return
if self.inputMacdSlowPeriodLen <= EMPTY_INT: return
if self.inputMacdSignalPeriodLen <= EMPTY_INT: return
maxLen = max(self.inputMacdFastPeriodLen,self.inputMacdSlowPeriodLen)+self.inputMacdSignalPeriodLen+1
#maxLen = maxLen * 3 # 注:数据长度需要足够,才能准确。测试过,3倍长度才可以与国内的文华等软件一致
if len(self.lineBar) < maxLen:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算MACD需要:{1}'.format(len(self.lineBar), maxLen))
return
if self.mode == self.TICK_MODE:
listClose =[x.close for x in self.lineBar[-maxLen:-1]]
else:
listClose =[x.close for x in self.lineBar[-maxLen-1:]]
dif, dea, macd = ta.MACD(numpy.array(listClose, dtype=float), fastperiod=self.inputMacdFastPeriodLen,
slowperiod=self.inputMacdSlowPeriodLen, signalperiod=self.inputMacdSignalPeriodLen)
#dif, dea, macd = ta.MACDEXT(numpy.array(listClose, dtype=float),
# fastperiod=self.inputMacdFastPeriodLen, fastmatype=1,
# slowperiod=self.inputMacdSlowPeriodLen, slowmatype=1,
# signalperiod=self.inputMacdSignalPeriodLen, signalmatype=1)
if len(self.lineDif) > maxLen:
del self.lineDif[0]
self.lineDif.append(dif[-1])
if len(self.lineDea) > maxLen:
del self.lineDea[0]
self.lineDea.append(dea[-1])
if len(self.lineMacd) > maxLen:
del self.lineMacd[0]
self.lineMacd.append(macd[-1]*2) # 国内一般是2倍
def __recountCci(self):
"""CCI计算
顺势指标又叫CCI指标,CCI指标是美国股市技术分析 家唐纳德·蓝伯特(Donald Lambert)于20世纪80年代提出的,专门测量股价、外汇或者贵金属交易
是否已超出常态分布范围。属于超买超卖类指标中较特殊的一种。波动于正无穷大和负无穷大之间。但是,又不需要以0为中轴线,这一点也和波动于正无穷大
和负无穷大的指标不同。
它最早是用于期货市场的判断,后运用于股票市场的研判,并被广泛使用。与大多数单一利用股票的收盘价、开盘价、最高价或最低价而发明出的各种技术分析
指标不同,CCI指标是根据统计学原理,引进价格与固定期间的股价平均区间的偏离程度的概念,强调股价平均绝对偏差在股市技术分析中的重要性,是一种比
较独特的技术指标。
它与其他超买超卖型指标又有自己比较独特之处。象KDJ、W%R等大多数超买超卖型指标都有“0-100”上下界限,因此,它们对待一般常态行情的研判比较适用
,而对于那些短期内暴涨暴跌的股票的价格走势时,就可能会发生指标钝化的现象。而CCI指标却是波动于正无穷大到负无穷大之间,因此不会出现指标钝化现
象,这样就有利于投资者更好地研判行情,特别是那些短期内暴涨暴跌的非常态行情。
http://baike.baidu.com/view/53690.htm?fromtitle=CCI%E6%8C%87%E6%A0%87&fromid=4316895&type=syn
"""
if self.inputCciLen <= 0:
return
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < self.inputCciLen+2:
self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算CCI需要:{1}'.
format(len(self.lineBar), self.inputCciLen + 2))
return
# 计算第1根RSI曲线
# 3、inputCc1Len(包含当前周期)
if self.mode == self.TICK_MODE:
listClose = [x.close for x in self.lineBar[-self.inputCciLen - 2:-1]]
listHigh = [x.high for x in self.lineBar[-self.inputCciLen - 2:-1]]
listLow = [x.low for x in self.lineBar[-self.inputCciLen - 2:-1]]
idx = 2
else:
listClose = [x.close for x in self.lineBar[-self.inputCciLen-1:]]
listHigh = [x.high for x in self.lineBar[-self.inputCciLen - 1:]]
listLow = [x.low for x in self.lineBar[-self.inputCciLen - 1:]]
idx = 1
barCci = ta.CCI(high=numpy.array(listHigh, dtype=float), low=numpy.array(listLow, dtype=float),
close=numpy.array(listClose, dtype=float), timeperiod=self.inputCciLen)[-1]
barCci = round(float(barCci), 3)
l = len(self.lineCci)
if l > self.inputCciLen*8:
del self.lineCci[0]
self.lineCci.append(barCci)
def __recountKF(self):
"""计算卡尔曼过滤器均线"""
min_len = 20
if not self.inputKF or self.kf is None:
return
if len(self.lineBar) < min_len:
# 数量不足时,不做滤波处理,直接吻合(若改为EMA更好)
if self.mode == self.TICK_MODE and len(self.lineBar)>1:
self.lineStateMean.append(self.lineBar[-2].close)
else:
self.lineStateMean.append(self.lineBar[-1].close)
return
if len(self.lineStateMean) ==0 or len(self.lineStateCovar) ==0:
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
listClose = [x.close for x in self.lineBar[-min_len - 1:-1]]
else:
listClose = [x.close for x in self.lineBar[-min_len:]]
state_means, state_covariances = self.kf.filter(numpy.array(listClose, dtype=float))
m = state_means[-1].item()
c = state_covariances[-1].item()
else:
m = self.lineStateMean[-1]
c = self.lineStateCovar[-1]
if self.mode == self.TICK_MODE:
o = self.lineBar[-2].close
else:
o = self.lineBar[-1].close
state_means, state_covariances = self.kf.filter_update(filtered_state_mean=m,
filtered_state_covariance=c,
observation=numpy.array(o, dtype=float))
m = state_means[-1].item()
c = state_covariances[-1].item()
if len(self.lineStateMean) > min_len:
del self.lineStateMean[0]
if len(self.lineStateCovar) > min_len:
del self.lineStateCovar[0]
self.lineStateMean.append(m)
self.lineStateCovar.append(c)
# ----------------------------------------------------------------------
def writeCtaLog(self, content):
"""记录CTA日志"""
self.strategy.writeCtaLog(u'['+self.name+u']'+content)
def debugCtaLog(self,content):
"""记录CTA日志"""
if DEBUGCTALOG:
self.strategy.writeCtaLog(u'['+self.name+u'-DEBUG]'+content)
class CtaDayBar(object):
"""日线"""
# 区别:
# -使用tick模式时,当tick到达后,最新一个lineBar[-1]是当前的正在拟合的bar,不断累积tick,传统按照OnBar来计算的话,是使用LineBar[-2]。
# -使用bar模式时,当一个bar到达时,lineBar[-1]是当前生成出来的Bar,不再更新
TICK_MODE = 'tick'
BAR_MODE = 'bar'
# 参数列表,保存了参数的名称
paramList = ['vtSymbol']
def __init__(self, strategy, onBarFunc, setting=None, ):
self.paramList.append('inputPreLen')
self.paramList.append('minDiff')
self.paramList.append('shortSymbol')
self.paramList.append('name')
# 输入参数
self.name = u'DayBar'
self.mode = self.TICK_MODE
self.inputPreLen = EMPTY_INT # 1
# OnBar事件回调函数
self.onBarFunc = onBarFunc
self.lineBar = []
self.currTick = None
self.lastTick = None
self.shortSymbol = EMPTY_STRING # 商品的短代码
self.minDiff = 1 # 商品的最小价格单位
def onTick(self, tick):
"""行情更新"""
if self.currTick is None:
self.currTick = tick
self.__drawLineBar(tick)
self.lastTick = tick
def addBar(self, bar):
"""予以外部初始化程序增加bar"""
l1 = len(self.lineBar)
if l1 == 0:
bar.datetme = bar.datetime.replace(minute=0, second=0)
bar.time = bar.datetime.strftime('%H:%M:%S')
self.lineBar.append(bar)
return
# 与最后一个BAR的时间比对,判断是否超过K线的周期
lastBar = self.lineBar[-1]
if bar.tradingDay != lastBar.datetime:
bar.datetme = bar.datetime.replace(minute=0, second=0)
bar.time = bar.datetime.strftime('%H:%M:%S')
self.lineBar.append(bar)
self.onBar(lastBar)
return
# 更新最后一个bar
# 此段代码,针对一部分短周期生成长周期的k线更新,如3根5分钟k线,合并成1根15分钟k线。
lastBar.close = bar.close
lastBar.high = max(lastBar.high, bar.high)
lastBar.low = min(lastBar.low, bar.low)
lastBar.mid4 = round((2 * lastBar.close + lastBar.high + lastBar.low) / 4, self.round_n)
lastBar.mid5 = round((2 * lastBar.close + lastBar.open + lastBar.high + lastBar.low) / 5, self.round_n)
def __firstTick(self, tick):
""" K线的第一个Tick数据"""
self.bar = CtaBarData() # 创建新的K线
self.bar.vtSymbol = tick.vtSymbol
self.bar.symbol = tick.symbol
self.bar.exchange = tick.exchange
self.bar.openInterest = tick.openInterest
self.bar.open = tick.lastPrice # O L H C
self.bar.high = tick.lastPrice
self.bar.low = tick.lastPrice
self.bar.close = tick.lastPrice
# K线的日期时间
self.bar.tradingDay = tick.tradingDay # K线所在的交易日期
self.bar.date = tick.date # K线的日期,(夜盘的话,与交易日期不同哦)
self.bar.datetime = tick.datetime
# K线的日期时间(去除分钟、秒)设为第一个Tick的时间
self.bar.datetime = self.bar.datetime.replace(minute=0, second=0, microsecond=0)
self.bar.time = self.bar.datetime.strftime('%H:%M:%S')
self.barFirstTick = True # 标识该Tick属于该Bar的第一个tick数据
self.lineBar.append(self.bar) # 推入到lineBar队列
# ----------------------------------------------------------------------
def __drawLineBar(self, tick):
"""生成 line Bar """
l1 = len(self.lineBar)
# 保存第一个K线数据
if l1 == 0:
self.__firstTick(tick)
return
# 清除480周期前的数据,
if l1 > 60 * 8:
del self.lineBar[0]
# 与最后一个BAR的时间比对,判断是否超过5分钟
lastBar = self.lineBar[-1]
# 处理日内的间隔时段最后一个tick,如10:15分,11:30分,15:00 和 2:30分
endtick = False
if (tick.datetime.hour == 10 and tick.datetime.minute == 15) \
or (tick.datetime.hour == 11 and tick.datetime.minute == 30) \
or (tick.datetime.hour == 15 and tick.datetime.minute == 00) \
or (tick.datetime.hour == 2 and tick.datetime.minute == 30):
endtick = True
# 夜盘1:30收盘
if self.shortSymbol in NIGHT_MARKET_SQ2 and tick.datetime.hour == 1 and tick.datetime.minute == 00:
endtick = True
# 夜盘23:00收盘
if self.shortSymbol in NIGHT_MARKET_SQ3 and tick.datetime.hour == 23 and tick.datetime.minute == 00:
endtick = True
# 夜盘23:30收盘
if self.shortSymbol in NIGHT_MARKET_ZZ or self.shortSymbol in NIGHT_MARKET_DL:
if tick.datetime.hour == 23 and tick.datetime.minute == 30:
endtick = True
# 满足时间要求,tick的时间(夜盘21点;或者日盘9点,上一个tick为日盘收盘时间
if (tick.datetime.hour == 21 or tick.datetime.hour == 9 ) and 14 <= self.lastTick.datetime.hour <= 15:
# 创建并推入新的Bar
self.__firstTick(tick)
# 触发OnBar事件
self.onBar(lastBar)
else:
# 更新当前最后一个bar
self.barFirstTick = False
# 更新最高价、最低价、收盘价、成交量
lastBar.high = max(lastBar.high, tick.lastPrice)
lastBar.low = min(lastBar.low, tick.lastPrice)
lastBar.close = tick.lastPrice
# 更新Bar的颜色
if lastBar.close > lastBar.open:
lastBar.color = COLOR_RED
elif lastBar.close < lastBar.open:
lastBar.color = COLOR_BLUE
else:
lastBar.color = COLOR_EQUAL
def displayLastBar(self):
"""显示最后一个Bar的信息"""
msg = u'[' + self.name + u']'
if len(self.lineBar) < 2:
return msg
if self.mode == self.TICK_MODE:
displayBar = self.lineBar[-2]
else:
displayBar = self.lineBar[-1]
msg = msg + u'{0} o:{1};h{2};l:{3};c:{4}'. \
format(displayBar.date + ' ' + displayBar.time, displayBar.open, displayBar.high,
displayBar.low, displayBar.close)
return msg
def onBar(self, bar):
"""OnBar事件"""
self.__recountPreHighLow()
# 回调上层调用者
self.onBarFunc(bar)
# ----------------------------------------------------------------------
def __recountPreHighLow(self):
"""计算 K线的前周期最高和最低"""
if self.inputPreLen <= 0: return # 不计算
# 1、lineBar满足长度才执行计算
if len(self.lineBar) < self.inputPreLen:
self.writeCtaLog(u'数据未充分,当前{0}r数据数量:{1},计算High、Low需要:{2}'.
format(self.name, len(self.lineBar), self.inputPreLen))
return
# 2.计算前inputPreLen周期内(不包含当前周期)的Bar高点和低点
preHigh = EMPTY_FLOAT
preLow = EMPTY_FLOAT
if self.mode == self.TICK_MODE:
idx = 2
else:
idx = 1
for i in range(len(self.lineBar)-idx, len(self.lineBar)-idx-self.inputPreLen, -1):
if self.lineBar[i].high > preHigh or preHigh == EMPTY_FLOAT:
preHigh = self.lineBar[i].high # 前InputPreLen周期高点
if self.lineBar[i].low < preLow or preLow == EMPTY_FLOAT:
preLow = self.lineBar[i].low # 前InputPreLen周期低点
# 保存
if len(self.preHigh) > self.inputPreLen * 8:
del self.preHigh[0]
self.preHigh.append(preHigh)
# 保存
if len(self.preLow)> self.inputPreLen * 8:
del self.preLow[0]
self.preLow.append(preLow) |
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { setToken, getToken, canTurnTo, formatRouters } from '@/libs/util'
import config from '@/config'
const { homeName } = config
Vue.use(Router)
// 存放加载的动态路由
let dyncRouters = []
let BASE_URL = ''
switch (process.env.NODE_ENV) {
case 'development':
BASE_URL = config.publicPath.dev // 这里是本地的请求url
break
case 'production':
BASE_URL = config.publicPath.pro // 生产环境url
break
}
const router = new Router({
base: BASE_URL,
routes: routes,
mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'
const permitList = [LOGIN_PAGE_NAME, 'loginSuccess']
const turnTo = (to, access, next) => {
if (!to.name) {
// 防止地址栏刷新动态路由跳转到401或404,先跳转到homeName
router.replace(to)
} else if (canTurnTo(to.name, access, routes)) {
next()
} else {
// 无权限,重定向到401页面
next({ replace: true, name: 'error_401' })
}
}
router.beforeEach((to, from, next) => {
iView.LoadingBar.start()
const token = getToken()
if (!token && !permitList.includes(to.name)) {
// 未登录,并且不是白名单
next({
name: LOGIN_PAGE_NAME // 跳转到登录页
})
} else if (!token && permitList.includes(to.name)) {
next() // 跳转
} else if (token && to.name === LOGIN_PAGE_NAME) {
// 已登录且要跳转的页面是登录页
next({
name: homeName // 跳转到homeName页
})
} else {
turnTo(to, store.state.user.access, next)
if (store.state.user.hasGetInfo) {
turnTo(to, store.state.user.access, next)
} else {
store.dispatch('getUserInfo').then(res => {
if (!dyncRouters || dyncRouters.length === 0) {
console.log("------------")
console.log(dyncRouters)
dyncRouters = dyncRouters.concat(...formatRouters(store.state.user.menus, store.state.user.access))
console.log(dyncRouters)
// 防止重复添加路由报错
router.addRoutes(dyncRouters)
console.log("======")
console.log(router)
routes.push(...dyncRouters)
}
turnTo(to, store.state.user.access, next)
}).catch(err => {
setToken('')
next({
name: 'login'
})
})
}
}
})
router.afterEach(to => {
iView.LoadingBar.finish()
window.scrollTo(0, 0)
})
export default router
|
# -*- coding: utf-8 -*- #
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run a workflow template."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import uuid
from googlecloudsdk.api_lib.dataproc import dataproc as dp
from googlecloudsdk.api_lib.dataproc import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dataproc import flags
from googlecloudsdk.core import log
@base.Deprecate(is_removed=False,
warning='Workflow template run command is deprecated, please '
'use instantiate command: "gcloud beta dataproc '
'workflow-templates instantiate"')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Run(base.CreateCommand):
"""Run a workflow template."""
@staticmethod
def Args(parser):
flags.AddTemplateResourceArg(parser, 'run', api_version='v1beta2')
flags.AddTimeoutFlag(parser, default='24h')
base.ASYNC_FLAG.AddToParser(parser)
def Run(self, args):
# TODO (b/68774667): deprecate Run command in favor of Instantiate command.
dataproc = dp.Dataproc(self.ReleaseTrack())
msgs = dataproc.messages
template_ref = args.CONCEPTS.template.Parse()
instantiate_request = dataproc.messages.InstantiateWorkflowTemplateRequest()
instantiate_request.instanceId = uuid.uuid4().hex # request UUID
request = msgs.DataprocProjectsRegionsWorkflowTemplatesInstantiateRequest(
instantiateWorkflowTemplateRequest=instantiate_request,
name=template_ref.RelativeName())
operation = dataproc.client.projects_regions_workflowTemplates.Instantiate(
request)
if args.async:
log.status.Print('Running [{0}].'.format(template_ref.Name()))
return
operation = util.WaitForWorkflowTemplateOperation(
dataproc, operation, timeout_s=args.timeout)
return operation
|
module.exports = function (PerfectScrollBar) {
const tables = document.querySelectorAll(".table-custom-scroll");
[...tables].forEach(table => {
const scroll = new PerfectScrollBar(table, {
});
$(scroll.element).on("ps-x-reach-start", function () {
$(this)
.addClass("ps-scroll-reach-start")
.removeClass("ps-scroll-reach-end");
$(this).parent()
.addClass("parent-ps-scroll-reach-start")
.removeClass("parent-ps-scroll-reach-end");
});
$(scroll.element).on("ps-x-reach-end", function () {
$(this)
.addClass("ps-scroll-reach-end")
.removeClass("ps-scroll-reach-start");
$(this).parent()
.addClass("parent-ps-scroll-reach-end")
.removeClass("parent-ps-scroll-reach-start");
});
$(window).resize(function () {
scroll.update();
});
});
};
|
'use strict';
describe('Feature Test:', function (){
var plane;
var airport;
beforeEach(function(){
plane = new Plane();
airport = new Airport();
});
it('planes can be istructed to land at an airport', function(){
plane.land(airport);
expect(airport.planes()).toContain(plane);
});
it('planes can be instructed to takeoff', function(){
plane.land(airport)
plane.takeoff();
expect(airport.planes()).not.toContain(plane);
});
it("planes can't take off in stormy weather", function (){
plane.land(airport)
spyOn(airport, 'isStormy').and.returnValue(true);
expect(function(){ plane.takeoff();}).toThrowError('cannot takeoff during storm');
expect(airport.planes()).toContain(plane);
});
});
|
/* =========================================================
* bootstrap-datepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
*
* 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.
* ========================================================= */
!function ($) {
function UTCDate() {
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday() {
var today = new Date();
return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
}
// Picker object
var Datepicker = function (element, options) {
var that = this;
this.element = $(element);
this.language = options.language || this.element.data('date-language') || "en";
this.language = this.language in dates ? this.language : this.language.split('-')[0]; //Check if "de-DE" style date is available, if not language should fallback to 2 letter code eg "de"
this.language = this.language in dates ? this.language : "en";
this.isRTL = dates[this.language].rtl || false;
this.format = DPGlobal.parseFormat(options.format || this.element.data('date-format') || dates[this.language].format || 'mm/dd/yyyy');
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if (this.component && this.component.length === 0)
this.component = false;
this.forceParse = true;
if ('forceParse' in options) {
this.forceParse = options.forceParse;
} else if ('dateForceParse' in this.element.data()) {
this.forceParse = this.element.data('date-force-parse');
}
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if (this.isInline) {
this.picker.addClass('datepicker-inline').appendTo(this.element);
} else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.isRTL) {
this.picker.addClass('datepicker-rtl');
this.picker.find('.prev i, .next i')
.toggleClass('fa fa-arrow-left fa-arrow-right');
}
this.autoclose = false;
if ('autoclose' in options) {
this.autoclose = options.autoclose;
} else if ('dateAutoclose' in this.element.data()) {
this.autoclose = this.element.data('date-autoclose');
}
this.keyboardNavigation = true;
if ('keyboardNavigation' in options) {
this.keyboardNavigation = options.keyboardNavigation;
} else if ('dateKeyboardNavigation' in this.element.data()) {
this.keyboardNavigation = this.element.data('date-keyboard-navigation');
}
this.viewMode = this.startViewMode = 0;
switch (options.startView || this.element.data('date-start-view')) {
case 2:
case 'decade':
this.viewMode = this.startViewMode = 2;
break;
case 1:
case 'year':
this.viewMode = this.startViewMode = 1;
break;
}
this.minViewMode = options.minViewMode || this.element.data('date-min-view-mode') || 0;
if (typeof this.minViewMode === 'string') {
switch (this.minViewMode) {
case 'months':
this.minViewMode = 1;
break;
case 'years':
this.minViewMode = 2;
break;
default:
this.minViewMode = 0;
break;
}
}
this.viewMode = this.startViewMode = Math.max(this.startViewMode, this.minViewMode);
this.todayBtn = (options.todayBtn || this.element.data('date-today-btn') || false);
this.todayHighlight = (options.todayHighlight || this.element.data('date-today-highlight') || false);
this.calendarWeeks = false;
if ('calendarWeeks' in options) {
this.calendarWeeks = options.calendarWeeks;
} else if ('dateCalendarWeeks' in this.element.data()) {
this.calendarWeeks = this.element.data('date-calendar-weeks');
}
if (this.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function (i, val) {
return parseInt(val) + 1;
});
this._allow_update = false;
this.weekStart = ((options.weekStart || this.element.data('date-weekstart') || dates[this.language].weekStart || 0) % 7);
this.weekEnd = ((this.weekStart + 6) % 7);
this.startDate = -Infinity;
this.endDate = Infinity;
this.daysOfWeekDisabled = [];
this.setStartDate(options.startDate || this.element.data('date-startdate'));
this.setEndDate(options.endDate || this.element.data('date-enddate'));
this.setDaysOfWeekDisabled(options.daysOfWeekDisabled || this.element.data('date-days-of-week-disabled'));
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if (this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_events: [],
_secondaryEvents: [],
_applyEvents: function (evs) {
for (var i = 0, el, ev; i < evs.length; i++) {
el = evs[i][0];
ev = evs[i][1];
el.on(ev);
}
},
_unapplyEvents: function (evs) {
for (var i = 0, el, ev; i < evs.length; i++) {
el = evs[i][0];
ev = evs[i][1];
el.off(ev);
}
},
_buildEvents: function () {
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}]
];
} else if (this.component && this.hasInput) { // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
} else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
} else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
mousedown: $.proxy(function (e) {
// Clicked outside the datepicker, hide it
if ($(e.target).closest('.datepicker.datepicker-inline, .datepicker.datepicker-dropdown').length === 0) {
this.hide();
}
}, this)
}]
];
},
_attachEvents: function () {
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function () {
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function () {
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function () {
this._unapplyEvents(this._secondaryEvents);
},
show: function (e) {
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
this._attachSecondaryEvents();
if (e) {
e.preventDefault();
}
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function (e) {
if (this.isInline) return;
if (!this.picker.is(':visible')) return;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.startViewMode;
this.showMode();
if (
this.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this.element.trigger({
type: 'hide',
date: this.date
});
},
remove: function () {
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput) {
delete this.element.data().date;
}
},
getDate: function () {
var d = this.getUTCDate();
return new Date(d.getTime() + (d.getTimezoneOffset() * 60000));
},
getUTCDate: function () {
return this.date;
},
setDate: function (d) {
this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset() * 60000)));
},
setUTCDate: function (d) {
this.date = d;
this.setValue();
},
setValue: function () {
var formatted = this.getFormattedDate();
if (!this.isInput) {
if (this.component) {
this.element.find('input').val(formatted);
}
this.element.data('date', formatted);
} else {
this.element.val(formatted);
}
},
getFormattedDate: function (format) {
if (format === undefined)
format = this.format;
return DPGlobal.formatDate(this.date, format, this.language);
},
setStartDate: function (startDate) {
this.startDate = startDate || -Infinity;
if (this.startDate !== -Infinity) {
this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language);
}
this.update();
this.updateNavArrows();
},
setEndDate: function (endDate) {
this.endDate = endDate || Infinity;
if (this.endDate !== Infinity) {
this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language);
}
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function (daysOfWeekDisabled) {
this.daysOfWeekDisabled = daysOfWeekDisabled || [];
if (!$.isArray(this.daysOfWeekDisabled)) {
this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
}
this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
this.update();
this.updateNavArrows();
},
place: function () {
if (this.isInline) return;
var zIndex = parseInt(this.element.parents().filter(function () {
return $(this).css('z-index') != 'auto';
}).first().css('z-index')) + 10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
this.picker.css({
top: offset.top + height,
left: offset.left,
zIndex: zIndex
});
},
_allow_update: true,
update: function () {
if (!this._allow_update) return;
var date, fromArgs = false;
if (arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
date = arguments[0];
fromArgs = true;
} else {
date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
}
this.date = DPGlobal.parseDate(date, this.format, this.language);
if (fromArgs) this.setValue();
if (this.date < this.startDate) {
this.viewDate = new Date(this.startDate);
} else if (this.date > this.endDate) {
this.viewDate = new Date(this.endDate);
} else {
this.viewDate = new Date(this.date);
}
this.fill();
},
fillDow: function () {
var dowCnt = this.weekStart,
html = '<tr>';
if (this.calendarWeeks) {
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">' + dates[this.language].daysMin[(dowCnt++) % 7] + '</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function () {
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">' + dates[this.language].monthsShort[i++] + '</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
fill: function () {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
currentDate = this.date && this.date.valueOf(),
today = new Date();
this.picker.find('.datepicker-days thead th.switch')
.text(dates[this.language].months[month] + ' ' + year);
this.picker.find('tfoot th.today')
.text(dates[this.language].today)
.toggle(this.todayBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7) % 7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while (prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() == this.weekStart) {
html.push('<tr>');
if (this.calendarWeeks) {
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">' + calWeek + '</td>');
}
}
clsName = '';
if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
clsName += ' old';
} else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
clsName += ' new';
}
// Compare internal UTC date with local today, not UTC today
if (this.todayHighlight &&
prevMonth.getUTCFullYear() == today.getFullYear() &&
prevMonth.getUTCMonth() == today.getMonth() &&
prevMonth.getUTCDate() == today.getDate()) {
clsName += ' today';
}
if (currentDate && prevMonth.valueOf() == currentDate) {
clsName += ' active';
}
if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
$.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) {
clsName += ' disabled';
}
html.push('<td class="day' + clsName + '">' + prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() == this.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date && this.date.getUTCFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear && currentYear == year) {
months.eq(this.date.getUTCMonth()).addClass('active');
}
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year == startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year == endYear) {
months.slice(endMonth + 1).addClass('disabled');
}
html = '';
year = parseInt(year / 10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year' + (i == -1 || i == 10 ? ' old' : '') + (currentYear == year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : '') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function () {
if (!this._allow_update) return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function (e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length == 1) {
switch (target[0].nodeName.toLowerCase()) {
case 'th':
switch (target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
switch (this.viewMode) {
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.todayBtn == 'linked' ? null : 'view';
this._setDate(date, which);
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this.element.trigger({
type: 'changeMonth',
date: this.viewDate
});
if (this.minViewMode == 1) {
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
} else {
var year = parseInt(target.text(), 10) || 0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this.element.trigger({
type: 'changeYear',
date: this.viewDate
});
if (this.minViewMode == 2) {
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')) {
var day = parseInt(target.text(), 10) || 1;
var year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
break;
}
}
},
_setDate: function (date, which) {
if (!which || which == 'date')
this.date = date;
if (!which || which == 'view')
this.viewDate = date;
this.fill();
this.setValue();
this.element.trigger({
type: 'changeDate',
date: this.date
});
var element;
if (this.isInput) {
element = this.element;
} else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
if (this.autoclose && (!which || which == 'date')) {
this.hide();
}
}
},
moveMonth: function (date, dir) {
if (!dir) return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag == 1) {
test = dir == -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function () {
return new_date.getUTCMonth() == month;
}
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function () {
return new_date.getUTCMonth() != new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
} else {
// For magnitudes >1, move one month at a time...
for (var i = 0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function () {
return new_month != new_date.getUTCMonth();
};
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()) {
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function (date, dir) {
return this.moveMonth(date, dir * 12);
},
dateWithinRange: function (date) {
return date >= this.startDate && date <= this.endDate;
},
keydown: function (e) {
if (this.picker.is(':not(:visible)')) {
if (e.keyCode == 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, day, month,
newDate, newViewDate;
switch (e.keyCode) {
case 27: // escape
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.keyboardNavigation) break;
dir = e.keyCode == 37 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey) {
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)) {
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 38: // up
case 40: // down
if (!this.keyboardNavigation) break;
dir = e.keyCode == 38 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey) {
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)) {
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 13: // enter
this.hide();
e.preventDefault();
break;
case 9: // tab
this.hide();
break;
}
if (dateChanged) {
this.element.trigger({
type: 'changeDate',
date: this.date
});
var element;
if (this.isInput) {
element = this.element;
} else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function (dir) {
if (dir) {
this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
}
/*
vitalets: fixing bug of very special conditions:
jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
Method show() does not set display css correctly and datepicker is not shown.
Changed to .css('display', 'block') solve the problem.
See https://github.com/vitalets/x-editable/issues/37
In jquery 1.7.2+ everything works fine.
*/
//this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
this.updateNavArrows();
}
};
$.fn.datepicker = function (option) {
var args = Array.apply(null, arguments);
args.shift();
return this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults, options))));
}
if (typeof option == 'string' && typeof data[option] == 'function') {
data[option].apply(data, args);
}
});
};
$.fn.datepicker.defaults = {};
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function (format) {
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0) {
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function (date, format, language) {
if (date instanceof Date) return date;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
var parts = date && date.match(this.nonpunctuation) || [],
date = new Date(),
parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function (d, v) {
return d.setUTCFullYear(v);
},
yy: function (d, v) {
return d.setUTCFullYear(2000 + v);
},
m: function (d, v) {
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() != v)
d.setUTCDate(d.getUTCDate() - 1);
return d;
},
d: function (d, v) {
return d.setUTCDate(v);
}
},
val, filtered, part;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length != fparts.length) {
fparts = $(fparts).filter(function (i, p) {
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
if (parts.length == fparts.length) {
for (var i = 0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch (part) {
case 'MM':
filtered = $(dates[language].months).filter(function () {
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(function () {
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
for (var i = 0, s; i < setters_order.length; i++) {
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s]))
setters_map[s](date, parsed[s]);
}
}
return date;
},
formatDate: function (date, format, language) {
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [],
seps = $.extend([], format.separators);
for (var i = 0, cnt = format.parts.length; i < cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>' +
'<tr>' +
'<th class="prev"><i class="fa fa-arrow-left"/></th>' +
'<th colspan="5" class="switch"></th>' +
'<th class="next"><i class="fa fa-arrow-right"/></th>' +
'</tr>' +
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
};
DPGlobal.template = '<div class="datepicker">' +
'<div class="datepicker-days">' +
'<table class=" table-condensed">' +
DPGlobal.headTemplate +
'<tbody></tbody>' +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-years">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
}(window.jQuery);
|
self["webpackHotUpdate_N_E"]("webpack",{},
/******/ function(__webpack_require__) { // webpackRuntimeModules
/******/ "use strict";
/******/
/******/ /* webpack/runtime/getFullHash */
/******/ !function() {
/******/ __webpack_require__.h = function() { return "960686566055d109b371"; }
/******/ }();
/******/
/******/ }
);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fTl9FL3dlYnBhY2svcnVudGltZS9nZXRGdWxsSGFzaCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7VUFBQSxvQ0FBb0MsK0JBQStCLEUiLCJmaWxlIjoic3RhdGljL3dlYnBhY2svd2VicGFjay5lMzI1MTJhMTM2MmY1MTkxMWUxNS5ob3QtdXBkYXRlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiX193ZWJwYWNrX3JlcXVpcmVfXy5oID0gZnVuY3Rpb24oKSB7IHJldHVybiBcIjk2MDY4NjU2NjA1NWQxMDliMzcxXCI7IH0iXSwic291cmNlUm9vdCI6IiJ9 |
"""
Local Density Congruence
"""
##########################################################################
## Methods which compute the local densities for representing a number
## by a quadratic form at a prime (possibly subject to additional
## congruence conditions).
##########################################################################
from copy import deepcopy
from sage.sets.set import Set
from sage.rings.rational_field import QQ
from sage.rings.arith import valuation
from sage.misc.misc import verbose
from sage.quadratic_forms.count_local_2 import count_modp__by_gauss_sum
def count_modp_solutions__by_Gauss_sum(self, p, m):
"""
Returns the number of solutions of `Q(x) = m (mod p)` of a
non-degenerate quadratic form over the finite field `Z/pZ`,
where `p` is a prime number > 2.
Note: We adopt the useful convention that a zero-dimensional
quadratic form has exactly one solution always (i.e. the empty
vector).
These are defined in Table 1 on p363 of Hanke's "Local
Densities..." paper.
INPUT:
`p` -- a prime number > 2
`m` -- an integer
OUTPUT:
an integer >= 0
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1])
sage: [Q.count_modp_solutions__by_Gauss_sum(3, m) for m in range(3)]
[9, 6, 12]
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,2])
sage: [Q.count_modp_solutions__by_Gauss_sum(3, m) for m in range(3)]
[9, 12, 6]
"""
if self.dim() == 0:
return 1
else:
return count_modp__by_gauss_sum(self.dim(), p, m, self.Gram_det())
def local_good_density_congruence_odd(self, p, m, Zvec, NZvec):
"""
Finds the Good-type local density of Q representing `m` at `p`.
(Assuming that `p` > 2 and Q is given in local diagonal form.)
The additional congruence condition arguments Zvec and NZvec can
be either a list of indices or None. Zvec = [] is equivalent to
Zvec = None which both impose no additional conditions, but NZvec
= [] returns no solutions always while NZvec = None imposes no
additional condition.
TO DO: Add type checking for Zvec, NZvec, and that Q is in local
normal form.
INPUT:
Q -- quadratic form assumed to be diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_good_density_congruence_odd(3, 1, None, None)
2/3
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_good_density_congruence_odd(3, 1, None, None)
8/9
"""
n = self.dim()
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
## Assuming Q is diagonal, find the indices of the p-unit (diagonal) entries
UnitVec = [i for i in range(n) if (self[i,i] % p) != 0]
NonUnitVec = list(Set(range(n)) - Set(UnitVec))
## Take cases on the existence of additional non-zero congruence conditions (mod p)
UnitVec_minus_Zvec = list(Set(UnitVec) - Set(Zvec))
NonUnitVec_minus_Zvec = list(Set(NonUnitVec) - Set(Zvec))
Q_Unit_minus_Zvec = self.extract_variables(UnitVec_minus_Zvec)
if (NZvec is None):
if m % p != 0:
total = Q_Unit_minus_Zvec.count_modp_solutions__by_Gauss_sum(p, m) * p**len(NonUnitVec_minus_Zvec) ## m != 0 (mod p)
else:
total = (Q_Unit_minus_Zvec.count_modp_solutions__by_Gauss_sum(p, m) - 1) * p**len(NonUnitVec_minus_Zvec) ## m == 0 (mod p)
else:
UnitVec_minus_ZNZvec = list(Set(UnitVec) - (Set(Zvec) + Set(NZvec)))
NonUnitVec_minus_ZNZvec = list(Set(NonUnitVec) - (Set(Zvec) + Set(NZvec)))
Q_Unit_minus_ZNZvec = self.extract_variables(UnitVec_minus_ZNZvec)
if m % p != 0: ## m != 0 (mod p)
total = Q_Unit_minus_Zvec.count_modp_solutions__by_Gauss_sum(p, m) * p**len(NonUnitVec_minus_Zvec) \
- Q_Unit_minus_ZNZvec.count_modp_solutions__by_Gauss_sum(p, m) * p**len(NonUnitVec_minus_ZNZvec)
else: ## m == 0 (mod p)
total = (Q_Unit_minus_Zvec.count_modp_solutions__by_Gauss_sum(p, m) - 1) * p**len(NonUnitVec_minus_Zvec) \
- (Q_Unit_minus_ZNZvec.count_modp_solutions__by_Gauss_sum(p, m) - 1) * p**len(NonUnitVec_minus_ZNZvec)
## Return the Good-type representation density
good_density = QQ(total) / p**(n-1)
return good_density
def local_good_density_congruence_even(self, m, Zvec, NZvec):
"""
Finds the Good-type local density of Q representing `m` at `p=2`.
(Assuming Q is given in local diagonal form.)
The additional congruence condition arguments Zvec and NZvec can
be either a list of indices or None. Zvec = [] is equivalent to
Zvec = None which both impose no additional conditions, but NZvec
= [] returns no solutions always while NZvec = None imposes no
additional condition.
WARNING: Here the indices passed in Zvec and NZvec represent
indices of the solution vector `x` of Q(`x`) = `m (mod p^k)`, and *not*
the Jordan components of Q. They therefore are required (and
assumed) to include either all or none of the indices of a given
Jordan component of Q. This is only important when `p=2` since
otherwise all Jordan blocks are 1x1, and so there the indices and
Jordan blocks coincide.
TO DO: Add type checking for Zvec, NZvec, and that Q is in local
normal form.
INPUT:
Q -- quadratic form assumed to be block diagonal and 2-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_good_density_congruence_even(1, None, None)
1
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_good_density_congruence_even(1, None, None)
1
sage: Q.local_good_density_congruence_even(2, None, None)
3/2
sage: Q.local_good_density_congruence_even(3, None, None)
1
sage: Q.local_good_density_congruence_even(4, None, None)
1/2
::
sage: Q = QuadraticForm(ZZ, 4, range(10))
sage: Q[0,0] = 5
sage: Q[1,1] = 10
sage: Q[2,2] = 15
sage: Q[3,3] = 20
sage: Q
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 5 1 2 3 ]
[ * 10 5 6 ]
[ * * 15 8 ]
[ * * * 20 ]
sage: Q.theta_series(20)
1 + 2*q^5 + 2*q^10 + 2*q^14 + 2*q^15 + 2*q^16 + 2*q^18 + O(q^20)
sage: Q.local_normal_form(2)
Quadratic form in 4 variables over Integer Ring with coefficients:
[ 0 1 0 0 ]
[ * 0 0 0 ]
[ * * 0 1 ]
[ * * * 0 ]
sage: Q.local_good_density_congruence_even(1, None, None)
3/4
sage: Q.local_good_density_congruence_even(2, None, None)
1
sage: Q.local_good_density_congruence_even(5, None, None)
3/4
"""
n = self.dim()
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
## Find the indices of x for which the associated Jordan blocks are non-zero mod 8 TO DO: Move this to special Jordan block code separately!
## -------------------------------------------------------------------------------
Not8vec = []
for i in range(n):
## DIAGNOSTIC
verbose(" i = " + str(i))
verbose(" n = " + str(n))
verbose(" Not8vec = " + str(Not8vec))
nz_flag = False
## Check if the diagonal entry isn't divisible 8
if ((self[i,i] % 8) != 0):
nz_flag = True
## Check appropriate off-diagonal entries aren't divisible by 8
else:
## Special check for first off-diagonal entry
if ((i == 0) and ((self[i,i+1] % 8) != 0)):
nz_flag = True
## Special check for last off-diagonal entry
elif ((i == n-1) and ((self[i-1,i] % 8) != 0)):
nz_flag = True
## Check for the middle off-diagonal entries
else:
if ( (i > 0) and (i < n-1) and (((self[i,i+1] % 8) != 0) or ((self[i-1,i] % 8) != 0)) ):
nz_flag = True
## Remember the (vector) index if it's not part of a Jordan block of norm divisible by 8
if (nz_flag == True):
Not8vec += [i]
## Compute the number of Good-type solutions mod 8:
## ------------------------------------------------
## Setup the indexing sets for additional zero congruence solutions
Q_Not8 = self.extract_variables(Not8vec)
Not8 = Set(Not8vec)
Is8 = Set(range(n)) - Not8
Z = Set(Zvec)
Z_Not8 = Not8.intersection(Z)
Z_Is8 = Is8.intersection(Z)
Is8_minus_Z = Is8 - Z_Is8
## DIAGNOSTIC
verbose("Z = " + str(Z))
verbose("Z_Not8 = " + str(Z_Not8))
verbose("Z_Is8 = " + str(Z_Is8))
verbose("Is8_minus_Z = " + str(Is8_minus_Z))
## Take cases on the existence of additional non-zero congruence conditions (mod 2)
if NZvec is None:
total = (4 ** len(Z_Is8)) * (8 ** len(Is8_minus_Z)) \
* Q_Not8.count_congruence_solutions__good_type(2, 3, m, list(Z_Not8), None)
else:
ZNZ = Z + Set(NZvec)
ZNZ_Not8 = Not8.intersection(ZNZ)
ZNZ_Is8 = Is8.intersection(ZNZ)
Is8_minus_ZNZ = Is8 - ZNZ_Is8
## DIAGNOSTIC
verbose("ZNZ = " + str(ZNZ))
verbose("ZNZ_Not8 = " + str(ZNZ_Not8))
verbose("ZNZ_Is8 = " + str(ZNZ_Is8))
verbose("Is8_minus_ZNZ = " + str(Is8_minus_ZNZ))
total = (4 ** len(Z_Is8)) * (8 ** len(Is8_minus_Z)) \
* Q_Not8.count_congruence_solutions__good_type(2, 3, m, list(Z_Not8), None) \
- (4 ** len(ZNZ_Is8)) * (8 ** len(Is8_minus_ZNZ)) \
* Q_Not8.count_congruence_solutions__good_type(2, 3, m, list(ZNZ_Not8), None)
## DIAGNOSTIC
verbose("total = " + str(total))
## Return the associated Good-type representation density
good_density = QQ(total) / 8**(n-1)
return good_density
def local_good_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the Good-type local density of Q representing `m` at `p`.
(Front end routine for parity specific routines for p.)
TO DO: Add Documentation about the additional congruence
conditions Zvec and NZvec.
INPUT:
Q -- quadratic form assumed to be block diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_good_density_congruence(2, 1, None, None)
1
sage: Q.local_good_density_congruence(3, 1, None, None)
2/3
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_good_density_congruence(2, 1, None, None)
1
sage: Q.local_good_density_congruence(3, 1, None, None)
8/9
"""
## DIAGNOSTIC
verbose(" In local_good_density_congruence with ")
verbose(" Q is: \n" + str(self))
verbose(" p = " + str(p))
verbose(" m = " + str(m))
verbose(" Zvec = " + str(Zvec))
verbose(" NZvec = " + str(NZvec))
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
n = self.dim()
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
## Check that Q is in local normal form -- should replace this with a diagonalization check?
## (it often may not be since the reduction procedure
## often mixes up the order of the valuations...)
#
#if (self != self.local_normal_form(p))
# print "Warning in local_good_density_congruence: Q is not in local normal form! \n";
## Decide which routine to use to compute the Good-type density
if (p > 2):
return self.local_good_density_congruence_odd(p, m, Zvec, NZvec)
if (p == 2):
#print "\n Using the (p=2) Local_Good_Density_Even routine! \n"
return self.local_good_density_congruence_even(m, Zvec, NZvec)
raise RuntimeError("\n Error in Local_Good_Density: The 'prime' p = " + str(p) + " is < 2. \n")
def local_zero_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the Zero-type local density of Q representing `m` at `p`,
allowing certain congruence conditions mod p.
INPUT:
Q -- quadratic form assumed to be block diagonal and `p`-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_zero_density_congruence(2, 2, None, None)
0
sage: Q.local_zero_density_congruence(2, 4, None, None)
1/2
sage: Q.local_zero_density_congruence(3, 6, None, None)
0
sage: Q.local_zero_density_congruence(3, 9, None, None)
2/9
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_zero_density_congruence(2, 2, None, None)
0
sage: Q.local_zero_density_congruence(2, 4, None, None)
1/4
sage: Q.local_zero_density_congruence(3, 6, None, None)
0
sage: Q.local_zero_density_congruence(3, 9, None, None)
8/81
"""
## DIAGNOSTIC
verbose(" In local_zero_density_congruence with ")
verbose(" Q is: \n" + str(self))
verbose(" p = " + str(p))
verbose(" m = " + str(m))
verbose(" Zvec = " + str(Zvec))
verbose(" NZvec = " + str(NZvec))
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
n = self.dim()
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
p2 = p * p
## Check some conditions for no zero-type solutions to exist
if ((m % (p2) != 0) or (NZvec is not None)):
return 0
## Use the reduction procedure to return the result
return self.local_density_congruence(p, m / p2, None, None) / p**(self.dim() - 2)
def local_badI_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the Bad-type I local density of Q representing `m` at `p`.
(Assuming that p > 2 and Q is given in local diagonal form.)
INPUT:
Q -- quadratic form assumed to be block diagonal and `p`-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_badI_density_congruence(2, 1, None, None)
0
sage: Q.local_badI_density_congruence(2, 2, None, None)
1
sage: Q.local_badI_density_congruence(2, 4, None, None)
0
sage: Q.local_badI_density_congruence(3, 1, None, None)
0
sage: Q.local_badI_density_congruence(3, 6, None, None)
0
sage: Q.local_badI_density_congruence(3, 9, None, None)
0
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_badI_density_congruence(2, 1, None, None)
0
sage: Q.local_badI_density_congruence(2, 2, None, None)
0
sage: Q.local_badI_density_congruence(2, 4, None, None)
0
sage: Q.local_badI_density_congruence(3, 2, None, None)
0
sage: Q.local_badI_density_congruence(3, 6, None, None)
0
sage: Q.local_badI_density_congruence(3, 9, None, None)
0
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,3,9])
sage: Q.local_badI_density_congruence(3, 1, None, None)
0
sage: Q.local_badI_density_congruence(3, 3, None, None)
4/3
sage: Q.local_badI_density_congruence(3, 6, None, None)
4/3
sage: Q.local_badI_density_congruence(3, 9, None, None)
0
sage: Q.local_badI_density_congruence(3, 18, None, None)
0
"""
## DIAGNOSTIC
verbose(" In local_badI_density_congruence with ")
verbose(" Q is: \n" + str(self))
verbose(" p = " + str(p))
verbose(" m = " + str(m))
verbose(" Zvec = " + str(Zvec))
verbose(" NZvec = " + str(NZvec))
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
n = self.dim()
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
## Define the indexing set S_0, and determine if S_1 is empty:
## -----------------------------------------------------------
S0 = []
S1_empty_flag = True ## This is used to check if we should be computing BI solutions at all!
## (We should really to this earlier, but S1 must be non-zero to proceed.)
## Find the valuation of each variable (which will be the same over 2x2 blocks),
## remembering those of valuation 0 and if an entry of valuation 1 exists.
for i in range(n):
## Compute the valuation of each index, allowing for off-diagonal terms
if (self[i,i] == 0):
if (i == 0):
val = valuation(self[i,i+1], p) ## Look at the term to the right
else:
if (i == n-1):
val = valuation(self[i-1,i], p) ## Look at the term above
else:
val = valuation(self[i,i+1] + self[i-1,i], p) ## Finds the valuation of the off-diagonal term since only one isn't zero
else:
val = valuation(self[i,i], p)
if (val == 0):
S0 += [i]
elif (val == 1):
S1_empty_flag = False ## Need to have a non-empty S1 set to proceed with Bad-type I reduction...
## Check that S1 is non-empty and p|m to proceed, otherwise return no solutions.
if (S1_empty_flag == True) or (m % p != 0):
return 0
## Check some conditions for no bad-type I solutions to exist
if (NZvec is not None) and (len(Set(S0).intersection(Set(NZvec))) != 0):
return 0
## Check that the form is primitive... WHY DO WE NEED TO DO THIS?!?
if (S0 == []):
print " Using Q = " + str(self)
print " and p = " + str(p)
raise RuntimeError("Oops! The form is not primitive!")
## DIAGNOSTIC
verbose(" m = " + str(m) + " p = " + str(p))
verbose(" S0 = " + str(S0))
verbose(" len(S0) = " + str(len(S0)))
## Make the form Qnew for the reduction procedure:
## -----------------------------------------------
Qnew = deepcopy(self) ## TO DO: DO THIS WITHOUT A copy(). =)
for i in range(n):
if i in S0:
Qnew[i,i] = p * Qnew[i,i]
if ((p == 2) and (i < n-1)):
Qnew[i,i+1] = p * Qnew[i,i+1]
else:
Qnew[i,i] = Qnew[i,i] / p
if ((p == 2) and (i < n-1)):
Qnew[i,i+1] = Qnew[i,i+1] / p
## DIAGNOSTIC
verbose("\n\n Check of Bad-type I reduction: \n")
verbose(" Q is " + str(self))
verbose(" Qnew is " + str(Qnew))
verbose(" p = " + str(p))
verbose(" m / p = " + str(m/p))
verbose(" NZvec " + str(NZvec))
## Do the reduction
Zvec_geq_1 = list(Set([i for i in Zvec if i not in S0]))
if NZvec is None:
NZvec_geq_1 = NZvec
else:
NZvec_geq_1 = list(Set([i for i in NZvec if i not in S0]))
return QQ(p**(1 - len(S0))) * Qnew.local_good_density_congruence(p, m / p, Zvec_geq_1, NZvec_geq_1)
def local_badII_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the Bad-type II local density of Q representing `m` at `p`.
(Assuming that `p` > 2 and Q is given in local diagonal form.)
INPUT:
Q -- quadratic form assumed to be block diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_badII_density_congruence(2, 1, None, None)
0
sage: Q.local_badII_density_congruence(2, 2, None, None)
0
sage: Q.local_badII_density_congruence(2, 4, None, None)
0
sage: Q.local_badII_density_congruence(3, 1, None, None)
0
sage: Q.local_badII_density_congruence(3, 6, None, None)
0
sage: Q.local_badII_density_congruence(3, 9, None, None)
0
sage: Q.local_badII_density_congruence(3, 27, None, None)
0
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,3,9,9])
sage: Q.local_badII_density_congruence(3, 1, None, None)
0
sage: Q.local_badII_density_congruence(3, 3, None, None)
0
sage: Q.local_badII_density_congruence(3, 6, None, None)
0
sage: Q.local_badII_density_congruence(3, 9, None, None)
4/27
sage: Q.local_badII_density_congruence(3, 18, None, None)
4/9
"""
## DIAGNOSTIC
verbose(" In local_badII_density_congruence with ")
verbose(" Q is: \n" + str(self))
verbose(" p = " + str(p))
verbose(" m = " + str(m))
verbose(" Zvec = " + str(Zvec))
verbose(" NZvec = " + str(NZvec))
## Put the Zvec congruence condition in a standard form
if Zvec is None:
Zvec = []
n = self.dim()
## Sanity Check on Zvec and NZvec:
## -------------------------------
Sn = Set(range(n))
if (Zvec is not None) and (len(Set(Zvec) + Sn) > n):
raise RuntimeError("Zvec must be a subset of {0, ..., n-1}.")
if (NZvec is not None) and (len(Set(NZvec) + Sn) > n):
raise RuntimeError("NZvec must be a subset of {0, ..., n-1}.")
## Define the indexing sets S_i:
## -----------------------------
S0 = []
S1 = []
S2plus = []
for i in range(n):
## Compute the valuation of each index, allowing for off-diagonal terms
if (self[i,i] == 0):
if (i == 0):
val = valuation(self[i,i+1], p) ## Look at the term to the right
elif (i == n-1):
val = valuation(self[i-1,i], p) ## Look at the term above
else:
val = valuation(self[i,i+1] + self[i-1,i], p) ## Finds the valuation of the off-diagonal term since only one isn't zero
else:
val = valuation(self[i,i], p)
## Sort the indices into disjoint sets by their valuation
if (val == 0):
S0 += [i]
elif (val == 1):
S1 += [i]
elif (val >= 2):
S2plus += [i]
## Check that S2 is non-empty and p^2 divides m to proceed, otherwise return no solutions.
p2 = p * p
if (S2plus == []) or (m % p2 != 0):
return 0
## Check some conditions for no bad-type II solutions to exist
if (NZvec is not None) and (len(Set(S2plus).intersection(Set(NZvec))) == 0):
return 0
## Check that the form is primitive... WHY IS THIS NECESSARY?
if (S0 == []):
print " Using Q = " + str(self)
print " and p = " + str(p)
raise RuntimeError("Oops! The form is not primitive!")
## DIAGNOSTIC
verbose("\n Entering BII routine ")
verbose(" S0 is " + str(S0))
verbose(" S1 is " + str(S1))
verbose(" S2plus is " + str(S2plus))
verbose(" m = " + str(m) + " p = " + str(p))
## Make the form Qnew for the reduction procedure:
## -----------------------------------------------
Qnew = deepcopy(self) ## TO DO: DO THIS WITHOUT A copy(). =)
for i in range(n):
if i in S2plus:
Qnew[i,i] = Qnew[i,i] / p2
if (p == 2) and (i < n-1):
Qnew[i,i+1] = Qnew[i,i+1] / p2
## DIAGNOSTIC
verbose("\n\n Check of Bad-type II reduction: \n")
verbose(" Q is " + str(self))
verbose(" Qnew is " + str(Qnew))
## Perform the reduction formula
Zvec_geq_2 = list(Set([i for i in Zvec if i in S2plus]))
if NZvec is None:
NZvec_geq_2 = NZvec
else:
NZvec_geq_2 = list(Set([i for i in NZvec if i in S2plus]))
return QQ(p**(len(S2plus) + 2 - n)) \
* (Qnew.local_density_congruence(p, m / p2, Zvec_geq_2, NZvec_geq_2) \
- Qnew.local_density_congruence(p, m / p2, S2plus , NZvec_geq_2))
def local_bad_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the Bad-type local density of Q representing
`m` at `p`, allowing certain congruence conditions mod `p`.
INPUT:
Q -- quadratic form assumed to be block diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_bad_density_congruence(2, 1, None, None)
0
sage: Q.local_bad_density_congruence(2, 2, None, None)
1
sage: Q.local_bad_density_congruence(2, 4, None, None)
0
sage: Q.local_bad_density_congruence(3, 1, None, None)
0
sage: Q.local_bad_density_congruence(3, 6, None, None)
0
sage: Q.local_bad_density_congruence(3, 9, None, None)
0
sage: Q.local_bad_density_congruence(3, 27, None, None)
0
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,3,9,9])
sage: Q.local_bad_density_congruence(3, 1, None, None)
0
sage: Q.local_bad_density_congruence(3, 3, None, None)
4/3
sage: Q.local_bad_density_congruence(3, 6, None, None)
4/3
sage: Q.local_bad_density_congruence(3, 9, None, None)
4/27
sage: Q.local_bad_density_congruence(3, 18, None, None)
4/9
sage: Q.local_bad_density_congruence(3, 27, None, None)
8/27
"""
return self.local_badI_density_congruence(p, m, Zvec, NZvec) + self.local_badII_density_congruence(p, m, Zvec, NZvec)
#########################################################
## local_density and local_density_congruence routines ##
#########################################################
def local_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the local density of Q representing `m` at `p`,
allowing certain congruence conditions mod `p`.
INPUT:
Q -- quadratic form assumed to be block diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_density_congruence(p=2, m=1, Zvec=None, NZvec=None)
1
sage: Q.local_density_congruence(p=3, m=1, Zvec=None, NZvec=None)
8/9
sage: Q.local_density_congruence(p=5, m=1, Zvec=None, NZvec=None)
24/25
sage: Q.local_density_congruence(p=7, m=1, Zvec=None, NZvec=None)
48/49
sage: Q.local_density_congruence(p=11, m=1, Zvec=None, NZvec=None)
120/121
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_density_congruence(2, 1, None, None)
1
sage: Q.local_density_congruence(2, 2, None, None)
1
sage: Q.local_density_congruence(2, 4, None, None)
3/2
sage: Q.local_density_congruence(3, 1, None, None)
2/3
sage: Q.local_density_congruence(3, 6, None, None)
4/3
sage: Q.local_density_congruence(3, 9, None, None)
14/9
sage: Q.local_density_congruence(3, 27, None, None)
2
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,3,9,9])
sage: Q.local_density_congruence(3, 1, None, None)
2
sage: Q.local_density_congruence(3, 3, None, None)
4/3
sage: Q.local_density_congruence(3, 6, None, None)
4/3
sage: Q.local_density_congruence(3, 9, None, None)
2/9
sage: Q.local_density_congruence(3, 18, None, None)
4/9
"""
return self.local_good_density_congruence(p, m, Zvec, NZvec) \
+ self.local_zero_density_congruence(p, m, Zvec, NZvec) \
+ self.local_bad_density_congruence(p, m, Zvec, NZvec)
def local_primitive_density_congruence(self, p, m, Zvec=None, NZvec=None):
"""
Finds the primitive local density of Q representing
`m` at `p`, allowing certain congruence conditions mod `p`.
Note: The following routine is not used internally, but is included for consistency.
INPUT:
Q -- quadratic form assumed to be block diagonal and p-integral
`p` -- a prime number
`m` -- an integer
Zvec, NZvec -- non-repeating lists of integers in range(self.dim()) or None
OUTPUT:
a rational number
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
sage: Q.local_primitive_density_congruence(p=2, m=1, Zvec=None, NZvec=None)
1
sage: Q.local_primitive_density_congruence(p=3, m=1, Zvec=None, NZvec=None)
8/9
sage: Q.local_primitive_density_congruence(p=5, m=1, Zvec=None, NZvec=None)
24/25
sage: Q.local_primitive_density_congruence(p=7, m=1, Zvec=None, NZvec=None)
48/49
sage: Q.local_primitive_density_congruence(p=11, m=1, Zvec=None, NZvec=None)
120/121
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,2,3])
sage: Q.local_primitive_density_congruence(2, 1, None, None)
1
sage: Q.local_primitive_density_congruence(2, 2, None, None)
1
sage: Q.local_primitive_density_congruence(2, 4, None, None)
1
sage: Q.local_primitive_density_congruence(3, 1, None, None)
2/3
sage: Q.local_primitive_density_congruence(3, 6, None, None)
4/3
sage: Q.local_primitive_density_congruence(3, 9, None, None)
4/3
sage: Q.local_primitive_density_congruence(3, 27, None, None)
4/3
::
sage: Q = DiagonalQuadraticForm(ZZ, [1,3,3,9,9])
sage: Q.local_primitive_density_congruence(3, 1, None, None)
2
sage: Q.local_primitive_density_congruence(3, 3, None, None)
4/3
sage: Q.local_primitive_density_congruence(3, 6, None, None)
4/3
sage: Q.local_primitive_density_congruence(3, 9, None, None)
4/27
sage: Q.local_primitive_density_congruence(3, 18, None, None)
4/9
sage: Q.local_primitive_density_congruence(3, 27, None, None)
8/27
sage: Q.local_primitive_density_congruence(3, 81, None, None)
8/27
sage: Q.local_primitive_density_congruence(3, 243, None, None)
8/27
"""
return self.local_good_density_congruence(p, m, Zvec, NZvec) \
+ self.local_bad_density_congruence(p, m, Zvec, NZvec)
|
angular.module('ovh-api-services').service('OvhApiXdslModemAvailableWLANChannel', ($injector, $cacheFactory) => {
const cache = $cacheFactory('OvhApiXdslModemAvailableWLANChannel');
return {
v6() {
return $injector.get('OvhApiXdslModemAvailableWLANChannelV6');
},
resetCache: cache.removeAll,
cache,
};
});
|
# *****************************************************************************
# *****************************************************************************
#
# Name: asmtables.py
# Author: Paul Robson ([email protected])
# Date: 13th March 2021
# Purpose: Generate various tables (assembler specific)
#
# *****************************************************************************
# *****************************************************************************
from tokens import *
import os,re,sys
t = Tokens()
header= ";\n;\tAutomatically generated\n;\n" # header used.
genDir = "../source/generated/".replace("/",os.sep)
#
groupStart = [ 0 ] * 6
n = t.getBaseAsmToken()
while t.getFromID(1,n) is not None:
info = t.getAsmInfo(t.getFromID(1,n)["token"])
lvl = int(info[2])
if groupStart[lvl] == 0:
groupStart[lvl] = n
n = n + 1
groupStart[5] = n
#
# Create the constants table.
#
h = open(genDir+"asmconst.inc","w")
h.write(header)
for i in range(1,5):
h.write("TKA_GROUP{0} = ${1:02x}\n".format(i,groupStart[i]))
h.write("TKA_END4 = ${0:02x}\n\n".format(groupStart[5] ))
h.close()
#
# Create the data tables for assembler.
#
h = open(genDir+"asmtables.inc","w")
h.write(header)
#
# Token ID to Opcode
#
h.write("OpcodeTable:\n")
for i in range(groupStart[1],groupStart[5]):
m = t.getFromID(1,i)
opcode = int(t.getAsmInfo(m["token"])[0],16)
h.write("\t.byte\t${0:02x}\t\t\t; ${1:02x} {2}\n".format(opcode,i,m["token"].lower()))
h.write("\n")
#
# Group 2 Usage
#
h.write("Group2OpcodeAvailability:\n")
for i in range(groupStart[2],groupStart[3]):
m = t.getFromID(1,i)
info = t.getAsmInfo(m["token"])
opcode = int(info[0],16)
bitMask = 0
for b in range(0,8):
if info[b+3] != "":
bitMask += (1 << b)
h.write("\t.byte\t${0:02x}\t\t\t; ${1:02x} {2} ${3:02x}\n".format(bitMask,i,m["token"].lower(),opcode))
h.write("\n")
#
# Special cases (token,mode,opcode), ends with token 0
#
h.write("AssemblerSpecialCases:\n")
for c in t.getAsmSpecialCases():
token = t.getFromToken(c[1])
h.write("\t.byte\t${1:02x},{2},${0:02x}\t\t; {3} {4}\n".format(int(c[0],16),token["id"],c[3],c[1],c[4]))
h.write("\t.byte\t0\n")
h.close()
|
const Joi = require('joi');
const mongoose = require('mongoose');
const ticket = mongoose.model('Ticket', new mongoose.Schema({
client:{
type: mongoose.Schema.Types.ObjectId,
ref: 'client',
},
parts: [
type: mongoose.Schema.Types.ObjectId,
ref: 'part',
],
notes: {
type: String,
minlength: 0,
maxlength: 1000
},
creationDate:{
type:Date,
required: True
},
appointmentDate:{
type:Date,
required:True
},
deviceModel:{
type: String,
required: True,
maxlength: 50
},
deviceColor: {
type: String,
required: True,
maxlength: 50
},
deviceIMEI:{
type: String,
required: True,
maxlength: 14
},
description:{
type: String,
required: True,
maxlength: 1000
},
deviceCode:{
type: String,
required: True,
maxlength: 6
},
status:{
type:String,
maxlength: 20
},
protection:{
type:String,
maxlength: 20
},
issues:[
type: String,
maxlength: 20
],
appleID:{
type: String,
maxlength: 50
},
appleIDPassword:{
type: String,
maxlength: 25
}
}));
function validatePart(part) {
const schema = {
notes: Joi.string().min(0).max(1000).required(),
creationDate: Joi.date().required(),
appointmentDate: Joi.date().required(),
deviceModel: Joi.string().max(50).required(),
description: Joi.string().max(1000),
deviceCode: Joi.string().max(6),
protection: Joi.string().max(20),
appleID: Joi.string().max(50),
appleIDPassword: Joi.string().max(25)
};
return Joi.validate(ticket, schema);
}
exports.Tickets = Ticket;
exports.validate = validateTicket;
|
const User = require("../user");
const email = require("../services/email");
const {
connectMongoose,
clearDatabase,
disconnectMongoose,
request
} = require("../../test/util");
jest.mock("../services/email");
beforeAll(connectMongoose);
beforeEach(clearDatabase);
afterAll(disconnectMongoose);
test("GET /users should returns a list of users", async () => {
await User.create([
{ name: "John Doe", email: "[email protected]" },
{ name: "Joana Doe", email: "[email protected]" }
]);
const res = await request().get("/users");
expect(res.status).toBe(200);
expect(res.body.length).toBe(2);
});
test("GET /users/:id should return an user by the given id", async () => {
const userParam = { name: "John Doe", email: "[email protected]" };
const user = await User.create(userParam);
const res = await request().get(`/users/${user.id}`);
expect(res.status).toBe(200);
expect(res.body.name).toBe(userParam.name);
expect(res.body.email).toBe(userParam.email);
});
test("POST /users should create a new user", async () => {
const userParam = { name: "John Doe", email: "[email protected]" };
const res = await request()
.post("/users")
.send({ user: userParam });
expect(res.status).toBe(201);
expect(res.body.name).toBe(userParam.name);
expect(res.body.email).toBe(userParam.email);
});
test("PUT /users/:id should update an user", async () => {
const user = await User.create({
name: "John Doe",
email: "[email protected]"
});
const userParams = { name: "Joana Doe", email: "[email protected]" };
const res = await request()
.put(`/users/${user.id}`)
.send({ user: userParams });
expect(res.status).toBe(200);
expect(res.body.name).toBe(userParams.name);
expect(res.body.email).toBe(userParams.email);
});
test("DELETE /users/:id should delete an user", async () => {
const user = await User.create({
name: "John Doe",
email: "[email protected]"
});
const res = await request().delete(`/users/${user.id}`);
expect(res.status).toBe(204);
expect(await User.findById(user.id)).toBe(null);
});
test("POST /raffle should raffle the users", async () => {
await User.create([
{ name: "John Doe", email: "[email protected]" },
{ name: "Joana Doe", email: "[email protected]" },
{ name: "Joe Doe", email: "[email protected]" }
]);
const res = await request().post("/raffle");
expect(res.status).toBe(200);
expect(res.body.message).toBe("Draw was successful");
});
test("POST /raffle should send emails to the participants", async () => {
await User.create([
{ name: "John Doe", email: "[email protected]" },
{ name: "Joana Doe", email: "[email protected]" },
{ name: "Joe Doe", email: "[email protected]" }
]);
await request().post("/raffle");
expect(email.sendRaffleEmail).toBeCalled();
});
|
import React, { useEffect } from 'react';
const MyNotes = () => {
useEffect(() => {
// update the document title
document.title = 'My Notes — Notedly';
});
return (
<div>
<p>These are my notes</p>
</div>
);
};
export default MyNotes;
|
"""
Print all permutations of a string
"""
def permutate(str_list: list, start: int, end: int) -> None:
"""
Time Complexity: O(n*n!)
"""
if start == end:
print("".join(str_list)) # O(n)
else:
for i in range(start, end + 1):
str_list[start], str_list[i] = str_list[i], str_list[start]
permutate(str_list, start + 1, end)
str_list[start], str_list[i] = str_list[i], str_list[start]
if __name__ == "__main__":
print("permutation of ABC:")
permutate(list("ABC"), 0, 2)
print("Permutation of ABCD")
permutate(list("ABCDE"), 0, 3)
|
var searchData=
[
['clienthandler_2ecpp_30',['clienthandler.cpp',['../clienthandler_8cpp.html',1,'']]],
['clienthandler_2eh_31',['clienthandler.h',['../clienthandler_8h.html',1,'']]]
];
|
/*!
* delims <https://github.com/jonschlinkert/delims>
*
* Copyright (c) 2014 Jon Schlinkert
* Licensed under the MIT license.
*/
'use strict';
var merge = require('mixin-deep');
var arrayify = require('arrayify-compact');
// Escape custom template delimiters
exports.escapeDelim = function (re) {
return re.replace(/(.)/g, '\\$1');
};
// Build RegExp patterns for delimiters
exports.buildRegexGroup = function (re, options) {
var opts = merge({
escape: false, // Escape delimiter regex
noncapture: false // Build a non-capture group
}, options);
re = arrayify(re);
var len = re.length;
re = (len > 0) ? re.join('|') : re;
re = (opts.escape === true)
? exports.escapeDelim(re)
: re;
if(opts.noncapture === true || len > 1) {
re = '(?:' + re + ')';
}
return re;
};
|
(this.webpackJsonpclient=this.webpackJsonpclient||[]).push([[0],{100:function(e,t,a){},136:function(e,t){},139:function(e,t,a){},182:function(e,t,a){},183:function(e,t,a){},184:function(e,t,a){},185:function(e,t,a){},186:function(e,t,a){},187:function(e,t,a){},188:function(e,t,a){"use strict";a.r(t);var n,r=a(0),l=a.n(r),c=a(23),s=a.n(c),o=a(15),m=a(4),i=a(11),u=a(25),E=a(26),h=a(30),g=a(29),f=a(27),p=a.n(f),b=a(189),A=a(190),d=a(191),v=a(195),N=a(192),y=a(193),O=a(194),C=function(e){Object(h.a)(a,e);var t=Object(g.a)(a);function a(){var e;Object(u.a)(this,a);for(var n=arguments.length,r=new Array(n),l=0;l<n;l++)r[l]=arguments[l];return(e=t.call.apply(t,[this].concat(r))).state={isOpen:!1},e.toggle=function(){e.setState({isOpen:!e.state.isOpen})},e}return Object(E.a)(a,[{key:"render",value:function(){return l.a.createElement("div",null,l.a.createElement(b.a,{style:S,dark:!0,expand:"sm",className:"mb-2"},l.a.createElement(A.a,{style:j,href:"/"},l.a.createElement("img",{src:p.a,alt:"bee img",style:{width:100,height:100}}),"The Chat Bee"),l.a.createElement(d.a,{onClick:this.toggle}),l.a.createElement(v.a,{isOpen:this.state.isOpen,navbar:!0},l.a.createElement(N.a,{className:"ml-auto",navbar:!0},l.a.createElement(y.a,{style:I},l.a.createElement(o.b,{to:"/About"},l.a.createElement(O.a,null,"About"))),l.a.createElement(y.a,{style:I},l.a.createElement(O.a,{href:"https://github.com/Monil007/thechatbee"},"Git Repository"))))))}}]),a}(r.Component),j={padding:"0.75rem",color:"rgb(255, 215, 103)",fontSize:"2.5rem",fontWeight:"700",fontFamily:"Georgia",float:"right",backgroundColor:"Navy"},S={backgroundColor:"navy"},I={fontSize:"1.5rem"},k=C,x=(a(51),a(100),function(){var e=Object(r.useState)(""),t=Object(i.a)(e,2),a=t[0],n=t[1],c=Object(r.useState)(""),s=Object(i.a)(c,2),m=s[0],u=s[1];return l.a.createElement("div",null,l.a.createElement("div",null,l.a.createElement(k,null)),l.a.createElement("div",{className:"joinOuterContainer"},l.a.createElement("div",{className:"joinInnerContainer"},l.a.createElement("h1",{className:"heading"},"Get Started"),l.a.createElement("div",null,l.a.createElement("input",{placeholder:"Name",className:"joinInput",type:"text",onChange:function(e){return n(e.target.value)}})),l.a.createElement("div",null,l.a.createElement("input",{placeholder:"Hive",className:"joinInput mt-20",type:"text",onChange:function(e){return u(e.target.value)}})),l.a.createElement(o.b,{onClick:function(e){return a&&m?null:e.preventDefault()},to:"/chat?name=".concat(a,"&room=").concat(m)},l.a.createElement("button",{className:"button mt-20",type:"submit"},"Sign In")))))}),w=a(82),M=a(77),B=a.n(M),R=a(78),U=a.n(R),z=a(28),G=a.n(z),T=(a(139),function(e){var t=e.users;return l.a.createElement("div",{className:"textContainer"},t?l.a.createElement("div",{className:"activeContainer"},l.a.createElement("h4",null,"Online:"),l.a.createElement("h4",null,t.map((function(e){var t=e.name;return l.a.createElement("div",{key:t,className:"activeItem"},l.a.createElement("img",{classname:"activeImg",alt:"Online Icon",src:G.a}),"\xa0 ",t)})))):null)}),W=a(79),K=a.n(W),J=(a(182),a(80)),P=a.n(J),Q=function(e){var t=e.message,a=t.user,n=t.text,r=!1,c=e.name.trim().toLowerCase();return a===c&&(r=!0),r?l.a.createElement("div",{className:"messageContainer justifyEnd"},l.a.createElement("p",{className:"sentText pr-10"},c),l.a.createElement("div",{className:"messageBox backgroundNavy"},l.a.createElement("p",{className:"messageText colorWhite"},P.a.emojify(n)))):l.a.createElement("div",{className:"messageContainer justifyStart"},l.a.createElement("div",{className:"messageBox backgroundLight"},l.a.createElement("p",{className:"messageText colorDark"},n)),l.a.createElement("p",{className:"sentText pl-10"},a))},Y=(a(183),function(e){var t=e.messages,a=e.name;return l.a.createElement(K.a,{className:"messages"},t.map((function(e,t){return l.a.createElement("div",{key:t},l.a.createElement(Q,{message:e,name:a}))})))}),D=a(81),F=a.n(D),V=(a(184),function(e){var t=e.room;return l.a.createElement("div",{className:"infoBar"},l.a.createElement("div",{className:"leftInnerContainer"},l.a.createElement("img",{className:"onlineIcon",src:G.a,alt:"online"}),l.a.createElement("h3",null,t)),l.a.createElement("div",{className:"rightInnerContainer"},l.a.createElement("a",{href:"/"},l.a.createElement("img",{src:F.a,alt:"close"}))))}),L=(a(185),function(e){var t=e.message,a=e.setMessage,n=e.sendMessage;return l.a.createElement("form",{className:"form"},l.a.createElement("input",{className:"input",type:"text",placeholder:"Type a message...",value:t,onChange:function(e){return a(e.target.value)},onKeyPress:function(e){return"Enter"===e.key?n(e):null}}),l.a.createElement("button",{className:"sendButton",onClick:function(e){return n(e)}},"Send"))}),q=function(e){Object(h.a)(a,e);var t=Object(g.a)(a);function a(){var e;Object(u.a)(this,a);for(var n=arguments.length,r=new Array(n),l=0;l<n;l++)r[l]=arguments[l];return(e=t.call.apply(t,[this].concat(r))).state={isOpen:!1},e.toggle=function(){e.setState({isOpen:!e.state.isOpen})},e}return Object(E.a)(a,[{key:"render",value:function(){return l.a.createElement("div",null,l.a.createElement(b.a,{style:X,dark:!0,expand:"sm",className:"mb-2"},l.a.createElement(A.a,{style:H,href:"/"},l.a.createElement("img",{src:p.a,alt:"bee img",style:{width:100,height:100}}),"The Chat Bee"),l.a.createElement(d.a,{onClick:this.toggle}),l.a.createElement(v.a,{isOpen:this.state.isOpen,navbar:!0},l.a.createElement(N.a,{className:"ml-auto",navbar:!0},l.a.createElement(y.a,{style:Z},l.a.createElement(O.a,{href:"/"},"Join")),l.a.createElement(y.a,{style:Z},l.a.createElement(O.a,{href:"https://github.com/Monil007/thechatbee"},"Git Repository"))))))}}]),a}(r.Component),H={padding:"0.75rem",color:"rgb(255, 215, 103)",fontSize:"2.5rem",fontWeight:"700",fontFamily:"Georgia",float:"right",backgroundColor:"Navy"},X={backgroundColor:"navy"},Z={fontSize:"1.5rem"},$=q,_=(a(186),function(e){var t=e.location,a=Object(r.useState)(""),c=Object(i.a)(a,2),s=c[0],o=c[1],m=Object(r.useState)(""),u=Object(i.a)(m,2),E=u[0],h=u[1],g=Object(r.useState)(""),f=Object(i.a)(g,2),p=f[0],b=f[1],A=Object(r.useState)(""),d=Object(i.a)(A,2),v=d[0],N=d[1],y=Object(r.useState)([]),O=Object(i.a)(y,2),C=O[0],j=O[1],S="https://chat-bee-app.herokuapp.com/";Object(r.useEffect)((function(){var e=B.a.parse(t.search),a=e.name,r=e.room;n=U()(S),h(r),o(a),n.emit("join",{name:a,room:r},(function(e){e&&alert(e)}))}),[S,t.search]),Object(r.useEffect)((function(){n.on("message",(function(e){j((function(t){return[].concat(Object(w.a)(t),[e])}))})),n.on("roomData",(function(e){var t=e.users;b(t)}))}),[]);return l.a.createElement("div",null,l.a.createElement("div",null,l.a.createElement($,null)),l.a.createElement("div",{className:"outerContainer"},l.a.createElement("div",{className:"container"},l.a.createElement(V,{room:E}),l.a.createElement(Y,{messages:C,name:s}),l.a.createElement(L,{message:v,setMessage:N,sendMessage:function(e){e.preventDefault(),v&&n.emit("sendMessage",v,(function(){return N("")}))}})),l.a.createElement(T,{users:p})))}),ee=(a(187),function(){return l.a.createElement("div",null,l.a.createElement("div",null,l.a.createElement($,null)),l.a.createElement("div",{className:"aboutOuterContainer"},l.a.createElement("div",{className:"aboutInnerContainer"},l.a.createElement("h1",{className:"aboutHeading"},"What's the Buzzz?")," ",l.a.createElement("hr",{className:"hr"}),l.a.createElement("h3",{className:"aboutAuthor"},"Author: Monil Kaneria"),l.a.createElement("br",null),l.a.createElement("p",{className:"aboutPara"},"This is a free online chat app!"),l.a.createElement("p",{className:"aboutPara"},"It lets you chat with your friends without worrying about data piracy."),l.a.createElement("br",null),l.a.createElement("p",{className:"aboutPara"},"To start chatting with your friends follow the steps..."),l.a.createElement("ol",{className:"aboutOl"},l.a.createElement("li",{className:"aboutOl"},"Go to Join."),l.a.createElement("li",{className:"aboutOl"},"Write your name in the Name tab."),l.a.createElement("li",{className:"aboutOl"},"Write a Hive name. Make sure that every ","person in your chat enters the same hive.")),l.a.createElement("ul",{className:"aboutUl"},l.a.createElement("li",{className:"aboutUl"},l.a.createElement("strong",null,"Note:")," This chat doesn't store your data."," ","Hence, all the chat history will be","deleted once you leave the chat.")),l.a.createElement("br",null),l.a.createElement("h4",{className:"aboutPara"},l.a.createElement("strong",null,"Keep Buzzzing!!!")))))}),te=function(){return l.a.createElement(o.a,null,l.a.createElement(m.a,{path:"/",exact:!0,component:x}),l.a.createElement(m.a,{path:"/chat",component:_}),l.a.createElement(m.a,{path:"/About",component:ee}))};s.a.render(l.a.createElement(te,null),document.querySelector("#root"))},27:function(e,t,a){e.exports=a.p+"static/media/beeicon.c97effa6.ico"},28:function(e,t){e.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAAXNSR0IArs4c6QAAAExJREFUCB1jbPh/le3lx5tNDIwMcQwg8J9hkTi/eh0LWJCBoRwoAAPlQDEGJrhKmDCIBupmQuYjs5lAZiILgNlAMRaQRSAz4UZCLQcAIwYaiAejKoYAAAAASUVORK5CYII="},81:function(e,t){e.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAAHBJREFUGBmNkAEKwCAMA2VfGP2mrx3sOV2us6IymIXQGlNTW9zdhCqcZQm4dmelFUp+CZZa6sYpeUVIFyIixMqjCO51Wy5unQExuYSbSF5JASLqPsqRM21lOoWc89tagr3PSMgOiWlwnUeXWA/E78IfuAX270S3ydAAAAAASUVORK5CYII="},84:function(e,t,a){e.exports=a(188)}},[[84,1,2]]]);
//# sourceMappingURL=main.527a3c44.chunk.js.map |
import os
import scipy.signal
import sklearn.utils
import numpy as np
import tensorflow as tf
from sklearn.model_selection import KFold
class DataReader(object):
def __init__(self, input_size, output_size, x_range, y_range, cross_val=5, val_fold=0, batch_size=100,
shuffle_size=100, data_dir=os.path.dirname(__file__), rand_seed=1234):
"""
Initialize a data reader
:param input_size: input size of the arrays
:param output_size: output size of the arrays
:param x_range: columns of input data in the txt file
:param y_range: columns of output data in the txt file
:param cross_val: number of cross validation folds
:param val_fold: which fold to be used for validation
:param batch_size: size of the batch read every time
:param shuffle_size: size of the batch when shuffle the dataset
:param data_dir: parent directory of where the data is stored, by default it's the current directory
:param rand_seed: random seed
"""
self.input_size = input_size
self.output_size = output_size
self.x_range = x_range
self.y_range = y_range
self.cross_val = cross_val
self.val_fold = val_fold
self.batch_size = batch_size
self.shuffle_zie = shuffle_size
self.data_dir = data_dir
np.random.seed(rand_seed)
def data_reader(self, is_train, train_valid_tuple):
"""
Read feature and label
:param is_train: the dataset is used for training or not
:param train_valid_tuple: if it's not none, it will be the names of train and valid files
:return: feature and label read from csv files, one line each time
"""
if not train_valid_tuple:
data_file = os.path.join(self.data_dir, 'data', 'UnitCellData_V7.txt')
x = np.loadtxt(data_file, delimiter=',', usecols=self.x_range)
y = np.loadtxt(data_file, delimiter=',', usecols=self.y_range)
y = scipy.signal.resample(y, self.output_size, axis=1)
(x, y) = sklearn.utils.shuffle(x, y, random_state=0)
kf = KFold(n_splits=self.cross_val)
for cnt, (train_idx, valid_idx) in enumerate(kf.split(x)):
if cnt == self.val_fold:
if is_train:
ftr, lbl = x[train_idx, :], y[train_idx, :]
else:
valid_num = valid_idx.shape[0] // self.batch_size * self.batch_size
ftr, lbl = x[valid_idx[:valid_num], :], y[valid_idx[:valid_num], :]
for (f, l) in zip(ftr, lbl):
yield f, l
else:
train_data_file = os.path.join(self.data_dir, 'data', train_valid_tuple[0])
valid_data_file = os.path.join(self.data_dir, 'data', train_valid_tuple[1])
if is_train:
ftr = np.loadtxt(train_data_file, delimiter=',', usecols=self.x_range)
lbl = np.loadtxt(train_data_file, delimiter=',', usecols=self.y_range)
else:
ftr = np.loadtxt(valid_data_file, delimiter=',', usecols=self.x_range)
lbl = np.loadtxt(valid_data_file, delimiter=',', usecols=self.y_range)
lbl = scipy.signal.resample(lbl, self.output_size, axis=1)
for (f, l) in zip(ftr, lbl):
yield f, l
def get_dataset(self, train_valid_tuple):
"""
Create a tf.Dataset from the generator defined
:param train_valid_tuple: if it's not none, it will be the names of train and valid files
:return: a tf.Dataset object
"""
def generator_train(): return self.data_reader(True, train_valid_tuple)
def generator_valid(): return self.data_reader(False, train_valid_tuple)
dataset_train = tf.data.Dataset.from_generator(generator_train, (tf.float32, tf.float32),
(self.input_size, self.output_size))
dataset_valid = tf.data.Dataset.from_generator(generator_valid, (tf.float32, tf.float32),
(self.input_size, self.output_size))
return dataset_train, dataset_valid
def get_data_holder_and_init_op(self, train_valid_tuple=None):
"""
Get tf iterator as well as init operation for both training and validation
:param train_valid_tuple: if it's not none, it will be the names of train and valid files
:return: features, labels, training init operation, validation init operation
"""
dataset_train, dataset_valid = self.get_dataset(train_valid_tuple)
dataset_train = dataset_train.shuffle(self.shuffle_zie)
dataset_train = dataset_train.repeat()
dataset_train = dataset_train.batch(self.batch_size)
dataset_valid = dataset_valid.batch(self.batch_size)
iterator = tf.data.Iterator.from_structure(dataset_train.output_types, dataset_train.output_shapes)
features, labels = iterator.get_next()
train_init_op = iterator.make_initializer(dataset_train)
valid_init_op = iterator.make_initializer(dataset_valid)
return features, labels, train_init_op, valid_init_op
|
import Store from "../index";
/**
* Initiate your global store with default state.
*/
const { state, listen, detach } = Store({
count: 5
}, true );
/**
* Set up initial content.
*/
const countEl = document.querySelector("#count");
countEl.innerHTML = JSON.stringify({count: 0});
const stateEl = document.querySelector("#state");
stateEl.innerHTML = JSON.stringify(state);
/**
* Global listener.
*/
listen(newState => stateEl.innerHTML = JSON.stringify(newState))
/**
* Methods to adjust the state.
*/
window.add = () => state.count++;
window.sub = () => state.count--;
/**
* Allow resetting of the DOM and state.
*/
window.reset = () => {
state.count = 5;
countEl.innerHTML = JSON.stringify({count: 0})
detach('count')
}
/**
* Opt-in listeners.
*/
window.listen = () => {
countEl.innerHTML = JSON.stringify( state )
listen(newState =>
countEl.innerHTML = JSON.stringify(newState),
'count'
)
}
window.detach = () => {
detach('count');
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Policy provides an api for specifying how each parsed field should
* be treated, as well as what to do with fields not specified (discard or keep?).
*
* The actual policy is specified by an map of key value pairs where each key represents
* a field and its value should be one of boolean, string, function.
*
* Boolean values are decided by child classes of this Policy.
* String values must be one of the recongnized filter operators and will replace whatever
* was parsed.
* Functions are applied to the value allowing validation, transformation etc before the final
* query is used.
*
* @abstract
* @param {object} fields
*/
var Policy = function () {
function Policy(fields) {
_classCallCheck(this, Policy);
this.__fields = fields;
}
_createClass(Policy, [{
key: '_getFilter',
value: function _getFilter(field, op, value) {
var clause = Object.create(null);
switch (op) {
case '=':
clause[field] = value;
break;
case '>':
clause[field] = {
$gt: value
};
break;
case '>=':
clause[field] = {
$gte: value
};
break;
case '<':
clause[field] = {
$lt: value
};
break;
case '<=':
clause[field] = {
$lte: value
};
break;
case '$in':
clause[field] = {
$in: value
};
break;
case '?':
clause[field] = {
$regex: value.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"),
$options: 'i'
};
break;
default:
break;
}
return clause;
}
/**
* willEliminate is implemented by child Policy's to
* determine whether a field should be kept or dismissed.
* @abstract
* @param {string} field
* @param {string} op
* @param {*} value
*/
}, {
key: 'willEliminate',
value: function willEliminate(field, op, value) {}
/**
* enforce this policy
* @param {string} field
* @param {string} op
* @param {*} value
* @return {object}
*/
}, {
key: 'enforce',
value: function enforce(field, op, value) {
var spec;
if (this.willEliminate(field, op, value)) return null;
spec = this.__fields[field];
if ((typeof spec === 'undefined' ? 'undefined' : _typeof(spec)) === 'object') {
op = spec.op || op;
value = spec.value ? spec.value(value) : value;
} else if (typeof spec === 'function') {
value = spec(value);
} else if (typeof spec === 'string') {
op = spec;
}
return this._getFilter(field, op, value);
}
}]);
return Policy;
}();
exports.default = Policy;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9Qb2xpY3kuanMiXSwibmFtZXMiOlsiUG9saWN5IiwiZmllbGRzIiwiX19maWVsZHMiLCJmaWVsZCIsIm9wIiwidmFsdWUiLCJjbGF1c2UiLCJPYmplY3QiLCJjcmVhdGUiLCIkZ3QiLCIkZ3RlIiwiJGx0IiwiJGx0ZSIsIiRpbiIsIiRyZWdleCIsInJlcGxhY2UiLCIkb3B0aW9ucyIsInNwZWMiLCJ3aWxsRWxpbWluYXRlIiwiX2dldEZpbHRlciJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7O0FBQUE7Ozs7Ozs7Ozs7Ozs7Ozs7SUFnQnFCQSxNO0FBRWpCLG9CQUFZQyxNQUFaLEVBQW9CO0FBQUE7O0FBRWhCLGFBQUtDLFFBQUwsR0FBZ0JELE1BQWhCO0FBRUg7Ozs7bUNBRVVFLEssRUFBT0MsRSxFQUFJQyxLLEVBQU87O0FBRXpCLGdCQUFJQyxTQUFTQyxPQUFPQyxNQUFQLENBQWMsSUFBZCxDQUFiOztBQUVBLG9CQUFRSixFQUFSOztBQUVJLHFCQUFLLEdBQUw7QUFDSUUsMkJBQU9ILEtBQVAsSUFBZ0JFLEtBQWhCO0FBQ0E7O0FBRUoscUJBQUssR0FBTDtBQUNJQywyQkFBT0gsS0FBUCxJQUFnQjtBQUNaTSw2QkFBS0o7QUFETyxxQkFBaEI7QUFHQTs7QUFFSixxQkFBSyxJQUFMO0FBQ0lDLDJCQUFPSCxLQUFQLElBQWdCO0FBQ1pPLDhCQUFNTDtBQURNLHFCQUFoQjtBQUdBOztBQUVKLHFCQUFLLEdBQUw7QUFDSUMsMkJBQU9ILEtBQVAsSUFBZ0I7QUFDWlEsNkJBQUtOO0FBRE8scUJBQWhCO0FBR0E7O0FBRUoscUJBQUssSUFBTDtBQUNJQywyQkFBT0gsS0FBUCxJQUFnQjtBQUNaUyw4QkFBTVA7QUFETSxxQkFBaEI7QUFHQTs7QUFFSixxQkFBSyxLQUFMO0FBQ0lDLDJCQUFPSCxLQUFQLElBQWdCO0FBQ1pVLDZCQUFLUjtBQURPLHFCQUFoQjtBQUdBOztBQUVKLHFCQUFLLEdBQUw7O0FBRUlDLDJCQUFPSCxLQUFQLElBQWdCO0FBQ1pXLGdDQUFRVCxNQUFNVSxPQUFOLENBQWMsd0JBQWQsRUFBd0MsTUFBeEMsQ0FESTtBQUVaQyxrQ0FBVTtBQUZFLHFCQUFoQjtBQUlBO0FBQ0o7QUFDSTs7QUE1Q1I7O0FBZ0RBLG1CQUFPVixNQUFQO0FBRUg7O0FBRUQ7Ozs7Ozs7Ozs7O3NDQVFjSCxLLEVBQU9DLEUsRUFBSUMsSyxFQUFPLENBRS9COztBQUVEOzs7Ozs7Ozs7O2dDQU9RRixLLEVBQU9DLEUsRUFBSUMsSyxFQUFPOztBQUV0QixnQkFBSVksSUFBSjs7QUFFQSxnQkFBSSxLQUFLQyxhQUFMLENBQW1CZixLQUFuQixFQUEwQkMsRUFBMUIsRUFBOEJDLEtBQTlCLENBQUosRUFDSSxPQUFPLElBQVA7O0FBRUpZLG1CQUFPLEtBQUtmLFFBQUwsQ0FBY0MsS0FBZCxDQUFQOztBQUVBLGdCQUFJLFFBQU9jLElBQVAseUNBQU9BLElBQVAsT0FBZ0IsUUFBcEIsRUFBK0I7O0FBRTNCYixxQkFBS2EsS0FBS2IsRUFBTCxJQUFXQSxFQUFoQjtBQUNBQyx3QkFBUVksS0FBS1osS0FBTCxHQUFZWSxLQUFLWixLQUFMLENBQVdBLEtBQVgsQ0FBWixHQUFnQ0EsS0FBeEM7QUFFSCxhQUxELE1BS00sSUFBSSxPQUFPWSxJQUFQLEtBQWdCLFVBQXBCLEVBQWdDOztBQUVsQ1osd0JBQVFZLEtBQUtaLEtBQUwsQ0FBUjtBQUVILGFBSkssTUFJQyxJQUFJLE9BQU9ZLElBQVAsS0FBZ0IsUUFBcEIsRUFBOEI7O0FBRWpDYixxQkFBS2EsSUFBTDtBQUVIOztBQUVELG1CQUFPLEtBQUtFLFVBQUwsQ0FBZ0JoQixLQUFoQixFQUF1QkMsRUFBdkIsRUFBMkJDLEtBQTNCLENBQVA7QUFFSDs7Ozs7O2tCQTdHZ0JMLE0iLCJmaWxlIjoiUG9saWN5LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBQb2xpY3kgcHJvdmlkZXMgYW4gYXBpIGZvciBzcGVjaWZ5aW5nIGhvdyBlYWNoIHBhcnNlZCBmaWVsZCBzaG91bGRcbiAqIGJlIHRyZWF0ZWQsIGFzIHdlbGwgYXMgd2hhdCB0byBkbyB3aXRoIGZpZWxkcyBub3Qgc3BlY2lmaWVkIChkaXNjYXJkIG9yIGtlZXA/KS5cbiAqXG4gKiBUaGUgYWN0dWFsIHBvbGljeSBpcyBzcGVjaWZpZWQgYnkgYW4gbWFwIG9mIGtleSB2YWx1ZSBwYWlycyB3aGVyZSBlYWNoIGtleSByZXByZXNlbnRzXG4gKiBhIGZpZWxkIGFuZCBpdHMgdmFsdWUgc2hvdWxkIGJlIG9uZSBvZiBib29sZWFuLCBzdHJpbmcsIGZ1bmN0aW9uLlxuICpcbiAqIEJvb2xlYW4gdmFsdWVzIGFyZSBkZWNpZGVkIGJ5IGNoaWxkIGNsYXNzZXMgb2YgdGhpcyBQb2xpY3kuXG4gKiBTdHJpbmcgdmFsdWVzIG11c3QgYmUgb25lIG9mIHRoZSByZWNvbmduaXplZCBmaWx0ZXIgb3BlcmF0b3JzIGFuZCB3aWxsIHJlcGxhY2Ugd2hhdGV2ZXJcbiAqIHdhcyBwYXJzZWQuXG4gKiBGdW5jdGlvbnMgYXJlIGFwcGxpZWQgdG8gdGhlIHZhbHVlIGFsbG93aW5nIHZhbGlkYXRpb24sIHRyYW5zZm9ybWF0aW9uIGV0YyBiZWZvcmUgdGhlIGZpbmFsXG4gKiBxdWVyeSBpcyB1c2VkLlxuICpcbiAqIEBhYnN0cmFjdFxuICogQHBhcmFtIHtvYmplY3R9IGZpZWxkc1xuICovXG5leHBvcnQgZGVmYXVsdCBjbGFzcyBQb2xpY3kge1xuXG4gICAgY29uc3RydWN0b3IoZmllbGRzKSB7XG5cbiAgICAgICAgdGhpcy5fX2ZpZWxkcyA9IGZpZWxkcztcblxuICAgIH1cblxuICAgIF9nZXRGaWx0ZXIoZmllbGQsIG9wLCB2YWx1ZSkge1xuXG4gICAgICAgIHZhciBjbGF1c2UgPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuXG4gICAgICAgIHN3aXRjaCAob3ApIHtcblxuICAgICAgICAgICAgY2FzZSAnPSc6XG4gICAgICAgICAgICAgICAgY2xhdXNlW2ZpZWxkXSA9IHZhbHVlO1xuICAgICAgICAgICAgICAgIGJyZWFrO1xuXG4gICAgICAgICAgICBjYXNlICc+JzpcbiAgICAgICAgICAgICAgICBjbGF1c2VbZmllbGRdID0ge1xuICAgICAgICAgICAgICAgICAgICAkZ3Q6IHZhbHVlXG4gICAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgICAgICBicmVhaztcblxuICAgICAgICAgICAgY2FzZSAnPj0nOlxuICAgICAgICAgICAgICAgIGNsYXVzZVtmaWVsZF0gPSB7XG4gICAgICAgICAgICAgICAgICAgICRndGU6IHZhbHVlXG4gICAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgICAgICBicmVhaztcblxuICAgICAgICAgICAgY2FzZSAnPCc6XG4gICAgICAgICAgICAgICAgY2xhdXNlW2ZpZWxkXSA9IHtcbiAgICAgICAgICAgICAgICAgICAgJGx0OiB2YWx1ZVxuICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgICAgIGNhc2UgJzw9JzpcbiAgICAgICAgICAgICAgICBjbGF1c2VbZmllbGRdID0ge1xuICAgICAgICAgICAgICAgICAgICAkbHRlOiB2YWx1ZVxuICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgICAgIGNhc2UgJyRpbic6XG4gICAgICAgICAgICAgICAgY2xhdXNlW2ZpZWxkXSA9IHtcbiAgICAgICAgICAgICAgICAgICAgJGluOiB2YWx1ZVxuICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgICAgIGNhc2UgJz8nOlxuXG4gICAgICAgICAgICAgICAgY2xhdXNlW2ZpZWxkXSA9IHtcbiAgICAgICAgICAgICAgICAgICAgJHJlZ2V4OiB2YWx1ZS5yZXBsYWNlKC9bLVxcL1xcXFxeJCorPy4oKXxbXFxde31dL2csIFwiXFxcXCQmXCIpLFxuICAgICAgICAgICAgICAgICAgICAkb3B0aW9uczogJ2knXG4gICAgICAgICAgICAgICAgfTtcbiAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiBjbGF1c2U7XG5cbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiB3aWxsRWxpbWluYXRlIGlzIGltcGxlbWVudGVkIGJ5IGNoaWxkIFBvbGljeSdzIHRvXG4gICAgICogZGV0ZXJtaW5lIHdoZXRoZXIgYSBmaWVsZCBzaG91bGQgYmUga2VwdCBvciBkaXNtaXNzZWQuXG4gICAgICogQGFic3RyYWN0XG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGZpZWxkXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IG9wXG4gICAgICogQHBhcmFtIHsqfSB2YWx1ZVxuICAgICAqL1xuICAgIHdpbGxFbGltaW5hdGUoZmllbGQsIG9wLCB2YWx1ZSkge1xuXG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogZW5mb3JjZSB0aGlzIHBvbGljeVxuICAgICAqIEBwYXJhbSB7c3RyaW5nfSBmaWVsZFxuICAgICAqIEBwYXJhbSB7c3RyaW5nfSBvcFxuICAgICAqIEBwYXJhbSB7Kn0gdmFsdWVcbiAgICAgKiBAcmV0dXJuIHtvYmplY3R9XG4gICAgICovXG4gICAgZW5mb3JjZShmaWVsZCwgb3AsIHZhbHVlKSB7XG5cbiAgICAgICAgdmFyIHNwZWM7XG5cbiAgICAgICAgaWYgKHRoaXMud2lsbEVsaW1pbmF0ZShmaWVsZCwgb3AsIHZhbHVlKSlcbiAgICAgICAgICAgIHJldHVybiBudWxsO1xuXG4gICAgICAgIHNwZWMgPSB0aGlzLl9fZmllbGRzW2ZpZWxkXTtcblxuICAgICAgICBpZiggdHlwZW9mIHNwZWMgPT09ICdvYmplY3QnICkge1xuXG4gICAgICAgICAgICBvcCA9IHNwZWMub3AgfHwgb3A7XG4gICAgICAgICAgICB2YWx1ZSA9IHNwZWMudmFsdWU/IHNwZWMudmFsdWUodmFsdWUpIDogdmFsdWU7XG5cbiAgICAgICAgfWVsc2UgaWYgKHR5cGVvZiBzcGVjID09PSAnZnVuY3Rpb24nKSB7XG5cbiAgICAgICAgICAgIHZhbHVlID0gc3BlYyh2YWx1ZSk7XG5cbiAgICAgICAgfSBlbHNlIGlmICh0eXBlb2Ygc3BlYyA9PT0gJ3N0cmluZycpIHtcblxuICAgICAgICAgICAgb3AgPSBzcGVjO1xuXG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gdGhpcy5fZ2V0RmlsdGVyKGZpZWxkLCBvcCwgdmFsdWUpO1xuXG4gICAgfVxuXG59XG4iXX0= |
import datetime
from collections import OrderedDict, defaultdict
import pytest
import pytz
from bs4 import BeautifulSoup
from pytest import param as case
from urwid import Columns, Divider, Padding, Text
from zulipterminal.config.keys import keys_for_command
from zulipterminal.config.symbols import (
QUOTED_TEXT_MARKER,
STATUS_ACTIVE,
STATUS_INACTIVE,
STREAM_TOPIC_SEPARATOR,
TIME_MENTION_MARKER,
)
from zulipterminal.helper import powerset
from zulipterminal.ui_tools.boxes import MessageBox
from zulipterminal.ui_tools.views import (
LeftColumnView,
MessageView,
MiddleColumnView,
ModListWalker,
RightColumnView,
StreamsView,
StreamsViewDivider,
TopicsView,
UsersView,
)
SUBDIR = "zulipterminal.ui_tools"
BOXES = SUBDIR + ".boxes"
VIEWS = SUBDIR + ".views"
MESSAGEVIEW = VIEWS + ".MessageView"
MIDCOLVIEW = VIEWS + ".MiddleColumnView"
SERVER_URL = "https://chat.zulip.zulip"
@pytest.fixture(params=[True, False], ids=["ignore_mouse_click", "handle_mouse_click"])
def compose_box_is_open(request):
return request.param
class TestModListWalker:
@pytest.fixture
def mod_walker(self):
return ModListWalker([list(range(1))])
@pytest.mark.parametrize(
"num_items, focus_position",
[
(5, 0),
(0, 0),
],
)
def test_extend(self, num_items, focus_position, mod_walker, mocker):
items = list(range(num_items))
mocker.patch.object(mod_walker, "_set_focus")
mod_walker.extend(items)
mod_walker._set_focus.assert_called_once_with(focus_position)
def test__set_focus(self, mod_walker, mocker):
mod_walker.read_message = mocker.Mock()
mod_walker._set_focus(0)
mod_walker.read_message.assert_called_once_with()
def test_set_focus(self, mod_walker, mocker):
mod_walker.read_message = mocker.Mock()
mod_walker.set_focus(0)
mod_walker.read_message.assert_called_once_with()
class TestMessageView:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker):
self.model = mocker.MagicMock()
self.view = mocker.Mock()
self.urwid = mocker.patch(VIEWS + ".urwid")
@pytest.fixture
def msg_view(self, mocker, msg_box):
mocker.patch(MESSAGEVIEW + ".main_view", return_value=[msg_box])
mocker.patch(MESSAGEVIEW + ".read_message")
mocker.patch(MESSAGEVIEW + ".set_focus")
msg_view = MessageView(self.model, self.view)
msg_view.log = mocker.Mock()
msg_view.body = mocker.Mock()
return msg_view
def test_init(self, mocker, msg_view, msg_box):
assert msg_view.model == self.model
msg_view.set_focus.assert_called_once_with(0)
assert msg_view.old_loading is False
assert msg_view.new_loading is False
@pytest.mark.parametrize("narrow_focus_pos, focus_msg", [(set(), 1), (0, 0)])
def test_main_view(self, mocker, narrow_focus_pos, focus_msg):
mocker.patch(MESSAGEVIEW + ".read_message")
self.urwid.SimpleFocusListWalker.return_value = mocker.Mock()
mocker.patch(MESSAGEVIEW + ".set_focus")
msg_list = ["MSG1", "MSG2"]
mocker.patch(VIEWS + ".create_msg_box_list", return_value=msg_list)
self.model.get_focus_in_current_narrow.return_value = narrow_focus_pos
msg_view = MessageView(self.model, self.view)
assert msg_view.focus_msg == focus_msg
@pytest.mark.parametrize(
"messages_fetched",
[
{},
{201: "M1"},
OrderedDict([(201, "M1"), (202, "M2")]),
],
)
@pytest.mark.parametrize(
"ids_in_narrow",
[
set(),
{0}, # Shouldn't apply to empty log case?
],
)
def test_load_old_messages_empty_log(
self, mocker, msg_view, ids_in_narrow, messages_fetched
):
# Expand parameters to use in test
new_msg_ids = set(messages_fetched.keys())
new_msg_widgets = list(messages_fetched.values())
mocker.patch.object(
msg_view.model,
"get_message_ids_in_current_narrow",
side_effect=[ids_in_narrow, ids_in_narrow | new_msg_ids],
)
create_msg_box_list = mocker.patch(
VIEWS + ".create_msg_box_list", return_value=new_msg_widgets
)
# Specific to this version of the test
msg_view.log = []
msg_view.load_old_messages(0)
assert msg_view.old_loading is False
assert msg_view.log == list(messages_fetched.values()) # code vs orig
if messages_fetched:
create_msg_box_list.assert_called_once_with(msg_view.model, new_msg_ids)
self.model.controller.update_screen.assert_called_once_with()
else:
create_msg_box_list.assert_not_called()
self.model.controller.update_screen.assert_not_called()
self.model.get_messages.assert_called_once_with(
num_before=30, num_after=0, anchor=0
)
@pytest.mark.parametrize(
"messages_fetched",
[
{},
{201: "M1"},
OrderedDict([(201, "M1"), (202, "M2")]),
],
)
@pytest.mark.parametrize(
"top_id_in_narrow, other_ids_in_narrow",
[
(99, set()),
(99, {101}),
(99, {101, 103}),
],
)
def test_load_old_messages_mocked_log(
self, mocker, msg_view, top_id_in_narrow, other_ids_in_narrow, messages_fetched
):
# Expand parameters to use in test
new_msg_ids = set(messages_fetched.keys())
new_msg_widgets = list(messages_fetched.values())
# Parameter constraints
assert top_id_in_narrow not in other_ids_in_narrow
assert top_id_in_narrow not in new_msg_ids
assert other_ids_in_narrow & new_msg_ids == set()
top_widget = mocker.Mock()
top_widget.original_widget.message = {"id": top_id_in_narrow}
ids_in_narrow = {top_id_in_narrow} | other_ids_in_narrow
mocker.patch.object(
msg_view.model,
"get_message_ids_in_current_narrow",
side_effect=[ids_in_narrow, ids_in_narrow | new_msg_ids],
)
create_msg_box_list = mocker.patch(
VIEWS + ".create_msg_box_list",
return_value=(new_msg_widgets + [top_widget]),
)
initial_log = [top_widget] + len(other_ids_in_narrow) * ["existing"]
msg_view.log = initial_log[:]
msg_view.load_old_messages(0)
assert msg_view.old_loading is False
assert msg_view.log == new_msg_widgets + initial_log
if messages_fetched:
create_msg_box_list.assert_called_once_with(
msg_view.model, {top_id_in_narrow} | new_msg_ids
)
self.model.controller.update_screen.assert_called_once_with()
else:
create_msg_box_list.assert_not_called()
self.model.controller.update_screen.assert_not_called()
self.model.get_messages.assert_called_once_with(
num_before=30, num_after=0, anchor=0
)
# FIXME: Improve this test by covering more parameters
@pytest.mark.parametrize(
"ids_in_narrow",
[
({0}),
],
)
def test_load_new_messages_empty_log(self, mocker, msg_view, ids_in_narrow):
mocker.patch.object(
msg_view.model,
"get_message_ids_in_current_narrow",
return_value=ids_in_narrow,
)
create_msg_box_list = mocker.patch(
VIEWS + ".create_msg_box_list", return_value=["M1", "M2"]
)
msg_view.log = []
msg_view.load_new_messages(0)
assert msg_view.new_loading is False
assert msg_view.log == ["M1", "M2"]
create_msg_box_list.assert_called_once_with(
msg_view.model, set(), last_message=None
)
self.model.controller.update_screen.assert_called_once_with()
self.model.get_messages.assert_called_once_with(
num_before=0, num_after=30, anchor=0
)
# FIXME: Improve this test by covering more parameters
@pytest.mark.parametrize(
"ids_in_narrow",
[
({0}),
],
)
def test_load_new_messages_mocked_log(self, mocker, msg_view, ids_in_narrow):
mocker.patch.object(
msg_view.model,
"get_message_ids_in_current_narrow",
return_value=ids_in_narrow,
)
create_msg_box_list = mocker.patch(
VIEWS + ".create_msg_box_list", return_value=["M1", "M2"]
)
msg_view.log = [mocker.Mock()]
msg_view.load_new_messages(0)
assert msg_view.new_loading is False
assert msg_view.log[-2:] == ["M1", "M2"]
expected_last_msg = msg_view.log[0].original_widget.message
create_msg_box_list.assert_called_once_with(
msg_view.model, set(), last_message=expected_last_msg
)
self.model.controller.update_screen.assert_called_once_with()
self.model.get_messages.assert_called_once_with(
num_before=0, num_after=30, anchor=0
)
@pytest.mark.parametrize(
"event, button, keypress",
[
("mouse press", 4, "up"),
("mouse press", 5, "down"),
],
)
def test_mouse_event(self, mocker, msg_view, event, button, keypress, widget_size):
mocker.patch.object(msg_view, "keypress")
size = widget_size(msg_view)
msg_view.mouse_event(size, event, button, 0, 0, mocker.Mock())
msg_view.keypress.assert_called_once_with(size, keypress)
@pytest.mark.parametrize("key", keys_for_command("GO_DOWN"))
def test_keypress_GO_DOWN(self, mocker, msg_view, key, widget_size):
size = widget_size(msg_view)
msg_view.new_loading = False
mocker.patch(MESSAGEVIEW + ".focus_position", return_value=0)
mocker.patch(MESSAGEVIEW + ".set_focus_valign")
msg_view.log.next_position.return_value = 1
msg_view.keypress(size, key)
msg_view.log.next_position.assert_called_once_with(msg_view.focus_position)
msg_view.set_focus.assert_called_with(1, "above")
msg_view.set_focus_valign.assert_called_once_with("middle")
@pytest.mark.parametrize("view_is_focused", [True, False])
@pytest.mark.parametrize("key", keys_for_command("GO_DOWN"))
def test_keypress_GO_DOWN_exception(
self, mocker, msg_view, key, widget_size, view_is_focused
):
size = widget_size(msg_view)
msg_view.new_loading = False
mocker.patch(MESSAGEVIEW + ".focus_position", return_value=0)
mocker.patch(MESSAGEVIEW + ".set_focus_valign")
msg_view.log.next_position = Exception()
mocker.patch(
MESSAGEVIEW + ".focus",
mocker.MagicMock() if view_is_focused else None,
)
mocker.patch.object(msg_view, "load_new_messages")
return_value = msg_view.keypress(size, key)
if view_is_focused:
msg_view.load_new_messages.assert_called_once_with(
msg_view.focus.original_widget.message["id"],
)
else:
msg_view.load_new_messages.assert_not_called()
assert return_value == key
@pytest.mark.parametrize("key", keys_for_command("GO_UP"))
def test_keypress_GO_UP(self, mocker, msg_view, key, widget_size):
size = widget_size(msg_view)
mocker.patch(MESSAGEVIEW + ".focus_position", return_value=0)
mocker.patch(MESSAGEVIEW + ".set_focus_valign")
msg_view.old_loading = False
msg_view.log.prev_position.return_value = 1
msg_view.keypress(size, key)
msg_view.log.prev_position.assert_called_once_with(msg_view.focus_position)
msg_view.set_focus.assert_called_with(1, "below")
msg_view.set_focus_valign.assert_called_once_with("middle")
@pytest.mark.parametrize("view_is_focused", [True, False])
@pytest.mark.parametrize("key", keys_for_command("GO_UP"))
def test_keypress_GO_UP_exception(
self, mocker, msg_view, key, widget_size, view_is_focused
):
size = widget_size(msg_view)
msg_view.old_loading = False
mocker.patch(MESSAGEVIEW + ".focus_position", return_value=0)
mocker.patch(MESSAGEVIEW + ".set_focus_valign")
msg_view.log.prev_position = Exception()
mocker.patch(
MESSAGEVIEW + ".focus",
mocker.MagicMock() if view_is_focused else None,
)
mocker.patch.object(msg_view, "load_old_messages")
return_value = msg_view.keypress(size, key)
if view_is_focused:
msg_view.load_old_messages.assert_called_once_with(
msg_view.focus.original_widget.message["id"],
)
else:
msg_view.load_old_messages.assert_not_called()
assert return_value == key
def test_read_message(self, mocker, msg_box):
mocker.patch(MESSAGEVIEW + ".main_view", return_value=[msg_box])
self.urwid.SimpleFocusListWalker.return_value = mocker.Mock()
mocker.patch(MESSAGEVIEW + ".set_focus")
mocker.patch(MESSAGEVIEW + ".update_search_box_narrow")
msg_view = MessageView(self.model, self.view)
msg_view.model.is_search_narrow = lambda: False
msg_view.model.controller.in_explore_mode = False
msg_view.log = mocker.Mock()
msg_view.body = mocker.Mock()
msg_w = mocker.MagicMock()
msg_view.model.controller.view = mocker.Mock()
msg_view.model.controller.view.body.focus_col = 1
msg_w.attr_map = {None: "unread"}
msg_w.original_widget.message = {"id": 1}
msg_w.set_attr_map.return_value = None
msg_view.body.get_focus.return_value = (msg_w, 0)
msg_view.body.get_prev.return_value = (None, 1)
msg_view.model.narrow = []
msg_view.model.index = {
"messages": {
1: {
"flags": [],
}
},
"pointer": {"[]": 0},
}
mocker.patch(MESSAGEVIEW + ".focus_position")
msg_view.focus_position = 1
msg_view.model.controller.view.body.focus_col = 1
msg_view.log = list(msg_view.model.index["messages"])
msg_view.read_message()
assert msg_view.update_search_box_narrow.called
assert msg_view.model.index["messages"][1]["flags"] == ["read"]
self.model.mark_message_ids_as_read.assert_called_once_with([1])
def test_message_calls_search_and_header_bar(self, mocker, msg_view):
msg_w = mocker.MagicMock()
msg_w.original_widget.message = {"id": 1}
msg_view.update_search_box_narrow(msg_w.original_widget)
msg_w.original_widget.top_header_bar.assert_called_once_with
(msg_w.original_widget)
msg_w.original_widget.top_search_bar.assert_called_once_with()
def test_read_message_no_msgw(self, mocker, msg_view):
# MSG_W is NONE CASE
msg_view.body.get_focus.return_value = (None, 0)
msg_view.read_message()
self.model.mark_message_ids_as_read.assert_not_called()
def test_read_message_in_explore_mode(self, mocker, msg_box):
mocker.patch(MESSAGEVIEW + ".main_view", return_value=[msg_box])
mocker.patch(MESSAGEVIEW + ".set_focus")
mocker.patch(MESSAGEVIEW + ".update_search_box_narrow")
msg_view = MessageView(self.model, self.view)
msg_w = mocker.Mock()
msg_view.body = mocker.Mock()
msg_view.body.get_focus.return_value = (msg_w, 0)
msg_view.model.is_search_narrow = lambda: False
msg_view.model.controller.in_explore_mode = True
msg_view.read_message()
assert msg_view.update_search_box_narrow.called
assert not self.model.mark_message_ids_as_read.called
def test_read_message_search_narrow(self, mocker, msg_box):
mocker.patch(MESSAGEVIEW + ".main_view", return_value=[msg_box])
mocker.patch(MESSAGEVIEW + ".set_focus")
mocker.patch(MESSAGEVIEW + ".update_search_box_narrow")
msg_view = MessageView(self.model, self.view)
msg_view.model.controller.view = mocker.Mock()
msg_w = mocker.Mock()
msg_view.body = mocker.Mock()
msg_view.body.get_focus.return_value = (msg_w, 0)
msg_view.model.is_search_narrow = lambda: True
msg_view.model.controller.in_explore_mode = False
msg_view.read_message()
assert msg_view.update_search_box_narrow.called
assert not self.model.mark_message_ids_as_read.called
def test_read_message_last_unread_message_focused(
self, mocker, message_fixture, empty_index, msg_box
):
mocker.patch(MESSAGEVIEW + ".main_view", return_value=[msg_box])
mocker.patch(MESSAGEVIEW + ".set_focus")
msg_view = MessageView(self.model, self.view)
msg_view.model.is_search_narrow = lambda: False
msg_view.model.controller.in_explore_mode = False
msg_view.log = [0, 1]
msg_view.body = mocker.Mock()
msg_view.update_search_box_narrow = mocker.Mock()
self.model.controller.view = mocker.Mock()
self.model.controller.view.body.focus_col = 0
self.model.index = empty_index
msg_w = mocker.Mock()
msg_w.attr_map = {None: "unread"}
msg_w.original_widget.message = message_fixture
msg_view.body.get_focus.return_value = (msg_w, 1)
msg_view.body.get_prev.return_value = (None, 0)
msg_view.read_message(1)
self.model.mark_message_ids_as_read.assert_called_once_with(
[message_fixture["id"]]
)
class TestStreamsViewDivider:
def test_init(self):
streams_view_divider = StreamsViewDivider()
assert isinstance(streams_view_divider, Divider)
assert streams_view_divider.stream_id == -1
assert streams_view_divider.stream_name == ""
class TestStreamsView:
@pytest.fixture
def stream_view(self, mocker):
mocker.patch(VIEWS + ".threading.Lock")
self.view = mocker.Mock()
self.stream_search_box = mocker.patch(VIEWS + ".PanelSearchBox")
stream_btn = mocker.Mock()
stream_btn.stream_name = "FOO"
self.streams_btn_list = [stream_btn]
return StreamsView(self.streams_btn_list, view=self.view)
def test_init(self, mocker, stream_view):
assert stream_view.view == self.view
assert stream_view.streams_btn_list == self.streams_btn_list
assert stream_view.stream_search_box
self.stream_search_box.assert_called_once_with(
stream_view, "SEARCH_STREAMS", stream_view.update_streams
)
@pytest.mark.parametrize(
"new_text, expected_log, to_pin",
[
# NOTE: '' represents StreamsViewDivider's stream name.
("f", ["fan", "FOO", "foo", "FOOBAR"], []),
("bar", ["bar"], []),
("foo", ["FOO", "foo", "FOOBAR"], []),
("FOO", ["FOO", "foo", "FOOBAR"], []),
("test", ["test here"], []),
("here", ["test here"], []),
("test here", ["test here"], []),
# With 'foo' pinned.
("f", ["foo", "", "fan", "FOO", "FOOBAR"], ["foo"]),
("FOO", ["foo", "", "FOO", "FOOBAR"], ["foo"]),
# With 'bar' pinned.
("bar", ["bar"], ["bar"]),
("baar", "search error", []),
],
)
def test_update_streams(self, mocker, stream_view, new_text, expected_log, to_pin):
stream_names = ["FOO", "FOOBAR", "foo", "fan", "boo", "BOO", "bar", "test here"]
stream_names.sort(key=lambda stream_name: stream_name.lower())
self.view.pinned_streams = [{"name": name} for name in to_pin]
stream_names.sort(
key=lambda stream_name: stream_name in [stream for stream in to_pin],
reverse=True,
)
self.view.controller.is_in_editor_mode = lambda: True
search_box = stream_view.stream_search_box
stream_view.streams_btn_list = [
mocker.Mock(stream_name=stream_name) for stream_name in stream_names
]
stream_view.update_streams(search_box, new_text)
if expected_log != "search error":
assert [stream.stream_name for stream in stream_view.log] == expected_log
else:
assert hasattr(stream_view.log[0].original_widget, "text")
self.view.controller.update_screen.assert_called_once_with()
def test_mouse_event(self, mocker, stream_view, widget_size):
mocker.patch.object(stream_view, "keypress")
size = widget_size(stream_view)
col = 1
row = 1
focus = "WIDGET"
# Left click
stream_view.mouse_event(size, "mouse press", 4, col, row, focus)
stream_view.keypress.assert_called_once_with(size, "up")
# Right click
stream_view.mouse_event(size, "mouse press", 5, col, row, focus)
stream_view.keypress.assert_called_with(size, "down")
@pytest.mark.parametrize("key", keys_for_command("SEARCH_STREAMS"))
def test_keypress_SEARCH_STREAMS(self, mocker, stream_view, key, widget_size):
size = widget_size(stream_view)
mocker.patch.object(stream_view, "set_focus")
stream_view.log.extend(["FOO", "foo", "fan", "boo", "BOO"])
stream_view.log.set_focus(3)
stream_view.keypress(size, key)
assert stream_view.focus_index_before_search == 3
stream_view.set_focus.assert_called_once_with("header")
@pytest.mark.parametrize("key", keys_for_command("GO_BACK"))
def test_keypress_GO_BACK(self, mocker, stream_view, key, widget_size):
size = widget_size(stream_view)
mocker.patch.object(stream_view, "set_focus")
mocker.patch(VIEWS + ".urwid.Frame.keypress")
mocker.patch.object(stream_view.stream_search_box, "reset_search_text")
stream_view.streams_btn_list = ["FOO", "foo", "fan", "boo", "BOO"]
stream_view.focus_index_before_search = 3
# Simulate search
stream_view.log.clear()
stream_view.log.extend(stream_view.streams_btn_list[3])
stream_view.log.set_focus(0)
stream_view.keypress(size, "down")
assert stream_view.log.get_focus()[1] != stream_view.focus_index_before_search
# Exit search
stream_view.keypress(size, key)
# Check state reset after search
stream_view.set_focus.assert_called_once_with("body")
assert stream_view.stream_search_box.reset_search_text.called
assert stream_view.log == stream_view.streams_btn_list
assert stream_view.log.get_focus()[1] == stream_view.focus_index_before_search
class TestTopicsView:
@pytest.fixture
def topic_view(self, mocker, stream_button):
self.stream_button = stream_button
mocker.patch(VIEWS + ".threading.Lock")
self.topic_search_box = mocker.patch(VIEWS + ".PanelSearchBox")
self.view = mocker.Mock()
self.view.controller = mocker.Mock()
topic_btn = mocker.Mock()
topic_btn.caption = "BOO"
self.topics_btn_list = [topic_btn]
self.header_list = mocker.patch(VIEWS + ".urwid.Pile")
self.divider = mocker.patch(VIEWS + ".urwid.Divider")
return TopicsView(self.topics_btn_list, self.view, self.stream_button)
def test_init(self, mocker, topic_view):
assert topic_view.stream_button == self.stream_button
assert topic_view.view == self.view
assert topic_view.topic_search_box
self.topic_search_box.assert_called_once_with(
topic_view, "SEARCH_TOPICS", topic_view.update_topics
)
self.header_list.assert_called_once_with(
[topic_view.stream_button, self.divider("─"), topic_view.topic_search_box]
)
@pytest.mark.parametrize(
"new_text, expected_log",
[
("f", ["FOO", "FOOBAR", "foo", "fan"]),
("a", ["FOOBAR", "fan", "bar"]),
("bar", ["FOOBAR", "bar"]),
("foo", ["FOO", "FOOBAR", "foo"]),
("FOO", ["FOO", "FOOBAR", "foo"]),
("(no", ["(no topic)"]),
("topic", ["(no topic)"]),
("cc", "search error"),
],
)
def test_update_topics(self, mocker, topic_view, new_text, expected_log):
topic_names = ["FOO", "FOOBAR", "foo", "fan", "boo", "BOO", "bar", "(no topic)"]
self.view.controller.is_in_editor_mode = lambda: True
new_text = new_text
search_box = topic_view.topic_search_box
topic_view.topics_btn_list = [
mocker.Mock(topic_name=topic_name) for topic_name in topic_names
]
topic_view.update_topics(search_box, new_text)
if expected_log != "search error":
assert [topic.topic_name for topic in topic_view.log] == expected_log
else:
assert hasattr(topic_view.log[0].original_widget, "text")
self.view.controller.update_screen.assert_called_once_with()
@pytest.mark.parametrize(
"topic_name, topic_initial_log, topic_final_log",
[
("TOPIC3", ["TOPIC2", "TOPIC3", "TOPIC1"], ["TOPIC3", "TOPIC2", "TOPIC1"]),
("TOPIC1", ["TOPIC1", "TOPIC2", "TOPIC3"], ["TOPIC1", "TOPIC2", "TOPIC3"]),
(
"TOPIC4",
["TOPIC1", "TOPIC2", "TOPIC3"],
["TOPIC4", "TOPIC1", "TOPIC2", "TOPIC3"],
),
("TOPIC1", [], ["TOPIC1"]),
],
ids=[
"reorder_topic3",
"topic1_discussion_continues",
"new_topic4",
"first_topic_1",
],
)
def test_update_topics_list(
self, mocker, topic_view, topic_name, topic_initial_log, topic_final_log
):
mocker.patch(SUBDIR + ".buttons.TopButton.__init__", return_value=None)
set_focus_valign = mocker.patch(VIEWS + ".urwid.ListBox.set_focus_valign")
topic_view.view.controller.model.stream_dict = {86: {"name": "PTEST"}}
topic_view.view.controller.model.is_muted_topic = mocker.Mock(
return_value=False
)
topic_view.log = [
mocker.Mock(topic_name=topic_name) for topic_name in topic_initial_log
]
topic_view.update_topics_list(86, topic_name, 1001)
assert [topic.topic_name for topic in topic_view.log] == topic_final_log
set_focus_valign.assert_called_once_with("bottom")
@pytest.mark.parametrize("key", keys_for_command("SEARCH_TOPICS"))
def test_keypress_SEARCH_TOPICS(self, mocker, topic_view, key, widget_size):
size = widget_size(topic_view)
mocker.patch(VIEWS + ".TopicsView.set_focus")
topic_view.log.extend(["FOO", "foo", "fan", "boo", "BOO"])
topic_view.log.set_focus(3)
topic_view.keypress(size, key)
topic_view.set_focus.assert_called_once_with("header")
topic_view.header_list.set_focus.assert_called_once_with(2)
assert topic_view.focus_index_before_search == 3
@pytest.mark.parametrize("key", keys_for_command("GO_BACK"))
def test_keypress_GO_BACK(self, mocker, topic_view, key, widget_size):
size = widget_size(topic_view)
mocker.patch(VIEWS + ".TopicsView.set_focus")
mocker.patch(VIEWS + ".urwid.Frame.keypress")
mocker.patch.object(topic_view.topic_search_box, "reset_search_text")
topic_view.topics_btn_list = ["FOO", "foo", "fan", "boo", "BOO"]
topic_view.focus_index_before_search = 3
# Simulate search
topic_view.log.clear()
topic_view.log.extend(topic_view.topics_btn_list[3])
topic_view.log.set_focus(0)
topic_view.keypress(size, "down")
assert topic_view.log.get_focus()[1] != topic_view.focus_index_before_search
# Exit search
topic_view.keypress(size, key)
# Check state reset after search
topic_view.set_focus.assert_called_once_with("body")
assert topic_view.topic_search_box.reset_search_text.called
assert topic_view.log == topic_view.topics_btn_list
assert topic_view.log.get_focus()[1] == topic_view.focus_index_before_search
class TestUsersView:
@pytest.fixture
def user_view(self, mocker):
mocker.patch(VIEWS + ".urwid.SimpleFocusListWalker", return_value=[])
controller = mocker.Mock()
return UsersView(controller, "USER_BTN_LIST")
def test_mouse_event(self, mocker, user_view, widget_size):
mocker.patch.object(user_view, "keypress")
size = widget_size(user_view)
col = 1
row = 1
focus = "WIDGET"
# Left click
user_view.mouse_event(size, "mouse press", 4, col, row, focus)
user_view.keypress.assert_called_with(size, "up")
# Right click
user_view.mouse_event(size, "mouse press", 5, col, row, focus)
user_view.keypress.assert_called_with(size, "down")
def test_mouse_event_left_click(
self, mocker, user_view, widget_size, compose_box_is_open
):
super_mouse_event = mocker.patch(VIEWS + ".urwid.ListBox.mouse_event")
user_view.controller.is_in_editor_mode.return_value = compose_box_is_open
size = widget_size(user_view)
focus = mocker.Mock()
user_view.mouse_event(size, "mouse press", 1, 1, 1, focus)
if compose_box_is_open:
super_mouse_event.assert_not_called()
else:
super_mouse_event.assert_called_once_with(
size, "mouse press", 1, 1, 1, focus
)
@pytest.mark.parametrize(
"event, button",
[
("mouse release", 0),
("mouse press", 3),
("mouse release", 4),
],
ids=[
"unsupported_mouse_release_action",
"unsupported_right_click_mouse_press_action",
"invalid_event_button_combination",
],
)
def test_mouse_event_invalid(self, user_view, event, button, widget_size):
size = widget_size(user_view)
col = 1
row = 1
focus = "WIDGET"
return_value = user_view.mouse_event(size, event, button, col, row, focus)
assert return_value is False
class TestMiddleColumnView:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker):
mocker.patch(MESSAGEVIEW + "", return_value="MSG_LIST")
self.model = mocker.Mock()
self.view = mocker.Mock()
self.write_box = mocker.Mock()
self.search_box = mocker.Mock()
self.super = mocker.patch(VIEWS + ".urwid.Frame.__init__")
self.super_keypress = mocker.patch(VIEWS + ".urwid.Frame.keypress")
self.model.controller == mocker.Mock()
@pytest.fixture
def mid_col_view(self):
return MiddleColumnView(self.view, self.model, self.write_box, self.search_box)
def test_init(self, mid_col_view):
assert mid_col_view.model == self.model
assert mid_col_view.controller == self.model.controller
assert mid_col_view.last_unread_topic is None
assert mid_col_view.last_unread_pm is None
assert mid_col_view.search_box == self.search_box
assert self.view.message_view == "MSG_LIST"
self.super.assert_called_once_with(
"MSG_LIST", header=self.search_box, footer=self.write_box
)
def test_get_next_unread_topic(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_topics": {1: 1, 2: 1}}
return_value = mid_col_view.get_next_unread_topic()
assert return_value == 1
assert mid_col_view.last_unread_topic == 1
def test_get_next_unread_topic_again(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_topics": {1: 1, 2: 1}}
mid_col_view.last_unread_topic = 1
return_value = mid_col_view.get_next_unread_topic()
assert return_value == 2
assert mid_col_view.last_unread_topic == 2
def test_get_next_unread_topic_no_unread(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_topics": {}}
return_value = mid_col_view.get_next_unread_topic()
assert return_value is None
assert mid_col_view.last_unread_topic is None
def test_get_next_unread_pm(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_pms": {1: 1, 2: 1}}
return_value = mid_col_view.get_next_unread_pm()
assert return_value == 1
assert mid_col_view.last_unread_pm == 1
def test_get_next_unread_pm_again(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_pms": {1: 1, 2: 1}}
mid_col_view.last_unread_pm = 1
return_value = mid_col_view.get_next_unread_pm()
assert return_value == 2
assert mid_col_view.last_unread_pm == 2
def test_get_next_unread_pm_no_unread(self, mid_col_view):
mid_col_view.model.unread_counts = {"unread_pms": {}}
return_value = mid_col_view.get_next_unread_pm()
assert return_value is None
assert mid_col_view.last_unread_pm is None
@pytest.mark.parametrize("key", keys_for_command("GO_BACK"))
def test_keypress_GO_BACK(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".header")
mocker.patch(MIDCOLVIEW + ".footer")
mocker.patch(MIDCOLVIEW + ".set_focus")
mid_col_view.keypress(size, key)
mid_col_view.header.keypress.assert_called_once_with(size, key)
mid_col_view.footer.keypress.assert_called_once_with(size, key)
mid_col_view.set_focus.assert_called_once_with("body")
self.super_keypress.assert_called_once_with(size, key)
@pytest.mark.parametrize("key", keys_for_command("SEARCH_MESSAGES"))
def test_keypress_focus_header(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mid_col_view.focus_part = "header"
mid_col_view.keypress(size, key)
self.super_keypress.assert_called_once_with(size, key)
@pytest.mark.parametrize("key", keys_for_command("SEARCH_MESSAGES"))
def test_keypress_SEARCH_MESSAGES(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".set_focus")
mid_col_view.keypress(size, key)
mid_col_view.controller.enter_editor_mode_with.assert_called_once_with(
mid_col_view.search_box
)
mid_col_view.set_focus.assert_called_once_with("header")
@pytest.mark.parametrize("enter_key", keys_for_command("ENTER"))
@pytest.mark.parametrize("reply_message_key", keys_for_command("REPLY_MESSAGE"))
def test_keypress_REPLY_MESSAGE(
self, mid_col_view, mocker, widget_size, reply_message_key, enter_key
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".body")
mocker.patch(MIDCOLVIEW + ".footer")
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".set_focus")
mid_col_view.keypress(size, reply_message_key)
mid_col_view.body.keypress.assert_called_once_with(size, enter_key)
mid_col_view.set_focus.assert_called_once_with("footer")
assert mid_col_view.footer.focus_position == 1
@pytest.mark.parametrize("key", keys_for_command("STREAM_MESSAGE"))
def test_keypress_STREAM_MESSAGE(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".body")
mocker.patch(MIDCOLVIEW + ".footer")
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".set_focus")
mid_col_view.keypress(size, key)
mid_col_view.body.keypress.assert_called_once_with(size, key)
mid_col_view.set_focus.assert_called_once_with("footer")
assert mid_col_view.footer.focus_position == 0
@pytest.mark.parametrize("key", keys_for_command("REPLY_AUTHOR"))
def test_keypress_REPLY_AUTHOR(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".body")
mocker.patch(MIDCOLVIEW + ".footer")
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".set_focus")
mid_col_view.keypress(size, key)
mid_col_view.body.keypress.assert_called_once_with(size, key)
mid_col_view.set_focus.assert_called_once_with("footer")
assert mid_col_view.footer.focus_position == 1
@pytest.mark.parametrize("key", keys_for_command("NEXT_UNREAD_TOPIC"))
def test_keypress_NEXT_UNREAD_TOPIC_stream(
self, mid_col_view, mocker, widget_size, key
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(
MIDCOLVIEW + ".get_next_unread_topic",
return_value=("1", "topic"),
)
mid_col_view.model.stream_dict = {"1": {"name": "stream"}}
mid_col_view.keypress(size, key)
mid_col_view.get_next_unread_topic.assert_called_once_with()
mid_col_view.controller.narrow_to_topic.assert_called_once_with(
stream_name="stream", topic_name="topic"
)
@pytest.mark.parametrize("key", keys_for_command("NEXT_UNREAD_TOPIC"))
def test_keypress_NEXT_UNREAD_TOPIC_no_stream(
self, mid_col_view, mocker, widget_size, key
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".get_next_unread_topic", return_value=None)
return_value = mid_col_view.keypress(size, key)
assert return_value == key
@pytest.mark.parametrize("key", keys_for_command("NEXT_UNREAD_PM"))
def test_keypress_NEXT_UNREAD_PM_stream(
self, mid_col_view, mocker, key, widget_size
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".get_next_unread_pm", return_value=1)
mid_col_view.model.user_id_email_dict = {1: "EMAIL"}
mid_col_view.keypress(size, key)
mid_col_view.controller.narrow_to_user.assert_called_once_with(
recipient_emails=["EMAIL"],
contextual_message_id=1,
)
@pytest.mark.parametrize("key", keys_for_command("NEXT_UNREAD_PM"))
def test_keypress_NEXT_UNREAD_PM_no_pm(
self, mid_col_view, mocker, key, widget_size
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".get_next_unread_pm", return_value=None)
return_value = mid_col_view.keypress(size, key)
assert return_value == key
@pytest.mark.parametrize("key", keys_for_command("PRIVATE_MESSAGE"))
def test_keypress_PRIVATE_MESSAGE(self, mid_col_view, mocker, key, widget_size):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
mocker.patch(MIDCOLVIEW + ".get_next_unread_pm", return_value=None)
mid_col_view.footer = mocker.Mock()
return_value = mid_col_view.keypress(size, key)
mid_col_view.footer.private_box_view.assert_called_once_with()
assert mid_col_view.footer.focus_position == 0
assert return_value == key
class TestRightColumnView:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker):
self.view = mocker.Mock()
self.user_search = mocker.patch(VIEWS + ".PanelSearchBox")
self.connect_signal = mocker.patch(VIEWS + ".urwid.connect_signal")
self.line_box = mocker.patch(VIEWS + ".urwid.LineBox")
self.thread = mocker.patch(VIEWS + ".threading")
self.super = mocker.patch(VIEWS + ".urwid.Frame.__init__")
self.view.model.unread_counts = { # Minimal, though an UnreadCounts
"unread_pms": {
1: 1,
2: 1,
}
}
@pytest.fixture
def right_col_view(self, mocker, width=50):
mocker.patch(VIEWS + ".RightColumnView.users_view")
return RightColumnView(width, self.view)
def test_init(self, right_col_view):
assert right_col_view.view == self.view
assert right_col_view.user_search == self.user_search(right_col_view)
assert right_col_view.view.user_search == right_col_view.user_search
self.thread.Lock.assert_called_with()
assert right_col_view.search_lock == self.thread.Lock()
self.super.assert_called_once_with(
right_col_view.users_view(),
header=self.line_box(right_col_view.user_search),
)
def test_update_user_list_editor_mode(self, mocker, right_col_view):
right_col_view.view.controller.update_screen = mocker.Mock()
right_col_view.view.controller.is_in_editor_mode = lambda: False
right_col_view.update_user_list("SEARCH_BOX", "NEW_TEXT")
right_col_view.view.controller.update_screen.assert_not_called()
@pytest.mark.parametrize(
"search_string, assert_list, match_return_value",
[("U", ["USER1", "USER2"], True), ("F", [], False)],
ids=[
"user match",
"no user match",
],
)
def test_update_user_list(
self, right_col_view, mocker, search_string, assert_list, match_return_value
):
right_col_view.view.controller.is_in_editor_mode = lambda: True
self.view.users = ["USER1", "USER2"]
mocker.patch(VIEWS + ".match_user", return_value=match_return_value)
mocker.patch(VIEWS + ".UsersView")
list_w = mocker.patch(VIEWS + ".urwid.SimpleFocusListWalker")
set_body = mocker.patch(VIEWS + ".urwid.Frame.set_body")
right_col_view.update_user_list("SEARCH_BOX", search_string)
if assert_list:
right_col_view.users_view.assert_called_with(assert_list)
set_body.assert_called_once_with(right_col_view.body)
def test_update_user_presence(self, right_col_view, mocker, user_list):
set_body = mocker.patch(VIEWS + ".urwid.Frame.set_body")
right_col_view.update_user_list(user_list=user_list)
right_col_view.users_view.assert_called_with(user_list)
set_body.assert_called_once_with(right_col_view.body)
@pytest.mark.parametrize(
"users, users_btn_len, editor_mode, status",
[
(None, 1, False, "active"),
(
[
{
"user_id": 2,
"status": "inactive",
}
],
1,
True,
"active",
),
(None, 0, False, "inactive"),
],
)
def test_users_view(
self, users, users_btn_len, editor_mode, status, mocker, width=40
):
self.view.users = [{"user_id": 1, "status": status}]
self.view.controller.is_in_editor_mode = lambda: editor_mode
user_btn = mocker.patch(VIEWS + ".UserButton")
users_view = mocker.patch(VIEWS + ".UsersView")
right_col_view = RightColumnView(width, self.view)
if status != "inactive":
unread_counts = right_col_view.view.model.unread_counts
user_btn.assert_called_once_with(
self.view.users[0],
controller=self.view.controller,
view=self.view,
width=width,
color="user_" + self.view.users[0]["status"],
state_marker=STATUS_ACTIVE,
count=1,
is_current_user=False,
)
users_view.assert_called_once_with(
self.view.controller, right_col_view.users_btn_list
)
assert len(right_col_view.users_btn_list) == users_btn_len
@pytest.mark.parametrize("key", keys_for_command("SEARCH_PEOPLE"))
def test_keypress_SEARCH_PEOPLE(self, right_col_view, mocker, key, widget_size):
size = widget_size(right_col_view)
mocker.patch(VIEWS + ".RightColumnView.set_focus")
right_col_view.keypress(size, key)
right_col_view.set_focus.assert_called_once_with("header")
@pytest.mark.parametrize("key", keys_for_command("GO_BACK"))
def test_keypress_GO_BACK(self, right_col_view, mocker, key, widget_size):
size = widget_size(right_col_view)
mocker.patch(VIEWS + ".UsersView")
mocker.patch(VIEWS + ".RightColumnView.set_focus")
mocker.patch(VIEWS + ".RightColumnView.set_body")
mocker.patch.object(right_col_view.user_search, "reset_search_text")
right_col_view.users_btn_list = []
right_col_view.keypress(size, key)
right_col_view.set_body.assert_called_once_with(right_col_view.body)
right_col_view.set_focus.assert_called_once_with("body")
assert right_col_view.user_search.reset_search_text.called
class TestLeftColumnView:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker):
self.view = mocker.Mock()
self.view.model = mocker.Mock()
self.view.model.unread_counts = { # Minimal, though an UnreadCounts
"all_msg": 2,
"all_pms": 0,
"streams": {
86: 1,
14: 1,
99: 1,
1: 1,
2: 1,
1000: 1,
},
"unread_topics": {
(205, "TOPIC1"): 34,
(205, "TOPIC2"): 100,
},
"all_mentions": 1,
}
self.view.model.initial_data = {
"starred_messages": [1117554, 1117558, 1117574],
}
self.view.controller = mocker.Mock()
self.super_mock = mocker.patch(VIEWS + ".urwid.Pile.__init__")
def test_menu_view(self, mocker, width=40):
self.streams_view = mocker.patch(VIEWS + ".LeftColumnView.streams_view")
home_button = mocker.patch(VIEWS + ".HomeButton")
pm_button = mocker.patch(VIEWS + ".PMButton")
starred_button = mocker.patch(VIEWS + ".StarredButton")
mocker.patch(VIEWS + ".urwid.ListBox")
mocker.patch(VIEWS + ".urwid.SimpleFocusListWalker")
mocker.patch(VIEWS + ".StreamButton.mark_muted")
left_col_view = LeftColumnView(width, self.view)
home_button.assert_called_once_with(
left_col_view.controller, count=2, width=width
)
pm_button.assert_called_once_with(
left_col_view.controller, count=0, width=width
)
starred_button.assert_called_once_with(
left_col_view.controller, count=3, width=width
)
@pytest.mark.parametrize("pinned", powerset([1, 2, 99, 1000]))
def test_streams_view(self, mocker, streams, pinned, width=40):
self.view.unpinned_streams = [s for s in streams if s["id"] not in pinned]
self.view.pinned_streams = [s for s in streams if s["id"] in pinned]
stream_button = mocker.patch(VIEWS + ".StreamButton")
stream_view = mocker.patch(VIEWS + ".StreamsView")
line_box = mocker.patch(VIEWS + ".urwid.LineBox")
divider = mocker.patch(VIEWS + ".StreamsViewDivider")
left_col_view = LeftColumnView(width, self.view)
if pinned:
assert divider.called
else:
divider.assert_not_called()
stream_button.assert_has_calls(
[
mocker.call(
stream,
controller=self.view.controller,
width=width,
view=self.view,
count=1,
)
for stream in (self.view.pinned_streams + self.view.unpinned_streams)
]
)
def test_topics_view(self, mocker, stream_button, width=40):
mocker.patch(VIEWS + ".LeftColumnView.streams_view")
mocker.patch(VIEWS + ".LeftColumnView.menu_view")
topic_button = mocker.patch(VIEWS + ".TopicButton")
topics_view = mocker.patch(VIEWS + ".TopicsView")
line_box = mocker.patch(VIEWS + ".urwid.LineBox")
topic_list = ["TOPIC1", "TOPIC2", "TOPIC3"]
unread_count_list = [34, 100, 0]
self.view.model.topics_in_stream = mocker.Mock(return_value=topic_list)
left_col_view = LeftColumnView(width, self.view)
left_col_view.topics_view(stream_button)
self.view.model.topics_in_stream.assert_called_once_with(205)
topic_button.assert_has_calls(
[
mocker.call(
stream_id=205,
topic=topic,
controller=self.view.controller,
view=self.view,
width=40,
count=count,
)
for topic, count in zip(topic_list, unread_count_list)
]
)
class TestMessageBox:
@pytest.fixture(autouse=True)
def mock_external_classes(self, mocker, initial_index):
self.model = mocker.MagicMock()
self.model.index = initial_index
@pytest.mark.parametrize(
"message_type, set_fields",
[
("stream", [("stream_name", ""), ("stream_id", None), ("topic_name", "")]),
("private", [("email", ""), ("user_id", None)]),
],
)
def test_init(self, mocker, message_type, set_fields):
mocker.patch.object(MessageBox, "main_view")
message = dict(
display_recipient=[
{"id": 7, "email": "[email protected]", "full_name": "Boo is awesome"}
],
stream_id=5,
subject="hi",
sender_email="[email protected]",
sender_id=4209,
type=message_type,
)
msg_box = MessageBox(message, self.model, None)
assert msg_box.last_message == defaultdict(dict)
for field, invalid_default in set_fields:
assert getattr(msg_box, field) != invalid_default
if message_type == "stream":
assert msg_box.topic_links == OrderedDict()
assert msg_box.message_links == OrderedDict()
assert msg_box.time_mentions == list()
def test_init_fails_with_bad_message_type(self):
message = dict(type="BLAH")
with pytest.raises(RuntimeError):
msg_box = MessageBox(message, self.model, None)
def test_private_message_to_self(self, mocker):
message = dict(
type="private",
display_recipient=[
{"full_name": "Foo Foo", "email": "[email protected]", "id": None}
],
sender_id=9,
content="<p> self message. </p>",
sender_full_name="Foo Foo",
sender_email="[email protected]",
timestamp=150989984,
)
self.model.user_email = "[email protected]"
mocker.patch(
BOXES + ".MessageBox._is_private_message_to_self", return_value=True
)
mocker.patch.object(MessageBox, "main_view")
msg_box = MessageBox(message, self.model, None)
assert msg_box.recipient_emails == ["[email protected]"]
msg_box._is_private_message_to_self.assert_called_once_with()
@pytest.mark.parametrize(
"content, expected_markup",
[
case("", [], id="empty"),
case("<p>hi</p>", ["", "hi"], id="p"),
case(
'<span class="user-mention">@Bob Smith',
[("msg_mention", "@Bob Smith")],
id="user-mention",
),
case(
'<span class="user-group-mention">@A Group',
[("msg_mention", "@A Group")],
id="group-mention",
),
case("<code>some code", [("msg_code", "some code")], id="code"),
case(
'<div class="codehilite">some code',
[("msg_code", "some code")],
id="codehilite",
),
case("<strong>Something", [("msg_bold", "Something")], id="strong"),
case("<em>Something", [("msg_bold", "Something")], id="em"),
case("<blockquote>stuff", [("msg_quote", ["", "stuff"])], id="blockquote"),
# FIXME Unsupported:
case(
'<div class="message_embed">',
["[EMBEDDED CONTENT NOT RENDERED]"],
id="embedded_content",
),
# TODO: Generate test cases to work with both soup2markup and
# footlinks_view.
case(
'<a href="http://foo">Foo</a><a href="https://bar.org">Bar</a>',
[
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
("msg_link", "Bar"),
" ",
("msg_link_index", "[2]"),
],
id="link_two",
),
case(
'<a href="http://foo">Foo</a><a href="http://foo">Another foo</a>',
[
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
("msg_link", "Another foo"),
" ",
("msg_link_index", "[1]"),
],
id="link_samelinkdifferentname",
),
case(
'<a href="http://foo">Foo</a><a href="https://bar.org">Bar</a>'
'<a href="http://foo">Foo</a><a href="https://bar.org">Bar</a>',
[
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
("msg_link", "Bar"),
" ",
("msg_link_index", "[2]"),
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
("msg_link", "Bar"),
" ",
("msg_link_index", "[2]"),
],
id="link_duplicatelink",
),
case(
'<a href="http://baz.com/">http://baz.com/</a>',
[("msg_link", "http://baz.com"), " ", ("msg_link_index", "[1]")],
id="link_trailingslash",
),
case(
'<a href="http://foo.com/">Foo</a><a href="http://foo.com">Foo</a>',
[
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
("msg_link", "Foo"),
" ",
("msg_link_index", "[1]"),
],
id="link_trailingslashduplicatelink",
),
case(
'<a href="http://foo">http://foo</a>',
[("msg_link", "http://foo"), " ", ("msg_link_index", "[1]")],
id="link_sametext",
),
case(
'<a href="http://foo/bar.png">http://foo/bar.png</a>',
[("msg_link", "bar.png"), " ", ("msg_link_index", "[1]")],
id="link_sameimage",
),
case(
'<a href="http://foo">bar</a>',
[("msg_link", "bar"), " ", ("msg_link_index", "[1]")],
id="link_differenttext",
),
case(
'<a href="/user_uploads/blah.gif"',
[("msg_link", "blah.gif"), " ", ("msg_link_index", "[1]")],
id="link_userupload",
),
case(
'<a href="/api"',
[("msg_link", "/api"), " ", ("msg_link_index", "[1]")],
id="link_api",
),
case(
f'<a href="some/relative_url">{SERVER_URL}/some/relative_url</a>',
[("msg_link", "/some/relative_url"), " ", ("msg_link_index", "[1]")],
id="link_serverrelative_same",
),
case(
'<a href="http://foo.com/bar">foo.com/bar</a>',
[("msg_link", "foo.com"), " ", ("msg_link_index", "[1]")],
id="link_textwithoutscheme",
),
case(
'<a href="http://foo.com">foo.com</a>'
'<a href="http://foo.com">http://foo.com</a>'
'<a href="https://foo.com">https://foo.com</a>'
'<a href="http://foo.com">Text</a>',
[
("msg_link", "foo.com"),
" ",
("msg_link_index", "[1]"),
("msg_link", "http://foo.com"),
" ",
("msg_link_index", "[1]"),
("msg_link", "https://foo.com"),
" ",
("msg_link_index", "[2]"),
("msg_link", "Text"),
" ",
("msg_link_index", "[1]"),
],
id="link_differentscheme",
),
case("<li>Something", ["\n", " \N{BULLET} ", "", "Something"], id="li"),
case("<li></li>", ["\n", " \N{BULLET} ", ""], id="empty_li"),
case(
"<li>\n<p>Something",
["\n", " \N{BULLET} ", "", "", "", "Something"],
id="li_with_li_p_newline",
),
case(
"<li>Something<li>else",
[
"\n",
" \N{BULLET} ",
"",
"Something",
"\n",
" \N{BULLET} ",
"",
"else",
],
id="two_li",
),
case(
"<li>\n<p>Something</p>\n</li><li>else",
[
"\n",
" \N{BULLET} ",
"",
"",
"",
"Something",
"",
"\n",
" \N{BULLET} ",
"",
"else",
],
id="two_li_with_li_p_newlines",
),
case(
"<ul><li>Something<ul><li>nested",
[
"",
" \N{BULLET} ",
"",
"Something",
"",
"\n",
" \N{RING OPERATOR} ",
"",
"nested",
],
id="li_nested",
),
case(
"<ul><li>Something<ul><li>nested<ul><li>a<ul><li>lot",
[
"",
" \N{BULLET} ",
"",
"Something",
"",
"\n",
" \N{RING OPERATOR} ",
"",
"nested",
"",
"\n",
" \N{HYPHEN} ",
"",
"a",
"",
"\n",
" \N{BULLET} ",
"",
"lot",
],
id="li_heavily_nested",
),
case("<br>", [], id="br"),
case("<br/>", [], id="br2"),
case("<hr>", ["[RULER NOT RENDERED]"], id="hr"),
case("<hr/>", ["[RULER NOT RENDERED]"], id="hr2"),
case("<img>", ["[IMAGE NOT RENDERED]"], id="img"),
case("<img/>", ["[IMAGE NOT RENDERED]"], id="img2"),
case(
"<table><thead><tr><th>Firstname</th><th>Lastname</th></tr></thead>"
"<tbody><tr><td>John</td><td>Doe</td></tr><tr><td>Mary</td><td>Moe"
"</td></tr></tbody></table>",
[
"┌─",
"─────────",
"─┬─",
"────────",
"─┐\n",
"│ ",
("table_head", "Firstname"),
" │ ",
("table_head", "Lastname"),
" │\n",
"├─",
"─────────",
"─┼─",
"────────",
"─┤\n",
"│ ",
(None, "John "),
" │ ",
(None, "Doe "),
" │\n",
"│ ",
(None, "Mary "),
" │ ",
(None, "Moe "),
" │\n",
"└─",
"─────────",
"─┴─",
"────────",
"─┘",
],
id="table_default",
),
case(
'<table><thead><tr><th align="left">Name</th><th align="right">Id'
'</th></tr></thead><tbody><tr><td align="left">Robert</td>'
'<td align="right">1</td></tr><tr><td align="left">Mary</td>'
'<td align="right">100</td></tr></tbody></table>',
[
"┌─",
"──────",
"─┬─",
"───",
"─┐\n",
"│ ",
("table_head", "Name "),
" │ ",
("table_head", " Id"),
" │\n",
"├─",
"──────",
"─┼─",
"───",
"─┤\n",
"│ ",
(None, "Robert"),
" │ ",
(None, " 1"),
" │\n",
"│ ",
(None, "Mary "),
" │ ",
(None, "100"),
" │\n",
"└─",
"──────",
"─┴─",
"───",
"─┘",
],
id="table_with_left_and_right_alignments",
),
case(
'<table><thead><tr><th align="center">Name</th><th align="right">Id'
'</th></tr></thead><tbody><tr><td align="center">Robert</td>'
'<td align="right">1</td></tr><tr><td align="center">Mary</td>'
'<td align="right">100</td></tr></tbody></table>',
[
"┌─",
"──────",
"─┬─",
"───",
"─┐\n",
"│ ",
("table_head", " Name "),
" │ ",
("table_head", " Id"),
" │\n",
"├─",
"──────",
"─┼─",
"───",
"─┤\n",
"│ ",
(None, "Robert"),
" │ ",
(None, " 1"),
" │\n",
"│ ",
(None, " Mary "),
" │ ",
(None, "100"),
" │\n",
"└─",
"──────",
"─┴─",
"───",
"─┘",
],
id="table_with_center_and_right_alignments",
),
case(
"<table><thead><tr><th>Name</th></tr></thead><tbody><tr><td>Foo</td>"
"</tr><tr><td>Bar</td></tr><tr><td>Baz</td></tr></tbody></table>",
[
"┌─",
"────",
"─┐\n",
"│ ",
("table_head", "Name"),
" │\n",
"├─",
"────",
"─┤\n",
"│ ",
(None, "Foo "),
" │\n",
"│ ",
(None, "Bar "),
" │\n",
"│ ",
(None, "Baz "),
" │\n",
"└─",
"────",
"─┘",
],
id="table_with_single_column",
),
case(
"<table><thead><tr><th>Column1</th></tr></thead><tbody><tr><td></td>"
"</tr></tbody></table>",
[
"┌─",
"───────",
"─┐\n",
"│ ",
("table_head", "Column1"),
" │\n",
"├─",
"───────",
"─┤\n",
"│ ",
(None, " "),
" │\n",
"└─",
"───────",
"─┘",
],
id="table_with_the_bare_minimum",
),
case(
'<time datetime="2020-08-07T04:30:00Z"> Fri, Aug 7 2020, 10:00AM IST'
"</time>",
[("msg_time", f" {TIME_MENTION_MARKER} Fri, Aug 7 2020, 10:00 (IST) ")],
id="time_human_readable_input",
),
case(
'<time datetime="2020-08-11T16:32:58Z"> 1597163578</time>',
[
(
"msg_time",
f" {TIME_MENTION_MARKER} Tue, Aug 11 2020, 22:02 (IST) ",
)
],
id="time_UNIX_timestamp_input",
),
case(
# Markdown:
# ```math
# some-math
# ```
'<span class="katex-display"><span class="katex"><semantics>'
"<annotation>some-math</annotation></semantics></span></span>",
[("msg_math", "some-math")],
id="katex_HTML_response_math_fenced_markdown",
),
case(
# Markdown:
# $$ some-math $$
'<span class="katex"><semantics><annotation>some-math</annotation>'
"</semantics></span>",
[("msg_math", "some-math")],
id="katex_HTML_response_double_$_fenced_markdown",
),
case("<ul><li>text</li></ul>", ["", " \N{BULLET} ", "", "text"], id="ul"),
case(
"<ul>\n<li>text</li>\n</ul>",
["", "", " \N{BULLET} ", "", "text", ""],
id="ul_with_ul_li_newlines",
),
case("<ol><li>text</li></ol>", ["", " 1. ", "", "text"], id="ol"),
case(
"<ol>\n<li>text</li>\n</ol>",
["", "", " 1. ", "", "text", ""],
id="ol_with_ol_li_newlines",
),
case(
'<ol start="5"><li>text</li></ol>',
["", " 5. ", "", "text"],
id="ol_starting_at_5",
),
# FIXME Strikethrough
case("<del>text</del>", ["", "text"], id="strikethrough_del"),
# FIXME inline image?
case(
'<div class="message_inline_image">'
'<a href="x"><img src="x"></a></div>',
[],
id="inline_image",
),
# FIXME inline ref?
case('<div class="message_inline_ref">blah</div>', [], id="inline_ref"),
case(
'<span class="emoji">:smile:</span>',
[("msg_emoji", ":smile:")],
id="emoji",
),
case(
'<div class="inline-preview-twitter"',
["[TWITTER PREVIEW NOT RENDERED]"],
id="preview-twitter",
),
case(
'<img class="emoji" title="zulip"/>',
[("msg_emoji", ":zulip:")],
id="zulip_extra_emoji",
),
case(
'<img class="emoji" title="github"/>',
[("msg_emoji", ":github:")],
id="custom_emoji",
),
],
)
def test_soup2markup(self, content, expected_markup, mocker):
mocker.patch(
BOXES + ".get_localzone", return_value=pytz.timezone("Asia/Kolkata")
)
soup = BeautifulSoup(content, "lxml").find(name="body")
metadata = dict(
server_url=SERVER_URL,
message_links=OrderedDict(),
time_mentions=list(),
bq_len=0,
)
markup, *_ = MessageBox.soup2markup(soup, metadata)
assert markup == [""] + expected_markup
@pytest.mark.parametrize(
"message, last_message",
[
(
{
"sender_id": 1,
"display_recipient": "Verona",
"sender_full_name": "aaron",
"submessages": [],
"stream_id": 5,
"subject": "Verona2",
"id": 37,
"subject_links": [],
"content": (
"<p>It's nice and it feels more modern, but I think"
" this will take some time to get used to</p>"
),
"timestamp": 1531716583,
"sender_realm_str": "zulip",
"client": "populate_db",
"content_type": "text/html",
"reactions": [],
"type": "stream",
"is_me_message": False,
"flags": ["read"],
"sender_email": "[email protected]",
},
None,
),
(
{
"sender_id": 5,
"display_recipient": [
{
"is_mirror_dummy": False,
"email": "[email protected]",
"id": 1,
"full_name": "aaron",
},
{
"is_mirror_dummy": False,
"email": "[email protected]",
"id": 5,
"full_name": "Iago",
},
],
"sender_full_name": "Iago",
"submessages": [],
"subject": "",
"id": 107,
"subject_links": [],
"content": "<p>what are you planning to do this week</p>",
"timestamp": 1532103879,
"sender_realm_str": "zulip",
"client": "ZulipTerminal",
"content_type": "text/html",
"reactions": [],
"type": "private",
"is_me_message": False,
"flags": ["read"],
"sender_email": "[email protected]",
},
None,
),
],
)
def test_main_view(self, mocker, message, last_message):
self.model.stream_dict = {
5: {
"color": "#bd6",
},
}
msg_box = MessageBox(message, self.model, last_message)
@pytest.mark.parametrize(
"message",
[
{
"id": 4,
"type": "stream",
"display_recipient": "Verona",
"stream_id": 5,
"subject": "Test topic",
"is_me_message": True, # will be overridden by test function.
"flags": [],
"content": "", # will be overridden by test function.
"reactions": [],
"sender_full_name": "Alice",
"timestamp": 1532103879,
}
],
)
@pytest.mark.parametrize(
"content, is_me_message",
[
("<p>/me is excited!</p>", True),
("<p>/me is excited! /me is not excited.</p>", True),
("<p>This is /me not.</p>", False),
("<p>/me is excited!</p>", False),
],
)
def test_main_view_renders_slash_me(self, mocker, message, content, is_me_message):
mocker.patch(BOXES + ".urwid.Text")
message["content"] = content
message["is_me_message"] = is_me_message
msg_box = MessageBox(message, self.model, message)
msg_box.main_view()
name_index = 11 if is_me_message else -1 # 11 = len(<str><strong>)
assert (
msg_box.message["content"].find(message["sender_full_name"]) == name_index
)
@pytest.mark.parametrize(
"message",
[
{
"id": 4,
"type": "stream",
"display_recipient": "Verona",
"stream_id": 5,
"subject": "Test topic",
"flags": [],
"is_me_message": False,
"content": "<p>what are you planning to do this week</p>",
"reactions": [],
"sender_full_name": "Alice",
"timestamp": 1532103879,
}
],
)
@pytest.mark.parametrize(
"to_vary_in_last_message",
[
{"display_recipient": "Verona offtopic"},
{"subject": "Test topic (previous)"},
{"type": "private"},
],
ids=[
"different_stream_before",
"different_topic_before",
"PM_before",
],
)
def test_main_view_generates_stream_header(
self, mocker, message, to_vary_in_last_message
):
self.model.stream_dict = {
5: {
"color": "#bd6",
},
}
last_message = dict(message, **to_vary_in_last_message)
msg_box = MessageBox(message, self.model, last_message)
view_components = msg_box.main_view()
assert len(view_components) == 3
assert isinstance(view_components[0], Columns)
assert isinstance(view_components[0][0], Text)
assert isinstance(view_components[0][1], Text)
assert isinstance(view_components[0][2], Divider)
@pytest.mark.parametrize(
"message",
[
{
"id": 4,
"type": "private",
"sender_email": "[email protected]",
"sender_id": 5,
"display_recipient": [
{"email": "[email protected]", "id": 1, "full_name": "aaron"},
{"email": "[email protected]", "id": 5, "full_name": "Iago"},
],
"flags": [],
"is_me_message": False,
"content": "<p>what are you planning to do this week</p>",
"reactions": [],
"sender_full_name": "Alice",
"timestamp": 1532103879,
},
],
)
@pytest.mark.parametrize(
"to_vary_in_last_message",
[
{
"display_recipient": [
{"email": "[email protected]", "id": 1, "full_name": "aaron"},
{"email": "[email protected]", "id": 5, "full_name": "Iago"},
{"email": "[email protected]", "id": 6, "full_name": "Someone Else"},
],
},
{"type": "stream"},
],
ids=[
"larger_pm_group",
"stream_before",
],
)
def test_main_view_generates_PM_header(
self, mocker, message, to_vary_in_last_message
):
last_message = dict(message, **to_vary_in_last_message)
msg_box = MessageBox(message, self.model, last_message)
view_components = msg_box.main_view()
assert len(view_components) == 3
assert isinstance(view_components[0], Columns)
assert isinstance(view_components[0][0], Text)
assert isinstance(view_components[0][1], Text)
assert isinstance(view_components[0][2], Divider)
@pytest.mark.parametrize(
"msg_narrow, msg_type, assert_header_bar, assert_search_bar",
[
([], 0, f"PTEST {STREAM_TOPIC_SEPARATOR} ", "All messages"),
([], 1, "You and ", "All messages"),
([], 2, "You and ", "All messages"),
(
[["stream", "PTEST"]],
0,
f"PTEST {STREAM_TOPIC_SEPARATOR} ",
("bar", [("s#bd6", "PTEST")]),
),
(
[["stream", "PTEST"], ["topic", "b"]],
0,
f"PTEST {STREAM_TOPIC_SEPARATOR}",
("bar", [("s#bd6", "PTEST"), ("s#bd6", ": topic narrow")]),
),
([["is", "private"]], 1, "You and ", "All private messages"),
([["is", "private"]], 2, "You and ", "All private messages"),
([["pm_with", "[email protected]"]], 1, "You and ", "Private conversation"),
(
[["pm_with", "[email protected], [email protected]"]],
2,
"You and ",
"Group private conversation",
),
(
[["is", "starred"]],
0,
f"PTEST {STREAM_TOPIC_SEPARATOR} ",
"Starred messages",
),
([["is", "starred"]], 1, "You and ", "Starred messages"),
([["is", "starred"]], 2, "You and ", "Starred messages"),
([["is", "starred"], ["search", "FOO"]], 1, "You and ", "Starred messages"),
(
[["search", "FOO"]],
0,
f"PTEST {STREAM_TOPIC_SEPARATOR} ",
"All messages",
),
([["is", "mentioned"]], 0, f"PTEST {STREAM_TOPIC_SEPARATOR} ", "Mentions"),
([["is", "mentioned"]], 1, "You and ", "Mentions"),
([["is", "mentioned"]], 2, "You and ", "Mentions"),
([["is", "mentioned"], ["search", "FOO"]], 1, "You and ", "Mentions"),
],
)
def test_msg_generates_search_and_header_bar(
self,
mocker,
messages_successful_response,
msg_type,
msg_narrow,
assert_header_bar,
assert_search_bar,
):
self.model.stream_dict = {
205: {
"color": "#bd6",
},
}
self.model.narrow = msg_narrow
messages = messages_successful_response["messages"]
current_message = messages[msg_type]
msg_box = MessageBox(current_message, self.model, messages[0])
search_bar = msg_box.top_search_bar()
header_bar = msg_box.top_header_bar(msg_box)
assert header_bar[0].text.startswith(assert_header_bar)
assert search_bar.text_to_fill == assert_search_bar
# Assume recipient (PM/stream/topic) header is unchanged below
@pytest.mark.parametrize(
"message",
[
{
"id": 4,
"type": "stream",
"display_recipient": "Verona",
"stream_id": 5,
"subject": "Test topic",
"flags": [],
"is_me_message": False,
"content": "<p>what are you planning to do this week</p>",
"reactions": [],
"sender_full_name": "alice",
"timestamp": 1532103879,
}
],
)
@pytest.mark.parametrize(
"current_year", [2018, 2019, 2050], ids=["now_2018", "now_2019", "now_2050"]
)
@pytest.mark.parametrize(
"starred_msg",
["this", "last", "neither"],
ids=["this_starred", "last_starred", "no_stars"],
)
@pytest.mark.parametrize(
"expected_header, to_vary_in_last_message",
[
(
[STATUS_INACTIVE, "alice", " ", "DAYDATETIME"],
{"sender_full_name": "bob"},
),
([" ", " ", " ", "DAYDATETIME"], {"timestamp": 1532103779}),
([STATUS_INACTIVE, "alice", " ", "DAYDATETIME"], {"timestamp": 0}),
],
ids=[
"show_author_as_authors_different",
"merge_messages_as_only_slightly_earlier_message",
"dont_merge_messages_as_much_earlier_message",
],
)
def test_main_view_content_header_without_header(
self,
mocker,
message,
expected_header,
current_year,
starred_msg,
to_vary_in_last_message,
):
date = mocker.patch(BOXES + ".date")
date.today.return_value = datetime.date(current_year, 1, 1)
date.side_effect = lambda *args, **kw: datetime.date(*args, **kw)
output_date_time = "Fri Jul 20 21:54" # corresponding to timestamp
self.model.formatted_local_time.side_effect = [ # for this- and last-message
output_date_time,
" ",
] * 2 # called once in __init__ and then in main_view explicitly
# The empty dict is responsible for INACTIVE status of test user.
self.model.user_dict = {} # called once in main_view explicitly
stars = {
msg: ({"flags": ["starred"]} if msg == starred_msg else {})
for msg in ("this", "last")
}
this_msg = dict(message, **stars["this"])
all_to_vary = dict(to_vary_in_last_message, **stars["last"])
last_msg = dict(message, **all_to_vary)
msg_box = MessageBox(this_msg, self.model, last_msg)
expected_header[2] = output_date_time
if current_year > 2018:
expected_header[2] = "2018 - " + expected_header[2]
expected_header[3] = "*" if starred_msg == "this" else " "
view_components = msg_box.main_view()
assert len(view_components) == 2
assert isinstance(view_components[0], Columns)
assert [w.text for w in view_components[0].widget_list] == expected_header
assert isinstance(view_components[1], Padding)
@pytest.mark.parametrize(
"to_vary_in_each_message",
[
{"sender_full_name": "bob"},
{"timestamp": 1532103779},
{"timestamp": 0},
{},
{"flags": ["starred"]},
],
ids=[
"common_author",
"common_timestamp",
"common_early_timestamp",
"common_unchanged_message",
"both_starred",
],
)
def test_main_view_compact_output(
self, mocker, message_fixture, to_vary_in_each_message
):
message_fixture.update({"id": 4})
varied_message = dict(message_fixture, **to_vary_in_each_message)
msg_box = MessageBox(varied_message, self.model, varied_message)
view_components = msg_box.main_view()
assert len(view_components) == 1
assert isinstance(view_components[0], Padding)
def test_main_view_generates_EDITED_label(
self, mocker, messages_successful_response
):
messages = messages_successful_response["messages"]
for message in messages:
self.model.index["edited_messages"].add(message["id"])
msg_box = MessageBox(message, self.model, message)
view_components = msg_box.main_view()
label = view_components[0].original_widget.contents[0]
assert label[0].text == "EDITED"
assert label[1][1] == 7
@pytest.mark.parametrize(
"to_vary_in_last_message, update_required",
[
({"sender_full_name": "Unique name (won't be in next message)"}, True),
({}, False),
],
ids=[
"author_field_present",
"author_field_not_present",
],
)
def test_update_message_author_status(
self,
message_fixture,
update_required,
to_vary_in_last_message,
):
message = message_fixture
last_msg = dict(message, **to_vary_in_last_message)
msg_box = MessageBox(message, self.model, last_msg)
assert msg_box.update_message_author_status() == update_required
@pytest.mark.parametrize("key", keys_for_command("STREAM_MESSAGE"))
@pytest.mark.parametrize(
"narrow, expect_to_prefill",
[
([], False),
([["stream", "general"]], True),
([["stream", "general"], ["topic", "Test"]], True),
([["is", "starred"]], False),
([["is", "mentioned"]], False),
([["is", "private"]], False),
([["pm_with", "[email protected]"]], False),
],
ids=[
"all_messages_narrow",
"stream_narrow",
"topic_narrow",
"private_conversation_narrow",
"starred_messages_narrow",
"mentions_narrow",
"private_messages_narrow",
],
)
def test_keypress_STREAM_MESSAGE(
self, mocker, msg_box, widget_size, narrow, expect_to_prefill, key
):
write_box = msg_box.model.controller.view.write_box
msg_box.model.narrow = narrow
size = widget_size(msg_box)
msg_box.keypress(size, key)
if expect_to_prefill:
write_box.stream_box_view.assert_called_once_with(
caption="PTEST",
stream_id=205,
)
else:
write_box.stream_box_view.assert_called_once_with(0)
@pytest.mark.parametrize("key", keys_for_command("EDIT_MESSAGE"))
@pytest.mark.parametrize(
[
"to_vary_in_each_message",
"realm_editing_allowed",
"msg_body_edit_enabled",
"msg_body_edit_limit",
"expect_editing_to_succeed",
],
[
({"sender_id": 2, "timestamp": 45}, True, True, 60, False),
({"sender_id": 1, "timestamp": 1}, True, False, 60, True),
({"sender_id": 1, "timestamp": 45}, False, True, 60, False),
({"sender_id": 1, "timestamp": 45}, True, True, 60, True),
({"sender_id": 1, "timestamp": 1}, True, True, 0, True),
],
ids=[
"msg_sent_by_other_user",
"topic_edit_only_after_time_limit",
"editing_not_allowed",
"all_conditions_met",
"no_msg_body_edit_limit",
],
)
def test_keypress_EDIT_MESSAGE(
self,
mocker,
message_fixture,
widget_size,
expect_editing_to_succeed,
to_vary_in_each_message,
realm_editing_allowed,
msg_body_edit_enabled,
msg_body_edit_limit,
key,
):
varied_message = dict(message_fixture, **to_vary_in_each_message)
msg_box = MessageBox(varied_message, self.model, message_fixture)
size = widget_size(msg_box)
msg_box.model.user_id = 1
msg_box.model.initial_data = {
"realm_allow_message_editing": realm_editing_allowed,
"realm_message_content_edit_limit_seconds": msg_body_edit_limit,
}
msg_box.model.client.get_raw_message.return_value = {
"raw_content": "Edit this message"
}
write_box = msg_box.model.controller.view.write_box
write_box.msg_edit_state = None
write_box.msg_body_edit_enabled = None
mocker.patch(BOXES + ".time", return_value=100)
# private messages cannot be edited after time-limit, if there is one.
if (
varied_message["type"] == "private"
and varied_message["timestamp"] == 1
and msg_body_edit_limit > 0
):
expect_editing_to_succeed = False
msg_box.keypress(size, key)
if expect_editing_to_succeed:
assert write_box.msg_edit_state.message_id == varied_message["id"]
assert write_box.msg_edit_state.old_topic == varied_message["subject"]
write_box.msg_write_box.set_edit_text.assert_called_once_with(
"Edit this message"
)
assert write_box.msg_body_edit_enabled == msg_body_edit_enabled
else:
assert write_box.msg_edit_state is None
write_box.msg_write_box.set_edit_text.assert_not_called()
@pytest.mark.parametrize(
"raw_html, expected_content",
[
# Avoid reformatting to preserve quote result readability
# fmt: off
case("""<blockquote>
<p>A</p>
</blockquote>
<p>B</p>""",
("{} A\n\n"
"B"),
id="quoted level 1"),
case("""<blockquote>
<blockquote>
<p>A</p>
</blockquote>
<p>B</p>
</blockquote>
<p>C</p>""",
("{} {} A\n\n"
"{} B\n\n"
"C"),
id="quoted level 2"),
case("""<blockquote>
<blockquote>
<blockquote>
<p>A</p>
</blockquote>
<p>B</p>
</blockquote>
<p>C</p>
</blockquote>
<p>D</p>""",
("{} {} {} A\n\n"
"{} {} B\n\n"
"{} C\n\n"
"D"),
id="quoted level 3"),
case("""<blockquote>
<p>A<br>
B</p>
</blockquote>
<p>C</p>""",
("{} A\n"
"{} B\n\n"
"C"),
id="multi-line quoting"),
case("""<blockquote>
<p><a href='https://chat.zulip.org/'>czo</a></p>
</blockquote>""",
("{} czo [1]\n"),
id="quoting with links"),
case("""<blockquote>
<blockquote>
<p>A<br>
B</p>
</blockquote>
</blockquote>""",
("{} {} A\n"
"{} {} B\n\n"),
id="multi-line level 2"),
case("""<blockquote>
<blockquote>
<p>A</p>
</blockquote>
<p>B</p>
<blockquote>
<p>C</p>
</blockquote>
</blockquote>""",
("{} {} A\n"
"{} B\n"
"{} \n"
"{} {} C\n\n"),
id="quoted level 2-1-2"),
case("""<p><a href='https://chat.zulip.org/1'>czo</a></p>
<blockquote>
<p><a href='https://chat.zulip.org/2'>czo</a></p>
<blockquote>
<p>A<br>
B</p>
</blockquote>
<p>C</p>
</blockquote>
<p>D</p>""",
("czo [1]\n"
"{} czo [2]\n"
"{} \n"
"{} {} A\n"
"{} {} B\n\n"
"{} C\n\n"
"D"),
id="quoted with links level 2"),
case("""<blockquote>
<blockquote>
<blockquote>
<p>A</p>
</blockquote>
<p>B</p>
<blockquote>
<p>C</p>
</blockquote>
<p>D</p>
</blockquote>
<p>E</p>
</blockquote>
<p>F</p>""",
("{} {} {} A\n"
"{} {} B\n"
"{} {} \n"
"{} {} {} C\n\n"
"{} {} D\n\n"
"{} E\n\n"
"F"),
id="quoted level 3-2-3"),
case("""<blockquote>
<p>A</p>
<blockquote>
<blockquote>
<blockquote>
<p>B<br>
C</p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>""",
("{} A\n"
"{} {} {} B\n"
"{} {} {} C\n"),
id="quoted level 1-3",
marks=pytest.mark.xfail(reason="rendered_bug")),
case("""<blockquote>
<p><a href="https://chat.zulip.org/1">czo</a></p>
<blockquote>
<p><a href="https://chat.zulip.org/2">czo</a></p>
<blockquote>
<p>A<br>
B</p>
</blockquote>
<p>C</p>
</blockquote>
<p>D<br>
E</p>
</blockquote>""",
("{} czo [1]\n"
"{} {} czo [2]\n"
"{} {} {} A\n"
"{} {} {} B\n"
"{} {} C\n"
"{} D\n"
"{} E\n"),
id="quoted with links level 1-3-1",
marks=pytest.mark.xfail(reason="rendered_bug")),
# fmt: on
],
)
def test_transform_content(self, mocker, raw_html, expected_content):
expected_content = expected_content.replace("{}", QUOTED_TEXT_MARKER)
content, *_ = MessageBox.transform_content(raw_html, SERVER_URL)
rendered_text = Text(content)
assert rendered_text.text == expected_content
# FIXME This is the same parametrize as MsgInfoView:test_height_reactions
@pytest.mark.parametrize(
"to_vary_in_each_message",
[
{
"reactions": [
{
"emoji_name": "thumbs_up",
"emoji_code": "1f44d",
"user": {
"email": "[email protected]",
"full_name": "Iago",
"id": 5,
},
"reaction_type": "unicode_emoji",
},
{
"emoji_name": "zulip",
"emoji_code": "zulip",
"user": {
"email": "[email protected]",
"full_name": "Iago",
"id": 5,
},
"reaction_type": "zulip_extra_emoji",
},
{
"emoji_name": "zulip",
"emoji_code": "zulip",
"user": {
"email": "[email protected]",
"full_name": "aaron",
"id": 1,
},
"reaction_type": "zulip_extra_emoji",
},
{
"emoji_name": "heart",
"emoji_code": "2764",
"user": {
"email": "[email protected]",
"full_name": "Iago",
"id": 5,
},
"reaction_type": "unicode_emoji",
},
]
}
],
)
def test_reactions_view(self, message_fixture, to_vary_in_each_message):
self.model.user_id = 1
varied_message = dict(message_fixture, **to_vary_in_each_message)
msg_box = MessageBox(varied_message, self.model, None)
reactions = to_vary_in_each_message["reactions"]
reactions_view = msg_box.reactions_view(reactions)
assert reactions_view.original_widget.text == (
":heart: 1 :thumbs_up: 1 :zulip: 2 "
)
assert reactions_view.original_widget.attrib == [
("reaction", 9),
(None, 1),
("reaction", 13),
(None, 1),
("reaction_mine", 9),
]
@pytest.mark.parametrize(
"message_links, expected_text, expected_attrib, expected_footlinks_width",
[
case(
OrderedDict(
[
(
"https://github.com/zulip/zulip-terminal/pull/1",
("#T1", 1, True),
),
]
),
"1: https://github.com/zulip/zulip-terminal/pull/1",
[("msg_link_index", 2), (None, 1), ("msg_link", 46)],
49,
id="one_footlink",
),
case(
OrderedDict(
[
("https://foo.com", ("Foo!", 1, True)),
("https://bar.com", ("Bar!", 2, True)),
]
),
"1: https://foo.com\n2: https://bar.com",
[
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
(None, 1),
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
],
18,
id="more_than_one_footlink",
),
case(
OrderedDict(
[
("https://example.com", ("https://example.com", 1, False)),
("http://example.com", ("http://example.com", 2, False)),
]
),
None,
None,
0,
id="similar_link_and_text",
),
case(
OrderedDict(
[
("https://foo.com", ("https://foo.com, Text", 1, True)),
("https://bar.com", ("Text, https://bar.com", 2, True)),
]
),
"1: https://foo.com\n2: https://bar.com",
[
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
(None, 1),
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
],
18,
id="different_link_and_text",
),
case(
OrderedDict(
[
("https://foo.com", ("Foo!", 1, True)),
("http://example.com", ("example.com", 2, False)),
("https://bar.com", ("Bar!", 3, True)),
]
),
"1: https://foo.com\n3: https://bar.com",
[
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
(None, 1),
("msg_link_index", 2),
(None, 1),
("msg_link", 15),
],
18,
id="http_default_scheme",
),
],
)
def test_footlinks_view(
self, message_links, expected_text, expected_attrib, expected_footlinks_width
):
footlinks, footlinks_width = MessageBox.footlinks_view(
message_links,
maximum_footlinks=3,
padded=True,
wrap="ellipsis",
)
if expected_text:
assert footlinks.original_widget.text == expected_text
assert footlinks.original_widget.attrib == expected_attrib
assert footlinks_width == expected_footlinks_width
else:
assert footlinks is None
assert not hasattr(footlinks, "original_widget")
@pytest.mark.parametrize(
"maximum_footlinks, expected_instance",
[
(0, type(None)),
(1, Padding),
(3, Padding),
],
)
def test_footlinks_limit(self, maximum_footlinks, expected_instance):
message_links = OrderedDict(
[
("https://github.com/zulip/zulip-terminal", ("ZT", 1, True)),
]
)
footlinks, _ = MessageBox.footlinks_view(
message_links,
maximum_footlinks=maximum_footlinks,
padded=True,
wrap="ellipsis",
)
assert isinstance(footlinks, expected_instance)
@pytest.mark.parametrize(
"key", keys_for_command("ENTER"), ids=lambda param: f"left_click-key:{param}"
)
def test_mouse_event_left_click(
self, mocker, msg_box, key, widget_size, compose_box_is_open
):
size = widget_size(msg_box)
col = 1
row = 1
focus = mocker.Mock()
mocker.patch(BOXES + ".keys_for_command", return_value=[key])
mocker.patch.object(msg_box, "keypress")
msg_box.model = mocker.Mock()
msg_box.model.controller.is_in_editor_mode.return_value = compose_box_is_open
msg_box.mouse_event(size, "mouse press", 1, col, row, focus)
if compose_box_is_open:
msg_box.keypress.assert_not_called()
else:
msg_box.keypress.assert_called_once_with(size, key)
|
require('./angular-locale_he-il');
module.exports = 'ngLocale';
|
import AddPermissionTemplate from './add-permissions-template';
import { debouncedAsyncValidator } from './validators';
export default {
fields: [
{
component: 'wizard',
name: 'wizzard',
isDynamic: true,
inModal: true,
showTitles: true,
title: 'Create role',
fields: [
{
title: 'Create role',
name: 'step-1',
nextStep: {
when: 'role-type',
stepMapper: {
copy: 'name-and-description',
create: 'add-permissions'
}
},
fields: [
{
component: 'radio',
name: 'role-type',
isRequired: true,
options: [
{
label: 'Create a role from scratch',
value: 'create'
},
{
label: 'Copy an existing role',
value: 'copy'
}
],
validate: [
{
type: 'required'
}
]
},
{
component: 'text-field',
name: 'role-name',
type: 'text',
label: 'Role name',
isRequired: true,
condition: {
when: 'role-type',
is: 'create'
},
validate: [
debouncedAsyncValidator,
{
type: 'required'
}
]
},
{
component: 'text-field',
name: 'role-description',
type: 'text',
label: 'Role description',
condition: {
when: 'role-type',
is: 'create'
}
},
{
component: 'base-role-table',
name: 'copy-base-role',
label: 'Base role',
isRequired: true,
condition: {
when: 'role-type',
is: 'copy'
},
validate: [
{
type: 'required'
}
]
}
]
},
{
title: 'Name and description',
name: 'name-and-description',
nextStep: 'add-permissions',
fields: [
{
component: 'text-field',
name: 'role-copy-name',
type: 'text',
label: 'Role name',
isRequired: true,
validate: [
debouncedAsyncValidator,
{
type: 'required'
}
]
},
{
component: 'text-field',
name: 'role-copy-description',
type: 'text',
label: 'Role description'
}
]
},
{
name: 'add-permissions',
title: 'Add permissions',
StepTemplate: AddPermissionTemplate,
fields: [
{
component: 'add-permissions-table',
name: 'add-permissions-table'
}
]
}
]
}
]
};
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Created by alex on 6/14/17.
*/
var core_1 = require("@angular/core");
require("./slider.component.htm");
var session_service_1 = require("../session/session.service");
var http_1 = require("@angular/http");
var slider_implementation_1 = require("./slider.implementation");
var ThrottleComponent = /** @class */ (function (_super) {
__extends(ThrottleComponent, _super);
function ThrottleComponent(sessionService, http, zone) {
return _super.call(this, sessionService, http, zone, function () { return '/throttle'; }, function (changedValue, sessionId) {
return { requestsPerSecond: changedValue, sessionId: sessionId };
}, function (jsonResponse) { return jsonResponse.requestsPerSecond; }, 20) || this;
}
ThrottleComponent = __decorate([
core_1.Component({
selector: 'throttle',
template: require('./slider.component.htm'),
styleUrls: []
}),
__metadata("design:paramtypes", [session_service_1.SessionService, http_1.Http, core_1.NgZone])
], ThrottleComponent);
return ThrottleComponent;
}(slider_implementation_1.SliderImpl));
exports.ThrottleComponent = ThrottleComponent;
//# sourceMappingURL=throttle.component.js.map |
// Just a random function
function randomNumber(min, max) {
return Math.floor(Math.random() * (1 + max - min) + min);
}
module.exports = randomNumber;
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/eda.ipynb (unless otherwise specified).
__all__ = [] |
import time
import requests
from typing import Union
from .baseendpoint import BaseEndpoint
from ..resources import KeepAliveResource
from ..exceptions import KeepAliveError, APIError, InvalidResponse
from ..utils import check_status_code
from ..compat import json
class KeepAlive(BaseEndpoint):
"""
KeepAlive operations.
"""
_error = KeepAliveError
def __call__(
self, session: requests.Session = None, lightweight: bool = None
) -> Union[dict, KeepAliveResource]:
"""
Makes keep alive request.
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: KeepAliveResource
"""
(response, response_json, elapsed_time) = self.request(session=session)
self.client.set_session_token(response_json.get("token"))
return self.process_response(
response_json, KeepAliveResource, elapsed_time, lightweight
)
def request(
self, method: str = None, params: dict = None, session: requests.Session = None
) -> (dict, float):
session = session or self.client.session
time_sent = time.time()
try:
response = session.post(
self.url,
headers=self.client.keep_alive_headers,
timeout=(self.connect_timeout, self.read_timeout),
)
except requests.ConnectionError as e:
raise APIError(None, exception=e)
except Exception as e:
raise APIError(None, exception=e)
elapsed_time = time.time() - time_sent
check_status_code(response)
try:
response_json = json.loads(response.content.decode("utf-8"))
except ValueError:
raise InvalidResponse(response.text)
if self._error_handler:
self._error_handler(response_json)
return response, response_json, elapsed_time
def _error_handler(
self, response: dict, method: str = None, params: dict = None
) -> None:
if response.get("status") != "SUCCESS":
raise self._error(response)
@property
def url(self) -> str:
return "%s%s" % (self.client.identity_uri, "keepAlive")
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
''' Provide a pandas DataFrame instance of four of the datasets from
gapminder.org. The data sets in this module are:
fertility, life_expectancy, population, regions
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh imports
from ..util.sampledata import external_csv
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
__all__ = (
'fertility',
'life_expectancy',
'population',
'regions',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
fertility = external_csv('gapminder', 'gapminder_fertility.csv', index_col='Country', encoding='utf-8')
life_expectancy = external_csv('gapminder', 'gapminder_life_expectancy.csv', index_col='Country', encoding='utf-8')
population = external_csv('gapminder', 'gapminder_population.csv', index_col='Country', encoding='utf-8')
regions = external_csv('gapminder', 'gapminder_regions.csv', index_col='Country', encoding='utf-8')
#-----------------------------------------------------------------------------
# Original data is from Gapminder - www.gapminder.org.
# The google docs links are maintained by gapminder
# The following script was used to get the data from gapminder
# and process it into the csvs stored in bokeh's sampledata.
'''
population_url = "http://spreadsheets.google.com/pub?key=phAwcNAVuyj0XOoBL_n5tAQ&output=xls"
fertility_url = "http://spreadsheets.google.com/pub?key=phAwcNAVuyj0TAlJeCEzcGQ&output=xls"
life_expectancy_url = "http://spreadsheets.google.com/pub?key=tiAiXcrneZrUnnJ9dBU-PAw&output=xls"
regions_url = "https://docs.google.com/spreadsheets/d/1OxmGUNWeADbPJkQxVPupSOK5MbAECdqThnvyPrwG5Os/pub?gid=1&output=xls"
def _get_data(url):
# Get the data from the url and return only 1962 - 2013
df = pd.read_excel(url, index_col=0)
df = df.unstack().unstack()
df = df[(df.index >= 1964) & (df.index <= 2013)]
df = df.unstack().unstack()
return df
fertility_df = _get_data(fertility_url)
life_expectancy_df = _get_data(life_expectancy_url)
population_df = _get_data(population_url)
regions_df = pd.read_excel(regions_url, index_col=0)
# have common countries across all data
fertility_df = fertility_df.drop(fertility_df.index.difference(life_expectancy_df.index))
population_df = population_df.drop(population_df.index.difference(life_expectancy_df.index))
regions_df = regions_df.drop(regions_df.index.difference(life_expectancy_df.index))
fertility_df.to_csv('gapminder_fertility.csv')
population_df.to_csv('gapminder_population.csv')
life_expectancy_df.to_csv('gapminder_life_expectancy.csv')
regions_df.to_csv('gapminder_regions.csv')
'''
#-----------------------------------------------------------------------------
|
const webpack = require('webpack');
const { CheckerPlugin } = require('awesome-typescript-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
output: {
path: path.resolve(__dirname, './dist/'),
filename: '[name].js',
libraryTarget: 'umd',
publicPath: '/',
},
module: {
rules: [{
test: /\.tsx?/,
loader: 'awesome-typescript-loader?module=es6'
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
]
},
entry: {
engine: path.resolve(__dirname, './src/index.tsx'),
},
devServer: {
contentBase: path.resolve(__dirname, './static'),
},
resolve: {
extensions: ['.ts', '.js', '.tsx', '.jsx'],
},
devtool: 'inline-source-map',
plugins: [
new CheckerPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './src/index.html'),
}),
]
} |
const {Worlds, Fortunes} = require('../models/sequelize');
const Bluebird = require('bluebird');
module.exports = {
getWorld: id => Worlds.findOne({where: {id}}),
getWorldLean: id => Worlds.findOne({where: {id}, raw: true}),
allFortunes: () => Fortunes.findAll(),
saveWorlds: worlds => Bluebird.all(worlds.map(world => world.save())),
}; |
"""
Database models for user_tasks.
"""
import logging
from uuid import uuid4
from celery import current_app
from django.conf import settings as django_settings
from django.core.validators import URLValidator
from django.db import models, transaction
from django.db.models import Q
from django.db.models.expressions import F
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from user_tasks import user_task_stopped
from .conf import settings
from .exceptions import TaskCanceledException
LOGGER = logging.getLogger(__name__)
# The pylint "disable=no-member" comments are needed because of the 'self' argument to the parent field definition.
# See https://github.com/landscapeio/pylint-django/issues/35 for more details
class UserTaskStatus(TimeStampedModel):
"""
The current status of an asynchronous task running on behalf of a particular user.
The methods of this class should generally not be run as part of larger
transactions. If they are, some deadlocks and race conditions become
possible.
"""
PENDING = 'Pending'
IN_PROGRESS = 'In Progress'
SUCCEEDED = 'Succeeded'
FAILED = 'Failed'
CANCELED = 'Canceled'
RETRYING = 'Retrying'
STATE_TRANSLATIONS = {
PENDING: _('Pending'),
IN_PROGRESS: _('In Progress'),
SUCCEEDED: _('Succeeded'),
FAILED: _('Failed'),
CANCELED: _('Canceled'),
RETRYING: _('Retrying'),
}
uuid = models.UUIDField(default=uuid4, unique=True, editable=False, help_text='Unique ID for use in APIs')
user = models.ForeignKey(
django_settings.AUTH_USER_MODEL,
help_text='The user who triggered the task',
on_delete=models.CASCADE,
)
# Auto-generated Celery task IDs will always be 36 characters, but longer custom ones can be specified
task_id = models.CharField(max_length=128, unique=True, db_index=True,
help_text='UUID of the associated Celery task')
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, default=None,
help_text='Status of the containing task grouping (if any)')
is_container = models.BooleanField(default=False,
help_text='True if this status corresponds to a container of multiple tasks')
task_class = models.CharField(max_length=128, help_text='Fully qualified class name of the task being performed')
name = models.CharField(max_length=255, help_text='A name for this task which the triggering user will understand')
state = models.CharField(max_length=128, default=PENDING)
completed_steps = models.PositiveSmallIntegerField(default=0)
total_steps = models.PositiveSmallIntegerField()
attempts = models.PositiveSmallIntegerField(default=1, help_text='How many times has execution been attempted?')
class Meta:
"""
Additional configuration for the UserTaskStatus model.
"""
verbose_name_plural = 'user task statuses'
def start(self):
"""
Mark the task as having been started (as opposed to waiting for an available worker), and save it.
"""
if self.state == UserTaskStatus.CANCELED and not self.is_container:
raise TaskCanceledException
self.state = UserTaskStatus.IN_PROGRESS
self.save(update_fields={'state', 'modified'})
if self.parent_id:
with transaction.atomic():
parent = UserTaskStatus.objects.select_for_update().get(pk=self.parent_id)
if parent.state in (UserTaskStatus.PENDING, UserTaskStatus.RETRYING):
parent.start()
def increment_completed_steps(self, steps=1):
"""
Increase the value of :py:attr:`completed_steps` by the given number and save, then check for cancellation.
If cancellation of the task has been requested, a TaskCanceledException
will be raised to abort execution. If any special cleanup is required,
this exception should be caught and handled appropriately.
This method should be called often enough to provide a useful
indication of progress, but not so often as to cause undue burden on
the database.
"""
UserTaskStatus.objects.filter(pk=self.id).update(completed_steps=F('completed_steps') + steps,
modified=now())
self.refresh_from_db(fields={'completed_steps', 'modified', 'state'})
if self.parent:
self.parent.increment_completed_steps(steps) # pylint: disable=no-member
# Was a cancellation command recently sent?
if self.state == self.CANCELED and not self.is_container:
raise TaskCanceledException
def increment_total_steps(self, steps):
"""Increase the value of :py:attr:`total_steps` by the given number and save."""
# Assume that other processes may be making concurrent changes
UserTaskStatus.objects.filter(pk=self.id).update(total_steps=F('total_steps') + steps, modified=now())
self.refresh_from_db(fields={'total_steps', 'modified'})
if self.parent:
self.parent.increment_total_steps(steps) # pylint: disable=no-member
def cancel(self):
"""
Cancel the associated task if it hasn't already finished running.
"""
if self.is_container:
children = UserTaskStatus.objects.filter(parent=self)
for child in children:
child.cancel()
elif self.state in (UserTaskStatus.PENDING, UserTaskStatus.RETRYING):
current_app.control.revoke(self.task_id)
user_task_stopped.send_robust(UserTaskStatus, status=self)
with transaction.atomic():
status = UserTaskStatus.objects.select_for_update().get(pk=self.id)
if status.state in (UserTaskStatus.CANCELED, UserTaskStatus.FAILED, UserTaskStatus.SUCCEEDED):
return
status.state = UserTaskStatus.CANCELED
status.save(update_fields={'state', 'modified'})
self.state = status.state
self.modified = status.modified
def fail(self, message):
"""
Mark the task as having failed for the given reason, and save it.
The message will be available as the :py:attr:`UserTaskArtifact.text`
field of a UserTaskArtifact with name "Error". There may be more than
one such artifact for a single UserTaskStatus, especially if it
represents a container for multiple parallel tasks.
"""
with transaction.atomic():
UserTaskArtifact.objects.create(status=self, name='Error', text=message)
self.state = UserTaskStatus.FAILED
self.save(update_fields={'state', 'modified'})
if self.parent:
self.parent.fail(message) # pylint: disable=no-member
def retry(self):
"""
Update the status to reflect that a problem was encountered and the task will be retried later.
"""
# Note that a retry does not affect the state of a containing task
# grouping; it's effectively still in progress
self.attempts += 1
self.state = UserTaskStatus.RETRYING
self.save(update_fields={'attempts', 'state', 'modified'})
def set_name(self, name):
"""
Give the specified name to this status and all of its ancestors.
"""
self.name = name
self.save(update_fields={'name', 'modified'})
if self.parent:
self.parent.set_name(name) # pylint: disable=no-member
def set_state(self, custom_state):
"""
Set the state to a custom in-progress value.
This can be done to indicate which stage of a long task is currently
being executed, like "Sending email messages".
"""
with transaction.atomic():
status = UserTaskStatus.objects.select_for_update().get(pk=self.id)
if status.state == UserTaskStatus.CANCELED and not self.is_container:
raise TaskCanceledException
status.state = custom_state
status.save(update_fields={'state', 'modified'})
self.state = status.state
self.modified = status.modified
if self.parent and self.parent.task_class != 'celery.group': # pylint: disable=no-member
self.parent.set_state(custom_state) # pylint: disable=no-member
@property
def state_text(self):
"""
Get the translation into the current language of the current state of this status instance.
"""
return self.STATE_TRANSLATIONS.get(self.state, self.state)
def succeed(self):
"""
Mark the task as having finished successfully and save it.
"""
if self.completed_steps < self.total_steps:
self.increment_completed_steps(self.total_steps - self.completed_steps)
self.state = UserTaskStatus.SUCCEEDED
self.save(update_fields={'state', 'modified'})
if self.parent_id:
query = UserTaskStatus.objects.filter(~Q(state=UserTaskStatus.SUCCEEDED), parent__pk=self.parent_id)
if not query.exists():
self.parent.succeed() # pylint: disable=no-member
def __str__(self):
"""
Get a string representation of this task.
"""
return f'<UserTaskStatus: {self.name}>'
class UserTaskArtifact(TimeStampedModel):
"""
An artifact (or error message) generated for a user by an asynchronous task.
May be a file, a URL, or text stored directly in the database table.
"""
uuid = models.UUIDField(default=uuid4, unique=True, editable=False, help_text='Unique ID for use in APIs')
status = models.ForeignKey(UserTaskStatus, on_delete=models.CASCADE, related_name='artifacts')
name = models.CharField(max_length=255, default='Output',
help_text='Distinguishes between multiple artifact types for the same task')
file = models.FileField(null=True, blank=True, storage=settings.USER_TASKS_ARTIFACT_STORAGE,
upload_to='user_tasks/%Y/%m/%d/')
url = models.TextField(blank=True, validators=[URLValidator()])
text = models.TextField(blank=True)
def __str__(self):
"""
Get a string representation of this artifact.
"""
if self.file:
content = self.file.name
elif self.url:
content = self.url
elif len(self.text) > 50:
content = self.text[:47] + '...'
else:
content = self.text
return f'<UserTaskArtifact: ({self.name}) {content}>'
|
# -*- coding: utf-8 -*-
"""Loan Qualifier Application.
This is a command line application to match applicants with qualifying loans.
Example:
$ python app.py
"""
import sys
import fire
import questionary
from pathlib import Path
import csv
from questionary.prompts.common import Choice
from questionary.prompts.confirm import confirm
from qualifier.utils.fileio import load_csv
from qualifier.utils.calculators import (
calculate_monthly_debt_ratio,
calculate_loan_to_value_ratio,
)
from qualifier.filters.max_loan_size import filter_max_loan_size
from qualifier.filters.credit_score import filter_credit_score
from qualifier.filters.debt_to_income import filter_debt_to_income
from qualifier.filters.loan_to_value import filter_loan_to_value
def load_bank_data():
"""Ask for the file path to the latest banking data and load the CSV file.
Returns:
The bank data from the data rate sheet CSV file.
"""
csvpath = questionary.text("Enter a file path to a rate-sheet (.csv):").ask()
csvpath = Path(csvpath)
if not csvpath.exists():
sys.exit(f"Oops! Can't find this path: {csvpath}")
return load_csv(csvpath)
def get_applicant_info():
"""Prompt dialog to get the applicant's financial information.
Returns:
Returns the applicant's financial information.
"""
credit_score = questionary.text("What's your credit score?").ask()
debt = questionary.text("What's your current amount of monthly debt?").ask()
income = questionary.text("What's your total monthly income?").ask()
loan_amount = questionary.text("What's your desired loan amount?").ask()
home_value = questionary.text("What's your home value?").ask()
credit_score = int(credit_score)
debt = float(debt)
income = float(income)
loan_amount = float(loan_amount)
home_value = float(home_value)
return credit_score, debt, income, loan_amount, home_value
def find_qualifying_loans(bank_data, credit_score, debt, income, loan, home_value):
"""Determine which loans the user qualifies for.
Loan qualification criteria is based on:
- Credit Score
- Loan Size
- Debit to Income ratio (calculated)
- Loan to Value ratio (calculated)
Args:
bank_data (list): A list of bank data.
credit_score (int): The applicant's current credit score.
debt (float): The applicant's total monthly debt payments.
income (float): The applicant's total monthly income.
loan (float): The total loan amount applied for.
home_value (float): The estimated home value.
Returns:
A list of the banks willing to underwrite the loan.
"""
# Calculate the monthly debt ratio
monthly_debt_ratio = calculate_monthly_debt_ratio(debt, income)
print(f"The monthly debt to income ratio is {monthly_debt_ratio:.02f}")
# Calculate loan to value ratio
loan_to_value_ratio = calculate_loan_to_value_ratio(loan, home_value)
print(f"The loan to value ratio is {loan_to_value_ratio:.02f}.")
# Run qualification filters
bank_data_filtered = filter_max_loan_size(loan, bank_data)
bank_data_filtered = filter_credit_score(credit_score, bank_data_filtered)
bank_data_filtered = filter_debt_to_income(monthly_debt_ratio, bank_data_filtered)
bank_data_filtered = filter_loan_to_value(loan_to_value_ratio, bank_data_filtered)
print(f"Found {len(bank_data_filtered)} qualifying loans")
return bank_data_filtered
def save_csv(qualifying_loans):
"""Allows the user to input a csv path to export his qualifying loans and then proceeds to write them into a csv file with a predetermined header.
Args:
qualifying_loans (list of lists): The qualifying bank loans.
"""
#This line of code asks the user where he would like to save his file using the questionary.text function, it also reminds them to add desired file name and extension
csvpath = questionary.text("Enter a file path to save your qualifying loans as a (.csv):, be sure to add the desired file name followed by the .csv extension, if you would like to save to the default press enter.").ask()
#This line of code allows for the user to press enter on the previous prompt to select a default saving path
if csvpath == "":
csvpath = Path("../loan_qualifier_app/data/qualifying_loans.csv")
#Sets the header for the output file
header = ["Lender","Max Loan Amount","Max LTV","Max DTI","Min Credit Score","Interest Rate"]
#Creates the csv file using the "csvpath" inputed or defaulted, proceeds to write the header and each applicable loan as a row
with open(csvpath, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(header)
for row in qualifying_loans:
csvwriter.writerow(row)
#Prints back the filepath of the save file to remind the user of where it has been saved
print(f"Your file has been saved to {csvpath}")
def save_qualifying_loans(qualifying_loans):
"""Saves the qualifying loans to a CSV file.
Args:
qualifying_loans (list of lists): The qualifying bank loans.
"""
# @TODO: Complete the usability dialog for savings the CSV Files.
# YOUR CODE HERE!
#This two lines of code verify if there are available loans to save, if there are none it returns a message telling the user to improve his credit conditions and exits the program
if len(qualifying_loans) == 0:
sys.exit("Please try to improve your credit score, debt-to-income ratio and loan-to-value ratio and try again!.")
#If there are available loans to save, it prompts the user to select whether he wants to save them or not using the questionary "Select" function, if the choice is "Yes"
# it calls the save_csv function, if choice is "No" it prints a Goodbye message and exits the system.
else:
confirm = questionary.confirm("Would you like to save the qualifying loans found in a .csv file?").ask()
if confirm == True:
save_csv(qualifying_loans)
else:
sys.exit(f"Goodbye, good luck in your loan search!")
def run():
"""The main function for running the script."""
# Load the latest Bank data
bank_data = load_bank_data()
# Get the applicant's information
credit_score, debt, income, loan_amount, home_value = get_applicant_info()
# Find qualifying loans
qualifying_loans = find_qualifying_loans(
bank_data, credit_score, debt, income, loan_amount, home_value
)
# Save qualifying loans
save_qualifying_loans(qualifying_loans)
if __name__ == "__main__":
fire.Fire(run)
|
import Vue from "vue";
import App from "./App.vue";
import router from "./router/index";
import "./registerServiceWorker";
import { store } from "./store/store";
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
|
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 13, 15, 12, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.