file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
form-component.js | (function($) {
//chosen select
$(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true});
//tag input
function onAddTag(tag) {
alert("Added a tag: " + tag);
}
function onRemoveTag(tag) {
alert("Removed a tag: " + tag);
}
function | (input,tag) {
alert("Changed a tag: " + tag);
}
$(function() {
$('#tags_1').tagsInput({width:'auto'});
$('.tags_input').tagsInput({width:'auto'});
$('#tags_2').tagsInput({
width: '250',
onChange: function(elem, elem_tags)
{
var languages = ['php','ruby','javascript'];
$('.tag', elem_tags).each(function()
{
if($(this).text().search(new RegExp('\\b(' + languages.join('|') + ')\\b')) >= 0)
$(this).css('background-color', 'yellow');
});
}
});
// Uncomment this line to see the callback functions in action
// $('input.tags').tagsInput({onAddTag:onAddTag,onRemoveTag:onRemoveTag,onChange: onChangeTag});
// Uncomment this line to see an input with no interface for adding new tags.
// $('input.tags').tagsInput({interactive:false});
});
//color picker
$('.cp1').colorpicker({
format: 'hex'
});
$('.cp2').colorpicker();
//time picker
$('#timepicker1, #timepicker3').timepicker();
$('#timepicker2, #timepicker4').timepicker({
minuteStep: 1,
template: 'modal',
showSeconds: true,
showMeridian: false
});
//clock face time picker
/*
$('#clockface_1').clockface();
$('#clockface_2').clockface({
format: 'HH:mm',
trigger: 'manual'
});
$('#clockface_2_toggle-btn').click(function (e) {
e.stopPropagation();
$('#clockface_2').clockface('toggle');
});
*/
//date picker
if (top.location != location) {
top.location.href = document.location.href ;
}
$(function(){
window.prettyPrint && prettyPrint();
$('#dp1').datepicker({
format: 'mm-dd-yyyy'
});
$('#dp2').datepicker();
$('#dp3').datepicker();
$('#dp3').datepicker();
$('#dpYears').datepicker();
$('#dpMonths').datepicker();
var startDate = new Date(2012,1,20);
var endDate = new Date(2012,1,25);
$('#dp4').datepicker()
.on('changeDate', function(ev){
if (ev.date.valueOf() > endDate.valueOf()){
$('#alert').show().find('strong').text('The start date can not be greater then the end date');
} else {
$('#alert').hide();
startDate = new Date(ev.date);
$('#startDate').text($('#dp4').data('date'));
}
$('#dp4').datepicker('hide');
});
$('#dp5').datepicker()
.on('changeDate', function(ev){
if (ev.date.valueOf() < startDate.valueOf()){
$('#alert').show().find('strong').text('The end date can not be less then the start date');
} else {
$('#alert').hide();
endDate = new Date(ev.date);
$('#endDate').text($('#dp5').data('date'));
}
$('#dp5').datepicker('hide');
});
// disabling dates
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').datepicker({
onRender: function(date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');
});
/*
//daterange picker
$('#reservation').daterangepicker();
$('#reportrange').daterangepicker(
{
ranges: {
'Today': ['today', 'today'],
'Yesterday': ['yesterday', 'yesterday'],
'Last 7 Days': [Date.today().add({ days: -6 }), 'today'],
'Last 30 Days': [Date.today().add({ days: -29 }), 'today'],
'This Month': [Date.today().moveToFirstDayOfMonth(), Date.today().moveToLastDayOfMonth()],
'Last Month': [Date.today().moveToFirstDayOfMonth().add({ months: -1 }), Date.today().moveToFirstDayOfMonth().add({ days: -1 })]
},
opens: 'left',
format: 'MM/dd/yyyy',
separator: ' to ',
startDate: Date.today().add({ days: -29 }),
endDate: Date.today(),
minDate: '01/01/2012',
maxDate: '12/31/2013',
locale: {
applyLabel: 'Submit',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
},
showWeekNumbers: true,
buttonClasses: ['btn-danger']
},
function(start, end) {
$('#reportrange span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy'));
}
);
//Set the initial state of the picker label
$('#reportrange span').html(Date.today().add({ days: -29 }).toString('MMMM d, yyyy') + ' - ' + Date.today().toString('MMMM d, yyyy'));
*/
//toggle button
/*
window.prettyPrint && prettyPrint();
$('#normal-toggle-button').toggleButtons();
$('#text-toggle-button').toggleButtons({
width: 220,
label: {
enabled: "Lorem Ipsum",
disabled: "Dolor Sit"
}
});
$('#not-animated-toggle-button').toggleButtons({
animated: false
});
$('#transition-percent-toggle-button').toggleButtons({
transitionspeed: "500%"
});
$('#transition-value-toggle-button').toggleButtons({
transitionspeed: 1 // default value: 0.05
});
$('#danger-toggle-button').toggleButtons({
style: {
// Accepted values ["primary", "danger", "info", "success", "warning"] or nothing
enabled: "danger",
disabled: "info"
}
});
$('#info-toggle-button').toggleButtons({
style: {
// Accepted values ["primary", "danger", "info", "success", "warning"] or nothing
enabled: "info",
disabled: "info"
}
});
$('#success-toggle-button').toggleButtons({
style: {
// Accepted values ["primary", "danger", "info", "success", "warning"] or nothing
enabled: "success",
disabled: "info"
}
});
$('#warning-toggle-button').toggleButtons({
style: {
// Accepted values ["primary", "danger", "info", "success", "warning"] or nothing
enabled: "warning",
disabled: "info"
}
});
$('#height-text-style-toggle-button').toggleButtons({
height: 100,
font: {
'line-height': '100px',
'font-size': '18px',
'font-style': 'regular'
}
});
*/
//WYSIWYG Editor
$('.wysihtmleditor5').wysihtml5();
})(jQuery);
$( document ).ajaxComplete(function( event, xhr, settings ) {
$(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true});
$('.wysihtmleditor5').each(function(){
if($(this).closest('div.control-group').find("ul.wysihtml5-toolbar").length ==0){
$(this).wysihtml5();
}
});
$('.tags_input').each(function(){
if($(this).closest('div.controls').find("div.tagsinput").length ==0){
$(this).tagsInput({width:'auto'});
}
});
//SCRIPT DE CHANGEMENT DU PLACEHOLDER DES SELECT-->
$(".search-field input.default").val(select_options);
$(".chzn-single.chzn-default span").html(select_option);
$(".chzn-select-deselect.chzn-default span").html(select_option);
//color picker
$('.cp1').colorpicker({
format: 'hex'
});
$('.cp2').colorpicker();
}); | onChangeTag |
Models.py | # MODELS contains a set of functions for minimisation to seismic spectra.
# It can be modified as appropriate.
import numpy as np
from . import config as cfg
MODS = ["BRUNE", "BOATWRIGHT"]
# UTIL FUNCS
def which_model(mod):
if mod in MODS:
if mod == "BRUNE":
return BRUNE_MODEL
if mod == "BOATWRIGHT":
return BOATWRIGHT_MODEL
else:
raise ValueError(f"Model {mod} not available. Choose from {MODS}.")
def scale_to_motion(motion, f):
if motion.lower() == 'displacement':
return 0
elif motion.lower() == 'velocity':
return np.log10(2*np.pi*f)
elif motion.lower() == 'acceleration':
|
else:
return None
# DEFAULT PARAMS FOR SOURCE MODE:
BRUNE_MODEL = (1, 2) # omega squared
BOATWRIGHT_MODEL = (2, 2) # omega cubed
#
MODEL = which_model(cfg.MODELS["MODEL"])
MOTION = cfg.MODELS["MOTION"]
# MINIMISATION FUNCTIONS
## Source model
def source(f, llpsp, fc):
gam, n = MODEL
loga = llpsp - (1/gam)*np.log10((1+(f/fc)**(gam*n)))
return loga
# freq independent t-star attenuation model
def t_star(f, ts):
return -(np.pi*f*ts / np.log(10))
# freq dependent t-star attenuation
def t_star_freq(f, ts, a):
return -(np.pi*(f**(1-a))*ts / np.log(10))
# combine models
def simple_model(f, llpsp, fc, ts):
global MOTION
"""
Simple attenuated source model to minimise.
"""
return source(f, llpsp, fc) + t_star(f, ts) + scale_to_motion(MOTION, f)
def simple_model_fdep(f, llpsp, fc, ts, a):
"""
Simple model but with frequency dependent attenuation.
"""
return source(f, llpsp, fc) + t_star_freq(f, ts, a) + scale_to_motion(MOTION, f)
| return np.log10(np.power(2*np.pi*f,2)) |
kivy_wrapper.py | """
A simple kivy wrapper
"""
import kivy
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.clock import Clock
"""
A really simple discrete environment to test for changing policies/environment
"""
import numpy as np
import random
from gym.spaces import Box, Discrete, Dict
import gym
from gym import Wrapper
class KivyWrapper(BoxLayout):
def __init__(self, env=None, **kwargs):
|
def show_screen(self, board, info, update):
text = ""
if update and board is not None:
text += "\n".join(board)
text += "\n"
text += "\n".join(info)
self.info.text = text
def update(self, dt):
for idx in range(10):
if self.action == str(idx):
self.action = idx
if self.action is not None:
text_render, info, done = self.env.play(self.action)
else:
text_render, info = self.env.render()
self.show_screen(text_render, info, True)
self.action = None
def _keyboard_closed(self):
# print('My keyboard have been closed!')
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
key_register = modifiers + [text]
# print("Key input received is:\n{}".format(key_register))
self.action = text
# Keycode is composed of an integer + a string
# If we hit escape, release the keyboard
if keycode[1] == "escape":
keyboard.release()
# Return True to accept the key. Otherwise, it will be used by
# the system.
return True
def app_wrapper(env):
class KivyApp(App):
def build(self):
game = KivyWrapper(env=env)
game.env.reset()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
return KivyApp
| super(KivyWrapper, self).__init__(**kwargs)
self.env = env
self.action = None
self.info = Label(text="Starting Game", font_name="RobotoMono-Regular")
# self._trigger = Clock.schedule_interval(self.update, 1.0/60.0)
self.add_widget(self.info)
self._keyboard = Window.request_keyboard(self._keyboard_closed, self, "text")
if self._keyboard.widget:
# If it exists, this widget is a VKeyboard object which you can use
# to change the keyboard layout.
pass
self._keyboard.bind(on_key_down=self._on_keyboard_down) |
report.go | package requester
import (
"bytes"
"fmt"
"io"
"log"
"sort"
"time"
)
const barChar = "■"
const maxRes = 1000000
type report struct {
avgTotal float64
fastest float64
slowest float64
average float64
rps float64
avgConn float64
avgDNS float64
avgReq float64
avgRes float64
avgDelay float64
connLats []float64
dnsLats []float64
reqLats []float64
resLats []float64
delayLats []float64
offsets []float64
statusCodes []int
results chan *result
done chan bool
total time.Duration
errorDist map[string]int
lats []float64
sizeTotal int64
numRes int64
output string
w io.Writer
}
func newReport(w io.Writer, results chan *result, output string, n int) *report {
| func runReporter(r *report) {
for res := range r.results {
r.numRes++
if res.err != nil {
r.errorDist[res.err.Error()]++
} else {
r.avgTotal += res.duration.Seconds()
r.avgConn += res.connDuration.Seconds()
r.avgDelay += res.delayDuration.Seconds()
r.avgDNS += res.dnsDuration.Seconds()
r.avgReq += res.reqDuration.Seconds()
r.avgRes += res.resDuration.Seconds()
if len(r.resLats) < maxRes {
r.lats = append(r.lats, res.duration.Seconds())
r.connLats = append(r.connLats, res.connDuration.Seconds())
r.dnsLats = append(r.dnsLats, res.dnsDuration.Seconds())
r.reqLats = append(r.reqLats, res.reqDuration.Seconds())
r.delayLats = append(r.delayLats, res.delayDuration.Seconds())
r.resLats = append(r.resLats, res.resDuration.Seconds())
r.statusCodes = append(r.statusCodes, res.statusCode)
r.offsets = append(r.offsets, res.offset.Seconds())
}
if res.contentLength > 0 {
r.sizeTotal += res.contentLength
}
}
}
r.done <- true
}
func (r *report) finalize(total time.Duration) {
r.total = total
r.rps = float64(r.numRes)
r.average = r.avgTotal / float64(len(r.lats))
r.avgConn = r.avgConn / float64(len(r.lats))
r.avgDelay = r.avgDelay / float64(len(r.lats))
r.avgDNS = r.avgDNS / float64(len(r.lats))
r.avgReq = r.avgReq / float64(len(r.lats))
r.avgRes = r.avgRes / float64(len(r.lats))
r.print()
}
func (r *report) print() {
buf := &bytes.Buffer{}
if err := newTemplate(r.output).Execute(buf, r.snapshot()); err != nil {
log.Println("error:", err.Error())
return
}
r.printf(buf.String())
r.printf("\n")
}
func (r *report) printf(s string, v ...interface{}) {
fmt.Fprintf(r.w, s, v...)
}
func (r *report) snapshot() Report {
snapshot := Report{
AvgTotal: r.avgTotal,
Average: r.average,
Rps: r.rps,
SizeTotal: r.sizeTotal,
AvgConn: r.avgConn,
AvgDNS: r.avgDNS,
AvgReq: r.avgReq,
AvgRes: r.avgRes,
AvgDelay: r.avgDelay,
Total: r.total,
ErrorDist: r.errorDist,
NumRes: r.numRes,
Lats: make([]float64, len(r.lats)),
ConnLats: make([]float64, len(r.lats)),
DnsLats: make([]float64, len(r.lats)),
ReqLats: make([]float64, len(r.lats)),
ResLats: make([]float64, len(r.lats)),
DelayLats: make([]float64, len(r.lats)),
Offsets: make([]float64, len(r.lats)),
StatusCodes: make([]int, len(r.lats)),
}
if len(r.lats) == 0 {
return snapshot
}
snapshot.SizeReq = r.sizeTotal / int64(len(r.lats))
copy(snapshot.Lats, r.lats)
copy(snapshot.ConnLats, r.connLats)
copy(snapshot.DnsLats, r.dnsLats)
copy(snapshot.ReqLats, r.reqLats)
copy(snapshot.ResLats, r.resLats)
copy(snapshot.DelayLats, r.delayLats)
copy(snapshot.StatusCodes, r.statusCodes)
copy(snapshot.Offsets, r.offsets)
sort.Float64s(r.lats)
r.fastest = r.lats[0]
r.slowest = r.lats[len(r.lats)-1]
sort.Float64s(r.connLats)
sort.Float64s(r.dnsLats)
sort.Float64s(r.reqLats)
sort.Float64s(r.resLats)
sort.Float64s(r.delayLats)
snapshot.Histogram = r.histogram()
snapshot.LatencyDistribution = r.latencies()
snapshot.Fastest = r.fastest
snapshot.Slowest = r.slowest
snapshot.ConnMax = r.connLats[0]
snapshot.ConnMin = r.connLats[len(r.connLats)-1]
snapshot.DnsMax = r.dnsLats[0]
snapshot.DnsMin = r.dnsLats[len(r.dnsLats)-1]
snapshot.ReqMax = r.reqLats[0]
snapshot.ReqMin = r.reqLats[len(r.reqLats)-1]
snapshot.DelayMax = r.delayLats[0]
snapshot.DelayMin = r.delayLats[len(r.delayLats)-1]
snapshot.ResMax = r.resLats[0]
snapshot.ResMin = r.resLats[len(r.resLats)-1]
statusCodeDist := make(map[int]int, len(snapshot.StatusCodes))
for _, statusCode := range snapshot.StatusCodes {
statusCodeDist[statusCode]++
}
snapshot.StatusCodeDist = statusCodeDist
return snapshot
}
func (r *report) latencies() []LatencyDistribution {
pctls := []int{10, 25, 50, 75, 90, 95, 99}
data := make([]float64, len(pctls))
j := 0
for i := 0; i < len(r.lats) && j < len(pctls); i++ {
current := i * 100 / len(r.lats)
if current >= pctls[j] {
data[j] = r.lats[i]
j++
}
}
res := make([]LatencyDistribution, len(pctls))
for i := 0; i < len(pctls); i++ {
if data[i] > 0 {
res[i] = LatencyDistribution{Percentage: pctls[i], Latency: data[i]}
}
}
return res
}
func (r *report) histogram() []Bucket {
bc := 10
buckets := make([]float64, bc+1)
counts := make([]int, bc+1)
bs := (r.slowest - r.fastest) / float64(bc)
for i := 0; i < bc; i++ {
buckets[i] = r.fastest + bs*float64(i)
}
buckets[bc] = r.slowest
var bi int
var max int
for i := 0; i < len(r.lats); {
if r.lats[i] <= buckets[bi] {
i++
counts[bi]++
if max < counts[bi] {
max = counts[bi]
}
} else if bi < len(buckets)-1 {
bi++
}
}
res := make([]Bucket, len(buckets))
for i := 0; i < len(buckets); i++ {
res[i] = Bucket{
Mark: buckets[i],
Count: counts[i],
Frequency: float64(counts[i]) / float64(len(r.lats)),
}
}
return res
}
type Report struct {
AvgTotal float64
Fastest float64
Slowest float64
Average float64
Rps float64
AvgConn float64
AvgDNS float64
AvgReq float64
AvgRes float64
AvgDelay float64
ConnMax float64
ConnMin float64
DnsMax float64
DnsMin float64
ReqMax float64
ReqMin float64
ResMax float64
ResMin float64
DelayMax float64
DelayMin float64
Lats []float64
ConnLats []float64
DnsLats []float64
ReqLats []float64
ResLats []float64
DelayLats []float64
Offsets []float64
StatusCodes []int
Total time.Duration
ErrorDist map[string]int
StatusCodeDist map[int]int
SizeTotal int64
SizeReq int64
NumRes int64
LatencyDistribution []LatencyDistribution
Histogram []Bucket
}
type LatencyDistribution struct {
Percentage int
Latency float64
}
type Bucket struct {
Mark float64
Count int
Frequency float64
}
| cap := min(n, maxRes)
return &report{
output: output,
results: results,
done: make(chan bool, 1),
errorDist: make(map[string]int),
w: w,
connLats: make([]float64, 0, cap),
dnsLats: make([]float64, 0, cap),
reqLats: make([]float64, 0, cap),
resLats: make([]float64, 0, cap),
delayLats: make([]float64, 0, cap),
lats: make([]float64, 0, cap),
statusCodes: make([]int, 0, cap),
}
}
|
inputComponentDriver.js | import ClickableComponentDriver from './clickableComponentDriver';
const ERRORS = {
INPUT_CANNOT_BE_CLICKED : ( label, state ) =>
`Input '${label}' cannot be clicked since it is ${state}`,
INPUT_CANNOT_CHANGE_VALUE : ( label, state ) =>
`Input '${label}' value cannot be changed since it is ${state}`,
INPUT_CANNOT_PRESS_KEY : ( label, state ) =>
`Cannot press a key on Input '${label}' since it is ${state}`
};
export default class | extends ClickableComponentDriver
{
constructor( wrapper, selector )
{
super( wrapper, selector || 'input' );
}
/**
* Simulates a full transaction of value input: focus, value change, blur.
* This is useful for fields as part of form that require a blur to complete
* the change of value.
* In order to set a value on its own please see inputValue()
* @param {String|Integer} value the value to set.
* @return {InputComponentDriver} this driver (for chaining commands)
*/
setInputValue( value )
{
checkIfSimulationIsValid( this.wrapper,
ERRORS.INPUT_CANNOT_CHANGE_VALUE );
const input = this.control;
const node = input.getNode();
this.focus();
node.value = value;
input.simulate( 'change' );
this.blur();
return this;
}
clearInputValue()
{
return this.setInputValue( '' );
}
/**
* Simulates the pressing of a given key. In case of a printable character
* the input will be updated accordingly as well.
* @param {Integer} keyCode the integer code of a key
* @return {InputComponentDriver} this driver (for chaining commands)
*/
pressKey( keyCode )
{
checkIfSimulationIsValid( this.wrapper, ERRORS.INPUT_CANNOT_PRESS_KEY );
this.control.simulate( 'keyDown', { which: keyCode } );
this.control.simulate( 'keyPress', { which: keyCode } );
if ( isCharPrintable( keyCode ) )
{
const node = this.control.getNode();
node.value += String.fromCharCode( keyCode );
this.control.simulate( 'change' );
}
this.control.simulate( 'keyUp', { which: keyCode } );
return this;
}
/**
* Pressing each character of the value one by one.
* @param {String} value a value press
* @return {InputComponentDriver} this driver (for chaining commands)
*/
inputValue( value )
{
const FIRST_CHARACTER = 0;
const keys = value.toString().split( '' );
keys.forEach( key =>
{
const keyCode = key.charCodeAt( FIRST_CHARACTER );
this.pressKey( keyCode );
} );
return this;
}
/**
* the Nessie component can behave as either a controlled or uncontrolled
* input. This depends on whether you set the value prop (controlled) or
* defaultValue prop (uncontrolled).
* In case the Nessie Component is used in a controlled manner, it is
* possible and recommneded to retreive it through the component's
* properties.
* For Uncotrolled value, this function is essential in order to retreive
* the value.
* @return {String} the input value
*/
getInputValue()
{
return this.control.getNode().value;
}
click()
{
checkIfSimulationIsValid( this.wrapper,
ERRORS.INPUT_CANNOT_BE_CLICKED );
return super.click();
}
}
/**
* Checks the state of the input, and throws an error in case the state is not
* permiting the simulated action.
* @param {Object} wrapper - The warpper object that is being simulated.
* @param {Function} errorIfInvalid - The error to throw in case the object is
* not avilable for a simulation.
*/
function checkIfSimulationIsValid( wrapper, errorIfInvalid )
{
const props = wrapper.props();
const label = props.label;
if ( props.isDisabled )
{
throw new Error( errorIfInvalid( label, 'disabled' ) );
}
else if ( props.isReadOnly )
{
throw new Error( errorIfInvalid( label, 'read only' ) );
}
}
/**
* Checks if a character is printable. (partial black listing of keys)
* @param {Integer} keyCode the key code to check
*/
function isCharPrintable( keyCode )
{
const blackList = [
13, // Enter
];
return !blackList.includes( keyCode );
}
| InputComponentDriver |
batch_tag_action_request_body.py | # coding: utf-8
import pprint
import re
import six
class BatchTagActionRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'action': 'str',
'tags': 'list[BatchTagActionTagOption]'
}
attribute_map = {
'action': 'action',
'tags': 'tags'
}
def __init__(self, action=None, tags=None):
"""BatchTagActionRequestBody - a model defined in huaweicloud sdk"""
self._action = None
self._tags = None
self.discriminator = None
self.action = action
self.tags = tags
@property
def | (self):
"""Gets the action of this BatchTagActionRequestBody.
操作标识。取值: - create,表示添加标签。 - delete,表示删除标签。
:return: The action of this BatchTagActionRequestBody.
:rtype: str
"""
return self._action
@action.setter
def action(self, action):
"""Sets the action of this BatchTagActionRequestBody.
操作标识。取值: - create,表示添加标签。 - delete,表示删除标签。
:param action: The action of this BatchTagActionRequestBody.
:type: str
"""
self._action = action
@property
def tags(self):
"""Gets the tags of this BatchTagActionRequestBody.
标签列表。
:return: The tags of this BatchTagActionRequestBody.
:rtype: list[BatchTagActionTagOption]
"""
return self._tags
@tags.setter
def tags(self, tags):
"""Sets the tags of this BatchTagActionRequestBody.
标签列表。
:param tags: The tags of this BatchTagActionRequestBody.
:type: list[BatchTagActionTagOption]
"""
self._tags = tags
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, BatchTagActionRequestBody):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| action |
vmx.rs | //! VMX extensions.
| use crate::{call, sys, Error, Vcpu};
/// Enum type of VMX cabability fields
#[repr(u32)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Capability {
/// Pin-based VMX capabilities.
PinBased = sys::hv_vmx_capability_t_HV_VMX_CAP_PINBASED,
/// Primary proc-based VMX capabilities.
ProcBased = sys::hv_vmx_capability_t_HV_VMX_CAP_PROCBASED,
/// Second proc-based VMX capabilities.
ProcBased2 = sys::hv_vmx_capability_t_HV_VMX_CAP_PROCBASED2,
/// VM-entry VMX capabilities.
Entry = sys::hv_vmx_capability_t_HV_VMX_CAP_ENTRY,
/// VM-exit VMX capabilities.
Exit = sys::hv_vmx_capability_t_HV_VMX_CAP_EXIT,
/// VMX preemption timer frequency.
PreemptionTimer = sys::hv_vmx_capability_t_HV_VMX_CAP_PREEMPTION_TIMER,
}
/// Returns the VMX capabilities of the host processor.
pub fn read_capability(field: Capability) -> Result<u64, Error> {
let mut out = 0_u64;
call!(sys::hv_vmx_read_capability(field as u32, &mut out))?;
Ok(out)
}
bitflags::bitflags! {
#[cfg(feature = "hv_10_15")]
pub struct ShadowFlags: u32 {
const NONE = sys::HV_SHADOW_VMCS_NONE;
const READ = sys::HV_SHADOW_VMCS_READ;
const WRITE = sys::HV_SHADOW_VMCS_WRITE;
}
}
pub trait VCpuVmxExt {
/// Returns the current value of a VMCS field of a vCPU.
fn read_vmcs(&self, field: Vmcs) -> Result<u64, Error>;
/// Set the value of a VMCS field of a vCPU.
fn write_vmcs(&self, field: Vmcs, value: u64) -> Result<(), Error>;
/// Returns the current value of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn read_shadow_vmcs(&self, field: Vmcs) -> Result<u64, Error>;
/// Set the value of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn write_shadow_vmcs(&self, field: Vmcs, value: u64) -> Result<(), Error>;
/// Set the access permissions of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn set_shadow_access(&self, field: Vmcs, flags: ShadowFlags) -> Result<(), Error>;
}
impl VCpuVmxExt for Vcpu {
/// Returns the current value of a VMCS field of a vCPU.
fn read_vmcs(&self, field: Vmcs) -> Result<u64, Error> {
let mut out = 0_u64;
call!(sys::hv_vmx_vcpu_read_vmcs(self.id, field as u32, &mut out))?;
Ok(out)
}
/// Set the value of a VMCS field of a vCPU.
fn write_vmcs(&self, field: Vmcs, value: u64) -> Result<(), Error> {
call!(sys::hv_vmx_vcpu_write_vmcs(self.id, field as u32, value))
}
/// Returns the current value of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn read_shadow_vmcs(&self, field: Vmcs) -> Result<u64, Error> {
let mut out = 0_u64;
call!(sys::hv_vmx_vcpu_read_shadow_vmcs(
self.id,
field as u32,
&mut out
))?;
Ok(out)
}
/// Set the value of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn write_shadow_vmcs(&self, field: Vmcs, value: u64) -> Result<(), Error> {
call!(sys::hv_vmx_vcpu_write_shadow_vmcs(
self.id,
field as u32,
value
))
}
/// Set the access permissions of a shadow VMCS field of a vCPU.
#[cfg(feature = "hv_10_15")]
fn set_shadow_access(&self, field: Vmcs, flags: ShadowFlags) -> Result<(), Error> {
call!(sys::hv_vmx_vcpu_set_shadow_access(
self.id,
field as u32,
flags.bits() as u64
))
}
}
/// Virtual Machine Control Structure (VMCS) Field IDs.
/// Identify the fields of the virtual machine control structure.
#[allow(non_camel_case_types)]
#[non_exhaustive]
#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Vmcs {
VPID = sys::VMCS_VPID,
CTRL_POSTED_INT_N_VECTOR = sys::VMCS_CTRL_POSTED_INT_N_VECTOR,
CTRL_EPTP_INDEX = sys::VMCS_CTRL_EPTP_INDEX,
GUEST_ES = sys::VMCS_GUEST_ES,
GUEST_CS = sys::VMCS_GUEST_CS,
GUEST_SS = sys::VMCS_GUEST_SS,
GUEST_DS = sys::VMCS_GUEST_DS,
GUEST_FS = sys::VMCS_GUEST_FS,
GUEST_GS = sys::VMCS_GUEST_GS,
GUEST_LDTR = sys::VMCS_GUEST_LDTR,
GUEST_TR = sys::VMCS_GUEST_TR,
GUEST_INT_STATUS = sys::VMCS_GUEST_INT_STATUS,
GUESTPML_INDEX = sys::VMCS_GUESTPML_INDEX,
HOST_ES = sys::VMCS_HOST_ES,
HOST_CS = sys::VMCS_HOST_CS,
HOST_SS = sys::VMCS_HOST_SS,
HOST_DS = sys::VMCS_HOST_DS,
HOST_FS = sys::VMCS_HOST_FS,
HOST_GS = sys::VMCS_HOST_GS,
HOST_TR = sys::VMCS_HOST_TR,
CTRL_IO_BITMAP_A = sys::VMCS_CTRL_IO_BITMAP_A,
CTRL_IO_BITMAP_B = sys::VMCS_CTRL_IO_BITMAP_B,
CTRL_MSR_BITMAPS = sys::VMCS_CTRL_MSR_BITMAPS,
CTRL_VMEXIT_MSR_STORE_ADDR = sys::VMCS_CTRL_VMEXIT_MSR_STORE_ADDR,
CTRL_VMEXIT_MSR_LOAD_ADDR = sys::VMCS_CTRL_VMEXIT_MSR_LOAD_ADDR,
CTRL_VMENTRY_MSR_LOAD_ADDR = sys::VMCS_CTRL_VMENTRY_MSR_LOAD_ADDR,
CTRL_EXECUTIVE_VMCS_PTR = sys::VMCS_CTRL_EXECUTIVE_VMCS_PTR,
CTRL_PML_ADDR = sys::VMCS_CTRL_PML_ADDR,
CTRL_TSC_OFFSET = sys::VMCS_CTRL_TSC_OFFSET,
CTRL_VIRTUAL_APIC = sys::VMCS_CTRL_VIRTUAL_APIC,
CTRL_APIC_ACCESS = sys::VMCS_CTRL_APIC_ACCESS,
CTRL_POSTED_INT_DESC_ADDR = sys::VMCS_CTRL_POSTED_INT_DESC_ADDR,
CTRL_VMFUNC_CTRL = sys::VMCS_CTRL_VMFUNC_CTRL,
CTRL_EPTP = sys::VMCS_CTRL_EPTP,
CTRL_EOI_EXIT_BITMAP_0 = sys::VMCS_CTRL_EOI_EXIT_BITMAP_0,
CTRL_EOI_EXIT_BITMAP_1 = sys::VMCS_CTRL_EOI_EXIT_BITMAP_1,
CTRL_EOI_EXIT_BITMAP_2 = sys::VMCS_CTRL_EOI_EXIT_BITMAP_2,
CTRL_EOI_EXIT_BITMAP_3 = sys::VMCS_CTRL_EOI_EXIT_BITMAP_3,
CTRL_EPTP_LIST_ADDR = sys::VMCS_CTRL_EPTP_LIST_ADDR,
CTRL_VMREAD_BITMAP_ADDR = sys::VMCS_CTRL_VMREAD_BITMAP_ADDR,
CTRL_VMWRITE_BITMAP_ADDR = sys::VMCS_CTRL_VMWRITE_BITMAP_ADDR,
CTRL_VIRT_EXC_INFO_ADDR = sys::VMCS_CTRL_VIRT_EXC_INFO_ADDR,
CTRL_XSS_EXITING_BITMAP = sys::VMCS_CTRL_XSS_EXITING_BITMAP,
CTRL_ENCLS_EXITING_BITMAP = sys::VMCS_CTRL_ENCLS_EXITING_BITMAP,
CTRL_TSC_MULTIPLIER = sys::VMCS_CTRL_TSC_MULTIPLIER,
GUEST_PHYSICAL_ADDRESS = sys::VMCS_GUEST_PHYSICAL_ADDRESS,
GUEST_LINK_POINTER = sys::VMCS_GUEST_LINK_POINTER,
GUEST_IA32_DEBUGCTL = sys::VMCS_GUEST_IA32_DEBUGCTL,
GUEST_IA32_PAT = sys::VMCS_GUEST_IA32_PAT,
GUEST_IA32_EFER = sys::VMCS_GUEST_IA32_EFER,
GUEST_IA32_PERF_GLOBAL_CTRL = sys::VMCS_GUEST_IA32_PERF_GLOBAL_CTRL,
GUEST_PDPTE0 = sys::VMCS_GUEST_PDPTE0,
GUEST_PDPTE1 = sys::VMCS_GUEST_PDPTE1,
GUEST_PDPTE2 = sys::VMCS_GUEST_PDPTE2,
GUEST_PDPTE3 = sys::VMCS_GUEST_PDPTE3,
GUEST_IA32_BNDCFGS = sys::VMCS_GUEST_IA32_BNDCFGS,
HOST_IA32_PAT = sys::VMCS_HOST_IA32_PAT,
HOST_IA32_EFER = sys::VMCS_HOST_IA32_EFER,
HOST_IA32_PERF_GLOBAL_CTRL = sys::VMCS_HOST_IA32_PERF_GLOBAL_CTRL,
CTRL_PIN_BASED = sys::VMCS_CTRL_PIN_BASED,
CTRL_CPU_BASED = sys::VMCS_CTRL_CPU_BASED,
CTRL_EXC_BITMAP = sys::VMCS_CTRL_EXC_BITMAP,
CTRL_PF_ERROR_MASK = sys::VMCS_CTRL_PF_ERROR_MASK,
CTRL_PF_ERROR_MATCH = sys::VMCS_CTRL_PF_ERROR_MATCH,
CTRL_CR3_COUNT = sys::VMCS_CTRL_CR3_COUNT,
CTRL_VMEXIT_CONTROLS = sys::VMCS_CTRL_VMEXIT_CONTROLS,
CTRL_VMEXIT_MSR_STORE_COUNT = sys::VMCS_CTRL_VMEXIT_MSR_STORE_COUNT,
CTRL_VMEXIT_MSR_LOAD_COUNT = sys::VMCS_CTRL_VMEXIT_MSR_LOAD_COUNT,
CTRL_VMENTRY_CONTROLS = sys::VMCS_CTRL_VMENTRY_CONTROLS,
CTRL_VMENTRY_MSR_LOAD_COUNT = sys::VMCS_CTRL_VMENTRY_MSR_LOAD_COUNT,
CTRL_VMENTRY_IRQ_INFO = sys::VMCS_CTRL_VMENTRY_IRQ_INFO,
CTRL_VMENTRY_EXC_ERROR = sys::VMCS_CTRL_VMENTRY_EXC_ERROR,
CTRL_VMENTRY_INSTR_LEN = sys::VMCS_CTRL_VMENTRY_INSTR_LEN,
CTRL_TPR_THRESHOLD = sys::VMCS_CTRL_TPR_THRESHOLD,
CTRL_CPU_BASED2 = sys::VMCS_CTRL_CPU_BASED2,
CTRL_PLE_GAP = sys::VMCS_CTRL_PLE_GAP,
CTRL_PLE_WINDOW = sys::VMCS_CTRL_PLE_WINDOW,
RO_INSTR_ERROR = sys::VMCS_RO_INSTR_ERROR,
RO_EXIT_REASON = sys::VMCS_RO_EXIT_REASON,
RO_VMEXIT_IRQ_INFO = sys::VMCS_RO_VMEXIT_IRQ_INFO,
RO_VMEXIT_IRQ_ERROR = sys::VMCS_RO_VMEXIT_IRQ_ERROR,
RO_IDT_VECTOR_INFO = sys::VMCS_RO_IDT_VECTOR_INFO,
RO_IDT_VECTOR_ERROR = sys::VMCS_RO_IDT_VECTOR_ERROR,
RO_VMEXIT_INSTR_LEN = sys::VMCS_RO_VMEXIT_INSTR_LEN,
RO_VMX_INSTR_INFO = sys::VMCS_RO_VMX_INSTR_INFO,
GUEST_ES_LIMIT = sys::VMCS_GUEST_ES_LIMIT,
GUEST_CS_LIMIT = sys::VMCS_GUEST_CS_LIMIT,
GUEST_SS_LIMIT = sys::VMCS_GUEST_SS_LIMIT,
GUEST_DS_LIMIT = sys::VMCS_GUEST_DS_LIMIT,
GUEST_FS_LIMIT = sys::VMCS_GUEST_FS_LIMIT,
GUEST_GS_LIMIT = sys::VMCS_GUEST_GS_LIMIT,
GUEST_LDTR_LIMIT = sys::VMCS_GUEST_LDTR_LIMIT,
GUEST_TR_LIMIT = sys::VMCS_GUEST_TR_LIMIT,
GUEST_GDTR_LIMIT = sys::VMCS_GUEST_GDTR_LIMIT,
GUEST_IDTR_LIMIT = sys::VMCS_GUEST_IDTR_LIMIT,
GUEST_ES_AR = sys::VMCS_GUEST_ES_AR,
GUEST_CS_AR = sys::VMCS_GUEST_CS_AR,
GUEST_SS_AR = sys::VMCS_GUEST_SS_AR,
GUEST_DS_AR = sys::VMCS_GUEST_DS_AR,
GUEST_FS_AR = sys::VMCS_GUEST_FS_AR,
GUEST_GS_AR = sys::VMCS_GUEST_GS_AR,
GUEST_LDTR_AR = sys::VMCS_GUEST_LDTR_AR,
GUEST_TR_AR = sys::VMCS_GUEST_TR_AR,
GUEST_IGNORE_IRQ = sys::VMCS_GUEST_IGNORE_IRQ,
GUEST_ACTIVITY_STATE = sys::VMCS_GUEST_ACTIVITY_STATE,
GUEST_SMBASE = sys::VMCS_GUEST_SMBASE,
GUEST_IA32_SYSENTER_CS = sys::VMCS_GUEST_IA32_SYSENTER_CS,
GUEST_VMX_TIMER_VALUE = sys::VMCS_GUEST_VMX_TIMER_VALUE,
HOST_IA32_SYSENTER_CS = sys::VMCS_HOST_IA32_SYSENTER_CS,
CTRL_CR0_MASK = sys::VMCS_CTRL_CR0_MASK,
CTRL_CR4_MASK = sys::VMCS_CTRL_CR4_MASK,
CTRL_CR0_SHADOW = sys::VMCS_CTRL_CR0_SHADOW,
CTRL_CR4_SHADOW = sys::VMCS_CTRL_CR4_SHADOW,
CTRL_CR3_VALUE0 = sys::VMCS_CTRL_CR3_VALUE0,
CTRL_CR3_VALUE1 = sys::VMCS_CTRL_CR3_VALUE1,
CTRL_CR3_VALUE2 = sys::VMCS_CTRL_CR3_VALUE2,
CTRL_CR3_VALUE3 = sys::VMCS_CTRL_CR3_VALUE3,
RO_EXIT_QUALIFIC = sys::VMCS_RO_EXIT_QUALIFIC,
RO_IO_RCX = sys::VMCS_RO_IO_RCX,
RO_IO_RSI = sys::VMCS_RO_IO_RSI,
RO_IO_RDI = sys::VMCS_RO_IO_RDI,
RO_IO_RIP = sys::VMCS_RO_IO_RIP,
RO_GUEST_LIN_ADDR = sys::VMCS_RO_GUEST_LIN_ADDR,
GUEST_CR0 = sys::VMCS_GUEST_CR0,
GUEST_CR3 = sys::VMCS_GUEST_CR3,
GUEST_CR4 = sys::VMCS_GUEST_CR4,
GUEST_ES_BASE = sys::VMCS_GUEST_ES_BASE,
GUEST_CS_BASE = sys::VMCS_GUEST_CS_BASE,
GUEST_SS_BASE = sys::VMCS_GUEST_SS_BASE,
GUEST_DS_BASE = sys::VMCS_GUEST_DS_BASE,
GUEST_FS_BASE = sys::VMCS_GUEST_FS_BASE,
GUEST_GS_BASE = sys::VMCS_GUEST_GS_BASE,
GUEST_LDTR_BASE = sys::VMCS_GUEST_LDTR_BASE,
GUEST_TR_BASE = sys::VMCS_GUEST_TR_BASE,
GUEST_GDTR_BASE = sys::VMCS_GUEST_GDTR_BASE,
GUEST_IDTR_BASE = sys::VMCS_GUEST_IDTR_BASE,
GUEST_DR7 = sys::VMCS_GUEST_DR7,
GUEST_RSP = sys::VMCS_GUEST_RSP,
GUEST_RIP = sys::VMCS_GUEST_RIP,
GUEST_RFLAGS = sys::VMCS_GUEST_RFLAGS,
GUEST_DEBUG_EXC = sys::VMCS_GUEST_DEBUG_EXC,
GUEST_SYSENTER_ESP = sys::VMCS_GUEST_SYSENTER_ESP,
GUEST_SYSENTER_EIP = sys::VMCS_GUEST_SYSENTER_EIP,
HOST_CR0 = sys::VMCS_HOST_CR0,
HOST_CR3 = sys::VMCS_HOST_CR3,
HOST_CR4 = sys::VMCS_HOST_CR4,
HOST_FS_BASE = sys::VMCS_HOST_FS_BASE,
HOST_GS_BASE = sys::VMCS_HOST_GS_BASE,
HOST_TR_BASE = sys::VMCS_HOST_TR_BASE,
HOST_GDTR_BASE = sys::VMCS_HOST_GDTR_BASE,
HOST_IDTR_BASE = sys::VMCS_HOST_IDTR_BASE,
HOST_IA32_SYSENTER_ESP = sys::VMCS_HOST_IA32_SYSENTER_ESP,
HOST_IA32_SYSENTER_EIP = sys::VMCS_HOST_IA32_SYSENTER_EIP,
HOST_RSP = sys::VMCS_HOST_RSP,
HOST_RIP = sys::VMCS_HOST_RIP,
MAX = sys::VMCS_MAX,
}
#[allow(non_camel_case_types)]
#[non_exhaustive]
#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Reason {
EXC_NMI = sys::VMX_REASON_EXC_NMI,
IRQ = sys::VMX_REASON_IRQ,
TRIPLE_FAULT = sys::VMX_REASON_TRIPLE_FAULT,
INIT = sys::VMX_REASON_INIT,
SIPI = sys::VMX_REASON_SIPI,
IO_SMI = sys::VMX_REASON_IO_SMI,
OTHER_SMI = sys::VMX_REASON_OTHER_SMI,
IRQ_WND = sys::VMX_REASON_IRQ_WND,
VIRTUAL_NMI_WND = sys::VMX_REASON_VIRTUAL_NMI_WND,
TASK = sys::VMX_REASON_TASK,
CPUID = sys::VMX_REASON_CPUID,
GETSEC = sys::VMX_REASON_GETSEC,
HLT = sys::VMX_REASON_HLT,
INVD = sys::VMX_REASON_INVD,
INVLPG = sys::VMX_REASON_INVLPG,
RDPMC = sys::VMX_REASON_RDPMC,
RDTSC = sys::VMX_REASON_RDTSC,
RSM = sys::VMX_REASON_RSM,
VMCALL = sys::VMX_REASON_VMCALL,
VMCLEAR = sys::VMX_REASON_VMCLEAR,
VMLAUNCH = sys::VMX_REASON_VMLAUNCH,
VMPTRLD = sys::VMX_REASON_VMPTRLD,
VMPTRST = sys::VMX_REASON_VMPTRST,
VMREAD = sys::VMX_REASON_VMREAD,
VMRESUME = sys::VMX_REASON_VMRESUME,
VMWRITE = sys::VMX_REASON_VMWRITE,
VMOFF = sys::VMX_REASON_VMOFF,
VMON = sys::VMX_REASON_VMON,
MOV_CR = sys::VMX_REASON_MOV_CR,
MOV_DR = sys::VMX_REASON_MOV_DR,
IO = sys::VMX_REASON_IO,
RDMSR = sys::VMX_REASON_RDMSR,
WRMSR = sys::VMX_REASON_WRMSR,
VMENTRY_GUEST = sys::VMX_REASON_VMENTRY_GUEST,
VMENTRY_MSR = sys::VMX_REASON_VMENTRY_MSR,
MWAIT = sys::VMX_REASON_MWAIT,
MTF = sys::VMX_REASON_MTF,
MONITOR = sys::VMX_REASON_MONITOR,
PAUSE = sys::VMX_REASON_PAUSE,
VMENTRY_MC = sys::VMX_REASON_VMENTRY_MC,
TPR_THRESHOLD = sys::VMX_REASON_TPR_THRESHOLD,
APIC_ACCESS = sys::VMX_REASON_APIC_ACCESS,
VIRTUALIZED_EOI = sys::VMX_REASON_VIRTUALIZED_EOI,
GDTR_IDTR = sys::VMX_REASON_GDTR_IDTR,
LDTR_TR = sys::VMX_REASON_LDTR_TR,
EPT_VIOLATION = sys::VMX_REASON_EPT_VIOLATION,
EPT_MISCONFIG = sys::VMX_REASON_EPT_MISCONFIG,
EPT_INVEPT = sys::VMX_REASON_EPT_INVEPT,
RDTSCP = sys::VMX_REASON_RDTSCP,
VMX_TIMER_EXPIRED = sys::VMX_REASON_VMX_TIMER_EXPIRED,
INVVPID = sys::VMX_REASON_INVVPID,
WBINVD = sys::VMX_REASON_WBINVD,
XSETBV = sys::VMX_REASON_XSETBV,
APIC_WRITE = sys::VMX_REASON_APIC_WRITE,
RDRAND = sys::VMX_REASON_RDRAND,
INVPCID = sys::VMX_REASON_INVPCID,
VMFUNC = sys::VMX_REASON_VMFUNC,
RDSEED = sys::VMX_REASON_RDSEED,
XSAVES = sys::VMX_REASON_XSAVES,
XRSTORS = sys::VMX_REASON_XRSTORS,
}
#[allow(non_camel_case_types)]
#[non_exhaustive]
#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum IrqInfo {
EXT_IRQ = sys::IRQ_INFO_EXT_IRQ,
NMI = sys::IRQ_INFO_NMI,
HARD_EXC = sys::IRQ_INFO_HARD_EXC,
SOFT_IRQ = sys::IRQ_INFO_SOFT_IRQ,
PRIV_SOFT_EXC = sys::IRQ_INFO_PRIV_SOFT_EXC,
SOFT_EXC = sys::IRQ_INFO_SOFT_EXC,
ERROR_VALID = sys::IRQ_INFO_ERROR_VALID,
VALID = sys::IRQ_INFO_VALID,
} | |
editorControl.js | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
define(["require", "exports", "vs/base/common/lifecycle", "vs/base/browser/dom", "vs/platform/registry/common/platform", "vs/workbench/browser/editor", "vs/workbench/services/layout/browser/layoutService", "vs/platform/instantiation/common/instantiation", "vs/platform/progress/common/progress", "vs/workbench/browser/parts/editor/editor", "vs/base/common/event", "vs/base/common/types"], function (require, exports, lifecycle_1, dom_1, platform_1, editor_1, layoutService_1, instantiation_1, progress_1, editor_2, event_1, types_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditorControl = void 0;
let EditorControl = class EditorControl extends lifecycle_1.Disposable {
constructor(parent, groupView, layoutService, instantiationService, editorProgressService) {
super();
this.parent = parent;
this.groupView = groupView;
this.layoutService = layoutService;
this.instantiationService = instantiationService;
this.editorProgressService = editorProgressService;
this._onDidFocus = this._register(new event_1.Emitter());
this.onDidFocus = this._onDidFocus.event;
this._onDidSizeConstraintsChange = this._register(new event_1.Emitter());
this.onDidSizeConstraintsChange = this._onDidSizeConstraintsChange.event;
this._activeEditorPane = null;
this.editorPanes = [];
this.activeEditorPaneDisposables = this._register(new lifecycle_1.DisposableStore());
this.editorOperation = this._register(new progress_1.LongRunningOperation(this.editorProgressService));
}
get minimumWidth() { var _a, _b; return (_b = (_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.minimumWidth) !== null && _b !== void 0 ? _b : editor_2.DEFAULT_EDITOR_MIN_DIMENSIONS.width; }
get minimumHeight() { var _a, _b; return (_b = (_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.minimumHeight) !== null && _b !== void 0 ? _b : editor_2.DEFAULT_EDITOR_MIN_DIMENSIONS.height; }
get maximumWidth() { var _a, _b; return (_b = (_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.maximumWidth) !== null && _b !== void 0 ? _b : editor_2.DEFAULT_EDITOR_MAX_DIMENSIONS.width; }
get maximumHeight() { var _a, _b; return (_b = (_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.maximumHeight) !== null && _b !== void 0 ? _b : editor_2.DEFAULT_EDITOR_MAX_DIMENSIONS.height; }
get activeEditorPane() { return this._activeEditorPane; }
async openEditor(editor, options) {
// Editor pane
const descriptor = platform_1.Registry.as(editor_1.Extensions.Editors).getEditor(editor);
if (!descriptor) {
throw new Error(`No editor descriptor found for input id ${editor.getTypeId()}`);
}
const editorPane = this.doShowEditorPane(descriptor);
// Set input
const editorChanged = await this.doSetInput(editorPane, editor, options);
return { editorPane, editorChanged };
}
doShowEditorPane(descriptor) {
// Return early if the currently active editor pane can handle the input
if (this._activeEditorPane && descriptor.describes(this._activeEditorPane)) { | // Create editor pane
const editorPane = this.doCreateEditorPane(descriptor);
// Set editor as active
this.doSetActiveEditorPane(editorPane);
// Show editor
const container = types_1.assertIsDefined(editorPane.getContainer());
this.parent.appendChild(container);
dom_1.show(container);
// Indicate to editor that it is now visible
editorPane.setVisible(true, this.groupView);
// Layout
if (this.dimension) {
editorPane.layout(this.dimension);
}
return editorPane;
}
doCreateEditorPane(descriptor) {
// Instantiate editor
const editorPane = this.doInstantiateEditorPane(descriptor);
// Create editor container as needed
if (!editorPane.getContainer()) {
const editorPaneContainer = document.createElement('div');
dom_1.addClass(editorPaneContainer, 'editor-instance');
editorPaneContainer.setAttribute('data-editor-id', descriptor.getId());
editorPane.create(editorPaneContainer);
}
return editorPane;
}
doInstantiateEditorPane(descriptor) {
// Return early if already instantiated
const existingEditorPane = this.editorPanes.find(editorPane => descriptor.describes(editorPane));
if (existingEditorPane) {
return existingEditorPane;
}
// Otherwise instantiate new
const editorPane = this._register(descriptor.instantiate(this.instantiationService));
this.editorPanes.push(editorPane);
return editorPane;
}
doSetActiveEditorPane(editorPane) {
this._activeEditorPane = editorPane;
// Clear out previous active editor pane listeners
this.activeEditorPaneDisposables.clear();
// Listen to editor pane changes
if (editorPane) {
this.activeEditorPaneDisposables.add(editorPane.onDidSizeConstraintsChange(e => this._onDidSizeConstraintsChange.fire(e)));
this.activeEditorPaneDisposables.add(editorPane.onDidFocus(() => this._onDidFocus.fire()));
}
// Indicate that size constraints could have changed due to new editor
this._onDidSizeConstraintsChange.fire(undefined);
}
async doSetInput(editorPane, editor, options) {
// If the input did not change, return early and only apply the options
// unless the options instruct us to force open it even if it is the same
const forceReload = options === null || options === void 0 ? void 0 : options.forceReload;
const inputMatches = editorPane.input && editorPane.input.matches(editor);
if (inputMatches && !forceReload) {
// Forward options
editorPane.setOptions(options);
// Still focus as needed
const focus = !options || !options.preserveFocus;
if (focus) {
editorPane.focus();
}
return false;
}
// Show progress while setting input after a certain timeout. If the workbench is opening
// be more relaxed about progress showing by increasing the delay a little bit to reduce flicker.
const operation = this.editorOperation.start(this.layoutService.isRestored() ? 800 : 3200);
// Call into editor pane
const editorWillChange = !inputMatches;
try {
await editorPane.setInput(editor, options, operation.token);
// Focus (unless prevented or another operation is running)
if (operation.isCurrent()) {
const focus = !options || !options.preserveFocus;
if (focus) {
editorPane.focus();
}
}
return editorWillChange;
}
finally {
operation.stop();
}
}
doHideActiveEditorPane() {
if (!this._activeEditorPane) {
return;
}
// Stop any running operation
this.editorOperation.stop();
// Indicate to editor pane before removing the editor from
// the DOM to give a chance to persist certain state that
// might depend on still being the active DOM element.
this._activeEditorPane.clearInput();
this._activeEditorPane.setVisible(false, this.groupView);
// Remove editor pane from parent
const editorPaneContainer = this._activeEditorPane.getContainer();
if (editorPaneContainer) {
this.parent.removeChild(editorPaneContainer);
dom_1.hide(editorPaneContainer);
}
// Clear active editor pane
this.doSetActiveEditorPane(null);
}
closeEditor(editor) {
if (this._activeEditorPane && editor.matches(this._activeEditorPane.input)) {
this.doHideActiveEditorPane();
}
}
setVisible(visible) {
var _a;
(_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.setVisible(visible, this.groupView);
}
layout(dimension) {
var _a;
this.dimension = dimension;
(_a = this._activeEditorPane) === null || _a === void 0 ? void 0 : _a.layout(dimension);
}
};
EditorControl = __decorate([
__param(2, layoutService_1.IWorkbenchLayoutService),
__param(3, instantiation_1.IInstantiationService),
__param(4, progress_1.IEditorProgressService)
], EditorControl);
exports.EditorControl = EditorControl;
});
//# __sourceMappingURL=editorControl.js.map | return this._activeEditorPane;
}
// Hide active one first
this.doHideActiveEditorPane(); |
parser.rs | use byteorder::LittleEndian;
use static_assertions::const_assert_eq;
use std::{convert::TryFrom, error::Error, io::BufRead, mem};
use zerocopy::{AsBytes, FromBytes, LayoutVerified, Unaligned};
const RECORDING_MAGIC: u32 = 0xFEEDFEED;
const RECORDING_FRAME_MAGIC: u32 = 0xAAAAFEED;
const GENERIC_METADATA_HEADER_MAGIC: u32 = 0xBACCDEEF;
type I32 = zerocopy::I32<LittleEndian>;
type I64 = zerocopy::I64<LittleEndian>;
type U32 = zerocopy::U32<LittleEndian>;
type U64 = zerocopy::U64<LittleEndian>;
#[derive(Debug, Clone, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct RecordingMetadata {
magic: U32,
unix_epoch_time_relative_nsec: U32,
unix_epoch_time_sec: U64,
}
const_assert_eq!(mem::size_of::<RecordingMetadata>(), 16);
#[derive(Debug, Clone, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct RecordedFrameMetadata {
magic: U32,
id: I32,
padding: I32,
width: I32,
height: I32,
format: I32,
timestamp: I64,
receive_timestamp: I64,
size: I64,
}
const_assert_eq!(mem::size_of::<RecordedFrameMetadata>(), 48);
#[derive(Debug, Clone, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct GenericMetadataHeader {
magic: U32,
generic_metadata_size: U32,
}
const_assert_eq!(mem::size_of::<GenericMetadataHeader>(), 8);
#[derive(Debug, Clone, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct RecordingIndexHeader {
magic: U32,
padding: U32,
}
const_assert_eq!(mem::size_of::<RecordingIndexHeader>(), 8);
#[derive(Debug, Clone)]
pub struct FrameInfo {
pub resolution: String,
pub format: VideoCaptureFormat,
pub raw_data: Vec<u8>,
pub timestamp: i64,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(i32)]
pub enum VideoCaptureFormat {
Rgb = 0,
Bgr = 1,
Yuv = 2,
Nv12 = 3,
Yuyv = 4,
Uyvy = 5,
Raw = 6,
Mono16 = 7,
Raw16 = 8,
Mono8 = 9,
H264 = -4601,
H265 = -4602,
MJPEG = -4603,
Stats = -4701,
}
impl VideoCaptureFormat {
pub fn ffmpeg_pix_fmt(&self) -> &'static str {
match self {
Self::Rgb => "rgb24",
Self::Bgr => "bgr24",
Self::Yuv => "yuv420p",
Self::Nv12 => "nv12",
Self::Yuyv => "yuyv422",
Self::Uyvy => "uyvy422",
Self::Raw => "bayer_rggb8", // raw 8 bit sensor data
Self::Mono16 => "gray16le", // assuming little endian
Self::Raw16 => "bayer_rggb16le", // raw 16 bit sensor data
Self::Mono8 => "gray",
Self::H264 | Self::H265 | Self::MJPEG | Self::Stats => panic!("Not raw"),
}
}
pub fn ffmpeg_demuxer(self) -> &'static str {
match self {
Self::Rgb
| Self::Bgr
| Self::Yuv
| Self::Nv12
| Self::Yuyv
| Self::Uyvy
| Self::Raw
| Self::Mono16
| Self::Raw16
| Self::Mono8 => "rawvideo",
Self::H264 => "h264",
Self::H265 => "hevc",
Self::MJPEG => "mjpeg",
Self::Stats => panic!("Not video"),
}
}
pub fn ffmpeg_codec(self) -> &'static str {
match self {
Self::Rgb
| Self::Bgr
| Self::Yuv
| Self::Nv12
| Self::Yuyv
| Self::Uyvy
| Self::Raw
| Self::Mono16
| Self::Raw16
| Self::Mono8 => "libx264",
Self::H264 | Self::H265 | Self::MJPEG => "copy",
Self::Stats => panic!("Not video"),
}
}
pub fn | (&self) -> bool {
matches!(
self,
VideoCaptureFormat::H264 | VideoCaptureFormat::H265 | VideoCaptureFormat::MJPEG
)
}
}
impl TryFrom<i32> for VideoCaptureFormat {
type Error = Box<dyn Error>;
fn try_from(format: i32) -> Result<Self, Self::Error> {
match format {
0 => Ok(VideoCaptureFormat::Rgb),
1 => Ok(VideoCaptureFormat::Bgr),
2 => Ok(VideoCaptureFormat::Yuv),
3 => Ok(VideoCaptureFormat::Nv12),
4 => Ok(VideoCaptureFormat::Yuyv),
5 => Ok(VideoCaptureFormat::Uyvy),
6 => Ok(VideoCaptureFormat::Raw),
7 => Ok(VideoCaptureFormat::Mono16),
8 => Ok(VideoCaptureFormat::Raw16),
9 => Ok(VideoCaptureFormat::Mono8),
-4601 => Ok(VideoCaptureFormat::H264),
-4602 => Ok(VideoCaptureFormat::H265),
-4603 => Ok(VideoCaptureFormat::MJPEG),
-4701 => Ok(VideoCaptureFormat::Stats),
_ => Err(format!("Unknown video capture format {}", format).into()),
}
}
}
fn parse_recording_metadata(bytes: &[u8]) -> Result<&RecordingMetadata, Box<dyn Error>> {
LayoutVerified::<&[u8], RecordingMetadata>::new_unaligned(bytes)
.ok_or_else(|| "Failed to parse RecordingMetadata".into())
.map(|lv| lv.into_ref())
.and_then(|res| {
if res.magic.get() == RECORDING_MAGIC {
Ok(res)
} else {
Err("Magic does not match".into())
}
})
}
fn parse_recorded_frame_metadata(bytes: &[u8]) -> Result<&RecordedFrameMetadata, Box<dyn Error>> {
LayoutVerified::<&[u8], RecordedFrameMetadata>::new_unaligned(bytes)
.ok_or_else(|| "Failed to parse RecordedFrameMetadata".into())
.map(|lv| lv.into_ref())
.and_then(|res| {
if res.magic.get() == RECORDING_FRAME_MAGIC {
Ok(res)
} else {
Err("Magic does not match".into())
}
})
}
fn parse_generic_metadata_header(bytes: &[u8]) -> Result<&GenericMetadataHeader, Box<dyn Error>> {
LayoutVerified::<&[u8], GenericMetadataHeader>::new_unaligned(bytes)
.ok_or_else(|| "Failed to parse GenericMetadataHeader".into())
.map(|lv| lv.into_ref())
.and_then(|res| {
if res.magic.get() == GENERIC_METADATA_HEADER_MAGIC {
Ok(res)
} else {
Err("Magic does not match".into())
}
})
}
pub fn parse_and_discard_recording_metadata(f: &mut dyn BufRead) -> Result<(), Box<dyn Error>> {
let mut recording_metadata_bytes: [u8; mem::size_of::<RecordingMetadata>()] =
[0; mem::size_of::<RecordingMetadata>()];
f.read_exact(&mut recording_metadata_bytes)?;
if parse_recording_metadata(&recording_metadata_bytes[..]).is_err() {
return Err(
"Error parsing recording metadata. (Input is probably not a .vraw file)".into(),
);
};
Ok(())
}
pub fn parse_raw_frame(f: &mut dyn BufRead) -> Result<FrameInfo, Box<dyn Error>> {
// ------------------------------------------------------------------------
// Parse header
let mut recorded_frame_metadata_bytes: [u8; mem::size_of::<RecordedFrameMetadata>()] =
[0; mem::size_of::<RecordedFrameMetadata>()];
f.read_exact(&mut recorded_frame_metadata_bytes)?;
let recorded_frame_metadata =
parse_recorded_frame_metadata(&recorded_frame_metadata_bytes[..])?;
if recorded_frame_metadata.size.get() <= 0 {
return Err("Frame size not parsed correctly.".into());
}
let format = VideoCaptureFormat::try_from(recorded_frame_metadata.format.get())?;
if format.is_coded() {
if recorded_frame_metadata.width.get() != 0 && recorded_frame_metadata.height.get() != 0 {
return Err("Frame width and height not parsed correctly.".into());
}
} else if format != VideoCaptureFormat::Stats
&& (recorded_frame_metadata.width.get() <= 0 || recorded_frame_metadata.height.get() <= 0)
{
return Err("Frame width and height not parsed correctly.".into());
}
// ------------------------------------------------------------------------
// Read frame data
let mut raw_frame_data: Vec<u8> = vec![0; recorded_frame_metadata.size.get() as usize];
f.read_exact(&mut raw_frame_data)?;
// ------------------------------------------------------------------------
// Parse generic metadata header
let mut generic_metadata_header_or_footer_data: [u8; 8] = [0; 8];
f.read_exact(&mut generic_metadata_header_or_footer_data)?;
let generic_metadata_header =
parse_generic_metadata_header(&generic_metadata_header_or_footer_data[..])?;
// ------------------------------------------------------------------------
// Parse generic metadata
let mut generic_metadata_data: Vec<u8> =
vec![0; generic_metadata_header.generic_metadata_size.get() as usize];
f.read_exact(&mut generic_metadata_data)?;
// ------------------------------------------------------------------------
// Parse generic metadata footer
f.read_exact(&mut generic_metadata_header_or_footer_data)?;
let resolution = recorded_frame_metadata.width.to_string()
+ "x"
+ &recorded_frame_metadata.height.to_string();
Ok(FrameInfo {
resolution,
format,
timestamp: recorded_frame_metadata.receive_timestamp.get(),
raw_data: raw_frame_data,
})
}
| is_coded |
config.rs | //! Defines structs for storing register values of commands in the SSD1322 that are associated with
//! relatively-static configuration.
use crate::command::*;
use crate::interface;
/// The portion of the configuration which will persist inside the `Display` because it shares
/// registers with functions that can be changed after initialization. This allows the rest of the
/// `Config` struct to be thrown away to save RAM after `Display::init` finishes.
pub(crate) struct PersistentConfig {
com_scan_direction: ComScanDirection,
com_layout: ComLayout,
}
impl PersistentConfig {
/// Transmit commands to the display at `iface` necessary to put that display into the
/// configuration encoded in `self`.
pub(crate) fn | <DI>(
&self,
iface: &mut DI,
increment_axis: IncrementAxis,
column_remap: ColumnRemap,
nibble_remap: NibbleRemap,
) -> Result<(), CommandError<DI::Error>>
where
DI: interface::DisplayInterface,
{
Command::SetRemapping(
increment_axis,
column_remap,
nibble_remap,
self.com_scan_direction,
self.com_layout,
)
.send(iface)
}
}
/// A configuration for the display. Builder methods offer a declarative way to either sent a
/// configuration command at init time, or to leave it at the chip's POR default.
pub struct Config {
pub(crate) persistent_config: PersistentConfig,
contrast_current_cmd: Option<Command>,
phase_lengths_cmd: Option<Command>,
clock_fosc_divset_cmd: Option<Command>,
display_enhancements_cmd: Option<Command>,
second_precharge_period_cmd: Option<Command>,
precharge_voltage_cmd: Option<Command>,
com_deselect_voltage_cmd: Option<Command>,
}
impl Config {
/// Create a new configuration. COM scan direction and COM layout are mandatory because the
/// display will not function correctly unless they are set, so they must be provided in the
/// constructor. All other options can be optionally set by calling the provided builder
/// methods on `Config`.
pub fn new(com_scan_direction: ComScanDirection, com_layout: ComLayout) -> Self {
Config {
persistent_config: PersistentConfig {
com_scan_direction: com_scan_direction,
com_layout: com_layout,
},
contrast_current_cmd: None,
phase_lengths_cmd: None,
clock_fosc_divset_cmd: None,
display_enhancements_cmd: None,
second_precharge_period_cmd: None,
precharge_voltage_cmd: None,
com_deselect_voltage_cmd: None,
}
}
/// Extend this `Config` to explicitly configure display contrast current. See
/// `Command::SetContrastCurrent`.
pub fn contrast_current(self, current: u8) -> Self {
Self {
contrast_current_cmd: Some(Command::SetContrastCurrent(current)),
..self
}
}
/// Extend this `Config` to explicitly configure OLED drive phase lengths. See
/// `Command::SetPhaseLengths`.
pub fn phase_lengths(self, reset: u8, first_precharge: u8) -> Self {
Self {
phase_lengths_cmd: Some(Command::SetPhaseLengths(reset, first_precharge)),
..self
}
}
/// Extend this `Config` to explicitly configure the display clock frequency and divider. See
/// `Command::SetClockFoscDivset`.
pub fn clock_fosc_divset(self, fosc: u8, divset: u8) -> Self {
Self {
clock_fosc_divset_cmd: Some(Command::SetClockFoscDivset(fosc, divset)),
..self
}
}
/// Extend this `Config` to explicitly configure display enhancement features. See
/// `Command::SetDisplayEnhancements`.
pub fn display_enhancements(self, external_vsl: bool, enhanced_low_gs_quality: bool) -> Self {
Self {
display_enhancements_cmd: Some(Command::SetDisplayEnhancements(
external_vsl,
enhanced_low_gs_quality,
)),
..self
}
}
/// Extend this `Config` to explicitly configure OLED drive second precharge period length. See
/// `Command::SetSecondPrechargePeriod`.
pub fn second_precharge_period(self, period: u8) -> Self {
Self {
second_precharge_period_cmd: Some(Command::SetSecondPrechargePeriod(period)),
..self
}
}
/// Extend this `Config` to explicitly configure OLED drive precharge voltage. See
/// `Command::SetPreChargeVoltage`.
pub fn precharge_voltage(self, voltage: u8) -> Self {
Self {
precharge_voltage_cmd: Some(Command::SetPreChargeVoltage(voltage)),
..self
}
}
/// Extend this `Config` to explicitly configure OLED drive COM deselect voltage. See
/// `Command::SetComDeselectVoltage`.
pub fn com_deselect_voltage(self, voltage: u8) -> Self {
Self {
com_deselect_voltage_cmd: Some(Command::SetComDeselectVoltage(voltage)),
..self
}
}
/// Transmit commands to the display at `iface` necessary to put that display into the
/// configuration encoded in `self`.
pub(crate) fn send<DI>(&self, iface: &mut DI) -> Result<(), CommandError<DI::Error>>
where
DI: interface::DisplayInterface,
{
self.phase_lengths_cmd.map_or(Ok(()), |c| c.send(iface))?;
self.contrast_current_cmd
.map_or(Ok(()), |c| c.send(iface))?;
self.clock_fosc_divset_cmd
.map_or(Ok(()), |c| c.send(iface))?;
self.display_enhancements_cmd
.map_or(Ok(()), |c| c.send(iface))?;
self.second_precharge_period_cmd
.map_or(Ok(()), |c| c.send(iface))?;
self.precharge_voltage_cmd
.map_or(Ok(()), |c| c.send(iface))?;
self.com_deselect_voltage_cmd
.map_or(Ok(()), |c| c.send(iface))?;
Ok(())
}
}
| send |
main.py | from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from src.build_model import convert, predict
app = FastAPI()
# pydantic models
class StockIn(BaseModel):
ticker: str
class StockOut(StockIn):
forecast: dict
# routes
@app.get("/ping")
async def pong():
return {"ping": "pong!"}
@app.post("/predict", response_model=StockOut, status_code=200)
def get_prediction(payload: StockIn):
ticker = payload.ticker
prediction_list = predict(ticker)
if not prediction_list: | return response_object | raise HTTPException(status_code=400, detail="Model not found.")
response_object = {"ticker": ticker, "forecast": convert(prediction_list)} |
navigation.rs | pub(super) fn next_scalar_value(index: usize, string: &str) -> usize {
if let Some((offset, _)) = string[index..].char_indices().nth(1) {
index + offset
} else {
string.len()
}
}
pub(super) fn previous_scalar_value(index: usize, string: &str) -> usize {
if let Some((new_index, _)) = string[..index].char_indices().next_back() {
new_index
} else {
0
}
}
pub(super) fn next_word(pivot: usize, string: &str) -> usize {
let end = string.len();
if pivot == end {
pivot
} else {
unicode_segmentation::UnicodeSegmentation::split_word_bound_indices(string)
.find(|pair| {
pair.0 > pivot && pair.1.chars().next().map_or(true, |c| !c.is_whitespace())
})
.map_or(string.len(), |pair| pair.0)
}
}
pub(super) fn previous_word(pivot: usize, string: &str) -> usize |
pub(super) fn previous_word_end(pivot: usize, string: &str) -> usize {
if pivot == 0 {
pivot
} else {
unicode_segmentation::UnicodeSegmentation::split_word_bound_indices(string)
.rfind(|pair| {
pair.0 + pair.1.len() < pivot
&& pair.1.chars().next().map_or(true, |c| !c.is_whitespace())
})
.map_or(0, |pair| pair.0 + pair.1.len())
}
}
// Allowed because it makes test clearer
#[allow(clippy::non_ascii_literal)]
#[cfg(test)]
mod test {
#[derive(Copy, Clone)]
enum Direction {
Forward,
Backward,
}
impl Direction {
pub(super) fn start_for(self, scenario: &str) -> usize {
match self {
Direction::Forward => 0,
Direction::Backward => scenario.len(),
}
}
}
struct Tester {
direction: Direction,
scenarios: [&'static str; 10],
}
impl Tester {
pub(super) fn prepare(direction: Direction) -> Self {
Self {
direction,
scenarios: [
"",
" \t ",
"AddZ \t ",
" \t AddZ",
" \t AddZ \t ",
"AddZ AdZ AZ \t O AZ AdZ AddZ",
"AddZ AdZ AZ \t 😀 AZ AdZ AddZ",
"AddZ AdZ AZ😀AZ \t O AZ AdZ AddZ",
"AddZ AdZ AZ \t 🇧🇷 AZ AdZ AddZ",
"AddZ AdZ AZ🇧🇷AZ \t O AZ AdZ AddZ",
],
}
}
pub(super) fn test<F, V>(&self, uut: F, validator: V)
where
F: Fn(usize, &str) -> usize,
V: Fn(usize, &str) -> bool,
{
for scenario in &self.scenarios {
test_scenario(
&uut,
&validator,
self.direction,
&scenario,
self.direction.start_for(&scenario),
0,
)
}
}
}
fn test_scenario<F, V>(
uut: F,
validator: V,
direction: Direction,
scenario: &str,
start: usize,
iteration: usize,
) where
F: Fn(usize, &str) -> usize,
V: Fn(usize, &str) -> bool,
{
let pivot = uut(start, scenario);
match direction {
Direction::Forward => {
if pivot == scenario.len() {
return;
}
assert!(pivot > start);
}
Direction::Backward => {
if pivot == 0 {
return;
}
assert!(pivot < start);
}
}
assert!(
validator(pivot, scenario),
"failed on iteration {} at index {} for \"{}\"",
iteration,
pivot,
scenario
);
test_scenario(uut, validator, direction, scenario, pivot, iteration + 1);
}
#[test]
fn next_word() {
let tester = Tester::prepare(Direction::Forward);
tester.test(super::next_word, |pivot, string| {
let c = string[pivot..].chars().next().unwrap();
c == 'A' || c == 'O' || c == '😀' || c == '🇧'
});
}
#[test]
fn previous_word() {
let tester = Tester::prepare(Direction::Backward);
tester.test(super::previous_word, |pivot, string| {
let c = string[pivot..].chars().next().unwrap();
c == 'A' || c == 'O' || c == '😀' || c == '🇧'
});
}
#[test]
fn previous_word_end() {
let tester = Tester::prepare(Direction::Backward);
tester.test(super::previous_word_end, |pivot, string| {
let c = string[..pivot].chars().next_back().unwrap();
c == 'Z' || c == 'O' || c == '😀' || c == '🇷'
});
}
#[test]
fn within_multiple_unicode_scalar_values() {
let string = "ab 🇧🇷 cd";
let pivot = "ab 🇧🇷".len() - 4;
assert_eq!(super::next_word(pivot, string), "ab 🇧🇷 ".len());
assert_eq!(super::previous_word(pivot, string), "ab ".len());
assert_eq!(super::previous_word_end(pivot, string), "ab".len());
}
#[test]
fn next_scalar_value() {
use super::next_scalar_value;
let string = "a😀øé🇧🇷";
let mut index = 0;
index = next_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), '😀');
index = next_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), 'ø');
index = next_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), 'é');
index = next_scalar_value(index, string);
assert_eq!(
string[index..].chars().next().unwrap(),
"🇧🇷".chars().next().unwrap()
);
index = next_scalar_value(index, string);
assert_eq!(
string[index..].chars().next().unwrap(),
"🇧🇷".chars().nth(1).unwrap()
);
index = next_scalar_value(index, string);
assert_eq!(index, string.len());
index = next_scalar_value(index, string);
assert_eq!(index, string.len());
}
#[test]
fn previous_scalar_value() {
use super::previous_scalar_value;
let string = "a😀øé🇧🇷";
let mut index = string.len();
index = previous_scalar_value(index, string);
assert_eq!(
string[index..].chars().next().unwrap(),
"🇧🇷".chars().nth(1).unwrap()
);
index = previous_scalar_value(index, string);
assert_eq!(
string[index..].chars().next().unwrap(),
"🇧🇷".chars().next().unwrap()
);
index = previous_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), 'é');
index = previous_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), 'ø');
index = previous_scalar_value(index, string);
assert_eq!(string[index..].chars().next().unwrap(), '😀');
index = previous_scalar_value(index, string);
assert_eq!(index, 0);
assert_eq!(string[index..].chars().next().unwrap(), 'a');
index = previous_scalar_value(index, string);
assert_eq!(index, 0);
}
}
| {
if pivot == 0 {
pivot
} else {
unicode_segmentation::UnicodeSegmentation::split_word_bound_indices(string)
.rfind(|pair| {
pair.0 < pivot && pair.1.chars().next().map_or(true, |c| !c.is_whitespace())
})
.map_or(0, |pair| pair.0)
}
} |
debug_handler.rs | use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::{parse::Parse, spanned::Spanned, FnArg, ItemFn, Token, Type};
pub(crate) fn expand(attr: Attrs, item_fn: ItemFn) -> TokenStream {
let check_extractor_count = check_extractor_count(&item_fn);
let check_request_last_extractor = check_request_last_extractor(&item_fn);
let check_path_extractor = check_path_extractor(&item_fn);
let check_multiple_body_extractors = check_multiple_body_extractors(&item_fn);
let check_inputs_impls_from_request = check_inputs_impls_from_request(&item_fn, &attr.body_ty);
let check_output_impls_into_response = check_output_impls_into_response(&item_fn);
let check_future_send = check_future_send(&item_fn);
quote! {
#item_fn
#check_extractor_count
#check_request_last_extractor
#check_path_extractor
#check_multiple_body_extractors
#check_inputs_impls_from_request
#check_output_impls_into_response
#check_future_send
}
}
pub(crate) struct Attrs {
body_ty: Type,
}
impl Parse for Attrs {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let mut body_ty = None;
while !input.is_empty() {
let ident = input.parse::<syn::Ident>()?;
if ident == "body" {
input.parse::<Token![=]>()?;
body_ty = Some(input.parse()?);
} else {
return Err(syn::Error::new_spanned(ident, "unknown argument"));
}
let _ = input.parse::<Token![,]>();
}
let body_ty = body_ty.unwrap_or_else(|| syn::parse_quote!(axum::body::Body));
Ok(Self { body_ty })
}
}
fn check_extractor_count(item_fn: &ItemFn) -> Option<TokenStream> {
let max_extractors = 16;
if item_fn.sig.inputs.len() <= max_extractors {
None
} else {
let error_message = format!(
"Handlers cannot take more than {} arguments. \
Use `(a, b): (ExtractorA, ExtractorA)` to further nest extractors",
max_extractors,
);
let error = syn::Error::new_spanned(&item_fn.sig.inputs, error_message).to_compile_error();
Some(error)
}
}
fn extractor_idents(item_fn: &ItemFn) -> impl Iterator<Item = (usize, &syn::FnArg, &syn::Ident)> {
item_fn
.sig
.inputs
.iter()
.enumerate()
.filter_map(|(idx, fn_arg)| match fn_arg {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_type) => {
if let Type::Path(type_path) = &*pat_type.ty {
type_path
.path
.segments
.last()
.map(|segment| (idx, fn_arg, &segment.ident))
} else {
None
}
}
})
}
fn check_request_last_extractor(item_fn: &ItemFn) -> Option<TokenStream> {
let request_extractor_ident =
extractor_idents(item_fn).find(|(_, _, ident)| *ident == "Request");
if let Some((idx, fn_arg, _)) = request_extractor_ident {
if idx != item_fn.sig.inputs.len() - 1 {
return Some(
syn::Error::new_spanned(fn_arg, "`Request` extractor should always be last")
.to_compile_error(),
);
}
}
None
}
fn | (item_fn: &ItemFn) -> TokenStream {
let path_extractors = extractor_idents(item_fn)
.filter(|(_, _, ident)| *ident == "Path")
.collect::<Vec<_>>();
if path_extractors.len() > 1 {
path_extractors
.into_iter()
.map(|(_, arg, _)| {
syn::Error::new_spanned(
arg,
"Multiple parameters must be extracted with a tuple \
`Path<(_, _)>` or a struct `Path<YourParams>`, not by applying \
multiple `Path<_>` extractors",
)
.to_compile_error()
})
.collect()
} else {
quote! {}
}
}
fn check_multiple_body_extractors(item_fn: &ItemFn) -> TokenStream {
let body_extractors = extractor_idents(item_fn)
.filter(|(_, _, ident)| {
*ident == "String"
|| *ident == "Bytes"
|| *ident == "Json"
|| *ident == "RawBody"
|| *ident == "BodyStream"
|| *ident == "Multipart"
|| *ident == "Request"
})
.collect::<Vec<_>>();
if body_extractors.len() > 1 {
body_extractors
.into_iter()
.map(|(_, arg, _)| {
syn::Error::new_spanned(arg, "Only one body extractor can be applied")
.to_compile_error()
})
.collect()
} else {
quote! {}
}
}
fn check_inputs_impls_from_request(item_fn: &ItemFn, body_ty: &Type) -> TokenStream {
if !item_fn.sig.generics.params.is_empty() {
return syn::Error::new_spanned(
&item_fn.sig.generics,
"`#[axum_macros::debug_handler]` doesn't support generic functions",
)
.into_compile_error();
}
item_fn
.sig
.inputs
.iter()
.enumerate()
.map(|(idx, arg)| {
let (span, ty) = match arg {
FnArg::Receiver(receiver) => {
if receiver.reference.is_some() {
return syn::Error::new_spanned(
receiver,
"Handlers must only take owned values",
)
.into_compile_error();
}
let span = receiver.span();
(span, syn::parse_quote!(Self))
}
FnArg::Typed(typed) => {
let ty = &typed.ty;
let span = ty.span();
(span, ty.clone())
}
};
let name = format_ident!(
"__axum_macros_check_{}_{}_from_request",
item_fn.sig.ident,
idx
);
quote_spanned! {span=>
#[allow(warnings)]
fn #name()
where
#ty: ::axum::extract::FromRequest<#body_ty> + Send,
{}
}
})
.collect::<TokenStream>()
}
fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {
let ty = match &item_fn.sig.output {
syn::ReturnType::Default => return quote! {},
syn::ReturnType::Type(_, ty) => ty,
};
let span = ty.span();
let declare_inputs = item_fn
.sig
.inputs
.iter()
.filter_map(|arg| match arg {
FnArg::Receiver(_) => None,
FnArg::Typed(pat_ty) => {
let pat = &pat_ty.pat;
let ty = &pat_ty.ty;
Some(quote! {
let #pat: #ty = panic!();
})
}
})
.collect::<TokenStream>();
let block = &item_fn.block;
let make_value_name = format_ident!(
"__axum_macros_check_{}_into_response_make_value",
item_fn.sig.ident
);
let make = if item_fn.sig.asyncness.is_some() {
quote_spanned! {span=>
#[allow(warnings)]
async fn #make_value_name() -> #ty {
#declare_inputs
#block
}
}
} else {
quote_spanned! {span=>
#[allow(warnings)]
fn #make_value_name() -> #ty {
#declare_inputs
#block
}
}
};
let name = format_ident!("__axum_macros_check_{}_into_response", item_fn.sig.ident);
if let Some(receiver) = self_receiver(item_fn) {
quote_spanned! {span=>
#make
#[allow(warnings)]
async fn #name() {
let value = #receiver #make_value_name().await;
fn check<T>(_: T)
where T: ::axum::response::IntoResponse
{}
check(value);
}
}
} else {
quote_spanned! {span=>
#[allow(warnings)]
async fn #name() {
#make
let value = #make_value_name().await;
fn check<T>(_: T)
where T: ::axum::response::IntoResponse
{}
check(value);
}
}
}
}
fn check_future_send(item_fn: &ItemFn) -> TokenStream {
if item_fn.sig.asyncness.is_none() {
match &item_fn.sig.output {
syn::ReturnType::Default => {
return syn::Error::new_spanned(
&item_fn.sig.fn_token,
"Handlers must be `async fn`s",
)
.into_compile_error();
}
syn::ReturnType::Type(_, ty) => ty,
};
}
let span = item_fn.span();
let handler_name = &item_fn.sig.ident;
let args = item_fn.sig.inputs.iter().map(|_| {
quote_spanned! {span=> panic!() }
});
let name = format_ident!("__axum_macros_check_{}_future", item_fn.sig.ident);
if let Some(receiver) = self_receiver(item_fn) {
quote_spanned! {span=>
#[allow(warnings)]
fn #name() {
let future = #receiver #handler_name(#(#args),*);
fn check<T>(_: T)
where T: ::std::future::Future + Send
{}
check(future);
}
}
} else {
quote_spanned! {span=>
#[allow(warnings)]
fn #name() {
#item_fn
let future = #handler_name(#(#args),*);
fn check<T>(_: T)
where T: ::std::future::Future + Send
{}
check(future);
}
}
}
}
fn self_receiver(item_fn: &ItemFn) -> Option<TokenStream> {
let takes_self = item_fn
.sig
.inputs
.iter()
.any(|arg| matches!(arg, syn::FnArg::Receiver(_)));
if takes_self {
return Some(quote! { Self:: });
}
if let syn::ReturnType::Type(_, ty) = &item_fn.sig.output {
if let syn::Type::Path(path) = &**ty {
let segments = &path.path.segments;
if segments.len() == 1 {
if let Some(last) = segments.last() {
match &last.arguments {
syn::PathArguments::None if last.ident == "Self" => {
return Some(quote! { Self:: });
}
_ => {}
}
}
}
}
}
None
}
#[test]
fn ui() {
#[rustversion::stable]
fn go() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/debug_handler/fail/*.rs");
t.pass("tests/debug_handler/pass/*.rs");
}
#[rustversion::not(stable)]
fn go() {}
go();
}
| check_path_extractor |
ltm_message_routing_generic_protocol_list.go | /*
* BigIP iControl REST
*
* REST API for F5 BigIP. List of operations is not complete, nor known to be accurate.
*
* OpenAPI spec version: 12.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package f5api
|
Kind string `json:"kind,omitempty"`
} | // This describes a message sent to or received from some operations
type LtmMessageRoutingGenericProtocolList struct {
Items []LtmMessageRoutingGenericProtocol `json:"items,omitempty"` |
mod.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
pub mod cluster_swarm_kube;
use anyhow::Result;
use async_trait::async_trait;
use futures::{future::try_join_all, try_join};
#[async_trait]
pub trait ClusterSwarm {
/// Inserts a validator into the ClusterSwarm if it doesn't exist. If it
/// exists, then updates the validator.
async fn upsert_validator(
&self,
index: u32,
num_validators: u32,
num_fullnodes: u32,
image_tag: &str,
delete_data: bool,
) -> Result<()>;
/// Deletes a validator from the ClusterSwarm
async fn delete_validator(&self, index: u32) -> Result<()>;
/// Creates a set of validators with the given `image_tag`
async fn create_validator_set(
&self,
num_validators: u32,
num_fullnodes_per_validator: u32,
image_tag: &str,
delete_data: bool,
) -> Result<()> |
/// Deletes a set of validators
async fn delete_validator_set(&self, num_validators: u32) -> Result<()> {
let validators = (0..num_validators).map(|i| self.delete_validator(i));
try_join_all(validators).await?;
Ok(())
}
/// Inserts a fullnode into the ClusterSwarm if it doesn't exist. If it
/// exists, then updates the fullnode.
async fn upsert_fullnode(
&self,
fullnode_index: u32,
num_fullnodes_per_validator: u32,
validator_index: u32,
num_validators: u32,
image_tag: &str,
delete_data: bool,
) -> Result<()>;
/// Deletes a fullnode from the ClusterSwarm
async fn delete_fullnode(&self, fullnode_index: u32, validator_index: u32) -> Result<()>;
/// Creates a set of fullnodes with the given `image_tag`
async fn create_fullnode_set(
&self,
num_validators: u32,
num_fullnodes_per_validator: u32,
image_tag: &str,
delete_data: bool,
) -> Result<()> {
let fullnodes = (0..num_validators).flat_map(move |validator_index| {
(0..num_fullnodes_per_validator).map(move |fullnode_index| {
self.upsert_fullnode(
fullnode_index,
num_fullnodes_per_validator,
validator_index,
num_validators,
image_tag,
delete_data,
)
})
});
try_join_all(fullnodes).await?;
Ok(())
}
/// Deletes a set of fullnodes
async fn delete_fullnode_set(
&self,
num_validators: u32,
num_fullnodes_per_validator: u32,
) -> Result<()> {
let fullnodes = (0..num_validators).flat_map(move |validator_index| {
(0..num_fullnodes_per_validator)
.map(move |fullnode_index| self.delete_fullnode(fullnode_index, validator_index))
});
try_join_all(fullnodes).await?;
Ok(())
}
/// Creates a set of validators and fullnodes with the given parameters
async fn create_validator_and_fullnode_set(
&self,
num_validators: u32,
num_fullnodes_per_validator: u32,
image_tag: &str,
delete_data: bool,
) -> Result<((), ())> {
try_join!(
self.create_validator_set(
num_validators,
num_fullnodes_per_validator,
image_tag,
delete_data
),
self.create_fullnode_set(
num_validators,
num_fullnodes_per_validator,
image_tag,
delete_data
),
)
}
/// Deletes a set of validators and fullnodes with the given parameters
async fn delete_validator_and_fullnode_set(
&self,
num_validators: u32,
num_fullnodes_per_validator: u32,
) -> Result<((), ())> {
try_join!(
self.delete_validator_set(num_validators),
self.delete_fullnode_set(num_validators, num_fullnodes_per_validator),
)
}
/// Deletes all validators and fullnodes in this cluster
async fn delete_all(&self) -> Result<()>;
}
| {
let validators = (0..num_validators).map(|i| {
self.upsert_validator(
i,
num_validators,
num_fullnodes_per_validator,
image_tag,
delete_data,
)
});
try_join_all(validators).await?;
Ok(())
} |
num_common.rs | //! common macros for num2.rs and num3.rs
use err::{PyErr, PyResult};
use python::Python;
use std::os::raw::c_int;
pub(super) fn err_if_invalid_value<T: PartialEq>(
py: Python,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value && PyErr::occurred(py) {
Err(PyErr::fetch(py))
} else {
Ok(actual_value)
}
}
#[macro_export]
macro_rules! int_fits_larger_int(
($rust_type:ty, $larger_type:ty) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python) -> PyObject {
(*self as $larger_type).into_object(py)
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObject {
(self as $larger_type).into_object(py)
}
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(obj: &'source PyObjectRef) -> PyResult<Self> {
let val = try!($crate::objectprotocol::ObjectProtocol::extract::<$larger_type>(obj));
match cast::<$larger_type, $rust_type>(val) {
Some(v) => Ok(v),
None => Err(exceptions::OverflowError.into())
}
}
}
)
);
// for 128bit Integers
#[macro_export]
macro_rules! int_convert_bignum (
($rust_type: ty, $byte_size: expr, $is_little_endian: expr, $is_signed: expr) => (
impl ToPyObject for $rust_type {
#[inline]
fn to_object(&self, py: Python) -> PyObject {
self.into_object(py)
}
}
impl IntoPyObject for $rust_type {
fn into_object(self, py: Python) -> PyObject {
unsafe {
let bytes = ::std::mem::transmute::<_, [c_uchar; $byte_size]>(self);
let obj = ffi::_PyLong_FromByteArray(
bytes.as_ptr() as *const c_uchar,
$byte_size,
$is_little_endian,
$is_signed,
);
PyObject::from_owned_ptr_or_panic(py, obj)
}
}
}
impl<'source> FromPyObject<'source> for $rust_type {
fn extract(ob: &'source PyObjectRef) -> PyResult<$rust_type> {
unsafe {
let num = ffi::PyNumber_Index(ob.as_ptr());
if num.is_null() {
return Err(PyErr::fetch(ob.py()));
}
let buffer: [c_uchar; $byte_size] = [0; $byte_size];
let ok = ffi::_PyLong_AsByteArray(
ob.as_ptr() as *mut ffi::PyLongObject,
buffer.as_ptr() as *const c_uchar,
$byte_size,
$is_little_endian,
$is_signed,
);
if ok == -1 {
Err(PyErr::fetch(ob.py()))
} else {
Ok(::std::mem::transmute::<_, $rust_type>(buffer))
}
}
}
}
)
);
// manual implementation for 128bit integers
#[cfg(target_endian = "little")]
pub(super) const IS_LITTLE_ENDIAN: c_int = 1;
#[cfg(not(target_endian = "little"))]
pub(super) const IS_LITTLE_ENDIAN: c_int = 0;
#[cfg(test)]
mod test {
use conversion::ToPyObject;
use python::Python;
use std;
#[test]
fn test_u32_max() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::u32::MAX;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<u32>(py).unwrap());
assert_eq!(v as u64, obj.extract::<u64>(py).unwrap());
assert!(obj.extract::<i32>(py).is_err());
}
#[test]
fn test_i64_max() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::i64::MAX;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<i64>(py).unwrap());
assert_eq!(v as u64, obj.extract::<u64>(py).unwrap());
assert!(obj.extract::<u32>(py).is_err());
}
#[test]
fn test_i64_min() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::i64::MIN;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<i64>(py).unwrap());
assert!(obj.extract::<i32>(py).is_err());
assert!(obj.extract::<u64>(py).is_err());
}
#[test]
fn test_u64_max() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::u64::MAX;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<u64>(py).unwrap());
assert!(obj.extract::<i64>(py).is_err());
}
#[test]
#[cfg(not(Py_LIMITED_API))]
fn test_i128_max() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::i128::MAX;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<i128>(py).unwrap());
assert_eq!(v as u128, obj.extract::<u128>(py).unwrap());
assert!(obj.extract::<u64>(py).is_err());
}
#[test] | let gil = Python::acquire_gil();
let py = gil.python();
let v = std::i128::MIN;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<i128>(py).unwrap());
assert!(obj.extract::<i64>(py).is_err());
assert!(obj.extract::<u128>(py).is_err());
}
#[test]
#[cfg(not(Py_LIMITED_API))]
fn test_u128_max() {
let gil = Python::acquire_gil();
let py = gil.python();
let v = std::u128::MAX;
let obj = v.to_object(py);
assert_eq!(v, obj.extract::<u128>(py).unwrap());
assert!(obj.extract::<i128>(py).is_err());
}
#[test]
#[cfg(not(Py_LIMITED_API))]
fn test_u128_overflow() {
use ffi;
use object::PyObject;
use std::os::raw::c_uchar;
use types::exceptions;
let gil = Python::acquire_gil();
let py = gil.python();
let overflow_bytes: [c_uchar; 20] = [255; 20];
unsafe {
let obj = ffi::_PyLong_FromByteArray(
overflow_bytes.as_ptr() as *const c_uchar,
20,
super::IS_LITTLE_ENDIAN,
0,
);
let obj = PyObject::from_owned_ptr_or_panic(py, obj);
let err = obj.extract::<u128>(py).unwrap_err();
assert!(err.is_instance::<exceptions::OverflowError>(py));
}
}
} | #[cfg(not(Py_LIMITED_API))]
fn test_i128_min() { |
context.rs | //! Methods and structures to work with a command's context, which includes
//! its environment, file redirections, arguments, and so on.
//!
use command::Registry;
use environment::Environment;
/// A context for running commands.
///
pub struct Context<'c> {
pub env: &'c mut Environment,
pub args: Vec<String>, | pub registry: &'c Registry,
} |
|
feature_proxy.py | #!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind with different proxy configuration.
Test plan:
- Start versessd's with different proxy configurations
- Use addnode to initiate connections
- Verify that proxies are connected to, and the right connection command is given
- Proxy configurations to test on versessd side:
- `-proxy` (proxy everything)
- `-onion` (proxy just onions)
- `-proxyrandomize` Circuit randomization
- Proxy configurations to test on proxy side,
- support no authentication (other proxy)
- support no authentication + user/pass authentication (Tor)
- proxy on IPv6
- Create various proxies (as threads)
- Create versessds that connect to them
- Manipulate the versessds using addnode (onetry) an observe effects
addnode connect to IPv4
addnode connect to IPv6
addnode connect to onion
addnode connect to generic DNS name
"""
import socket
import os
from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
PORT_MIN,
PORT_RANGE,
assert_equal,
)
from test_framework.netutil import test_ipv6_local
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
class ProxyTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 4
def setup_nodes(self):
|
def node_test(self, node, proxies, auth, test_onion=True):
rv = []
# Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"15.61.23.23")
assert_equal(cmd.port, 1234)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if self.have_ipv6:
# Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534")
assert_equal(cmd.port, 5443)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if test_onion:
# Test: outgoing onion connection through node
node.addnode("bitcoinostk4e4re.onion:8333", "onetry")
cmd = proxies[2].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"bitcoinostk4e4re.onion")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing DNS name connection through node
node.addnode("node.noumenon:8333", "onetry")
cmd = proxies[3].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"node.noumenon")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
return rv
def run_test(self):
# basic -proxy
self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False)
# -proxy plus -onion
self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False)
# -proxy plus -onion, -proxyrandomize
rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True)
# Check that credentials as used for -proxyrandomize connections are unique
credentials = set((x.username,x.password) for x in rv)
assert_equal(len(credentials), len(rv))
if self.have_ipv6:
# proxy on IPv6 localhost
self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False)
def networks_dict(d):
r = {}
for x in d['networks']:
r[x['name']] = x
return r
# test RPC getnetworkinfo
n0 = networks_dict(self.nodes[0].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n0[net]['proxy_randomize_credentials'], True)
assert_equal(n0['onion']['reachable'], True)
n1 = networks_dict(self.nodes[1].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n1[net]['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n1['onion']['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['reachable'], True)
n2 = networks_dict(self.nodes[2].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n2[net]['proxy_randomize_credentials'], True)
assert_equal(n2['onion']['reachable'], True)
if self.have_ipv6:
n3 = networks_dict(self.nodes[3].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr))
assert_equal(n3[net]['proxy_randomize_credentials'], False)
assert_equal(n3['onion']['reachable'], False)
if __name__ == '__main__':
ProxyTest().main()
| self.have_ipv6 = test_ipv6_local()
# Create two proxies on different ports
# ... one unauthenticated
self.conf1 = Socks5Configuration()
self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000))
self.conf1.unauth = True
self.conf1.auth = False
# ... one supporting authenticated and unauthenticated (Tor)
self.conf2 = Socks5Configuration()
self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000))
self.conf2.unauth = True
self.conf2.auth = True
if self.have_ipv6:
# ... one on IPv6 with similar configuration
self.conf3 = Socks5Configuration()
self.conf3.af = socket.AF_INET6
self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000))
self.conf3.unauth = True
self.conf3.auth = True
else:
self.log.warning("Testing without local IPv6 support")
self.serv1 = Socks5Server(self.conf1)
self.serv1.start()
self.serv2 = Socks5Server(self.conf2)
self.serv2.start()
if self.have_ipv6:
self.serv3 = Socks5Server(self.conf3)
self.serv3.start()
# Note: proxies are not used to connect to local nodes
# this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost
args = [
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'],
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'],
['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'],
[]
]
if self.have_ipv6:
args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion']
self.add_nodes(self.num_nodes, extra_args=args)
self.start_nodes() |
deployment_inspector.go | //
// DISCLAIMER
//
// Copyright 2020-2021 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
// Author Tomasz Mielech
//
package deployment
import (
"context"
"time"
inspectorInterface "github.com/arangodb/kube-arangodb/pkg/util/k8sutil/inspector"
"github.com/arangodb/kube-arangodb/pkg/util/errors"
"github.com/arangodb/kube-arangodb/pkg/deployment/patch"
operatorErrors "github.com/arangodb/kube-arangodb/pkg/util/errors"
"github.com/arangodb/kube-arangodb/pkg/deployment/resources/inspector"
"github.com/arangodb/kube-arangodb/pkg/apis/deployment"
api "github.com/arangodb/kube-arangodb/pkg/apis/deployment/v1"
"github.com/arangodb/kube-arangodb/pkg/metrics"
"github.com/arangodb/kube-arangodb/pkg/util"
"github.com/arangodb/kube-arangodb/pkg/util/k8sutil"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
timeoutReconciliationPerNode = time.Second * 20
)
var (
inspectDeploymentDurationGauges = metrics.MustRegisterGaugeVec(metricsComponent, "inspect_deployment_duration", "Amount of time taken by a single inspection of a deployment (in sec)", metrics.DeploymentName)
)
// getReconciliationTimeout gets timeout for the reconciliation loop.
// The whole reconciliation loop timeout depends on the number of nodes but not less then one minute.
func (d *Deployment) getReconciliationTimeout() (time.Duration, error) {
ctx, cancel := context.WithTimeout(context.TODO(), k8sutil.GetRequestTimeout())
defer cancel()
nodes, err := d.GetKubeCli().CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
return 0, errors.Wrapf(err, "Unable to get nodes")
}
if timeout := timeoutReconciliationPerNode * time.Duration(len(nodes.Items)); timeout > time.Minute {
return timeout, nil
}
// The minimum timeout for the reconciliation loop.
return time.Minute, nil
}
// inspectDeployment inspects the entire deployment, creates
// a plan to update if needed and inspects underlying resources.
// This function should be called when:
// - the deployment has changed
// - any of the underlying resources has changed
// - once in a while
// Returns the delay until this function should be called again.
func (d *Deployment) inspectDeployment(lastInterval util.Interval) util.Interval {
log := d.deps.Log
start := time.Now()
timeout, err := d.getReconciliationTimeout()
if err != nil {
log.Error().Err(err).Msg("Unable to get nodes")
return minInspectionInterval // Retry ASAP
}
ctxReconciliation, cancelReconciliation := context.WithTimeout(context.Background(), timeout)
defer cancelReconciliation()
defer func() {
d.deps.Log.Info().Msgf("Inspect loop took %s", time.Since(start))
}()
nextInterval := lastInterval
hasError := false
deploymentName := d.apiObject.GetName()
defer metrics.SetDuration(inspectDeploymentDurationGauges.WithLabelValues(deploymentName), start)
cachedStatus, err := inspector.NewInspector(d.GetKubeCli(), d.GetMonitoringV1Cli(), d.GetArangoCli(), d.GetNamespace())
if err != nil {
log.Error().Err(err).Msg("Unable to get resources")
return minInspectionInterval // Retry ASAP
}
// Check deployment still exists
var updated *api.ArangoDeployment
err = k8sutil.RunWithTimeout(ctxReconciliation, func(ctxChild context.Context) error {
var err error
updated, err = d.deps.DatabaseCRCli.DatabaseV1().ArangoDeployments(d.apiObject.GetNamespace()).Get(ctxChild, deploymentName, metav1.GetOptions{})
return err
})
if k8sutil.IsNotFound(err) {
// Deployment is gone
log.Info().Msg("Deployment is gone")
d.Delete()
return nextInterval
} else if updated != nil && updated.GetDeletionTimestamp() != nil {
// Deployment is marked for deletion
if err := d.runDeploymentFinalizers(ctxReconciliation, cachedStatus); err != nil {
hasError = true
d.CreateEvent(k8sutil.NewErrorEvent("ArangoDeployment finalizer inspection failed", err, d.apiObject))
}
} else {
// Check if maintenance annotation is set
if updated != nil && updated.Annotations != nil {
if v, ok := updated.Annotations[deployment.ArangoDeploymentPodMaintenanceAnnotation]; ok && v == "true" {
// Disable checks if we will enter maintenance mode
log.Info().Str("deployment", deploymentName).Msg("Deployment in maintenance mode")
return nextInterval
}
}
// Is the deployment in failed state, if so, give up.
if d.GetPhase() == api.DeploymentPhaseFailed {
log.Debug().Msg("Deployment is in Failed state.")
return nextInterval
}
d.apiObject = updated
inspectNextInterval, err := d.inspectDeploymentWithError(ctxReconciliation, nextInterval, cachedStatus)
if err != nil {
if !operatorErrors.IsReconcile(err) {
nextInterval = inspectNextInterval
hasError = true
d.CreateEvent(k8sutil.NewErrorEvent("Reconcilation failed", err, d.apiObject))
} else {
nextInterval = minInspectionInterval
}
}
}
// Update next interval (on errors)
if hasError {
if d.recentInspectionErrors == 0 {
nextInterval = minInspectionInterval
d.recentInspectionErrors++
}
} else {
d.recentInspectionErrors = 0
}
return nextInterval.ReduceTo(maxInspectionInterval)
}
func (d *Deployment) inspectDeploymentWithError(ctx context.Context, lastInterval util.Interval,
cachedStatus inspectorInterface.Inspector) (nextInterval util.Interval, inspectError error) {
t := time.Now()
d.SetCachedStatus(cachedStatus)
defer d.SetCachedStatus(nil)
defer func() {
d.deps.Log.Info().Msgf("Reconciliation loop took %s", time.Since(t))
}()
// Ensure that spec and status checksum are same
spec := d.GetSpec()
status, _ := d.getStatus()
nextInterval = lastInterval
inspectError = nil
checksum, err := spec.Checksum()
if err != nil {
return minInspectionInterval, errors.Wrapf(err, "Calculation of spec failed")
} else {
condition, exists := status.Conditions.Get(api.ConditionTypeUpToDate)
if checksum != status.AppliedVersion && (!exists || condition.IsTrue()) {
if err = d.updateCondition(ctx, api.ConditionTypeUpToDate, false, "Spec Changed", "Spec Object changed. Waiting until plan will be applied"); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable to update UpToDate condition")
}
return minInspectionInterval, nil // Retry ASAP
}
}
// Cleanup terminated pods on the beginning of loop
if x, err := d.resources.CleanupTerminatedPods(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Pod cleanup failed")
} else {
nextInterval = nextInterval.ReduceTo(x)
}
if err := d.resources.EnsureArangoMembers(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "ArangoMember creation failed")
}
if err := d.resources.EnsureServices(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Service creation failed")
}
if err := d.resources.EnsureSecrets(ctx, d.deps.Log, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Secret creation failed")
}
// Inspect secret hashes
if err := d.resources.ValidateSecretHashes(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Secret hash validation failed")
}
// Check for LicenseKeySecret
if err := d.resources.ValidateLicenseKeySecret(cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "License Key Secret invalid")
}
// Is the deployment in a good state?
if status.Conditions.IsTrue(api.ConditionTypeSecretsChanged) {
return minInspectionInterval, errors.Newf("Secrets changed")
}
// Ensure we have image info
if retrySoon, exists, err := d.ensureImages(ctx, d.apiObject); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Image detection failed")
} else if retrySoon || !exists {
return minInspectionInterval, nil
}
// Inspection of generated resources needed
if x, err := d.resources.InspectPods(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Pod inspection failed")
} else {
nextInterval = nextInterval.ReduceTo(x)
}
if x, err := d.resources.InspectPVCs(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "PVC inspection failed")
} else {
nextInterval = nextInterval.ReduceTo(x)
}
// Check members for resilience
if err := d.resilience.CheckMemberFailure(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Member failure detection failed")
}
// Immediate actions
if err := d.reconciler.CheckDeployment(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Reconciler immediate actions failed")
}
if interval, err := d.ensureResources(ctx, nextInterval, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Reconciler resource recreation failed")
} else {
nextInterval = interval
}
// Create scale/update plan
if _, ok := d.apiObject.Annotations[deployment.ArangoDeploymentPlanCleanAnnotation]; ok {
if err := d.ApplyPatch(ctx, patch.ItemRemove(patch.NewPath("metadata", "annotations", deployment.ArangoDeploymentPlanCleanAnnotation))); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable to create remove annotation patch")
}
if err := d.WithStatusUpdate(ctx, func(s *api.DeploymentStatus) bool {
s.Plan = nil
return true
}, true); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable clean plan")
}
} else if err, updated := d.reconciler.CreatePlan(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Plan creation failed")
} else if updated {
return minInspectionInterval, nil
}
if d.apiObject.Status.Plan.IsEmpty() && status.AppliedVersion != checksum {
if err := d.WithStatusUpdate(ctx, func(s *api.DeploymentStatus) bool {
s.AppliedVersion = checksum
return true
}); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable to update UpToDate condition")
}
return minInspectionInterval, nil
} else if status.AppliedVersion == checksum {
if !status.Plan.IsEmpty() && status.Conditions.IsTrue(api.ConditionTypeUpToDate) {
if err = d.updateCondition(ctx, api.ConditionTypeUpToDate, false, "Plan is not empty", "There are pending operations in plan"); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable to update UpToDate condition")
}
return minInspectionInterval, nil
}
if status.Plan.IsEmpty() && !status.Conditions.IsTrue(api.ConditionTypeUpToDate) {
if err = d.updateCondition(ctx, api.ConditionTypeUpToDate, true, "Spec is Up To Date", "Spec is Up To Date"); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Unable to update UpToDate condition")
}
return minInspectionInterval, nil
}
}
// Execute current step of scale/update plan
retrySoon, err := d.reconciler.ExecutePlan(ctx, cachedStatus)
if err != nil {
return minInspectionInterval, errors.Wrapf(err, "Plan execution failed")
}
if retrySoon {
nextInterval = minInspectionInterval
}
// Create access packages
if err := d.createAccessPackages(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "AccessPackage creation failed")
}
// Inspect deployment for obsolete members
if err := d.resources.CleanupRemovedMembers(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Removed member cleanup failed")
}
// At the end of the inspect, we cleanup terminated pods.
if x, err := d.resources.CleanupTerminatedPods(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Pod cleanup failed")
} else {
nextInterval = nextInterval.ReduceTo(x)
}
return
}
func (d *Deployment) ensureResources(ctx context.Context, lastInterval util.Interval, cachedStatus inspectorInterface.Inspector) (util.Interval, error) {
// Ensure all resources are created
if d.haveServiceMonitorCRD {
if err := d.resources.EnsureServiceMonitor(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Service monitor creation failed")
}
}
if err := d.resources.EnsurePVCs(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "PVC creation failed")
}
if err := d.resources.EnsurePods(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Pod creation failed")
}
if err := d.resources.EnsurePDBs(ctx); err != nil {
return minInspectionInterval, errors.Wrapf(err, "PDB creation failed")
}
if err := d.resources.EnsureAnnotations(ctx, cachedStatus); err != nil {
return minInspectionInterval, errors.Wrapf(err, "Annotation update failed")
}
if err := d.resources.EnsureLabels(ctx, cachedStatus); err != nil |
return lastInterval, nil
}
// triggerInspection ensures that an inspection is run soon.
func (d *Deployment) triggerInspection() {
d.inspectTrigger.Trigger()
}
// triggerCRDInspection ensures that an inspection is run soon.
func (d *Deployment) triggerCRDInspection() {
d.inspectCRDTrigger.Trigger()
}
func (d *Deployment) updateCondition(ctx context.Context, conditionType api.ConditionType, status bool, reason, message string) error {
d.deps.Log.Info().Str("condition", string(conditionType)).Bool("status", status).Str("reason", reason).Str("message", message).Msg("Updated condition")
if err := d.WithStatusUpdate(ctx, func(s *api.DeploymentStatus) bool {
return s.Conditions.Update(conditionType, status, reason, message)
}); err != nil {
return errors.Wrapf(err, "Unable to update condition")
}
return nil
}
| {
return minInspectionInterval, errors.Wrapf(err, "Labels update failed")
} |
wsgi.py | """
WSGI config for SentyectorAPI project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
""" |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SentyectorAPI.settings')
application = get_wsgi_application() |
import os
from django.core.wsgi import get_wsgi_application |
cat.rs | // Copyright 2017 rust-ipfs-api Developers | // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
use crate::request::ApiRequest;
use crate::serde::Serialize;
#[derive(Serialize)]
pub struct Cat<'a> {
#[serde(rename = "arg")]
pub path: &'a str,
}
impl<'a> ApiRequest for Cat<'a> {
const PATH: &'static str = "/cat";
} | // |
voronoi.rs | use super::{MapBuilder, Map,
TileType, Position, spawner, SHOW_MAPGEN_VISUALIZER,
remove_unreachable_areas_returning_most_distant, generate_voronoi_spawn_regions};
use rltk::RandomNumberGenerator;
use specs::prelude::*;
use std::collections::HashMap;
#[derive(PartialEq, Copy, Clone)]
#[allow(dead_code)]
pub enum DistanceAlgorithm { Pythagoras, Manhattan, Chebyshev }
pub struct VoronoiCellBuilder {
map : Map,
starting_position : Position,
depth: i32,
history: Vec<Map>,
noise_areas : HashMap<i32, Vec<usize>>,
n_seeds: usize,
distance_algorithm: DistanceAlgorithm, | impl MapBuilder for VoronoiCellBuilder {
fn get_map(&self) -> Map {
self.map.clone()
}
fn get_starting_position(&self) -> Position {
self.starting_position.clone()
}
fn get_snapshot_history(&self) -> Vec<Map> {
self.history.clone()
}
fn build_map(&mut self) {
self.build();
}
fn get_spawn_list(&self) -> &Vec<(usize, String)> {
&self.spawn_list
}
fn take_snapshot(&mut self) {
if SHOW_MAPGEN_VISUALIZER {
let mut snapshot = self.map.clone();
for v in snapshot.revealed_tiles.iter_mut() {
*v = true;
}
self.history.push(snapshot);
}
}
}
impl VoronoiCellBuilder {
#[allow(dead_code)]
pub fn new(new_depth : i32) -> VoronoiCellBuilder {
VoronoiCellBuilder{
map : Map::new(new_depth),
starting_position : Position{ x: 0, y : 0 },
depth : new_depth,
history: Vec::new(),
noise_areas : HashMap::new(),
n_seeds: 64,
distance_algorithm: DistanceAlgorithm::Pythagoras,
spawn_list : Vec::new()
}
}
#[allow(dead_code)]
pub fn pythagoras(new_depth : i32) -> VoronoiCellBuilder {
VoronoiCellBuilder{
map : Map::new(new_depth),
starting_position : Position{ x: 0, y : 0 },
depth : new_depth,
history: Vec::new(),
noise_areas : HashMap::new(),
n_seeds: 64,
distance_algorithm: DistanceAlgorithm::Pythagoras,
spawn_list : Vec::new()
}
}
#[allow(dead_code)]
pub fn manhattan(new_depth : i32) -> VoronoiCellBuilder {
VoronoiCellBuilder{
map : Map::new(new_depth),
starting_position : Position{ x: 0, y : 0 },
depth : new_depth,
history: Vec::new(),
noise_areas : HashMap::new(),
n_seeds: 64,
distance_algorithm: DistanceAlgorithm::Manhattan,
spawn_list : Vec::new()
}
}
#[allow(clippy::map_entry)]
fn build(&mut self) {
let mut rng = RandomNumberGenerator::new();
// Make a Voronoi diagram. We'll do this the hard way to learn about the technique!
let mut voronoi_seeds : Vec<(usize, rltk::Point)> = Vec::new();
while voronoi_seeds.len() < self.n_seeds {
let vx = rng.roll_dice(1, self.map.width-1);
let vy = rng.roll_dice(1, self.map.height-1);
let vidx = self.map.xy_idx(vx, vy);
let candidate = (vidx, rltk::Point::new(vx, vy));
if !voronoi_seeds.contains(&candidate) {
voronoi_seeds.push(candidate);
}
}
let mut voronoi_distance = vec![(0, 0.0f32) ; self.n_seeds];
let mut voronoi_membership : Vec<i32> = vec![0 ; self.map.width as usize * self.map.height as usize];
for (i, vid) in voronoi_membership.iter_mut().enumerate() {
let x = i as i32 % self.map.width;
let y = i as i32 / self.map.width;
for (seed, pos) in voronoi_seeds.iter().enumerate() {
let distance;
match self.distance_algorithm {
DistanceAlgorithm::Pythagoras => {
distance = rltk::DistanceAlg::PythagorasSquared.distance2d(
rltk::Point::new(x, y),
pos.1
);
}
DistanceAlgorithm::Manhattan => {
distance = rltk::DistanceAlg::Manhattan.distance2d(
rltk::Point::new(x, y),
pos.1
);
}
DistanceAlgorithm::Chebyshev => {
distance = rltk::DistanceAlg::Chebyshev.distance2d(
rltk::Point::new(x, y),
pos.1
);
}
}
voronoi_distance[seed] = (seed, distance);
}
voronoi_distance.sort_by(|a,b| a.1.partial_cmp(&b.1).unwrap());
*vid = voronoi_distance[0].0 as i32;
}
for y in 1..self.map.height-1 {
for x in 1..self.map.width-1 {
let mut neighbors = 0;
let my_idx = self.map.xy_idx(x, y);
let my_seed = voronoi_membership[my_idx];
if voronoi_membership[self.map.xy_idx(x-1, y)] != my_seed { neighbors += 1; }
if voronoi_membership[self.map.xy_idx(x+1, y)] != my_seed { neighbors += 1; }
if voronoi_membership[self.map.xy_idx(x, y-1)] != my_seed { neighbors += 1; }
if voronoi_membership[self.map.xy_idx(x, y+1)] != my_seed { neighbors += 1; }
if neighbors < 2 {
self.map.tiles[my_idx] = TileType::Floor;
}
}
self.take_snapshot();
}
// Find a starting point; start at the middle and walk left until we find an open tile
self.starting_position = Position{ x: self.map.width / 2, y : self.map.height / 2 };
let mut start_idx = self.map.xy_idx(self.starting_position.x, self.starting_position.y);
while self.map.tiles[start_idx] != TileType::Floor {
self.starting_position.x -= 1;
start_idx = self.map.xy_idx(self.starting_position.x, self.starting_position.y);
}
self.take_snapshot();
// Find all tiles we can reach from the starting point
let exit_tile = remove_unreachable_areas_returning_most_distant(&mut self.map, start_idx);
self.take_snapshot();
// Place the stairs
self.map.tiles[exit_tile] = TileType::DownStairs;
self.take_snapshot();
// Now we build a noise map for use in spawning entities later
self.noise_areas = generate_voronoi_spawn_regions(&self.map, &mut rng);
// Spawn the entities
for area in self.noise_areas.iter() {
spawner::spawn_region(&self.map, &mut rng, area.1, self.depth, &mut self.spawn_list);
}
}
} | spawn_list: Vec<(usize, String)>
}
|
install.py | #!/usr/bin/env python
# encoding: utf-8
"""
Script for installing the components of the ArPI home security system to a running Raspberry PI Zero Wifi host.
It uses the configuration file install.yaml!
---
@author: Gábor Kovács
@copyright: 2017 arpi-security.info. All rights reserved.
@contact: [email protected]
"""
import json
import logging
import subprocess
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from os import system
from os.path import join, exists
from socket import gaierror
from time import sleep
import paramiko
import yaml
from paramiko.ssh_exception import AuthenticationException, NoValidConnectionsError
from scp import SCPClient
from utils import (
deep_copy,
execute_remote,
generate_SSH_key,
list_copy,
print_lines,
show_progress
)
CONFIG = {}
logging.basicConfig(format="%(message)s")
logger = logging.getLogger()
logging.getLogger("paramiko").setLevel(logging.CRITICAL)
__all__ = []
__version__ = 0.1
__date__ = "2017-08-21"
__updated__ = "2019-08-21"
program_shortdesc = __import__("__main__").__doc__.split("---")[0]
program_license = """%s
Created by [email protected] on %s.
Copyright 2019 arpi-security.info. All rights reserved.
USAGE
""" % (
program_shortdesc,
str(__date__),
)
def get_connection():
try:
logger.info(
"Connecting with private key in '%s' %s@%s",
CONFIG["arpi_key_name"],
CONFIG["arpi_username"],
CONFIG["arpi_hostname"],
)
private_key = None
if exists(CONFIG["arpi_key_name"]):
private_key = paramiko.RSAKey.from_private_key_file(
CONFIG["arpi_key_name"], CONFIG["arpi_password"]
)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
CONFIG["arpi_hostname"],
username=CONFIG["arpi_username"],
password=CONFIG["arpi_password"],
pkey=private_key,
)
logger.info("Connected")
except (AuthenticationException, NoValidConnectionsError, gaierror):
try:
logger.info("Connecting %s@%s", CONFIG["default_username"], CONFIG["default_hostname"])
ssh.connect(
CONFIG["default_hostname"],
username=CONFIG["default_username"],
password=CONFIG["default_password"],
)
logger.info("Connected")
except (NoValidConnectionsError, gaierror):
raise Exception("Can't connect to the host!")
return ssh
def install_environment():
"""
Install prerequisites to an empty Raspberry PI.
"""
if not exists(CONFIG["arpi_key_name"]) and \
not exists(CONFIG["arpi_key_name"] + ".pub"):
generate_SSH_key(CONFIG["arpi_key_name"], CONFIG["arpi_password"])
dhparam_file = "arpi_dhparam.pem"
if not exists(dhparam_file):
logger.info("dhparam (%s) generating", dhparam_file)
system(f"openssl dhparam -out {dhparam_file} {CONFIG['dhparam_size']}")
else:
logger.info("dhparam (%s) already exists", dhparam_file)
system(f"openssl dhparam -in {dhparam_file} -text | head -3")
# create the env variables string because paramiko update_evironment ignores them
arguments = {
"ARPI_PASSWORD": CONFIG["arpi_password"],
"ARGUS_DB_SCHEMA": CONFIG["argus_db_schema"],
"ARGUS_DB_USERNAME": CONFIG["argus_db_username"],
"ARGUS_DB_PASSWORD": CONFIG["argus_db_password"],
"ARPI_HOSTNAME": CONFIG["arpi_hostname"],
"DHPARAM_FILE": join("/tmp", dhparam_file),
# progress
"QUIET": "" if CONFIG["progress"] else "-q",
"PROGRESS": "on" if CONFIG["progress"] else "off"
}
# adding package versions
arguments.update({p.upper(): f"{v}" for p, v in CONFIG["packages"].items() if v})
arguments = [f"export {key}={value}" for key, value in arguments.items()]
arguments = "; ".join(arguments)
ssh = get_connection()
scp = SCPClient(ssh.get_transport(), progress=show_progress if CONFIG["progress"] else None)
scp.put("scripts/install_environment.sh", remote_path=".")
deep_copy(ssh, join(CONFIG["server_path"], "etc"), "/tmp/etc", "**/*", CONFIG["progress"])
list_copy(
ssh,
((dhparam_file, "/tmp"),),
CONFIG["progress"]
)
channel = ssh.get_transport().open_session()
channel.get_pty()
channel.set_combine_stderr(True)
output = channel.makefile("r", -1)
logger.info("Starting install script...")
channel.exec_command(f"{arguments}; ./install_environment.sh")
print_lines(output)
ssh.close()
# waiting for user
# 1. deploy key can timeout
# 2. ssh accept password only from terminal
input("Waiting before deploying public key!")
command = f"ssh-copy-id -i {CONFIG['arpi_key_name']} {CONFIG['arpi_username']}@{CONFIG['default_hostname']}"
logger.info("Deploy public key: %s", command)
while subprocess.call(command, shell=True) != 0:
# retry after 2 seconds
sleep(2)
ssh = get_connection()
execute_remote(
message="Enabling key based ssh authentication",
ssh=ssh,
command="sudo sed -i -E -e 's/.*PasswordAuthentication (yes|no)/PasswordAuthentication no/g' /etc/ssh/sshd_config",
)
execute_remote(message="Restarting the host", ssh=ssh, command="sudo reboot")
def install_component(component, update=False, restart=False):
"""
Install the monitor component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Creating server directories...",
ssh=ssh,
command="mkdir -p server/etc server/scripts server/src server/webapplication",
)
logger.info("Copy common files...")
list_copy(
ssh,
( | (join(CONFIG["server_path"], "Pipfile"), "server"),
(join(CONFIG["server_path"], "Pipfile.lock"), "server"),
(join(CONFIG["server_path"], f".env_{CONFIG['environment']}"), "server/.env"),
(join(CONFIG["server_path"], "src", "data.py"), join("server", "src", "data.py")),
(join(CONFIG["server_path"], "src", "hash.py"), join("server", "src", "hash.py")),
(join(CONFIG["server_path"], "src", "models.py"), join("server", "src", "models.py")),
), CONFIG["progress"]
)
deep_copy(
ssh, join(CONFIG["server_path"], "src", "tools"), join("server", "src", "tools"), "**/*.py", CONFIG["progress"]
)
logger.info("Copy component '%s'...", component)
deep_copy(
ssh,
join(CONFIG["server_path"], "src", component),
join("server", "src", component),
"**/*.py",
CONFIG["progress"]
)
if update:
execute_remote(
message="Start installing python packages on sytem...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 pipenv install --system",
)
execute_remote(
message="Create virtual environment with python3 for argus...",
ssh=ssh,
command="cd server; PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
execute_remote(
message="Create virtual environment with python3 for root...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_monitor.service argus_server.service",
)
ssh.close()
def install_server(update=False, restart=False):
"""
Install the server component to a Raspberry PI.
"""
install_component("server", update=update, restart=restart)
def install_monitoring(update=False, restart=False):
"""
Install the monitor component to a Raspberry PI.
"""
install_component("monitoring", update=update, restart=restart)
def install_database():
"""
Install the database component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Initialize database...",
ssh=ssh,
command="cd server; pipenv run flask db init",
)
execute_remote(
message="Migrate database...",
ssh=ssh,
command="cd server; pipenv run flask db migrate",
)
execute_remote(
message="Upgrade database...",
ssh=ssh,
command="cd server; pipenv run flask db upgrade",
)
execute_remote(
message="Updating database content...",
ssh=ssh,
command=f"cd server; pipenv run src/data.py -d -c {CONFIG['argus_db_content']}",
)
ssh.close()
def install_webapplication(restart=False):
"""
Install the web application component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Delete old webapplication on remote site...",
ssh=ssh,
command="rm -R server/webapplication || true",
)
target = join("server", "webapplication")
logger.info("Copy web application: %s => %s", CONFIG["webapplication_path"], target)
deep_copy(ssh, CONFIG["webapplication_path"], target, "**/*", CONFIG["progress"])
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_server.service",
)
def main(argv=None): # IGNORE:C0111
"""Command line options."""
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
try:
# Setup argument parser
parser = ArgumentParser(
description=program_license, formatter_class=RawDescriptionHelpFormatter
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="count",
help="set verbosity level [default: %(default)s]",
)
parser.add_argument(
"component",
choices=["environment", "server", "monitoring", "webapplication", "database"],
)
parser.add_argument(
"-e",
"--env",
dest="environment",
default="",
help="Select a different config (install.{environment}.yaml)",
)
parser.add_argument(
"-r",
"--restart",
action="store_true",
help="Restart depending service(s) after deployment",
)
parser.add_argument(
"-u",
"--update",
action="store_true",
help="Update the python environment for the depending service(s) after deployment",
)
parser.add_argument(
"-p",
"--progress",
action="store_true",
help="Show progress bars",
)
# Process arguments
args = parser.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
logger.info("Verbose mode on")
else:
logger.setLevel(logging.INFO)
config_filename = __file__.replace(".py", ".yaml")
if args.environment:
config_filename = config_filename.replace(".yaml", "." + args.environment + ".yaml")
logger.info("Working with %s", args)
logger.info("Working from %s", config_filename)
with open(config_filename, "r") as stream:
global CONFIG
CONFIG = yaml.load(stream, Loader=yaml.FullLoader)
CONFIG["progress"] = args.progress
logger.info("Working with configuration: \n%s", json.dumps(CONFIG, indent=4, sort_keys=True))
input("Waiting before starting the installation to verify the configuration!")
if args.component == "environment":
install_environment()
elif args.component == "server":
install_server(args.update, args.restart)
elif args.component == "monitoring":
install_monitoring(args.update, args.restart)
elif args.component == "webapplication":
install_webapplication(args.restart)
elif args.component == "database":
install_database()
else:
logger.error("Unknown component: %s", args.component)
logger.info("Finished successfully!")
return 0
except KeyboardInterrupt:
# handle keyboard interrupt ###
logger.info("\n\nCancelled!\n")
return 0
except Exception:
logger.exception("Failed to execute!")
return 2
if __name__ == "__main__":
sys.exit(main()) | |
s3.py | from datetime import timedelta
from pathlib import Path
import click
from overhave.base_settings import LoggingSettings
from overhave.cli.group import overhave
from overhave.transport import OverhaveS3Bucket, OverhaveS3ManagerSettings, S3Manager
from overhave.utils import get_current_time
@overhave.group(short_help="Run s3 cloud interaction commands")
def s3() -> None:
pass
@s3.group(short_help="S3 cloud bucket's interaction commands")
def bucket() -> None:
pass
def _check_bucket_registered(name: str) -> None:
if name in (item.value for item in list(OverhaveS3Bucket)):
return
click.secho(f"Note: specified s3 bucket name '{name}' not presented in OverhaveS3Bucket enum!", fg="yellow")
def _get_s3_manager() -> S3Manager:
LoggingSettings().setup_logging()
manager = S3Manager(OverhaveS3ManagerSettings(autocreate_buckets=False))
manager.initialize()
return manager
@bucket.command(short_help="Create s3 cloud bucket")
@click.option(
"-n", "--name", type=str, help="Declared s3 bucket",
)
def create(name: str) -> None:
|
@bucket.command(short_help="Delete s3 cloud bucket")
@click.option(
"-n", "--name", type=str, help="Declared s3 bucket",
)
@click.option(
"-f", "--force", is_flag=True, help="Delete all files in bucket, then delete bucket",
)
def delete(name: str, force: bool) -> None:
""" Delete s3 bucket. """
_check_bucket_registered(name)
_get_s3_manager().delete_bucket(name, force=force)
@bucket.command(short_help="Remove old s3 cloud bucket files")
@click.option(
"-n", "--name", type=str, help="Declared s3 bucket",
)
@click.option(
"-d", "--days", type=int, help="Remove all files in bucket older then specified days value",
)
def remove_files(name: str, days: int) -> None:
""" Remove s3 bucket files older . """
_check_bucket_registered(name)
manager = _get_s3_manager()
target_date = get_current_time() - timedelta(days=days)
objects = manager.get_bucket_objects(name)
objects_to_delete = []
for obj in objects:
if not obj.modified_at < target_date:
continue
objects_to_delete.append(obj)
if not objects_to_delete:
click.secho(f"No one object older than {days} days.")
return
click.secho(f"Objects older then {days} days: {[x.name for x in objects_to_delete]}")
manager.delete_bucket_objects(bucket=bucket, objects=objects_to_delete)
@s3.command(short_help="Download file from s3 bucket")
@click.option(
"-b", "--bucket", type=str, help="Declared s3 bucket",
)
@click.option(
"-f", "--filename", type=str, help="Filename for downloading",
)
@click.option("-d", "--dir-to-save", type=str, help="Directory for saving file", default=".")
def download_file(bucket: str, filename: str, dir_to_save: str) -> None:
""" Create s3 bucket. """
_check_bucket_registered(bucket)
_get_s3_manager().download_file(filename=filename, bucket=bucket, dir_to_save=Path(dir_to_save))
| """ Create s3 bucket. """
_check_bucket_registered(name)
_get_s3_manager().create_bucket(name) |
cardinality.ts | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { i18n } from '@osd/i18n';
import { MetricAggType, IMetricAggConfig } from './metric_agg_type';
import { METRIC_TYPES } from './metric_agg_types';
import { OSD_FIELD_TYPES } from '../../../../common';
import { BaseAggParams } from '../types';
const uniqueCountTitle = i18n.translate('data.search.aggs.metrics.uniqueCountTitle', {
defaultMessage: 'Unique Count',
});
export interface AggParamsCardinality extends BaseAggParams {
field: string;
}
export const getCardinalityMetricAgg = () =>
new MetricAggType({
name: METRIC_TYPES.CARDINALITY,
title: uniqueCountTitle,
makeLabel(aggConfig: IMetricAggConfig) {
return i18n.translate('data.search.aggs.metrics.uniqueCountLabel', {
defaultMessage: 'Unique count of {field}',
values: { field: aggConfig.getFieldDisplayName() },
});
},
getSerializedFormat(agg) {
return {
id: 'number',
};
},
params: [
{
name: 'field',
type: 'field',
filterFieldTypes: Object.values(OSD_FIELD_TYPES).filter( | ],
}); | (type) => type !== OSD_FIELD_TYPES.HISTOGRAM
),
}, |
issue-2590.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct parser {
tokens: Vec<int> ,
}
trait parse {
fn parse(&self) -> Vec<int> ;
}
| }
fn main() {} | impl parse for parser {
fn parse(&self) -> Vec<int> {
self.tokens //~ ERROR cannot move out of dereference of `&`-pointer
} |
util.js | var path = require('path');
var async = require('async');
var fs = require('graceful-fs');
var Q = require('q');
/**
* Generate a list of unique directory paths given a list of file paths.
* @param {Array.<string>} files List of file paths.
* @return {Array.<string>} List of directory paths.
*/
var uniqueDirs = exports.uniqueDirs = function(files) {
var dirs = {};
files.forEach(function(filepath) {
var parts = path.dirname(filepath).split(path.sep);
var partial = parts[0];
dirs[partial] = true;
for (var i = 1, ii = parts.length; i < ii; ++i) {
partial = path.join(partial, parts[i]);
dirs[partial] = true;
}
});
return Object.keys(dirs);
};
/**
* Sort function for paths. Sorter paths come first. Paths of equal length are
* sorted alphanumerically in path segment order.
* @param {string} a First path.
* @param {string} b Second path.
* @return {number} Comparison.
*/
var byShortPath = exports.byShortPath = function(a, b) {
var aParts = a.split(path.sep);
var bParts = b.split(path.sep);
var aLength = aParts.length;
var bLength = bParts.length;
var cmp = 0;
if (aLength < bLength) {
cmp = -1;
} else if (aLength > bLength) {
cmp = 1;
} else {
var aPart, bPart;
for (var i = 0; i < aLength; ++i) {
aPart = aParts[i];
bPart = bParts[i];
if (aPart < bPart) {
cmp = -1;
break;
} else if (aPart > bPart) {
cmp = 1;
break;
}
}
}
return cmp;
};
/**
* Generate a list of directories to create given a list of file paths.
* @param {Array.<string>} files List of file paths.
* @return {Array.<string>} List of directory paths ordered by path length.
*/ | return uniqueDirs(files).sort(byShortPath);
};
/**
* Copy a file.
* @param {Object} obj Object with src and dest properties.
* @param {function(Error)} callback Callback
*/
var copyFile = exports.copyFile = function(obj, callback) {
var called = false;
function done(err) {
if (!called) {
called = true;
callback(err);
}
}
var read = fs.createReadStream(obj.src);
read.on('error', function(err) {
done(err);
});
var write = fs.createWriteStream(obj.dest);
write.on('error', function(err) {
done(err);
});
write.on('close', function(ex) {
done();
});
read.pipe(write);
};
/**
* Make directory, ignoring errors if directory already exists.
* @param {string} path Directory path.
* @param {function(Error)} callback Callback.
*/
function makeDir(path, callback) {
fs.mkdir(path, function(err) {
if (err) {
// check if directory exists
fs.stat(path, function(err2, stat) {
if (err2 || !stat.isDirectory()) {
callback(err);
} else {
callback();
}
});
} else {
callback();
}
});
}
/**
* Copy a list of files.
* @param {Array.<string>} files Files to copy.
* @param {string} base Base directory.
* @param {string} dest Destination directory.
* @return {Promise} A promise.
*/
exports.copy = function(files, base, dest) {
var deferred = Q.defer();
var pairs = [];
var destFiles = [];
files.forEach(function(file) {
var src = path.resolve(base, file);
var relative = path.relative(base, src);
var target = path.join(dest, relative);
pairs.push({
src: src,
dest: target
});
destFiles.push(target);
});
async.eachSeries(dirsToCreate(destFiles), makeDir, function(err) {
if (err) {
return deferred.reject(err);
}
async.each(pairs, copyFile, function(err) {
if (err) {
return deferred.reject(err);
} else {
return deferred.resolve();
}
});
});
return deferred.promise;
}; | var dirsToCreate = exports.dirsToCreate = function(files) { |
constants.js | /**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var assert = require('assert');
var recast = require('recast');
var types = recast.types;
var namedTypes = types.namedTypes;
var builders = types.builders;
var hasOwn = Object.prototype.hasOwnProperty;
function propagate(constants, source) {
return recast.print(transform(recast.parse(source), constants));
}
var DEV_EXPRESSION = builders.binaryExpression(
'!==',
builders.literal('production'),
builders.memberExpression(
builders.memberExpression(
builders.identifier('process'),
builders.identifier('env'),
false
),
builders.identifier('NODE_ENV'),
false
)
);
function | (ast, constants) {
constants = constants || {};
return types.traverse(ast, function(node, traverse) {
if (namedTypes.Identifier.check(node)) {
// If the identifier is the property of a member expression
// (e.g. object.property), then it definitely is not a constant
// expression that we want to replace.
if (namedTypes.MemberExpression.check(this.parent.node) &&
this.name === 'property' &&
!this.parent.node.computed) {
return false;
}
// There could in principle be a constant called "hasOwnProperty",
// so be careful always to use Object.prototype.hasOwnProperty.
if (node.name === '__DEV__') {
// replace __DEV__ with process.env.NODE_ENV !== 'production'
this.replace(DEV_EXPRESSION);
return false;
} else if (hasOwn.call(constants, node.name)) {
this.replace(builders.literal(constants[node.name]));
return false;
}
} else if (namedTypes.CallExpression.check(node)) {
if (namedTypes.Identifier.check(node.callee) &&
node.callee.name === 'invariant') {
// Truncate the arguments of invariant(condition, ...)
// statements to just the condition based on NODE_ENV
// (dead code removal will remove the extra bytes).
this.replace(
builders.conditionalExpression(
DEV_EXPRESSION,
node,
builders.callExpression(
node.callee,
[node.arguments[0]]
)
)
);
return false;
}
}
});
}
if (!module.parent) {
var constants = JSON.parse(process.argv[3]);
recast.run(function(ast, callback) {
callback(transform(ast, constants));
});
}
exports.propagate = propagate;
exports.transform = transform;
| transform |
content.js | /*----定数----*/
const CHROME_EXT_URL = chrome.extension.getURL("images/");
const CREW_COLORS = [
"rgba(197, 17, 17, 1.0)",
"rgba(19, 46, 209, 1.0)",
"rgba(17, 127, 45, 1.0)",
"rgba(237, 84, 186, 1.0)",
"rgba(255, 127, 39, 1.0)",
"rgba(245, 245, 87, 1.0)",
"rgba(99, 99, 99, 1.0)",
"rgba(214, 224, 240, 1.0)",
"rgba(106, 47, 185, 1.0)",
"rgba(113, 73, 30, 1.0)",
"rgba(56, 254, 220, 1.0)",
"rgba(80, 239, 57, 1.0)",
"rgba(241, 199, 208, 1.0)",
"rgba(113, 132, 148, 1.0)",
"rgba(143, 133, 115, 1.0)",
"rgba(114, 24, 24, 1.0)",
"rgba(254, 253, 189, 1.0)",
"rgba(215, 99, 100, 1.0)"
];
/*
const CREW_DEAD_ICON = [
"dead01.png",
"dead02.png",
"dead03.png",
"dead04.png",
"dead05.png",
"dead06.png",
"dead07.png",
"dead08.png",
"dead09.png",
"dead10.png",
"dead11.png",
"dead12.png"
];
*/
const SUS_COLOR = "#FF0000";
const SUS_CHAR_COLOR = "#FFFFFF";
const QUE_COLOR = "#999999";
const QUE_CHAR_COLOR = "#FFFFFF";
const PUR_COLOR = "#0080FF";
const PUR_CHAR_COLOR = "#FFFFFF";
const DEAD_COLOR = "#000000";
const DEAD_CHAR_COLOR = "#FF0000";
/*
const SUS_COLOR = "#000000";
const SUS_CHAR_COLOR = "#FFFFFF";
const QUE_COLOR = "#999999";
const QUE_CHAR_COLOR = "#FFFFFF";
const PUR_COLOR = "#FEFEFE";
const PUR_CHAR_COLOR = "#000000";
*/
/*----CSS読み込み----*/
function appendCSS(url) {
$("body").append(`<link rel="stylesheet" href="${url}">`);
}
appendCSS("https://fonts.googleapis.com/icon?family=Material+Icons");
appendCSS(chrome.extension.getURL("css/style.css"));
/*----追加HTML、前----*/
$("body").prepend(`
<div class="space">
</div>
`);
/*----追加HTML、後----*/
$("body").append(`
<div class="detective">
<div class="detectiveicon" data-id="0">
<div class="detectiveiconsub"><img src="${CHROME_EXT_URL}num01.png" width="16" height="16"></div>
<div class="detectiveiconsub"><img src="${CHROME_EXT_URL}num02.png" width="16" height="16"></div>
<div class="detectiveiconsub"><img src="${CHROME_EXT_URL}num03.png" width="16" height="16"></div>
</div>
<div class="detectivesub" data-id="0">
<div class="detectivelist" data-id="0">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="1">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="2">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="3">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="4">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="5">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="6">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="7">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="8">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="9">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="10">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="11">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="12">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="13">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="14">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
<div class="detectivelist" data-id="15">
<div class="detectivelistsub" data-id="0">?</div>
<div class="detectivelistsub" data-id="1">?</div>
<div class="detectivelistsub" data-id="2">?</div>
</div>
</div>
</div>
<div class="controlpanel">
<div class="controlpanelTitle">Control
</div>
<div class="coloricon"><img src="${CHROME_EXT_URL}coloricon.png" width="16" height="24">
</div>
<div class="playercolor">
<div class="colorbox" data-id="0">
<ul class=="ulcolorbox" data-id="0">
<li class="colorpalette" data-id="0" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="0" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="1">
<ul class=="ulcolorbox" data-id="1">
<li class="colorpalette" data-id="1" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="1" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="2">
<ul class=="ulcolorbox" data-id="2">
<li class="colorpalette" data-id="2" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="2" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="3">
<ul class=="ulcolorbox" data-id="3">
<li class="colorpalette" data-id="3" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="3" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="4">
<ul class=="ulcolorbox" data-id="4">
<li class="colorpalette" data-id="4" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li> | </div>
<div class="colorbox" data-id="5">
<ul class=="ulcolorbox" data-id="5">
<li class="colorpalette" data-id="5" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="5" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="6">
<ul class=="ulcolorbox" data-id="6">
<li class="colorpalette" data-id="6" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="6" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="7">
<ul class=="ulcolorbox" data-id="7">
<li class="colorpalette" data-id="7" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="7" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="8">
<ul class=="ulcolorbox" data-id="8">
<li class="colorpalette" data-id="8" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="8" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="9">
<ul class=="ulcolorbox" data-id="9">
<li class="colorpalette" data-id="9" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="9" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="10">
<ul class=="ulcolorbox" data-id="10">
<li class="colorpalette" data-id="10" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="10" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="11">
<ul class=="ulcolorbox" data-id="11">
<li class="colorpalette" data-id="11" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="11" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="12">
<ul class=="ulcolorbox" data-id="12">
<li class="colorpalette" data-id="12" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="12" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="13">
<ul class=="ulcolorbox" data-id="13">
<li class="colorpalette" data-id="13" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="13" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="14">
<ul class=="ulcolorbox" data-id="14">
<li class="colorpalette" data-id="14" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="14" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
<div class="colorbox" data-id="15">
<ul class=="ulcolorbox" data-id="15">
<li class="colorpalette" data-id="15" data-cid="0"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[0]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="1"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[1]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="2"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[2]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="3"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[3]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="4"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[4]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="5"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[5]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="6"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[6]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="7"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[7]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="8"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[8]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="9"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[9]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="10"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[10]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="11"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[11]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="12"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[12]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="13"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[13]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="14"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[14]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="15"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[15]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="15" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul>
</div>
</div>
<div class="detectiveop">
<div class="detectiveiconop" data-id="0">
<div class="detectiveiconsubop"><img src="${CHROME_EXT_URL}num01.png" width="16" height="16"></div>
<div class="detectiveiconsubop"><img src="${CHROME_EXT_URL}num02.png" width="16" height="16"></div>
<div class="detectiveiconsubop"><img src="${CHROME_EXT_URL}num03.png" width="16" height="16"></div>
</div>
<div class="detectivesubop">
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="0" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="0" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="0" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="0" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="0" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="0" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="0" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="0" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="0" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="0" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="0" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="0" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="1" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="1" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="1" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="1" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="1" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="1" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="1" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="1" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="1" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="1" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="1" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="1" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="2" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="2" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="2" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="2" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="2" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="2" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="2" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="2" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="2" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="2" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="2" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="2" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="3" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="3" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="3" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="3" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="3" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="3" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="3" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="3" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="3" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="3" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="3" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="3" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="4" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="4" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="4" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="4" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="4" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="4" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="4" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="4" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="4" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="4" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="4" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="4" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="5" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="5" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="5" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="5" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="5" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="5" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="5" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="5" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="5" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="5" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="5" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="5" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="6" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="6" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="6" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="6" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="6" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="6" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="6" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="6" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="6" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="6" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="6" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="6" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="7" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="7" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="7" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="7" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="7" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="7" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="7" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="7" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="7" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="7" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="7" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="7" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="8" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="8" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="8" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="8" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="8" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="8" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="8" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="8" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="8" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="8" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="8" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="8" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="9" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="9" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="9" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="9" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="9" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="9" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="9" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="9" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="9" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="9" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="9" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="9" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="10" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="10" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="10" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="10" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="10" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="10" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="10" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="10" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="10" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="10" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="10" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="10" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="11" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="11" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="11" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="11" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="11" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="11" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="11" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="11" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="11" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="11" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="11" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="11" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="12" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="12" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="12" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="12" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="12" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="12" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="12" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="12" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="12" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="12" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="12" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="12" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="13" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="13" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="13" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="13" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="13" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="13" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="13" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="13" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="13" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="13" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="13" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="13" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="14" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="14" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="14" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="14" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="14" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="14" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="14" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="14" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="14" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="14" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="14" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="14" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
<div class="detectivelistop">
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="15" data-num="0" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="15" data-num="0" data-cid="1">?</div>
<div class="detectiveselect2" data-id="15" data-num="0" data-cid="2">PUR</div>
<div class="crewstatus" data-id="15" data-num="0" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="15" data-num="1" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="15" data-num="1" data-cid="1">?</div>
<div class="detectiveselect2" data-id="15" data-num="1" data-cid="2">PUR</div>
<div class="crewstatus" data-id="15" data-num="1" data-cid="3">DEAD</div>
</div>
<div class="detectivelistsubop">
<div class="detectiveselect0" data-id="15" data-num="2" data-cid="0">SUS</div>
<div class="detectiveselect1" data-id="15" data-num="2" data-cid="1">?</div>
<div class="detectiveselect2" data-id="15" data-num="2" data-cid="2">PUR</div>
<div class="crewstatus" data-id="15" data-num="2" data-cid="3">DEAD</div>
</div>
</div>
</div>
</div>
<div class="resetbutton">SUS reset
</div>
</div>
`);
$("body").children("*").wrapAll("<main></main>");
/* DiscordOverlayの更新監視 */
const target = document.getElementById("app-mount");
const mutationObserver = new MutationObserver(callback);
const option = {
childList: true,
subtree: true,
};
/* DiscordOverlayの監視開始 */
mutationObserver.observe(target, option);
/* DiscordIDの一覧 */
var vUserList = [];
/* 更新検知時の動作 */
function callback(mutations) {
//プレイヤーのDiscordID一覧を取得
var vUsers = document.getElementsByClassName("user");
vUserList = [];
$.each(vUsers, function(i, val) {
var vUserName = val.innerText;
var vUserid = $(val).attr('data-reactid');
vUserList.push([vUserid,"",vUserName]);
});
//保存データがあれば、更新されたプレイヤー一覧に対応する色を表示
if(JSON.parse(localStorage.getItem('UserList'))) {
vSaveUserList = JSON.parse(localStorage.getItem("UserList"));
$.each(vUserList, function(i, val) {
$.each(vSaveUserList, function(i2, val2) {
if (val[0] == val2[0]) {
vUserList[i][1] = val2[1];
}
});
});
}
$.each(vUserList, function(i, val) {
changeAvatarColor(i, Number(val[1]));
changeAvatarButtonColor(i, Number(val[1]));
});
changeDetectiveDisplay(vUserList.length);
changeAvatarButtonDisplay(vUserList.length);
changeDetectiveButtonDisplay(vUserList.length);
}
/* 色選択パレットの表示・非表示 */
$(".colorbox").on("click", function () {
var vUcolors = $(this).children();
var vUcolor = vUcolors[0];
try {
if (vUcolor.style.display == "block") {
vUcolor.style.display = "none";
} else {
vUcolor.style.display = "block";
}
} catch (e) {
}
});
/* 色選択パレットで色を選択する */
$(".colorpalette").on("click", function () {
var vSelectId = Number($(this).attr('data-id'));
var vSelectColorId = Number($(this).attr('data-cid'));
changeAvatarButtonColor(vSelectId, vSelectColorId);
changeAvatarColor(vSelectId, vSelectColorId);
try {
var vUserData
if (vUserList.length >= vSelectId) {
vUserData = vUserList[vSelectId];
if (vUserData.length == 3) {
vUserData[1] = vSelectColorId;
}
}
} catch (e) {
}
// ローカルストレージへの色設定の保存
//localStorage.removeItem('UserList');
var vUserData2
var vSaveUserList
if (vUserList.length >= vSelectId) {
vUserData2 = vUserList[vSelectId];
if(JSON.parse(localStorage.getItem('UserList'))) {
vSaveUserList = JSON.parse(localStorage.getItem("UserList"));
// ローカルストレージに一致するDiscordIDが存在するか(無:-1、有:配列のindex)
var vSaveIdList = [];
$.each(vSaveUserList, function(i, val) {
vSaveIdList.push(val[0]);
});
var vSerchResult = $.inArray(vUserData2[0], vSaveIdList);
if(vSerchResult>-1){
//ID一致の場合上書き
vSaveUserList[vSerchResult] = vUserData2;
} else {
//ID一致しない場合追加
vSaveUserList.push(vUserData2);
}
//ローカルストレージに上書き保存
localStorage.setItem("UserList", JSON.stringify(vSaveUserList));
} else {
//ローカルストレージに新規保存
var vSaveData = [];
vSaveData.push(vUserData2);
localStorage.setItem("UserList", JSON.stringify(vSaveData));
}
}
});
/* アバターの色変更 */
function changeAvatarColor(UserIndex, ColorIndex) {
var vAvatars = document.getElementsByClassName("avatar");
$.each(vAvatars, function(i, val) {
if (i == UserIndex) {
val.style.backgroundColor = CREW_COLORS[ColorIndex];
}
});
}
/* アバターの色選択ボタンの色変更 */
function changeAvatarButtonColor(UserIndex, ColorIndex) {
var vDcolors = document.getElementsByClassName("colorbox");
$.each(vDcolors, function(i, val) {
if (i == UserIndex) {
val.style.backgroundColor = CREW_COLORS[ColorIndex];
}
});
}
/* アバターの色選択ボタンの表示数変更 */
function changeAvatarButtonDisplay(UserCount) {
var vDcolors = document.getElementsByClassName("colorbox");
$.each(vDcolors, function(i, val) {
if (i < UserCount) {
$(val).show();
} else {
$(val).hide();
}
});
}
/* アバターの推理結果の表示数変更 */
function changeDetectiveDisplay(UserCount) {
var vDcolors = document.getElementsByClassName("detectivelist");
$.each(vDcolors, function(i, val) {
if (i < UserCount) {
$(val).show();
} else {
$(val).hide();
}
});
}
/* アバターの推理結果の表示数変更 */
function changeDetectiveButtonDisplay(UserCount) {
var vDcolors = document.getElementsByClassName("detectivelistop");
$.each(vDcolors, function(i, val) {
if (i < UserCount) {
$(val).show();
} else {
$(val).hide();
}
});
}
/* 推理結果の選択 */
$(".detectiveselect0").on("click", function () {
var vSelectId = Number($(this).attr('data-id'));
var vSelectNumId = Number($(this).attr('data-num'));
var vSelectColorId = Number($(this).attr('data-cid'));
changeDetectiveSus(vSelectId, vSelectNumId, vSelectColorId);
});
$(".detectiveselect1").on("click", function () {
var vSelectId = Number($(this).attr('data-id'));
var vSelectNumId = Number($(this).attr('data-num'));
var vSelectColorId = Number($(this).attr('data-cid'));
changeDetectiveSus(vSelectId, vSelectNumId, vSelectColorId);
});
$(".detectiveselect2").on("click", function () {
var vSelectId = Number($(this).attr('data-id'));
var vSelectNumId = Number($(this).attr('data-num'));
var vSelectColorId = Number($(this).attr('data-cid'));
changeDetectiveSus(vSelectId, vSelectNumId, vSelectColorId);
});
$(".crewstatus").on("click", function () {
var vSelectId = Number($(this).attr('data-id'));
var vSelectNumId = Number($(this).attr('data-num'));
var vSelectColorId = Number($(this).attr('data-cid'));
changeDetectiveSus(vSelectId, vSelectNumId, vSelectColorId);
});
/* 推理結果のセット */
function changeDetectiveSus(UserIndex, NumIndex, ColorIndex) {
var vUserList = document.getElementsByClassName("detectivelist");
$.each(vUserList, function(i, val) {
if (i == UserIndex) {
var vSusList = val.getElementsByClassName("detectivelistsub");
var vSus = vSusList[NumIndex];
switch(ColorIndex){
case 0 : vSus.style.backgroundColor = SUS_COLOR; $(vSus).css("color",SUS_CHAR_COLOR); $(vSus).text("SUS"); break;
case 1 : vSus.style.backgroundColor = QUE_COLOR; $(vSus).css("color",QUE_CHAR_COLOR); $(vSus).text("?"); break;
case 2 : vSus.style.backgroundColor = PUR_COLOR; $(vSus).css("color",PUR_CHAR_COLOR); $(vSus).text("PUR"); break;
case 3 : vSus.style.backgroundColor = DEAD_COLOR; $(vSus).css("color",DEAD_CHAR_COLOR); $(vSus).text("DEAD"); break;
default : vSus.style.backgroundColor = QUE_COLOR; $(vSus).css("color",QUE_CHAR_COLOR); $(vSus).text("?"); break;
}
}
});
}
/* 推理結果のリセット */
$(".resetbutton").on("click", function () {
var vSusList = document.getElementsByClassName("detectivelistsub");
$.each(vSusList, function(i, val) {
val.style.backgroundColor = QUE_COLOR;
$(val).css("color",QUE_CHAR_COLOR);
$(val).text("?");
});
}); | <li class="colorpalette" data-id="4" data-cid="16"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[16]};"></label></li>
<li class="colorpalette" data-id="4" data-cid="17"><input type="radio" name="groupname"><label style="background-color: ${CREW_COLORS[17]};"></label></li>
</ul> |
tests_integ_yarn.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Integration tests for pySparkling for Spark running in YARN mode
"""
from integ_test_utils import IntegTestSuite
import test_utils
class YarnIntegTestSuite(IntegTestSuite):
def test_chicago_crime(self):
self.spark_master("yarn-client")
# Configure YARN environment
self.conf("spark.yarn.max.executor.failures", 1) # In fail of executor, fail the test
self.conf("spark.executor.instances", 3)
self.conf("spark.executor.memory", "2g")
self.conf("spark.ext.h2o.port.base", 63331)
self.conf("spark.driver.memory", "2g")
self.launch("examples/scripts/ChicagoCrimeDemo.py")
if __name__ == '__main__':
test_utils.run_tests([YarnIntegTestSuite], file_name="py_integ_yarn_tests_report") | # |
|
main.rs | use std::io::BufRead; // needed for lines()
pub type BoxError = std::boxed::Box<dyn
std::error::Error // must implement Error to satisfy ?
+ std::marker::Send // needed for threads
+ std::marker::Sync // needed for threads
>;
fn count(filename: &std::path::Path) -> Result<i32, BoxError> {
let file = std::fs::File::open(filename)?;
let file = std::io::BufReader::new(file);
let mut sum: i32 = 0;
for line in file.lines() {
sum += line?.parse::<i32>()?;
}
Ok(sum)
}
fn | () -> Result<(), BoxError> {
let sum = count(std::path::Path::new("numbers.txt"))?;
println!("The sum is: {}", sum);
Ok(())
} | main |
transform.ts | import type {
Optimizer,
InternalCache,
TransformModuleOptions,
TransformModuleResult,
} from './types';
import type TypeScript from 'typescript';
import { isJsxFile, toBase64 } from './utils';
export function transformModuleSync(
optimizer: Optimizer,
c: InternalCache,
opts: TransformModuleOptions,
ts: typeof TypeScript,
tsCompilerOptions: TypeScript.CompilerOptions
) {
const compilerOptions = getCompilerOptions(ts, tsCompilerOptions, optimizer, opts);
const cacheKey =
optimizer.isCacheEnabled() && typeof opts.createCacheKey === 'function'
? opts.createCacheKey(
JSON.stringify({
f: opts.filePath,
x: opts.text,
t: ts.version,
...compilerOptions,
})
)
: null;
if (cacheKey) {
const inMemoryCache = c.modules.find((c) => c.cacheKey === cacheKey);
if (inMemoryCache) {
return inMemoryCache;
}
if (typeof opts.readFromCacheSync === 'function') {
const cachedResult = opts.readFromCacheSync(cacheKey);
if (cachedResult) {
setInMemoryCache(c, cachedResult);
return cachedResult;
}
}
}
const tsResult = ts.transpileModule(opts.text, {
compilerOptions,
fileName: opts.filePath,
});
const result: TransformModuleResult = {
filePath: opts.filePath,
text: tsResult.outputText,
map: tsResult.sourceMapText,
cacheKey,
};
if (typeof result.text === 'string' && opts.sourcemap === 'inline' && result.map) {
try {
const sourceMap = JSON.parse(result.map);
sourceMap.file = opts.filePath;
sourceMap.sources = [opts.filePath];
delete sourceMap.sourceRoot;
const base64Map = toBase64(JSON.stringify(sourceMap));
if (base64Map !== '') {
const sourceMapInlined = `data:application/json;charset=utf-8;base64,${base64Map}`;
const commentPos = result.text.lastIndexOf('//#');
result.text = result.text.slice(0, commentPos) + '//# sourceMappingURL=' + sourceMapInlined;
result.map = undefined;
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
if (Array.isArray(tsResult.diagnostics) && tsResult.diagnostics.length > 0) {
return result;
}
if (cacheKey) {
setInMemoryCache(c, result);
if (typeof opts.writeToCacheSync === 'function') {
opts.writeToCacheSync(cacheKey, result);
}
}
return result;
}
function getCompilerOptions(
ts: typeof TypeScript,
tsconfigCompilerOpts: TypeScript.CompilerOptions,
optimizer: Optimizer,
opts: TransformModuleOptions
) {
const compilerOpts: TypeScript.CompilerOptions = {
...ts.getDefaultCompilerOptions(),
...tsconfigCompilerOpts,
declaration: false,
isolatedModules: true, | noResolve: true,
sourceMap: false,
inlineSourceMap: false,
inlineSources: false,
};
if (typeof compilerOpts.esModuleInterop !== 'boolean') {
compilerOpts.esModuleInterop = true;
}
compilerOpts.module = opts.module === 'cjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ES2020;
if (typeof compilerOpts.target === 'undefined') {
compilerOpts.target = ts.ScriptTarget.ES2017;
}
const sourcemap = opts.sourcemap || optimizer.getSourceMapOption();
if (sourcemap === 'inline') {
compilerOpts.inlineSourceMap = true;
compilerOpts.inlineSources = true;
} else if (sourcemap === 'external') {
compilerOpts.sourceMap = true;
}
if (isJsxFile(opts.filePath)) {
compilerOpts.jsx = ts.JsxEmit.ReactJSX;
compilerOpts.jsxImportSource = '@builder.io/qwik';
}
return compilerOpts;
}
function setInMemoryCache(c: InternalCache, result: TransformModuleResult) {
const currentIndex = c.modules.findIndex((c) => c.filePath === result.filePath);
if (currentIndex > -1) {
c.modules.splice(currentIndex, 1);
}
c.modules.push(result);
while (c.modules.length > 300) {
c.modules.shift();
}
} | skipLibCheck: true,
suppressOutputPathCheck: true,
allowNonTsExtensions: true,
noLib: true, |
id.rs | /// A (hopefully) unique snowflake.
///
/// The flake consists of a timestamp, datacenter id, machine id and a sequence number.
#[derive(Clone, Copy, Debug)]
pub struct Flake(pub u64);
impl Flake {
// Shifts and masks for the fields contained in the snowflake.
pub(crate) const TIMESTAMP_SHIFT: u64 = 22;
pub(crate) const DATACENTER_SHIFT: u64 = 17;
pub(crate) const DATACENTER_MASK: u64 = 0x3E0000;
pub(crate) const DATACENTER_BITS: u64 = 5;
pub(crate) const DATACENTER_MAX: i32 = (1 << Self::DATACENTER_BITS);
pub(crate) const MACHINE_SHIFT: u64 = 12;
pub(crate) const MACHINE_MASK: u64 = 0x1F000;
pub(crate) const MACHINE_BITS: u64 = 5;
pub(crate) const MACHINE_MAX: i32 = (1 << Self::MACHINE_BITS);
pub(crate) const SEQUENCE_MASK: u64 = 0xFFF;
pub(crate) const SEQUENCE_BITS: u64 = 12;
pub(crate) const SEQUENCE_MAX: i32 = (1 << Self::SEQUENCE_BITS);
/// Creates a new flake.
///
/// The timestamp must fit within 42 bits, the datacenter and machine id within 5 bits, and the sequence within 12 bits.
/// This is not checked so it is up to the caller to ensure this.
pub fn new(timestamp: u64, datacenter_id: i32, machine_id: i32, sequence: i32) -> Self {
let milliseconds = timestamp << Self::TIMESTAMP_SHIFT;
let datacenter_id = (datacenter_id as u64) << Self::DATACENTER_SHIFT;
let machine_id = (machine_id as u64) << Self::MACHINE_SHIFT;
let sequence = sequence as u64;
| Self(milliseconds | datacenter_id | machine_id | sequence)
}
/// Gets the timestamp contained in the snowflake. This can be at most 42 bits.
pub fn timestamp(&self) -> u64 {
self.0 >> Self::TIMESTAMP_SHIFT
}
/// Gets the datacenter ID contained in the snowflake. This can be at most 5 bits.
pub fn datacenter_id(&self) -> u64 {
(self.0 & Self::DATACENTER_MASK) >> Self::DATACENTER_SHIFT
}
/// Gets the machine ID contained in the snowflake. This can be at most 5 bits.
pub fn machine_id(&self) -> u64 {
(self.0 & Self::MACHINE_MASK) >> Self::MACHINE_SHIFT
}
/// Gets the sequence contained in the snowflake. This can be at most 12 bits.
pub fn sequence(&self) -> u64 {
self.0 & Self::SEQUENCE_MASK
}
} | |
run.py | import dvc.logger as logger
from dvc.command.base import CmdBase
from dvc.exceptions import DvcException
class CmdRun(CmdBase):
def _joined_cmd(self):
if len(self.args.command) == 0:
|
if len(self.args.command) == 1:
return self.args.command[0]
cmd = ''
for chunk in self.args.command:
if len(chunk.split()) != 1:
fmt = ' "{}"'
else:
fmt = ' {}'
cmd += fmt.format(chunk)
return cmd
def run(self):
overwrite = (self.args.yes or self.args.overwrite_dvcfile)
try:
self.project.run(cmd=self._joined_cmd(),
outs=self.args.outs,
outs_no_cache=self.args.outs_no_cache,
metrics_no_cache=self.args.metrics_no_cache,
deps=self.args.deps,
fname=self.args.file,
cwd=self.args.cwd,
no_exec=self.args.no_exec,
overwrite=overwrite,
ignore_build_cache=self.args.ignore_build_cache,
remove_outs=self.args.remove_outs)
except DvcException:
logger.error('failed to run command')
return 1
return 0
| return '' |
get.rs | use crate::commands::WholeStreamCommand;
use crate::data::Value;
use crate::errors::ShellError;
use crate::prelude::*;
use crate::utils::did_you_mean;
use log::trace;
pub struct Get;
#[derive(Deserialize)]
pub struct GetArgs {
member: ColumnPath,
rest: Vec<ColumnPath>,
}
impl WholeStreamCommand for Get {
fn name(&self) -> &str {
"get"
}
fn signature(&self) -> Signature {
Signature::build("get")
.required(
"member",
SyntaxShape::ColumnPath,
"the path to the data to get",
)
.rest(
SyntaxShape::ColumnPath,
"optionally return additional data by path",
)
}
fn usage(&self) -> &str {
"Open given cells as text."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, get)?.run()
}
}
pub type ColumnPath = Vec<Tagged<Value>>;
pub fn get_column_path(
path: &ColumnPath,
obj: &Tagged<Value>,
) -> Result<Tagged<Value>, ShellError> {
let fields = path.clone();
let value = obj.get_data_by_column_path(
obj.tag(),
path,
Box::new(move |(obj_source, column_path_tried)| {
match obj_source {
Value::Table(rows) => {
let total = rows.len();
let end_tag = match fields.iter().nth_back(if fields.len() > 2 { 1 } else { 0 })
{
Some(last_field) => last_field.tag(),
None => column_path_tried.tag(),
};
return ShellError::labeled_error_with_secondary(
"Row not found",
format!(
"There isn't a row indexed at '{}'",
match &*column_path_tried {
Value::Primitive(primitive) => primitive.format(None),
_ => String::from(""),
}
),
column_path_tried.tag(),
format!("The table only has {} rows (0..{})", total, total - 1),
end_tag,
);
}
_ => {}
}
match &column_path_tried {
Tagged {
item: Value::Primitive(Primitive::Int(index)),
..
} => {
return ShellError::labeled_error(
"No rows available",
format!(
"Not a table. Perhaps you meant to get the column '{}' instead?",
index
),
column_path_tried.tag(),
)
}
_ => match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => {
return ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", suggestions[0].1),
tag_for_tagged_list(fields.iter().map(|p| p.tag())),
)
}
None => {
return ShellError::labeled_error(
"Unknown column",
"row does not contain this column",
tag_for_tagged_list(fields.iter().map(|p| p.tag())),
)
}
},
}
}),
);
let res = match value {
Ok(fetched) => match fetched {
Some(Tagged { item: v, .. }) => Ok((v.clone()).tagged(&obj.tag)),
None => match obj {
// If its None check for certain values.
Tagged {
item: Value::Primitive(Primitive::String(_)),
..
} => Ok(obj.clone()),
Tagged {
item: Value::Primitive(Primitive::Path(_)),
..
} => Ok(obj.clone()),
_ => Ok(Value::nothing().tagged(&obj.tag)),
},
},
Err(reason) => Err(reason),
};
res
}
pub fn get(
GetArgs {
member,
rest: fields,
}: GetArgs,
RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> | {
trace!("get {:?} {:?}", member, fields);
let stream = input
.values
.map(move |item| {
let mut result = VecDeque::new();
let member = vec![member.clone()];
let column_paths = vec![&member, &fields]
.into_iter()
.flatten()
.collect::<Vec<&ColumnPath>>();
for path in column_paths {
let res = get_column_path(&path, &item);
match res {
Ok(got) => match got {
Tagged {
item: Value::Table(rows),
..
} => {
for row in rows {
result.push_back(ReturnSuccess::value(
Tagged {
item: row.item,
tag: Tag::from(&item.tag),
}
.map_anchored(&item.tag.anchor),
))
}
}
other => result
.push_back(ReturnSuccess::value((*other).clone().tagged(&item.tag))),
},
Err(reason) => result.push_back(Err(reason)),
}
}
result
})
.flatten();
Ok(stream.to_output_stream())
} |
|
relation.go | package controller
import (
//"encoding/json"
//"fmt"
"net/http"
//"strconv"
"filter"
"service"
"util"
//"github.com/studygolang/mux"
)
//关注 /relation/subscribe.json
func Subs | http.ResponseWriter, req *http.Request) {
var data = make(map[string]interface{})
user, _ := filter.CurrentUser(req)
from_user_id := user["uid"].(int)
to_user_id := util.MustInt(req.PostFormValue("to_user_id"))
isfans := service.IsFans(from_user_id, to_user_id)
if !isfans {
err := service.Subscribe(from_user_id, to_user_id)
if err == nil {
data["ok"] = 1
data["error"] = "已关注"
} else {
data["ok"] = 0
data["error"] = err.Error()
}
} else {
data["ok"] = 1
data["error"] = "已关注"
}
filter.SetData(req, data)
}
//取消关注/relation/unsubscribe.json
func UnsubscribeHandler(rw http.ResponseWriter, req *http.Request) {
var data = make(map[string]interface{})
user, _ := filter.CurrentUser(req)
from_user_id := user["uid"].(int)
to_user_id := util.MustInt(req.PostFormValue("to_user_id"))
isfans := service.IsFans(from_user_id, to_user_id)
if isfans {
err := service.Unsubscribe(from_user_id, to_user_id)
if err == nil {
data["ok"] = 1
data["error"] = "已取消关注"
} else {
data["ok"] = 0
data["error"] = err.Error()
}
} else {
data["ok"] = 1
data["error"] = "未关注"
}
filter.SetData(req, data)
}
| cribeHandler(rw |
gen.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// This program generates the trie for idna operations. The Unicode casing
// algorithm requires the lookup of various properties and mappings for each
// rune. The table generated by this generator combines several of the most
// frequently used of these into a single trie so that they can be accessed
// with a single lookup.
package main
import (
"fmt"
"io"
"log"
"unicode"
"unicode/utf8"
"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/internal/gen"
"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/internal/triegen"
"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/internal/ucd"
"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/unicode/bidi"
)
func main() {
gen.Init()
genTables()
gen.Repackage("gen_trieval.go", "trieval.go", "idna")
gen.Repackage("gen_common.go", "common_test.go", "idna")
}
var runes = map[rune]info{}
func | () {
t := triegen.NewTrie("idna")
ucd.Parse(gen.OpenUCDFile("DerivedNormalizationProps.txt"), func(p *ucd.Parser) {
r := p.Rune(0)
if p.String(1) == "NFC_QC" { // p.String(2) is "N" or "M"
runes[r] = mayNeedNorm
}
})
ucd.Parse(gen.OpenUCDFile("UnicodeData.txt"), func(p *ucd.Parser) {
r := p.Rune(0)
const cccVirama = 9
if p.Int(ucd.CanonicalCombiningClass) == cccVirama {
runes[p.Rune(0)] = viramaModifier
}
switch {
case unicode.In(r, unicode.Mark):
runes[r] |= modifier | mayNeedNorm
}
// TODO: by using UnicodeData.txt we don't mark undefined codepoints
// that are earmarked as RTL properly. However, an undefined cp will
// always fail, so there is no need to store this info.
switch p, _ := bidi.LookupRune(r); p.Class() {
case bidi.R, bidi.AL, bidi.AN:
if x := runes[r]; x != 0 && x != mayNeedNorm {
log.Fatalf("%U: rune both modifier and RTL letter/number", r)
}
runes[r] = rtl
}
})
ucd.Parse(gen.OpenUCDFile("extracted/DerivedJoiningType.txt"), func(p *ucd.Parser) {
switch v := p.String(1); v {
case "L", "D", "T", "R":
runes[p.Rune(0)] |= joinType[v] << joinShift
}
})
ucd.Parse(gen.OpenUnicodeFile("idna", "", "IdnaMappingTable.txt"), func(p *ucd.Parser) {
r := p.Rune(0)
// The mappings table explicitly defines surrogates as invalid.
if !utf8.ValidRune(r) {
return
}
cat := catFromEntry(p)
isMapped := cat == mapped || cat == disallowedSTD3Mapped || cat == deviation
if !isMapped {
// Only include additional category information for non-mapped
// runes. The additional information is only used after mapping and
// the bits would clash with mapping information.
// TODO: it would be possible to inline this data and avoid
// additional lookups. This is quite tedious, though, so let's first
// see if we need this.
cat |= category(runes[r])
}
s := string(p.Runes(2))
if s != "" && !isMapped {
log.Fatalf("%U: Mapping with non-mapping category %d", r, cat)
}
t.Insert(r, uint64(makeEntry(r, s))+uint64(cat))
})
w := gen.NewCodeWriter()
defer w.WriteVersionedGoFile("tables.go", "idna")
gen.WriteUnicodeVersion(w)
w.WriteVar("mappings", string(mappings))
w.WriteVar("xorData", string(xorData))
sz, err := t.Gen(w, triegen.Compact(&normCompacter{}))
if err != nil {
log.Fatal(err)
}
w.Size += sz
}
var (
// mappings contains replacement strings for mapped runes, each prefixed
// with a byte containing the length of the following string.
mappings = []byte{}
mapCache = map[string]int{}
// xorData is like mappings, except that it contains XOR data.
// We split these two tables so that we don't get an overflow.
xorData = []byte{}
xorCache = map[string]int{}
)
// makeEntry creates a trie entry.
func makeEntry(r rune, mapped string) info {
orig := string(r)
if len(orig) != len(mapped) {
// Store the mapped value as is in the mappings table.
index := len(mappings)
if x, ok := mapCache[mapped]; ok {
index = x
} else {
mapCache[mapped] = index
mappings = append(mappings, byte(len(mapped)))
mappings = append(mappings, mapped...)
}
return info(index) << indexShift
}
// Create per-byte XOR mask.
var b []byte
for i := 0; i < len(orig); i++ {
b = append(b, orig[i]^mapped[i])
}
// Remove leading 0 bytes, but keep at least one byte.
for ; len(b) > 1 && b[0] == 0; b = b[1:] {
}
if len(b) == 1 {
return xorBit | inlineXOR | info(b[0])<<indexShift
}
mapped = string(b)
// Store the mapped value as is in the mappings table.
index := len(xorData)
if x, ok := xorCache[mapped]; ok {
index = x
} else {
xorCache[mapped] = index
xorData = append(xorData, byte(len(mapped)))
xorData = append(xorData, mapped...)
}
return xorBit | info(index)<<indexShift
}
// The following code implements a triegen.Compacter that was originally
// designed for normalization. The IDNA table has some similarities with the
// norm table. Using this compacter, together with the XOR pattern approach,
// reduces the table size by roughly 100K. It can probably be compressed further
// by also including elements of the compacter used by cases, but for now it is
// good enough.
const maxSparseEntries = 16
type normCompacter struct {
sparseBlocks [][]uint64
sparseOffset []uint16
sparseCount int
}
func mostFrequentStride(a []uint64) int {
counts := make(map[int]int)
var v int
for _, x := range a {
if stride := int(x) - v; v != 0 && stride >= 0 {
counts[stride]++
}
v = int(x)
}
var maxs, maxc int
for stride, cnt := range counts {
if cnt > maxc || (cnt == maxc && stride < maxs) {
maxs, maxc = stride, cnt
}
}
return maxs
}
func countSparseEntries(a []uint64) int {
stride := mostFrequentStride(a)
var v, count int
for _, tv := range a {
if int(tv)-v != stride {
if tv != 0 {
count++
}
}
v = int(tv)
}
return count
}
func (c *normCompacter) Size(v []uint64) (sz int, ok bool) {
if n := countSparseEntries(v); n <= maxSparseEntries {
return (n+1)*4 + 2, true
}
return 0, false
}
func (c *normCompacter) Store(v []uint64) uint32 {
h := uint32(len(c.sparseOffset))
c.sparseBlocks = append(c.sparseBlocks, v)
c.sparseOffset = append(c.sparseOffset, uint16(c.sparseCount))
c.sparseCount += countSparseEntries(v) + 1
return h
}
func (c *normCompacter) Handler() string {
return "idnaSparse.lookup"
}
func (c *normCompacter) Print(w io.Writer) (retErr error) {
p := func(f string, x ...interface{}) {
if _, err := fmt.Fprintf(w, f, x...); retErr == nil && err != nil {
retErr = err
}
}
ls := len(c.sparseBlocks)
p("// idnaSparseOffset: %d entries, %d bytes\n", ls, ls*2)
p("var idnaSparseOffset = %#v\n\n", c.sparseOffset)
ns := c.sparseCount
p("// idnaSparseValues: %d entries, %d bytes\n", ns, ns*4)
p("var idnaSparseValues = [%d]valueRange {", ns)
for i, b := range c.sparseBlocks {
p("\n// Block %#x, offset %#x", i, c.sparseOffset[i])
var v int
stride := mostFrequentStride(b)
n := countSparseEntries(b)
p("\n{value:%#04x,lo:%#02x},", stride, uint8(n))
for i, nv := range b {
if int(nv)-v != stride {
if v != 0 {
p(",hi:%#02x},", 0x80+i-1)
}
if nv != 0 {
p("\n{value:%#04x,lo:%#02x", nv, 0x80+i)
}
}
v = int(nv)
}
if v != 0 {
p(",hi:%#02x},", 0x80+len(b)-1)
}
}
p("\n}\n\n")
return
}
| genTables |
intcode.rs | use std::convert::TryInto;
use std::io::{self, Read};
use std::collections::HashMap;
pub fn int_input(in_str: &str) -> Vec<i64> {
//println!("in: {}", &in_str.trim());
let results = in_str
.trim()
.split(',')
.filter_map(|x| if x.trim() != "" { x.trim().parse::<i64>().ok() } else { None })
.collect();
//println!("got input");
results
}
pub fn intcode(code: Vec<i64>, pc: usize) -> (Vec<i64>, Vec<i64>) {
let inputs = Vec::<i64>::new();
intcodes(code, pc, inputs)
}
pub fn intcodes(code: Vec<i64>, pc: usize, inputs: Vec<i64>) -> (Vec<i64>, Vec<i64>) {
intcodesw(code, pc, inputs, &mut io::stdout())
}
pub fn intcodesq(
code: Vec<i64>,
pc: usize,
inputs: Vec<i64>)
-> (Vec<i64>, Vec<i64>)
{
intcodesw(code, pc, inputs, &mut io::sink())
}
pub fn intcodesw(
code: Vec<i64>,
pc: usize,
inputs: Vec<i64>,
stdout: &mut io::Write)
-> (Vec<i64>, Vec<i64>)
{
let mut reversed_inputs = inputs.clone();
reversed_inputs.reverse();
let mut signals = Vec::<i64>::new();
let mut base = 0;
let memory: HashMap<i64, i64> = HashMap::new();
intcodes_internal(code, pc, &mut reversed_inputs, false, stdout,
&mut base, &mut signals, memory)
}
pub fn intcodesf(
code: Vec<i64>,
pc: usize,
inputs: Vec<i64>,
mut signals: &mut Vec<i64>)
-> (Vec<i64>, Vec<i64>)
{
let mut reversed_inputs = inputs.clone();
reversed_inputs.reverse();
let mut base = 0;
let memory: HashMap<i64, i64> = HashMap::new();
intcodes_internal(code, pc, &mut reversed_inputs, true, &mut io::sink(),
&mut base, &mut signals, memory)
//intcodes_internal(code, pc, &mut reversed_inputs, true, &mut io::stdout(), &mut signals)
}
fn update_dest(input: i64, dest: i64, mut code: Vec<i64>, mut memory: HashMap<i64, i64>) -> (Vec<i64>, HashMap<i64, i64>) {
if dest < (code.len() as i64) {
//println!("update: address: {} code.len:{} memory.len:{} = {} in code", dest, code.len(), memory.len(), input);
code[dest as usize] = input;
} else {
//println!("update: address: {} code.len:{} memory.len:{} = {} in memory", dest, code.len(), memory.len(), input);
memory.insert(dest, input);
}
(code, memory)
}
fn lookup_memory(pc: i64, code: &Vec<i64>, memory: &HashMap<i64, i64>) -> i64 {
if (pc as usize) < code.len() {
//println!("lookup: address: {} code.len:{} memory.len:{} in code", pc, code.len(), memory.len());
return *code.get(pc as usize).unwrap() as i64;
} else {
//println!("lookup: address: {} code.len:{} memory.len:{} in memory", pc, code.len(), memory.len());
let mut new_val: i64 = 0;
if memory.get(&pc).is_some() {
new_val = *memory.get(&pc).unwrap() as i64;
}
return new_val;
}
}
fn intcodes_internal(
code: Vec<i64>,
pc: usize,
inputs: &mut Vec<i64>,
feedback: bool,
stdout: &mut io::Write,
mut rel_base: &mut i64,
mut signals: &mut Vec<i64>,
memory: HashMap<i64, i64>)
-> (Vec<i64>, Vec<i64>)
{
// Intcode
// in set, place 0: opcode
// opcode 99: halt command processing
// opcode 1 (add): vec[set[3]] = vec[set[1]] + vec[set[2]]
// opcode 2 (mul): vec[set[3]] = vec[set[1]] * vec[set[2]]
let outputs = code.clone();
//let code_outputs = Vec::<i64>::new();
let op:i64 = code[pc];
//println!("DEBUG:Intcode:: op:{}", op);
if op == 99 {
writeln!(stdout, "Intcode:: EXIT (SUCCESS)").ok();
return (outputs, signals.to_vec());
}
if op < 1 || op > 22298 {
writeln!(stdout, "Intcode:: Received EXIT (FAILURE)").ok();
println!("EXIT badop: op: {} lengths:: code:{} memory:{} signals:{}", op, code.len(), memory.len(), signals.len());
signals.push(i64::min_value());
return (outputs, signals.to_vec());
}
let parameterized = |x: i64, op: i64| {
// 0 = position, 1 = immediate, 2 = relative base
op == x
|| op == (x + 100) /* a is immediate, b is position */
|| op == (x + 200) /* a is relative, b is position */
|| op == (x + 1000) /* a is position, b is immediate */
|| op == (x + 2000) /* a is position, b is relative */
|| op == (x + 1100) /* a is immediate, b is immediate */
|| op == (x + 1200) /* a is relative, b is immediate */
|| op == (x + 2100) /* a is immediate, b is relative */
|| op == (x + 2200) /* a is relative, b is relative */
|| op == (x + 20000) /* dest is relative */
|| op == (x + 20100) /* dest is relative, a immediate */
|| op == (x + 21100) /* dest is relative, a immediate, b immediate */
|| op == (x + 21200) /* dest is relative, a relative, b immediate */
|| op == (x + 22100) /* dest is relative, a immediate, b relative */
|| op == (x + 22200) /* dest is relative, a relative, b relative */
};
let modes = |x: i64| -> (u8, u8, u8) {
// 0 = position, 1 = immediate, 2 = relative base
// 100s -> update a
// 1000s -> update b
let mut a: u8 = 0;
let mut b: u8 = 0;
let mut d: u8 = 0;
if x < 100 /* position for all */ {
return (a, b, d);
}
a = ((x / 100) % 10).try_into().unwrap();
if x >= 1000 |
if x >= 10000 {
d = ((x / 10000) % 10).try_into().unwrap();
}
(a, b, d)
};
let mode = modes(op);
let op_add: bool = parameterized(1, op);
let op_mul: bool = parameterized(2, op);
let op_input: bool = op == 3 || op == 203;
let op_output: bool = op == 4 || op == 104 || op == 204;
let op_jump_true: bool = parameterized(5, op); // no dest
let op_jump_false: bool = parameterized(6, op); // no dest
let op_less_than: bool = parameterized(7, op);
let op_equals: bool = parameterized(8, op);
let op_rel: bool = op == 9 || op == 109 || op == 209;
// get the a parameter, handling mode
let mut a: i64 = code[pc + 1];
let mut dest: i64 = a;
if mode.0 == 0 {
//a = *code.get(a as usize).unwrap() as i64;
a = lookup_memory(a, &code, &memory);
} else if mode.0 == 2 {
//a = *code.get((a + *rel_base) as usize).unwrap() as i64;
dest = a + *rel_base;
a = lookup_memory(dest, &code, &memory);
}
//println!("DEBUG:: Looked up: a [{}] = {}", code[pc + 1], a);
if op_input {
//println!("DEBUG:: input <{}:{} ({})> +{} mode({}, {}, {})", op, dest, code[pc + 1], rel_base, mode.0, mode.1, mode.2);
// input
let input: i64;
if inputs.len() > 0 {
input = inputs.pop().unwrap();
writeln!(stdout, "Intcode:: Input: {}", input).ok();
}
else if feedback && signals.len() > 0 {
input = signals.remove(0);
writeln!(stdout, "Intcode:: Input: {}", input).ok();
}
else {
writeln!(stdout, "Intcode:: Input: ").ok();
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).ok();
input = buffer.trim().parse().unwrap();
}
let (outputs, memory) = update_dest(input, dest, outputs, memory);
return intcodes_internal(outputs, pc + 2, inputs, feedback, stdout, &mut rel_base, &mut signals, memory)
}
else if op_output {
//println!("DEBUG:: output <{}:{}> +{} mode({}, {}, {})", op, a, rel_base, mode.0, mode.1, mode.2);
// output
writeln!(stdout, "Intcode:: Print: {}", a).ok();
signals.push(a);
let (outputs, _) = intcodes_internal(outputs, pc + 2, inputs, feedback, stdout, &mut rel_base, &mut signals, memory);
return (outputs, signals.to_vec());
}
else if op_rel {
//println!("DEBUG:: +rel <{}:{} ({})> +{} mode({}, {}, {})", op, a, code[pc + 1], rel_base, mode.0, mode.1, mode.2);
*rel_base += a;
return intcodes_internal(outputs, pc + 2, inputs, feedback, stdout, &mut rel_base, &mut signals, memory);
}
// get the b parameter, handling mode
let mut b: i64 = code[pc + 2];
if mode.1 == 0 {
//b = *code.get(b as usize).unwrap() as i64;
b = lookup_memory(b, &code, &memory);
} else if mode.1 == 2 {
//b = *code.get((b + *rel_base) as usize).unwrap() as i64;
b = lookup_memory(b + *rel_base, &code, &memory);
}
//println!("DEBUG:: Looked up: b [{}] = {}", code[pc + 2], b);
if op_jump_true || op_jump_false {
//println!("DEBUG:: jump <{}:{},{}> +{} mode({}, {}, {})", op, a, b, rel_base, mode.0, mode.1, mode.2);
// jump-if-true | jump-if-false
// 0n->paramAB, 10n->paramB, 100n->paramA, 110n->immediate
let mut new_pc: usize = pc + 3;
if (a != 0 && op_jump_true) || (a == 0 && op_jump_false) {
new_pc = b as usize;
}
return intcodes_internal(outputs, new_pc, inputs, feedback, stdout, &mut rel_base, &mut signals, memory);
}
// Get the third operation
let mut dest: i64 = code[pc + 3];
if mode.2 == 2 {
//dest = lookup_memory(dest + *rel_base, &code, &memory);
dest = dest + *rel_base;
}
//println!("DEBUG:: Looked up: dest [{}] = {}", code[pc + 3], dest);
//println!("DEBUG:: a[{}]={} b[{}]={} dest[{}]={}", code[pc + 1], a, code[pc + 2], b, code[pc + 3], dest);
if op_less_than || op_equals {
//println!("DEBUG:: <|=cmp <{}:{} [{}],{} [{}],{} [{}]> +{} mode({}, {}, {})", op, a, code[pc + 1], b, code[pc + 2], dest, code[pc + 3], rel_base, mode.0, mode.1, mode.2);
let mut result = 0;
if (op_less_than && a < b) || (op_equals && a == b) {
result = 1;
}
let (outputs, memory) = update_dest(result, dest, outputs, memory);
return intcodes_internal(outputs, pc + 4, inputs, feedback, stdout, &mut rel_base, &mut signals, memory);
}
else if op_add || op_mul {
//println!("DEBUG:: add|mul<{}:{},{},{}> +{} mode({}, {}, {})", op, a, b, dest, rel_base, mode.0, mode.1, mode.2);
// add and multiply
let mut result = a + b;
if op_mul {
result = a * b;
}
let (outputs, memory) = update_dest(result, dest, outputs, memory);
return intcodes_internal(outputs, pc + 4, inputs, feedback, stdout, &mut rel_base, &mut signals, memory);
}
writeln!(stdout, "Intcode:: Received EXIT (FAILURE)").ok();
println!("EXIT fallout: op: {} lengths:: code:{} memory:{} signals:{}", op, code.len(), memory.len(), signals.len());
signals.push(i64::min_value());
(outputs, signals.to_vec())
}
| {
b = ((x / 1000) % 10).try_into().unwrap();
} |
api_op_CreateContact.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package ssmcontacts
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/ssmcontacts/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Contacts are either the contacts that Incident Manager engages during an
// incident or the escalation plans that Incident Manager uses to engage contacts
// in phases during an incident.
func (c *Client) CreateContact(ctx context.Context, params *CreateContactInput, optFns ...func(*Options)) (*CreateContactOutput, error) {
if params == nil {
params = &CreateContactInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateContact", params, optFns, c.addOperationCreateContactMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateContactOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateContactInput struct {
// The short name to quickly identify a contact or escalation plan. The contact
// alias must be unique and identifiable.
//
// This member is required.
Alias *string
// A list of stages. A contact has an engagement plan with stages that contact
// specified contact channels. An escalation plan uses stages that contact
// specified contacts.
//
// This member is required.
Plan *types.Plan
// To create an escalation plan use ESCALATION. To create a contact use PERSONAL.
//
// This member is required.
Type types.ContactType
// The full name of the contact or escalation plan.
DisplayName *string
// A token ensuring that the action is called only once with the specified details.
IdempotencyToken *string
// Adds a tag to the target. You can only tag resources created in the first Region
// of your replication set.
Tags []types.Tag
}
type CreateContactOutput struct {
// The Amazon Resource Name (ARN) of the created contact or escalation plan.
//
// This member is required.
ContactArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func (c *Client) addOperationCreateContactMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateContact{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateContact{}, middleware.After)
if err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addIdempotencyToken_opCreateContactMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateContactValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateContact(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateContact struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateContact) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateContact) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateContactInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateContactInput ")
}
if input.IdempotencyToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.IdempotencyToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateContactMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateContact{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func | (region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "ssm-contacts",
OperationName: "CreateContact",
}
}
| newServiceMetadataMiddleware_opCreateContact |
messageProtocol.ts | export interface MessageProtocol {
sendMessage(msg: string): void; | } |
|
conf.go | package conf
import (
"os"
"GoToolbox/cache"
"GoToolbox/model"
"GoToolbox/util"
"github.com/joho/godotenv"
)
// Init 初始化配置项
func Init() {
// | 读取环境变量
godotenv.Load()
// 设置日志级别
util.BuildLogger(os.Getenv("LOG_LEVEL"))
// 读取翻译文件
if err := LoadLocales("conf/locales/zh-cn.yaml"); err != nil {
util.Log().Panic("翻译文件加载失败 %v\n", err)
}
// 连接数据库
model.Database(os.Getenv("MYSQL_DSN"))
cache.Redis()
}
| 从本地 |
tiflash_test.go | // Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package executor_test
import (
"bytes"
"fmt"
"math"
"math/rand"
"strings"
"sync"
"sync/atomic"
"time"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/parser"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/kv"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/store/mockstore/unistore"
"github.com/pingcap/tidb/util/israce"
"github.com/pingcap/tidb/util/kvcache"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testleak"
"github.com/tikv/client-go/v2/testutils"
)
type tiflashTestSuite struct {
store kv.Storage
dom *domain.Domain
*parser.Parser
}
func (s *tiflashTestSuite) SetUpSuite(c *C) {
var err error
s.store, err = mockstore.NewMockStore(
mockstore.WithClusterInspector(func(c testutils.Cluster) {
mockCluster := c.(*unistore.Cluster)
_, _, region1 := mockstore.BootstrapWithSingleStore(c)
tiflashIdx := 0
for tiflashIdx < 2 {
store2 := c.AllocID()
peer2 := c.AllocID()
addr2 := fmt.Sprintf("tiflash%d", tiflashIdx)
mockCluster.AddStore(store2, addr2, &metapb.StoreLabel{Key: "engine", Value: "tiflash"})
mockCluster.AddPeer(region1, store2, peer2)
tiflashIdx++
}
}),
mockstore.WithStoreType(mockstore.EmbedUnistore),
)
c.Assert(err, IsNil)
session.SetSchemaLease(0)
session.DisableStats4Test()
s.dom, err = session.BootstrapSession(s.store)
c.Assert(err, IsNil)
s.dom.SetStatsUpdating(true)
}
func (s *tiflashTestSuite) TearDownSuite(c *C) {
s.dom.Close()
c.Assert(s.store.Close(), IsNil)
}
func (s *tiflashTestSuite) TestReadPartitionTable(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b int not null) partition by hash(a) partitions 2")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
tk.MustQuery("select /*+ STREAM_AGG() */ count(*) from t").Check(testkit.Rows("3"))
tk.MustQuery("select * from t order by a").Check(testkit.Rows("1 0", "2 0", "3 0"))
// test union scan
tk.MustExec("begin")
tk.MustExec("insert into t values(4,0)")
tk.MustQuery("select /*+ STREAM_AGG() */ count(*) from t").Check(testkit.Rows("4"))
tk.MustExec("insert into t values(5,0)")
tk.MustQuery("select /*+ STREAM_AGG() */ count(*) from t").Check(testkit.Rows("5"))
tk.MustExec("insert into t values(6,0)")
tk.MustQuery("select /*+ STREAM_AGG() */ count(*) from t").Check(testkit.Rows("6"))
tk.MustExec("commit")
}
func (s *tiflashTestSuite) TestReadUnsigedPK(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t(a bigint unsigned not null primary key, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("insert into t values(18446744073709551606,0)")
tk.MustExec("insert into t values(9223372036854775798,0)")
tk.MustExec("create table t1(a bigint unsigned not null primary key, b int not null)")
tk.MustExec("alter table t1 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t1")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t1 values(1,0)")
tk.MustExec("insert into t1 values(2,0)")
tk.MustExec("insert into t1 values(3,0)")
tk.MustExec("insert into t1 values(18446744073709551606,0)")
tk.MustExec("insert into t1 values(9223372036854775798,0)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
tk.MustExec("set @@session.tidb_opt_broadcast_join=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a").Check(testkit.Rows("5"))
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a and ((t1.a < 9223372036854775800 and t1.a > 2) or (t1.a <= 1 and t1.a > -1))").Check(testkit.Rows("3"))
}
// to fix https://github.com/pingcap/tidb/issues/27952
func (s *tiflashTestSuite) TestJoinRace(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,1)")
tk.MustExec("insert into t values(2,1)")
tk.MustExec("insert into t values(3,1)")
tk.MustExec("insert into t values(1,2)")
tk.MustExec("insert into t values(2,2)")
tk.MustExec("insert into t values(3,2)")
tk.MustExec("insert into t values(1,2)")
tk.MustExec("insert into t values(2,2)")
tk.MustExec("insert into t values(3,2)")
tk.MustExec("insert into t values(1,3)")
tk.MustExec("insert into t values(2,3)")
tk.MustExec("insert into t values(3,4)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_enforce_mpp=ON")
tk.MustExec("set @@tidb_opt_broadcast_cartesian_join=0")
tk.MustQuery("select count(*) from (select count(a) x from t group by b) t1 join (select count(a) x from t group by b) t2 on t1.x > t2.x").Check(testkit.Rows("6"))
}
func (s *tiflashTestSuite) TestMppExecution(c *C) {
if israce.RaceEnabled {
c.Skip("skip race test because of long running")
}
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("create table t1(a int primary key, b int not null)")
tk.MustExec("alter table t1 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t1")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t1 values(1,0)")
tk.MustExec("insert into t1 values(2,0)")
tk.MustExec("insert into t1 values(3,0)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
for i := 0; i < 20; i++ {
// test if it is stable.
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a").Check(testkit.Rows("3"))
}
// test multi-way join
tk.MustExec("create table t2(a int primary key, b int not null)")
tk.MustExec("alter table t2 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t2")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t2 values(1,0)")
tk.MustExec("insert into t2 values(2,0)")
tk.MustExec("insert into t2 values(3,0)")
tk.MustQuery("select count(*) from t1 , t, t2 where t1.a = t.a and t2.a = t.a").Check(testkit.Rows("3"))
// test avg
tk.MustQuery("select avg(t1.a) from t1 , t where t1.a = t.a").Check(testkit.Rows("2.0000"))
// test proj and selection
tk.MustQuery("select count(*) from (select a * 2 as a from t1) t1 , (select b + 4 as a from t)t where t1.a = t.a").Check(testkit.Rows("3"))
// test shuffle hash join.
tk.MustExec("set @@session.tidb_broadcast_join_threshold_size=1")
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a").Check(testkit.Rows("3"))
tk.MustQuery("select count(*) from t1 , t, t2 where t1.a = t.a and t2.a = t.a").Check(testkit.Rows("3"))
// test agg by expression
tk.MustExec("insert into t1 values(4,0)")
tk.MustQuery("select count(*) k, t2.b from t1 left join t2 on t1.a = t2.a group by t2.b order by k").Check(testkit.Rows("1 <nil>", "3 0"))
tk.MustQuery("select count(*) k, t2.b+1 from t1 left join t2 on t1.a = t2.a group by t2.b+1 order by k").Check(testkit.Rows("1 <nil>", "3 1"))
tk.MustQuery("select count(*) k, t2.b * t2.a from t2 group by t2.b * t2.a").Check(testkit.Rows("3 0"))
tk.MustQuery("select count(*) k, t2.a/2 m from t2 group by t2.a / 2 order by m").Check(testkit.Rows("1 0.5000", "1 1.0000", "1 1.5000"))
tk.MustQuery("select count(*) k, t2.a div 2 from t2 group by t2.a div 2 order by k").Check(testkit.Rows("1 0", "2 1"))
// test task id for same start ts.
tk.MustExec("begin")
tk.MustQuery("select count(*) from ( select * from t2 group by a, b) A group by A.b").Check(testkit.Rows("3"))
tk.MustQuery("select count(*) from t1 where t1.a+100 > ( select count(*) from t2 where t1.a=t2.a and t1.b=t2.b) group by t1.b").Check(testkit.Rows("4"))
txn, err := tk.Se.Txn(true)
c.Assert(err, IsNil)
ts := txn.StartTS()
taskID := tk.Se.GetSessionVars().AllocMPPTaskID(ts)
c.Assert(taskID, Equals, int64(6))
tk.MustExec("commit")
taskID = tk.Se.GetSessionVars().AllocMPPTaskID(ts + 1)
c.Assert(taskID, Equals, int64(1))
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(3)`)
// all the data is related to one store, so there are three tasks.
tk.MustQuery("select avg(t.a) from t join t t1 on t.a = t1.a").Check(testkit.Rows("2.0000"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t (c1 decimal(8, 5) not null, c2 decimal(9, 5), c3 decimal(9, 4) , c4 decimal(8, 4) not null)")
tk.MustExec("alter table t set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1.00000,1.00000,1.0000,1.0000)")
tk.MustExec("insert into t values(1.00010,1.00010,1.0001,1.0001)")
tk.MustExec("insert into t values(1.00001,1.00001,1.0000,1.0002)")
tk.MustQuery("select t1.c1 from t t1 join t t2 on t1.c1 = t2.c1 order by t1.c1").Check(testkit.Rows("1.00000", "1.00001", "1.00010"))
tk.MustQuery("select t1.c1 from t t1 join t t2 on t1.c1 = t2.c3 order by t1.c1").Check(testkit.Rows("1.00000", "1.00000", "1.00010"))
tk.MustQuery("select t1.c4 from t t1 join t t2 on t1.c4 = t2.c3 order by t1.c4").Check(testkit.Rows("1.0000", "1.0000", "1.0001"))
// let this query choose hash join
tk.MustQuery("select /*+ nth_plan(2) */ t1.c1 from t t1 join t t2 on t1.c1 = t2.c3 order by t1.c1").Check(testkit.Rows("1.00000", "1.00000", "1.00010"))
}
func (s *tiflashTestSuite) TestInjectExtraProj(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a bigint(20))")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustQuery("select avg(a) from t").Check(testkit.Rows("9223372036854775807.0000"))
tk.MustQuery("select avg(a), a from t group by a").Check(testkit.Rows("9223372036854775807.0000 9223372036854775807"))
}
func (s *tiflashTestSuite) TestTiFlashPartitionTableShuffledHashJoin(c *C) {
c.Skip("too slow")
tk := testkit.NewTestKit(c, s.store)
tk.MustExec(`create database tiflash_partition_SHJ`)
tk.MustExec("use tiflash_partition_SHJ")
tk.MustExec(`create table thash (a int, b int) partition by hash(a) partitions 4`)
tk.MustExec(`create table trange (a int, b int) partition by range(a) (
partition p0 values less than (100), partition p1 values less than (200),
partition p2 values less than (300), partition p3 values less than (400))`)
listPartitions := make([]string, 4)
for i := 0; i < 400; i++ {
idx := i % 4
if listPartitions[idx] != "" {
listPartitions[idx] += ", "
}
listPartitions[idx] = listPartitions[idx] + fmt.Sprintf("%v", i)
}
tk.MustExec(`create table tlist (a int, b int) partition by list(a) (
partition p0 values in (` + listPartitions[0] + `), partition p1 values in (` + listPartitions[1] + `),
partition p2 values in (` + listPartitions[2] + `), partition p3 values in (` + listPartitions[3] + `))`)
tk.MustExec(`create table tnormal (a int, b int)`)
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec("alter table " + tbl + " set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "tiflash_partition_SHJ", tbl)
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
}
vals := make([]string, 0, 100)
for i := 0; i < 100; i++ {
vals = append(vals, fmt.Sprintf("(%v, %v)", rand.Intn(400), rand.Intn(400)))
}
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec(fmt.Sprintf("insert into %v values %v", tbl, strings.Join(vals, ", ")))
tk.MustExec(fmt.Sprintf("analyze table %v", tbl))
}
tk.MustExec("SET tidb_enforce_mpp=1")
tk.MustExec("SET tidb_opt_broadcast_join=0")
tk.MustExec("SET tidb_broadcast_join_threshold_count=0")
tk.MustExec("SET tidb_broadcast_join_threshold_size=0")
tk.MustExec("set @@session.tidb_isolation_read_engines='tiflash'")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
lr := func() (int, int) {
l, r := rand.Intn(400), rand.Intn(400)
if l > r {
l, r = r, l
}
return l, r
}
for i := 0; i < 2; i++ {
l1, r1 := lr()
l2, r2 := lr()
cond := fmt.Sprintf("t1.b>=%v and t1.b<=%v and t2.b>=%v and t2.b<=%v", l1, r1, l2, r2)
var res [][]interface{}
for _, mode := range []string{"static", "dynamic"} {
tk.MustExec(fmt.Sprintf("set @@tidb_partition_prune_mode = '%v'", mode))
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
q := fmt.Sprintf("select count(*) from %v t1 join %v t2 on t1.a=t2.a where %v", tbl, tbl, cond)
if res == nil {
res = tk.MustQuery(q).Sort().Rows()
} else {
tk.MustQuery(q).Check(res)
}
}
}
}
}
func (s *tiflashTestSuite) TestTiFlashPartitionTableReader(c *C) {
c.Skip("too slow")
tk := testkit.NewTestKit(c, s.store)
tk.MustExec(`create database tiflash_partition_tablereader`)
tk.MustExec("use tiflash_partition_tablereader")
tk.MustExec(`create table thash (a int, b int) partition by hash(a) partitions 4`)
tk.MustExec(`create table trange (a int, b int) partition by range(a) (
partition p0 values less than (100), partition p1 values less than (200),
partition p2 values less than (300), partition p3 values less than (400))`)
listPartitions := make([]string, 4)
for i := 0; i < 400; i++ {
idx := i % 4
if listPartitions[idx] != "" {
listPartitions[idx] += ", "
}
listPartitions[idx] = listPartitions[idx] + fmt.Sprintf("%v", i)
}
tk.MustExec(`create table tlist (a int, b int) partition by list(a) (
partition p0 values in (` + listPartitions[0] + `), partition p1 values in (` + listPartitions[1] + `),
partition p2 values in (` + listPartitions[2] + `), partition p3 values in (` + listPartitions[3] + `))`)
tk.MustExec(`create table tnormal (a int, b int)`)
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec("alter table " + tbl + " set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "tiflash_partition_tablereader", tbl)
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
}
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
vals := make([]string, 0, 500)
for i := 0; i < 500; i++ {
vals = append(vals, fmt.Sprintf("(%v, %v)", rand.Intn(400), rand.Intn(400)))
}
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec(fmt.Sprintf("insert into %v values %v", tbl, strings.Join(vals, ", ")))
}
tk.MustExec("SET tidb_enforce_mpp=1")
tk.MustExec("set @@session.tidb_isolation_read_engines='tiflash'")
for i := 0; i < 10; i++ {
l, r := rand.Intn(400), rand.Intn(400)
if l > r {
l, r = r, l
}
cond := fmt.Sprintf("a>=%v and a<=%v", l, r)
var res [][]interface{}
for _, mode := range []string{"static", "dynamic"} {
tk.MustExec(fmt.Sprintf("set @@tidb_partition_prune_mode = '%v'", mode))
for _, tbl := range []string{"thash", "trange", "tlist", "tnormal"} {
q := fmt.Sprintf("select * from %v where %v", tbl, cond)
if res == nil {
res = tk.MustQuery(q).Sort().Rows()
} else {
tk.MustQuery(q).Sort().Check(res)
}
}
}
}
}
func (s *tiflashTestSuite) TestPartitionTable(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t(a int not null primary key, b int not null) partition by hash(a+1) partitions 4")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("insert into t values(4,0)")
failpoint.Enable("github.com/pingcap/tidb/executor/checkUseMPP", `return(true)`)
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(4)`)
tk.MustQuery("select count(*) from t").Check(testkit.Rows("4"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
tk.MustExec("set @@session.tidb_partition_prune_mode='static-only'")
failpoint.Enable("github.com/pingcap/tidb/executor/checkUseMPP", `return(false)`)
tk.MustQuery("select count(*) from t").Check(testkit.Rows("4"))
tk.MustExec("set @@session.tidb_partition_prune_mode='dynamic-only'")
failpoint.Enable("github.com/pingcap/tidb/executor/checkUseMPP", `return(true)`)
tk.MustExec("create table t1(a int not null primary key, b int not null) partition by hash(a) partitions 4")
tk.MustExec("alter table t1 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t1")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t1 values(1,4)")
tk.MustExec("insert into t1 values(2,3)")
tk.MustExec("insert into t1 values(3,2)")
tk.MustExec("insert into t1 values(4,1)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
tk.MustExec("set @@session.tidb_opt_broadcast_join=ON")
// test if it is really work.
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(8)`)
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a").Check(testkit.Rows("4"))
// test partition prune
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a and t1.a < 2 and t.a < 2").Check(testkit.Rows("1"))
tk.MustQuery("select count(*) from t1 , t where t1.a = t.a and t1.a < -1 and t.a < 2").Check(testkit.Rows("0"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
// test multi-way join
tk.MustExec("create table t2(a int not null primary key, b int not null)")
tk.MustExec("alter table t2 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t2")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t2 values(1,0)")
tk.MustExec("insert into t2 values(2,0)")
tk.MustExec("insert into t2 values(3,0)")
tk.MustExec("insert into t2 values(4,0)")
// test with no partition table
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(9)`)
tk.MustQuery("select count(*) from t1 , t, t2 where t1.a = t.a and t2.a = t.a").Check(testkit.Rows("4"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
tk.MustExec(`create table t3(a int not null, b int not null) PARTITION BY RANGE (b) (
PARTITION p0 VALUES LESS THAN (1),
PARTITION p1 VALUES LESS THAN (3),
PARTITION p2 VALUES LESS THAN (5),
PARTITION p3 VALUES LESS THAN (7)
);`)
tk.MustExec("alter table t3 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t3")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t3 values(1,0)")
tk.MustExec("insert into t3 values(2,2)")
tk.MustExec("insert into t3 values(3,4)")
tk.MustExec("insert into t3 values(4,6)")
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(7)`)
tk.MustQuery("select count(*) from t, t3 where t3.a = t.a and t3.b <= 4").Check(testkit.Rows("3"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(5)`)
tk.MustQuery("select count(*) from t, t3 where t3.a = t.a and t3.b > 10").Check(testkit.Rows("0"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
failpoint.Disable("github.com/pingcap/tidb/executor/checkUseMPP")
}
func (s *tiflashTestSuite) TestMppEnum(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b enum('aca','bca','zca'))")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,'aca')")
tk.MustExec("insert into t values(2,'bca')")
tk.MustExec("insert into t values(3,'zca')")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
tk.MustQuery("select t1.b from t t1 join t t2 on t1.a = t2.a order by t1.b").Check(testkit.Rows("aca", "bca", "zca"))
}
func (s *tiflashTestSuite) TestTiFlashPlanCacheable(c *C) {
tk := testkit.NewTestKit(c, s.store)
orgEnable := plannercore.PreparedPlanCacheEnabled()
defer func() {
plannercore.SetPreparedPlanCache(orgEnable)
}()
plannercore.SetPreparedPlanCache(true)
var err error
tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{
PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64),
})
c.Assert(err, IsNil)
tk.MustExec("use test;")
tk.MustExec("drop table if exists t;")
tk.MustExec("create table t(a int);")
tk.MustExec("set @@tidb_enable_collect_execution_info=0;")
tk.MustExec("alter table test.t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("set @@session.tidb_isolation_read_engines = 'tikv, tiflash'")
tk.MustExec("insert into t values(1);")
tk.MustExec("prepare stmt from 'select /*+ read_from_storage(tiflash[t]) */ * from t;';")
tk.MustQuery("execute stmt;").Check(testkit.Rows("1"))
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustQuery("execute stmt;").Check(testkit.Rows("1"))
// The TiFlash plan can not be cached.
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("prepare stmt from 'select /*+ read_from_storage(tikv[t]) */ * from t;';")
tk.MustQuery("execute stmt;").Check(testkit.Rows("1"))
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustQuery("execute stmt;").Check(testkit.Rows("1"))
// The TiKV plan can be cached.
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
// test the mpp plan
tk.MustExec("set @@session.tidb_allow_mpp = 1;")
tk.MustExec("set @@session.tidb_enforce_mpp = 1;")
tk.MustExec("prepare stmt from 'select count(t1.a) from t t1 join t t2 on t1.a = t2.a where t1.a > ?;';")
tk.MustExec("set @a = 0;")
tk.MustQuery("execute stmt using @a;").Check(testkit.Rows("1"))
tk.MustExec("set @a = 1;")
tk.MustQuery("execute stmt using @a;").Check(testkit.Rows("0"))
// The TiFlash plan can not be cached.
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
}
func (s *tiflashTestSuite) TestDispatchTaskRetry(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("insert into t values(4,0)")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("set @@session.tidb_enforce_mpp=ON")
c.Assert(failpoint.Enable("github.com/pingcap/tidb/store/mockstore/unistore/mppDispatchTimeout", "3*return(true)"), IsNil)
tk.MustQuery("select count(*) from t").Check(testkit.Rows("4"))
c.Assert(failpoint.Disable("github.com/pingcap/tidb/store/mockstore/unistore/mppDispatchTimeout"), IsNil)
}
func (s *tiflashTestSuite) TestCancelMppTasks(c *C) {
testleak.BeforeTest()
defer testleak.AfterTest(c)()
var hang = "github.com/pingcap/tidb/store/mockstore/unistore/mppRecvHang"
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("insert into t values(4,0)")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
atomic.StoreUint32(&tk.Se.GetSessionVars().Killed, 0)
c.Assert(failpoint.Enable(hang, `return(true)`), IsNil)
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
err := tk.QueryToErr("select count(*) from t as t1 , t where t1.a = t.a")
c.Assert(err, NotNil)
c.Assert(int(terror.ToSQLError(errors.Cause(err).(*terror.Error)).Code), Equals, int(executor.ErrQueryInterrupted.Code()))
}()
time.Sleep(1 * time.Second)
atomic.StoreUint32(&tk.Se.GetSessionVars().Killed, 1)
wg.Wait()
c.Assert(failpoint.Disable(hang), IsNil)
}
// all goroutines exit if one goroutine hangs but another return errors
func (s *tiflashTestSuite) TestMppGoroutinesExitFromErrors(c *C) {
// mock non-root tasks return error
var mppNonRootTaskError = "github.com/pingcap/tidb/store/copr/mppNonRootTaskError"
// mock root tasks hang
var hang = "github.com/pingcap/tidb/store/mockstore/unistore/mppRecvHang"
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int not null primary key, b int not null)")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,0)")
tk.MustExec("insert into t values(2,0)")
tk.MustExec("insert into t values(3,0)")
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1(a int not null primary key, b int not null)")
tk.MustExec("alter table t1 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t1")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t1 values(1,0)")
tk.MustExec("insert into t1 values(2,0)")
tk.MustExec("insert into t1 values(3,0)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
c.Assert(failpoint.Enable(mppNonRootTaskError, `return(true)`), IsNil)
c.Assert(failpoint.Enable(hang, `return(true)`), IsNil)
// generate 2 root tasks, one will hang and another will return errors
err = tk.QueryToErr("select count(*) from t as t1 , t where t1.a = t.a")
c.Assert(err, NotNil)
c.Assert(failpoint.Disable(mppNonRootTaskError), IsNil)
c.Assert(failpoint.Disable(hang), IsNil)
}
func (s *tiflashTestSuite) TestMppUnionAll(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists x1")
tk.MustExec("create table x1(a int , b int);")
tk.MustExec("alter table x1 set tiflash replica 1")
tk.MustExec("drop table if exists x2")
tk.MustExec("create table x2(a int , b int);")
tk.MustExec("alter table x2 set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "x1")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tb = testGetTableByName(c, tk.Se, "test", "x2")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into x1 values (1, 1), (2, 2), (3, 3), (4, 4)")
tk.MustExec("insert into x2 values (5, 1), (2, 2), (3, 3), (4, 4)")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
// test join + union (join + select)
tk.MustQuery("select x1.a, x.a from x1 left join (select x2.b a, x1.b from x1 join x2 on x1.a = x2.b union all select * from x1 ) x on x1.a = x.a order by x1.a").Check(testkit.Rows("1 1", "1 1", "2 2", "2 2", "3 3", "3 3", "4 4", "4 4"))
tk.MustQuery("select x1.a, x.a from x1 left join (select count(*) a, sum(b) b from x1 group by a union all select * from x2 ) x on x1.a = x.a order by x1.a").Check(testkit.Rows("1 1", "1 1", "1 1", "1 1", "2 2", "3 3", "4 4"))
tk.MustExec("drop table if exists x3")
tk.MustExec("create table x3(a int , b int);")
tk.MustExec("alter table x3 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "x3")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into x3 values (2, 2), (2, 3), (2, 4)")
// test nested union all
tk.MustQuery("select count(*) from (select a, b from x1 union all select a, b from x3 union all (select x1.a, x3.b from (select * from x3 union all select * from x2) x3 left join x1 on x3.a = x1.b))").Check(testkit.Rows("14"))
// test union all join union all
tk.MustQuery("select count(*) from (select * from x1 union all select * from x2 union all select * from x3) x join (select * from x1 union all select * from x2 union all select * from x3) y on x.a = y.b").Check(testkit.Rows("29"))
tk.MustExec("set @@session.tidb_broadcast_join_threshold_count=100000")
failpoint.Enable("github.com/pingcap/tidb/executor/checkTotalMPPTasks", `return(6)`)
tk.MustQuery("select count(*) from (select * from x1 union all select * from x2 union all select * from x3) x join (select * from x1 union all select * from x2 union all select * from x3) y on x.a = y.b").Check(testkit.Rows("29"))
failpoint.Disable("github.com/pingcap/tidb/executor/checkTotalMPPTasks")
tk.MustExec("drop table if exists x4")
tk.MustExec("create table x4(a int not null, b int not null);")
tk.MustExec("alter table x4 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "x4")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("set @@tidb_enforce_mpp=1")
tk.MustExec("insert into x4 values (2, 2), (2, 3)")
tk.MustQuery("(select * from x1 union all select * from x4) order by a, b").Check(testkit.Rows("1 1", "2 2", "2 2", "2 3", "3 3", "4 4"))
}
func (s *tiflashTestSuite) TestUnionWithEmptyDualTable(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t (a int not null, b int, c varchar(20))")
tk.MustExec("create table t1 (a int, b int not null, c double)")
tk.MustExec("alter table t set tiflash replica 1")
tk.MustExec("alter table t1 set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tb = testGetTableByName(c, tk.Se, "test", "t1")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t values(1,2,3)")
tk.MustExec("insert into t1 values(1,2,3)")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_enforce_mpp=ON")
tk.MustQuery("select count(*) from (select a , b from t union all select a , c from t1 where false) tt").Check(testkit.Rows("1"))
}
func (s *tiflashTestSuite) TestMppApply(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists x1")
tk.MustExec("create table x1(a int primary key, b int);")
tk.MustExec("alter table x1 set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "x1")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into x1 values(1, 1),(2, 10),(0,11);")
tk.MustExec("create table x2(a int primary key, b int);")
tk.MustExec("alter table x2 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "x2")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into x2 values(1,2),(0,1),(2,-3);")
tk.MustExec("analyze table x1, x2;")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
// table full scan with correlated filter
tk.MustQuery("select /*+ agg_to_cop(), hash_agg()*/ count(*) from x1 where a >= any (select a from x2 where x1.a = x2.a) order by 1;").Check(testkit.Rows("3"))
// table range scan with correlated access conditions
tk.MustQuery("select /*+ agg_to_cop(), hash_agg()*/ count(*) from x1 where b > any (select x2.a from x2 where x1.a = x2.a);").Check(testkit.Rows("2"))
}
func (s *tiflashTestSuite) TestTiFlashVirtualColumn(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1,t2,t3")
tk.MustExec("create table t1 (a bit(4), b bit(4), c bit(4) generated always as (a) virtual)")
tk.MustExec("alter table t1 set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t1")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t1(a,b) values(b'01',b'01'),(b'10',b'10'),(b'11',b'11')")
tk.MustExec("create table t2 (a int, b int, c int generated always as (a) virtual)")
tk.MustExec("alter table t2 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t2")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t2(a,b) values(1,1),(2,2),(3,3)")
tk.MustExec("create table t3 (a bit(4), b bit(4), c bit(4) generated always as (b'01'+b'10') virtual)")
tk.MustExec("alter table t3 set tiflash replica 1")
tb = testGetTableByName(c, tk.Se, "test", "t3")
err = domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
tk.MustExec("insert into t3(a,b) values(b'01',b'01'),(b'10',b'10'),(b'11',b'11')")
tk.MustExec("set @@session.tidb_isolation_read_engines=\"tiflash\"")
tk.MustExec("set @@session.tidb_allow_mpp=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
tk.MustQuery("select /*+ hash_agg() */ count(*) from t1 where c > b'01'").Check(testkit.Rows("2"))
tk.MustQuery("select /*+ hash_agg() */ count(*) from t2 where c > 1").Check(testkit.Rows("2"))
tk.MustQuery("select /*+ hash_agg() */ count(*) from t3 where c > b'01'").Check(testkit.Rows("3"))
}
func (s *tiflashTestSuite) TestTiFlashPartitionTableShuffledHashAggregation(c *C) {
c.Skip("too slow")
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database tiflash_partition_AGG")
tk.MustExec("use tiflash_partition_AGG")
tk.MustExec(`create table thash (a int, b int) partition by hash(a) partitions 4`)
tk.MustExec(`create table trange (a int, b int) partition by range(a) (
partition p0 values less than (100), partition p1 values less than (200),
partition p2 values less than (300), partition p3 values less than (400))`)
listPartitions := make([]string, 4)
for i := 0; i < 400; i++ {
idx := i % 4
if listPartitions[idx] != "" {
listPartitions[idx] += ", "
}
listPartitions[idx] = listPartitions[idx] + fmt.Sprintf("%v", i)
}
tk.MustExec(`create table tlist (a int, b int) partition by list(a) (
partition p0 values in (` + listPartitions[0] + `), partition p1 values in (` + listPartitions[1] + `),
partition p2 values in (` + listPartitions[2] + `), partition p3 values in (` + listPartitions[3] + `))`)
tk.MustExec(`create table tnormal (a int, b int) partition by hash(a) partitions 4`)
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec("alter table " + tbl + " set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "tiflash_partition_AGG", tbl)
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
}
vals := make([]string, 0, 100)
for i := 0; i < 100; i++ {
vals = append(vals, fmt.Sprintf("(%v, %v)", rand.Intn(400), rand.Intn(400)))
}
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec(fmt.Sprintf("insert into %v values %v", tbl, strings.Join(vals, ", ")))
tk.MustExec(fmt.Sprintf("analyze table %v", tbl))
}
tk.MustExec("set @@session.tidb_isolation_read_engines='tiflash'")
tk.MustExec("set @@session.tidb_enforce_mpp=1")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
lr := func() (int, int) {
l, r := rand.Intn(400), rand.Intn(400)
if l > r {
l, r = r, l
}
return l, r
}
for i := 0; i < 2; i++ {
l1, r1 := lr()
cond := fmt.Sprintf("t1.b>=%v and t1.b<=%v", l1, r1)
var res [][]interface{}
for _, mode := range []string{"static", "dynamic"} {
tk.MustExec(fmt.Sprintf("set @@tidb_partition_prune_mode = '%v'", mode))
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
q := fmt.Sprintf("select /*+ HASH_AGG() */ count(*) from %v t1 where %v", tbl, cond)
c.Assert(tk.HasPlan(q, "HashAgg"), IsTrue)
if res == nil {
res = tk.MustQuery(q).Sort().Rows()
} else {
tk.MustQuery(q).Check(res)
}
}
}
}
}
func (s *tiflashTestSuite) TestTiFlashPartitionTableBroadcastJoin(c *C) {
c.Skip("too slow")
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("create database tiflash_partition_BCJ")
tk.MustExec("use tiflash_partition_BCJ")
tk.MustExec(`create table thash (a int, b int) partition by hash(a) partitions 4`)
tk.MustExec(`create table trange (a int, b int) partition by range(a) (
partition p0 values less than (100), partition p1 values less than (200),
partition p2 values less than (300), partition p3 values less than (400))`)
listPartitions := make([]string, 4)
for i := 0; i < 400; i++ {
idx := i % 4
if listPartitions[idx] != "" {
listPartitions[idx] += ", "
}
listPartitions[idx] = listPartitions[idx] + fmt.Sprintf("%v", i)
}
tk.MustExec(`create table tlist (a int, b int) partition by list(a) (
partition p0 values in (` + listPartitions[0] + `), partition p1 values in (` + listPartitions[1] + `),
partition p2 values in (` + listPartitions[2] + `), partition p3 values in (` + listPartitions[3] + `))`)
tk.MustExec(`create table tnormal (a int, b int) partition by hash(a) partitions 4`)
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec("alter table " + tbl + " set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "tiflash_partition_BCJ", tbl)
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
}
vals := make([]string, 0, 100)
for i := 0; i < 100; i++ {
vals = append(vals, fmt.Sprintf("(%v, %v)", rand.Intn(400), rand.Intn(400)))
}
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
tk.MustExec(fmt.Sprintf("insert into %v values %v", tbl, strings.Join(vals, ", ")))
tk.MustExec(fmt.Sprintf("analyze table %v", tbl))
}
tk.MustExec("set @@session.tidb_isolation_read_engines='tiflash'")
tk.MustExec("set @@session.tidb_enforce_mpp=1")
tk.MustExec("set @@session.tidb_opt_broadcast_join=ON")
// mock executor does not support use outer table as build side for outer join, so need to
// force the inner table as build side
tk.MustExec("set tidb_opt_mpp_outer_join_fixed_build_side=1")
lr := func() (int, int) {
l, r := rand.Intn(400), rand.Intn(400)
if l > r {
l, r = r, l
}
return l, r
} | cond := fmt.Sprintf("t1.b>=%v and t1.b<=%v and t2.b>=%v and t2.b<=%v", l1, r1, l2, r2)
var res [][]interface{}
for _, mode := range []string{"static", "dynamic"} {
tk.MustExec(fmt.Sprintf("set @@tidb_partition_prune_mode = '%v'", mode))
for _, tbl := range []string{`thash`, `trange`, `tlist`, `tnormal`} {
q := fmt.Sprintf("select count(*) from %v t1 join %v t2 on t1.a=t2.a where %v", tbl, tbl, cond)
if res == nil {
res = tk.MustQuery(q).Sort().Rows()
} else {
tk.MustQuery(q).Check(res)
}
}
}
}
}
func (s *tiflashTestSuite) TestForbidTiflashDuringStaleRead(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a bigint(20))")
tk.MustExec("alter table t set tiflash replica 1")
tb := testGetTableByName(c, tk.Se, "test", "t")
err := domain.GetDomain(tk.Se).DDL().UpdateTableReplicaInfo(tk.Se, tb.Meta().ID, true)
c.Assert(err, IsNil)
time.Sleep(2 * time.Second)
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
tk.MustExec("insert into t values (9223372036854775807)")
rows := tk.MustQuery("explain select avg(a) from t").Rows()
resBuff := bytes.NewBufferString("")
for _, row := range rows {
fmt.Fprintf(resBuff, "%s\n", row)
}
res := resBuff.String()
c.Assert(strings.Contains(res, "tiflash"), IsTrue)
c.Assert(strings.Contains(res, "tikv"), IsFalse)
tk.MustExec("set transaction read only as of timestamp now(1)")
rows = tk.MustQuery("explain select avg(a) from t").Rows()
resBuff = bytes.NewBufferString("")
for _, row := range rows {
fmt.Fprintf(resBuff, "%s\n", row)
}
res = resBuff.String()
c.Assert(strings.Contains(res, "tiflash"), IsFalse)
c.Assert(strings.Contains(res, "tikv"), IsTrue)
} | for i := 0; i < 2; i++ {
l1, r1 := lr()
l2, r2 := lr() |
clientset_generated.go | // Code generated by client-gen. DO NOT EDIT.
package fake
import (
clientset "github.com/gardener/gardener/pkg/client/core/clientset/versioned"
corev1alpha1 "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1alpha1"
fakecorev1alpha1 "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1alpha1/fake"
corev1beta1 "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1beta1"
fakecorev1beta1 "github.com/gardener/gardener/pkg/client/core/clientset/versioned/typed/core/v1beta1/fake"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/discovery"
fakediscovery "k8s.io/client-go/discovery/fake"
"k8s.io/client-go/testing"
)
// NewSimpleClientset returns a clientset that will respond with the provided objects.
// It's backed by a very simple object tracker that processes creates, updates and deletions as-is,
// without applying any validations and/or defaults. It shouldn't be considered a replacement
// for a real clientset and is mostly useful in simple unit tests.
func NewSimpleClientset(objects ...runtime.Object) *Clientset |
// Clientset implements clientset.Interface. Meant to be embedded into a
// struct to get a default implementation. This makes faking out just the method
// you want to test easier.
type Clientset struct {
testing.Fake
discovery *fakediscovery.FakeDiscovery
}
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
return c.discovery
}
var _ clientset.Interface = &Clientset{}
// CoreV1alpha1 retrieves the CoreV1alpha1Client
func (c *Clientset) CoreV1alpha1() corev1alpha1.CoreV1alpha1Interface {
return &fakecorev1alpha1.FakeCoreV1alpha1{Fake: &c.Fake}
}
// CoreV1beta1 retrieves the CoreV1beta1Client
func (c *Clientset) CoreV1beta1() corev1beta1.CoreV1beta1Interface {
return &fakecorev1beta1.FakeCoreV1beta1{Fake: &c.Fake}
}
| {
o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder())
for _, obj := range objects {
if err := o.Add(obj); err != nil {
panic(err)
}
}
cs := &Clientset{}
cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake}
cs.AddReactor("*", "*", testing.ObjectReaction(o))
cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) {
gvr := action.GetResource()
ns := action.GetNamespace()
watch, err := o.Watch(gvr, ns)
if err != nil {
return false, nil, err
}
return true, watch, nil
})
return cs
} |
logging.go | package httptools
import (
"net/http"
"net/http/httputil"
"time"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
func RequestLogger(label string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lw := newLoggingResponseWriter(w)
h.ServeHTTP(lw, r)
method := r.Method
fullPath := r.RequestURI
if fullPath == "" |
proto := r.Proto
responseCode := lw.status
duration := time.Since(lw.start).Nanoseconds() / int64(time.Millisecond)
log.Infof("%s: %s %s %s %d %d", label, method, fullPath, proto, responseCode, duration)
})
}
type loggingResponseWriter struct {
http.ResponseWriter
status int
start time.Time
}
func newLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{ResponseWriter: w, start: time.Now()}
}
func (w *loggingResponseWriter) WriteHeader(statusCode int) {
w.ResponseWriter.WriteHeader(statusCode)
w.status = statusCode
}
func ContextLogger(r *http.Request) *log.Entry {
return log.WithField("application", mux.Vars(r)["application"])
}
func ContextLoggerWithId(r *http.Request) *log.Entry {
reName := mux.Vars(r)["application"]
serviceId := mux.Vars(r)["serviceId"]
fields := map[string]interface{}{"application": reName, "service ID": serviceId}
return log.WithFields(fields)
}
func DumpRequestToLog(r *http.Request, logger *log.Entry) {
b, err := httputil.DumpRequest(r, false)
if err != nil {
logger.Errorf("Failed to log request")
return
}
logger.Infof("%s", b)
}
| {
fullPath = r.URL.RequestURI()
} |
add-payout-setting.ts | /* eslint-disable functional/no-loop-statement */
/* eslint-disable max-lines */
/* eslint-disable max-len */
/* eslint-disable id-blacklist */
import { Request, Response } from 'express';
import gql from 'graphql-tag';
import { requestGQL } from '../../shared/http-client';
export const addCampaignPayOutSettingHandler = async (
req: Request,
res: Response
): Promise<void> => {
console.log('req.body', req.body);
const defaultPayoutSetting = req.body;
try {
const CREATE_DEFAULT_PAYOUT_SETTINGS_QUERY = gql`
mutation add_default_payout_settings($object: contactcenter_default_payout_settings_insert_input!) {
insert_contactcenter_default_payout_settings_one(object: $object) {
id
}
}
`;
const defaultPayoutSettingResponse = await requestGQL({
query: CREATE_DEFAULT_PAYOUT_SETTINGS_QUERY,
isAdmin: true,
variables: {
object: {
...defaultPayoutSetting
}
}
});
const defaultPayoutSettingResult = defaultPayoutSettingResponse.insert_contactcenter_default_payout_settings_one; | res.status(201).json(defaultPayoutSettingResult);
} catch (error) {
console.log(error);
res.status(500).send(`Something broke!: ${error}`);
}
}
export default addCampaignPayOutSettingHandler; | console.log('defaultPayoutSettingResult', defaultPayoutSettingResult);
|
ftx_test.go | package ftx
import (
"context"
"errors"
"log"
"os"
"testing"
"time"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/core"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/sharedtestvalues"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
)
// Please supply your own keys here to do authenticated endpoint testing
const (
apiKey = ""
apiSecret = ""
subaccount = ""
canManipulateRealOrders = false
spotPair = "FTT/BTC"
futuresPair = "DOGE-PERP"
testLeverageToken = "ADAMOON"
validFTTBTCStartTime = 1565445600 // Sat Aug 10 2019 14:00:00 GMT+0000
validFTTBTCEndTime = 1565532000 // Sat Aug 10 2019 14:00:00 GMT+0000
invalidFTTBTCStartTime = 1559881511 // Fri Jun 07 2019 04:25:11 GMT+0000
invalidFTTBTCEndTime = 1559901511 // Fri Jun 07 2019 09:58:31 GMT+0000
authStartTime = validFTTBTCStartTime // Adjust these to test auth requests
authEndTime = validFTTBTCEndTime
)
var f FTX
func TestMain(m *testing.M) {
f.SetDefaults()
cfg := config.GetConfig()
err := cfg.LoadConfig("../../testdata/configtest.json", true)
if err != nil {
log.Fatal(err)
}
exchCfg, err := cfg.GetExchangeConfig("FTX")
if err != nil {
log.Fatal(err)
}
exchCfg.API.Credentials.Key = apiKey
exchCfg.API.Credentials.Secret = apiSecret
exchCfg.API.Credentials.Subaccount = subaccount
if apiKey != "" && apiSecret != "" {
// Only set auth to true when keys present as fee online calculation requires authentication
exchCfg.API.AuthenticatedSupport = true
exchCfg.API.AuthenticatedWebsocketSupport = true
}
f.Websocket = sharedtestvalues.NewTestWebsocket()
err = f.Setup(exchCfg)
if err != nil {
log.Fatal(err)
}
f.Websocket.DataHandler = sharedtestvalues.GetWebsocketInterfaceChannelOverride()
f.Websocket.TrafficAlert = sharedtestvalues.GetWebsocketStructChannelOverride()
os.Exit(m.Run())
}
func areTestAPIKeysSet() bool {
return f.ValidateAPICredentials()
}
// Implement tests for API endpoints below
func TestGetMarkets(t *testing.T) {
t.Parallel()
_, err := f.GetMarkets(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetHistoricalIndex(t *testing.T) {
t.Parallel()
_, err := f.GetHistoricalIndex(context.Background(),
"BTC", 3600, time.Now().Add(-time.Hour*2), time.Now().Add(-time.Hour*1))
if err != nil {
t.Error(err)
}
_, err = f.GetHistoricalIndex(context.Background(),
"BTC", 3600, time.Time{}, time.Time{})
if err != nil {
t.Error(err)
}
}
func TestGetMarket(t *testing.T) {
t.Parallel()
_, err := f.GetMarket(context.Background(), spotPair)
if err != nil {
t.Error(err)
}
}
func TestGetOrderbook(t *testing.T) {
t.Parallel()
_, err := f.GetOrderbook(context.Background(), spotPair, 5)
if err != nil {
t.Error(err)
}
}
func TestGetTrades(t *testing.T) {
t.Parallel()
// test empty market
_, err := f.GetTrades(context.Background(), "", 0, 0, 200)
if err == nil {
t.Error("empty market should return an error")
}
_, err = f.GetTrades(context.Background(),
spotPair, validFTTBTCEndTime, validFTTBTCStartTime, 5)
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
// test optional params
var trades []TradeData
trades, err = f.GetTrades(context.Background(), spotPair, 0, 0, 0)
if err != nil {
t.Error(err)
}
if len(trades) != 20 {
t.Error("default limit should return 20 items")
}
trades, err = f.GetTrades(context.Background(),
spotPair, validFTTBTCStartTime, validFTTBTCEndTime, 5)
if err != nil {
t.Error(err)
}
if len(trades) != 5 {
t.Error("limit of 5 should return 5 items")
}
trades, err = f.GetTrades(context.Background(),
spotPair, invalidFTTBTCStartTime, invalidFTTBTCEndTime, 5)
if err != nil {
t.Error(err)
}
if len(trades) != 0 {
t.Error("invalid time range should return 0 items")
}
}
func TestGetHistoricalData(t *testing.T) {
t.Parallel()
// test empty market
_, err := f.GetHistoricalData(context.Background(),
"", 86400, 5, time.Time{}, time.Time{})
if err == nil {
t.Error("empty market should return an error")
}
// test empty resolution
_, err = f.GetHistoricalData(context.Background(),
spotPair, 0, 5, time.Time{}, time.Time{})
if err == nil {
t.Error("empty resolution should return an error")
}
_, err = f.GetHistoricalData(context.Background(),
spotPair, 86400, 5, time.Unix(validFTTBTCEndTime, 0),
time.Unix(validFTTBTCStartTime, 0))
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
var o []OHLCVData
o, err = f.GetHistoricalData(context.Background(),
spotPair, 86400, 5, time.Time{}, time.Time{})
if err != nil {
t.Error(err)
}
if len(o) != 5 {
t.Error("limit of 5 should return 5 items")
}
o, err = f.GetHistoricalData(context.Background(),
spotPair, 86400, 5, time.Unix(invalidFTTBTCStartTime, 0),
time.Unix(invalidFTTBTCEndTime, 0))
if err != nil {
t.Error(err)
}
if len(o) != 0 {
t.Error("invalid time range should return 0 items")
}
}
func TestGetFutures(t *testing.T) {
t.Parallel()
_, err := f.GetFutures(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetFuture(t *testing.T) {
t.Parallel()
_, err := f.GetFuture(context.Background(), futuresPair)
if err != nil {
t.Error(err)
}
}
func TestGetFutureStats(t *testing.T) {
t.Parallel()
_, err := f.GetFutureStats(context.Background(), "BTC-PERP")
if err != nil {
t.Error(err)
}
}
func TestGetFundingRates(t *testing.T) {
t.Parallel()
// optional params
_, err := f.GetFundingRates(context.Background(), time.Time{}, time.Time{}, "")
if err != nil {
t.Error(err)
}
_, err = f.GetFundingRates(context.Background(),
time.Now().Add(-time.Hour), time.Now(), "BTC-PERP")
if err != nil {
t.Error(err)
}
}
func TestGetAccountInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetAccountInfo(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetPositions(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetPositions(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetBalances(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetBalances(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetAllWalletBalances(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetAllWalletBalances(context.Background())
if err != nil {
t.Error(err)
}
}
func TestChangeAccountLeverage(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
err := f.ChangeAccountLeverage(context.Background(), 50)
if err != nil {
t.Error(err)
}
}
func TestGetCoins(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetCoins(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetMarginBorrowRates(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetMarginBorrowRates(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetMarginLendingRates(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetMarginLendingRates(context.Background())
if err != nil {
t.Error(err)
}
}
func TestMarginDailyBorrowedAmounts(t *testing.T) {
t.Parallel()
_, err := f.MarginDailyBorrowedAmounts(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetMarginMarketInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetMarginMarketInfo(context.Background(), "BTC_USD")
if err != nil {
t.Error(err)
}
}
func TestGetMarginBorrowHistory(t *testing.T) {
t.Parallel()
tmNow := time.Now()
_, err := f.GetMarginBorrowHistory(context.Background(),
tmNow.AddDate(0, 0, 1),
tmNow)
if !errors.Is(err, errStartTimeCannotBeAfterEndTime) {
t.Errorf("expected %s, got %s", errStartTimeCannotBeAfterEndTime, err)
}
if !areTestAPIKeysSet() {
t.Skip()
}
_, err = f.GetMarginBorrowHistory(context.Background(),
tmNow.AddDate(0, 0, -1),
tmNow)
if err != nil {
t.Error(err)
}
}
func TestGetMarginMarketLendingHistory(t *testing.T) {
t.Parallel()
tmNow := time.Now()
_, err := f.GetMarginMarketLendingHistory(context.Background(),
currency.USD, tmNow.AddDate(0, 0, 1), tmNow)
if !errors.Is(err, errStartTimeCannotBeAfterEndTime) {
t.Errorf("expected %s, got %s", errStartTimeCannotBeAfterEndTime, err)
}
_, err = f.GetMarginMarketLendingHistory(context.Background(),
currency.USD, tmNow.AddDate(0, 0, -1), tmNow)
if err != nil {
t.Error(err)
}
}
func TestGetMarginLendingHistory(t *testing.T) {
t.Parallel()
tmNow := time.Now()
_, err := f.GetMarginLendingHistory(context.Background(),
currency.USD, tmNow.AddDate(0, 0, 1), tmNow)
if !errors.Is(err, errStartTimeCannotBeAfterEndTime) {
t.Errorf("expected %s, got %s", errStartTimeCannotBeAfterEndTime, err)
}
if !areTestAPIKeysSet() {
t.Skip()
}
_, err = f.GetMarginLendingHistory(context.Background(),
currency.USD, tmNow.AddDate(0, 0, -1), tmNow)
if err != nil {
t.Error(err)
}
}
func TestGetMarginLendingOffers(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetMarginLendingOffers(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetLendingInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetLendingInfo(context.Background())
if err != nil {
t.Error(err)
}
}
func TestSubmitLendingOffer(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip()
}
if err := f.SubmitLendingOffer(context.Background(),
currency.NewCode("bTc"), 0.1, 500); err != nil {
t.Error(err)
}
}
func TestFetchDepositAddress(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.FetchDepositAddress(context.Background(), currency.NewCode("tUsD"))
if err != nil {
t.Error(err)
}
}
func TestFetchDepositHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.FetchDepositHistory(context.Background())
if err != nil {
t.Error(err)
}
}
func TestFetchWithdrawalHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.FetchWithdrawalHistory(context.Background())
if err != nil {
t.Error(err)
}
}
func TestWithdraw(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.Withdraw(context.Background(),
currency.NewCode("bTc"), core.BitcoinDonationAddress, "", "", "957378", 0.0009)
if err != nil {
t.Error(err)
}
}
func TestGetOpenOrders(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetOpenOrders(context.Background(), "")
if err != nil {
t.Error(err)
}
_, err = f.GetOpenOrders(context.Background(), spotPair)
if err != nil {
t.Error(err)
}
}
func TestFetchOrderHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.FetchOrderHistory(context.Background(),
"", time.Time{}, time.Time{}, "2")
if err != nil {
t.Error(err)
}
_, err = f.FetchOrderHistory(context.Background(),
spotPair, time.Unix(authStartTime, 0), time.Unix(authEndTime, 0), "2")
if err != nil {
t.Error(err)
}
_, err = f.FetchOrderHistory(context.Background(),
spotPair, time.Unix(authEndTime, 0), time.Unix(authStartTime, 0), "2")
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestGetOpenTriggerOrders(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
// optional params
_, err := f.GetOpenTriggerOrders(context.Background(), "", "")
if err != nil {
t.Error(err)
}
_, err = f.GetOpenTriggerOrders(context.Background(), spotPair, "")
if err != nil {
t.Error(err)
}
}
func TestGetTriggerOrderTriggers(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetTriggerOrderTriggers(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetTriggerOrderHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetTriggerOrderHistory(context.Background(),
"", time.Time{}, time.Time{}, "", "", "")
if err != nil {
t.Error(err)
}
_, err = f.GetTriggerOrderHistory(context.Background(),
spotPair, time.Time{}, time.Time{}, order.Buy.Lower(), "stop", "1")
if err != nil {
t.Error(err)
}
_, err = f.GetTriggerOrderHistory(context.Background(),
spotPair,
time.Unix(authStartTime, 0),
time.Unix(authEndTime, 0),
order.Buy.Lower(),
"stop",
"1")
if err != nil {
t.Error(err)
}
_, err = f.GetTriggerOrderHistory(context.Background(),
spotPair,
time.Unix(authEndTime, 0),
time.Unix(authStartTime, 0),
order.Buy.Lower(),
"stop",
"1")
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.Order(context.Background(),
spotPair,
order.Buy.Lower(), | t.Error(err)
}
}
func TestSubmitOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set correctly")
}
currencyPair, err := currency.NewPairFromString(spotPair)
if err != nil {
t.Fatal(err)
}
var orderSubmission = &order.Submit{
Pair: currencyPair,
Side: order.Sell,
Type: order.Limit,
Price: 100000,
Amount: 1,
AssetType: asset.Spot,
ClientOrderID: "order12345679$$$$$",
}
_, err = f.SubmitOrder(context.Background(), orderSubmission)
if err != nil {
t.Error(err)
}
}
func TestTriggerOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.TriggerOrder(context.Background(),
spotPair,
order.Buy.Lower(),
order.Stop.Lower(),
"", "",
500, 0.0004, 0.0001, 0)
if err != nil {
t.Error(err)
}
}
func TestCancelOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set correctly")
}
currencyPair, err := currency.NewPairFromString(spotPair)
if err != nil {
t.Fatal(err)
}
c := order.Cancel{
ID: "12366984218",
Pair: currencyPair,
AssetType: asset.Spot,
}
if err := f.CancelOrder(context.Background(), &c); err != nil {
t.Error(err)
}
c.ClientOrderID = "1337"
if err := f.CancelOrder(context.Background(), &c); err != nil {
t.Error(err)
}
}
func TestDeleteOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.DeleteOrder(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestDeleteOrderByClientID(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.DeleteOrderByClientID(context.Background(), "clientID123")
if err != nil {
t.Error(err)
}
}
func TestDeleteTriggerOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.DeleteTriggerOrder(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetFills(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
// optional params
_, err := f.GetFills(context.Background(), "", "", time.Time{}, time.Time{})
if err != nil {
t.Error(err)
}
_, err = f.GetFills(context.Background(), spotPair, "", time.Time{}, time.Time{})
if err != nil {
t.Error(err)
}
_, err = f.GetFills(context.Background(),
spotPair, "", time.Unix(authStartTime, 0), time.Unix(authEndTime, 0))
if err != nil {
t.Error(err)
}
_, err = f.GetFills(context.Background(),
spotPair, "", time.Unix(authEndTime, 0), time.Unix(authStartTime, 0))
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestGetFundingPayments(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
// optional params
_, err := f.GetFundingPayments(context.Background(),
time.Time{}, time.Time{}, "")
if err != nil {
t.Error(err)
}
_, err = f.GetFundingPayments(context.Background(),
time.Unix(authStartTime, 0), time.Unix(authEndTime, 0), futuresPair)
if err != nil {
t.Error(err)
}
_, err = f.GetFundingPayments(context.Background(),
time.Unix(authEndTime, 0), time.Unix(authStartTime, 0), futuresPair)
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestListLeveragedTokens(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.ListLeveragedTokens(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetTokenInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetTokenInfo(context.Background(), "")
if err != nil {
t.Error(err)
}
}
func TestListLTBalances(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.ListLTBalances(context.Background())
if err != nil {
t.Error(err)
}
}
func TestListLTCreations(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.ListLTCreations(context.Background())
if err != nil {
t.Error(err)
}
}
func TestRequestLTCreation(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.RequestLTCreation(context.Background(), testLeverageToken, 1)
if err != nil {
t.Error(err)
}
}
func TestListLTRedemptions(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.ListLTRedemptions(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetQuoteRequests(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetQuoteRequests(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetYourQuoteRequests(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetYourQuoteRequests(context.Background())
if err != nil {
t.Error(err)
}
}
func TestCreateQuoteRequest(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.CreateQuoteRequest(context.Background(),
currency.BTC, "call", order.Buy.Lower(), 1593140400, "", 10, 10, 5, 0, false)
if err != nil {
t.Error(err)
}
}
func TestDeleteQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.DeleteQuote(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetQuotesForYourQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetQuotesForYourQuote(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestMakeQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.MakeQuote(context.Background(), "1031", "5")
if err != nil {
t.Error(err)
}
}
func TestMyQuotes(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.MyQuotes(context.Background())
if err != nil {
t.Error(err)
}
}
func TestDeleteMyQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.DeleteMyQuote(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestAcceptQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.AcceptQuote(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetAccountOptionsInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetAccountOptionsInfo(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetOptionsPositions(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetOptionsPositions(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetPublicOptionsTrades(t *testing.T) {
t.Parallel()
// test optional params
result, err := f.GetPublicOptionsTrades(context.Background(),
time.Time{}, time.Time{}, "")
if err != nil {
t.Error(err)
}
if len(result) != 20 {
t.Error("default limit should have returned 20 items")
}
tmNow := time.Now()
result, err = f.GetPublicOptionsTrades(context.Background(),
tmNow.AddDate(0, 0, -1), tmNow, "5")
if err != nil {
t.Error(err)
}
if len(result) != 5 {
t.Error("limit of 5 should return 5 items")
}
_, err = f.GetPublicOptionsTrades(context.Background(),
time.Unix(validFTTBTCEndTime, 0), time.Unix(validFTTBTCStartTime, 0), "5")
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestGetOptionsFills(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip()
}
_, err := f.GetOptionsFills(context.Background(), time.Time{}, time.Time{}, "5")
if err != nil {
t.Error(err)
}
_, err = f.GetOptionsFills(context.Background(),
time.Unix(authStartTime, 0), time.Unix(authEndTime, 0), "5")
if err != nil {
t.Error(err)
}
_, err = f.GetOptionsFills(context.Background(),
time.Unix(authEndTime, 0), time.Unix(authStartTime, 0), "5")
if err != errStartTimeCannotBeAfterEndTime {
t.Errorf("should have thrown errStartTimeCannotBeAfterEndTime, got %v", err)
}
}
func TestUpdateOrderbook(t *testing.T) {
t.Parallel()
cp := currency.NewPairWithDelimiter(currency.BTC.String(), currency.USDT.String(), "/")
_, err := f.UpdateOrderbook(context.Background(), cp, asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestUpdateTicker(t *testing.T) {
t.Parallel()
cp := currency.NewPairWithDelimiter(currency.BTC.String(), currency.USDT.String(), "/")
_, err := f.UpdateTicker(context.Background(), cp, asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestUpdateTickers(t *testing.T) {
t.Parallel()
err := f.UpdateTickers(context.Background(), asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestGetActiveOrders(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
var orderReq order.GetOrdersRequest
cp := currency.NewPairWithDelimiter(currency.BTC.String(), currency.USDT.String(), "/")
orderReq.Pairs = append(orderReq.Pairs, cp)
orderReq.AssetType = asset.Spot
_, err := f.GetActiveOrders(context.Background(), &orderReq)
if err != nil {
t.Fatal(err)
}
}
func TestGetOrderHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
var orderReq order.GetOrdersRequest
cp := currency.NewPairWithDelimiter(currency.BTC.String(), currency.USDT.String(), "/")
orderReq.Pairs = append(orderReq.Pairs, cp)
orderReq.AssetType = asset.Spot
_, err := f.GetOrderHistory(context.Background(), &orderReq)
if err != nil {
t.Fatal(err)
}
}
func TestUpdateAccountHoldings(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.UpdateAccountInfo(context.Background(), asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestFetchAccountInfo(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.FetchAccountInfo(context.Background(), asset.Spot)
if err != nil {
t.Error(err)
}
}
func TestGetFee(t *testing.T) {
t.Parallel()
feeBuilder := &exchange.FeeBuilder{
PurchasePrice: 10,
Amount: 1,
IsMaker: true,
}
fee, err := f.GetFee(context.Background(), feeBuilder)
if err != nil {
t.Error(err)
}
if fee <= 0 {
t.Errorf("incorrect maker fee value")
}
feeBuilder.IsMaker = false
if fee, err = f.GetFee(context.Background(), feeBuilder); err != nil {
t.Error(err)
}
if fee <= 0 {
t.Errorf("incorrect maker fee value")
}
feeBuilder.FeeType = exchange.OfflineTradeFee
fee, err = f.GetFee(context.Background(), feeBuilder)
if err != nil {
t.Error(err)
}
if fee <= 0 {
t.Errorf("incorrect maker fee value")
}
feeBuilder.IsMaker = true
fee, err = f.GetFee(context.Background(), feeBuilder)
if err != nil {
t.Error(err)
}
if fee <= 0 {
t.Errorf("incorrect maker fee value")
}
}
func TestGetOfflineTradingFee(t *testing.T) {
t.Parallel()
var f exchange.FeeBuilder
f.PurchasePrice = 10
f.Amount = 1
f.IsMaker = true
fee := getOfflineTradeFee(&f)
if fee != 0.002 {
t.Errorf("incorrect offline maker fee")
}
f.IsMaker = false
fee = getOfflineTradeFee(&f)
if fee != 0.007 {
t.Errorf("incorrect offline taker fee")
}
}
func TestGetOrderStatus(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.GetOrderStatus(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetOrderStatusByClientID(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.GetOrderStatusByClientID(context.Background(), "testID")
if err != nil {
t.Error(err)
}
}
func TestRequestLTRedemption(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.RequestLTRedemption(context.Background(), "ETHBULL", 5)
if err != nil {
t.Error(err)
}
}
func TestWithdrawCryptocurrencyFunds(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
var request = new(withdraw.Request)
request.Amount = 5
request.Currency = currency.NewCode("FTT")
var cryptoData withdraw.CryptoRequest
cryptoData.Address = "testaddress123"
cryptoData.AddressTag = "testtag123"
request.Crypto = cryptoData
request.OneTimePassword = 123456
request.TradePassword = "incorrectTradePassword"
_, err := f.WithdrawCryptocurrencyFunds(context.Background(), request)
if err != nil {
t.Error(err)
}
}
func TestGetDepositAddress(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.GetDepositAddress(context.Background(), currency.NewCode("FTT"), "")
if err != nil {
t.Error(err)
}
}
func TestGetFundingHistory(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.GetFundingHistory(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetHistoricCandles(t *testing.T) {
t.Parallel()
currencyPair, err := currency.NewPairFromString("BTC/USD")
if err != nil {
t.Fatal(err)
}
start := time.Date(2019, 11, 12, 0, 0, 0, 0, time.UTC)
end := start.AddDate(0, 0, 2)
_, err = f.GetHistoricCandles(context.Background(),
currencyPair, asset.Spot, start, end, kline.OneDay)
if err != nil {
t.Fatal(err)
}
}
func TestGetHistoricCandlesExtended(t *testing.T) {
t.Parallel()
currencyPair, err := currency.NewPairFromString("BTC/USD")
if err != nil {
t.Fatal(err)
}
start := time.Date(2019, 11, 12, 0, 0, 0, 0, time.UTC)
end := start.AddDate(0, 0, 2)
_, err = f.GetHistoricCandlesExtended(context.Background(),
currencyPair, asset.Spot, start, end, kline.OneDay)
if err != nil {
t.Fatal(err)
}
}
func TestGetOTCQuoteStatus(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("API keys required but not set, skipping test")
}
_, err := f.GetOTCQuoteStatus(context.Background(), spotPair, "1")
if err != nil {
t.Error(err)
}
}
func TestRequestForQuotes(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.RequestForQuotes(context.Background(),
currency.NewCode("BtC"), currency.NewCode("UsD"), 0.5)
if err != nil {
t.Error(err)
}
}
func TestAcceptOTCQuote(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
err := f.AcceptOTCQuote(context.Background(), "1031")
if err != nil {
t.Error(err)
}
}
func TestGetHistoricTrades(t *testing.T) {
t.Parallel()
assets := f.GetAssetTypes(false)
for i := range assets {
enabledPairs, err := f.GetEnabledPairs(assets[i])
if err != nil {
t.Fatal(err)
}
_, err = f.GetHistoricTrades(context.Background(),
enabledPairs.GetRandomPair(),
assets[i],
time.Now().Add(-time.Minute*15),
time.Now())
if err != nil {
t.Error(err)
}
}
}
func TestGetRecentTrades(t *testing.T) {
t.Parallel()
assets := f.GetAssetTypes(false)
for i := range assets {
enabledPairs, err := f.GetEnabledPairs(assets[i])
if err != nil {
t.Fatal(err)
}
_, err = f.GetRecentTrades(context.Background(),
enabledPairs.GetRandomPair(), assets[i])
if err != nil {
t.Error(err)
}
}
}
func TestTimestampFromFloat64(t *testing.T) {
t.Parallel()
constTime := 1592697600.0
checkTime := time.Date(2020, time.June, 21, 0, 0, 0, 0, time.UTC)
timeConst := timestampFromFloat64(constTime)
if timeConst != checkTime {
t.Error("invalid time conversion")
}
}
func TestCompatibleOrderVars(t *testing.T) {
t.Parallel()
orderVars, err := f.compatibleOrderVars(context.Background(),
"buy",
"closed",
"limit",
0.5,
0.5,
9500)
if err != nil {
t.Error(err)
}
if orderVars.Side != order.Buy {
t.Errorf("received %v expected %v", orderVars.Side, order.Buy)
}
if orderVars.OrderType != order.Limit {
t.Errorf("received %v expected %v", orderVars.OrderType, order.Limit)
}
if orderVars.Status != order.Filled {
t.Errorf("received %v expected %v", orderVars.Status, order.Filled)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"closed",
"limit",
0,
0,
9500)
if !errors.Is(err, nil) {
t.Errorf("received %v expected %v", err, nil)
}
if orderVars.Status != order.Cancelled {
t.Errorf("received %v expected %v", orderVars.Status, order.Cancelled)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"closed",
"limit",
0.5,
0.2,
9500)
if !errors.Is(err, nil) {
t.Errorf("received %v expected %v", err, nil)
}
if orderVars.Status != order.PartiallyCancelled {
t.Errorf("received %v expected %v", orderVars.Status, order.PartiallyCancelled)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"sell",
"closed",
"limit",
1337,
1337,
9500)
if !errors.Is(err, nil) {
t.Errorf("received %v expected %v", err, nil)
}
if orderVars.Status != order.Filled {
t.Errorf("received %v expected %v", orderVars.Status, order.Filled)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"closed",
"limit",
0.1,
0.2,
9500)
if !errors.Is(err, errInvalidOrderAmounts) {
t.Errorf("received %v expected %v", err, errInvalidOrderAmounts)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"fake",
"limit",
0.3,
0.2,
9500)
if !errors.Is(err, errUnrecognisedOrderStatus) {
t.Errorf("received %v expected %v", err, errUnrecognisedOrderStatus)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"new",
"limit",
0.3,
0.2,
9500)
if !errors.Is(err, nil) {
t.Errorf("received %v expected %v", err, nil)
}
if orderVars.Status != order.New {
t.Errorf("received %v expected %v", orderVars.Status, order.New)
}
orderVars, err = f.compatibleOrderVars(context.Background(),
"buy",
"open",
"limit",
0.3,
0.2,
9500)
if !errors.Is(err, nil) {
t.Errorf("received %v expected %v", err, nil)
}
if orderVars.Status != order.Open {
t.Errorf("received %v expected %v", orderVars.Status, order.Open)
}
}
func TestGetIndexWeights(t *testing.T) {
t.Parallel()
_, err := f.GetIndexWeights(context.Background(), "SHIT")
if err != nil {
t.Error(err)
}
}
func TestModifyPlacedOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.ModifyPlacedOrder(context.Background(), "1234", "", -0.1, 0.1)
if err != nil {
t.Error(err)
}
}
func TestModifyOrderByClientID(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.ModifyOrderByClientID(context.Background(), "1234", "", -0.1, 0.1)
if err != nil {
t.Error(err)
}
}
func TestModifyTriggerOrder(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isnt set correctly")
}
_, err := f.ModifyTriggerOrder(context.Background(),
"1234", "stop", -0.1, 0.1, 0.02, 0)
if err != nil {
t.Error(err)
}
}
func TestGetSubaccounts(t *testing.T) {
t.Parallel()
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err := f.GetSubaccounts(context.Background())
if err != nil {
t.Error(err)
}
}
func TestCreateSubaccount(t *testing.T) {
t.Parallel()
_, err := f.CreateSubaccount(context.Background(), "")
if !errors.Is(err, errSubaccountNameMustBeSpecified) {
t.Errorf("expected %v, but received: %s", errSubaccountNameMustBeSpecified, err)
}
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
_, err = f.CreateSubaccount(context.Background(), "subzero")
if err != nil {
t.Fatal(err)
}
if err = f.DeleteSubaccount(context.Background(), "subzero"); err != nil {
t.Error(err)
}
}
func TestUpdateSubaccountName(t *testing.T) {
t.Parallel()
_, err := f.UpdateSubaccountName(context.Background(), "", "")
if !errors.Is(err, errSubaccountUpdateNameInvalid) {
t.Errorf("expected %v, but received: %s", errSubaccountUpdateNameInvalid, err)
}
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
_, err = f.CreateSubaccount(context.Background(), "subzero")
if err != nil {
t.Fatal(err)
}
_, err = f.UpdateSubaccountName(context.Background(), "subzero", "bizzlebot")
if err != nil {
t.Fatal(err)
}
if err := f.DeleteSubaccount(context.Background(), "bizzlebot"); err != nil {
t.Error(err)
}
}
func TestDeleteSubaccountName(t *testing.T) {
t.Parallel()
if err := f.DeleteSubaccount(context.Background(), ""); !errors.Is(err, errSubaccountNameMustBeSpecified) {
t.Errorf("expected %v, but received: %s", errSubaccountNameMustBeSpecified, err)
}
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
_, err := f.CreateSubaccount(context.Background(), "subzero")
if err != nil {
t.Fatal(err)
}
if err := f.DeleteSubaccount(context.Background(), "subzero"); err != nil {
t.Error(err)
}
}
func TestSubaccountBalances(t *testing.T) {
t.Parallel()
_, err := f.SubaccountBalances(context.Background(), "")
if !errors.Is(err, errSubaccountNameMustBeSpecified) {
t.Errorf("expected %s, but received: %s", errSubaccountNameMustBeSpecified, err)
}
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err = f.SubaccountBalances(context.Background(), "non-existent")
if err == nil {
t.Error("expecting non-existent subaccount to return an error")
}
_, err = f.CreateSubaccount(context.Background(), "subzero")
if err != nil {
t.Fatal(err)
}
_, err = f.SubaccountBalances(context.Background(), "subzero")
if err != nil {
t.Error(err)
}
if err := f.DeleteSubaccount(context.Background(), "subzero"); err != nil {
t.Error(err)
}
}
func TestSubaccountTransfer(t *testing.T) {
tt := []struct {
Coin currency.Code
Source string
Destination string
Size float64
ErrExpected error
}{
{ErrExpected: errCoinMustBeSpecified},
{Coin: currency.BTC, ErrExpected: errSubaccountTransferSizeGreaterThanZero},
{Coin: currency.BTC, Size: 420, ErrExpected: errSubaccountTransferSourceDestinationMustNotBeEqual},
}
for x := range tt {
_, err := f.SubaccountTransfer(context.Background(),
tt[x].Coin, tt[x].Source, tt[x].Destination, tt[x].Size)
if !errors.Is(err, tt[x].ErrExpected) {
t.Errorf("expected %s, but received: %s", tt[x].ErrExpected, err)
}
}
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
_, err := f.SubaccountTransfer(context.Background(),
currency.BTC, "", "test", 0.1)
if err != nil {
t.Error(err)
}
}
func TestGetStakes(t *testing.T) {
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err := f.GetStakes(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetUnstakeRequests(t *testing.T) {
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err := f.GetUnstakeRequests(context.Background())
if err != nil {
t.Error(err)
}
}
func TestGetStakeBalances(t *testing.T) {
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err := f.GetStakeBalances(context.Background())
if err != nil {
t.Error(err)
}
}
func TestUnstakeRequest(t *testing.T) {
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
r, err := f.UnstakeRequest(context.Background(), currency.FTT, 0.1)
if err != nil {
t.Fatal(err)
}
success, err := f.CancelUnstakeRequest(context.Background(), r.ID)
if err != nil || !success {
t.Errorf("unable to cancel unstaking request: %s", err)
}
}
func TestCancelUnstakeRequest(t *testing.T) {
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
_, err := f.CancelUnstakeRequest(context.Background(), 74351)
if err != nil {
t.Error(err)
}
}
func TestGetStakingRewards(t *testing.T) {
if !areTestAPIKeysSet() {
t.Skip("skipping test, api keys not set")
}
_, err := f.GetStakingRewards(context.Background())
if err != nil {
t.Error(err)
}
}
func TestStakeRequest(t *testing.T) {
if !areTestAPIKeysSet() || !canManipulateRealOrders {
t.Skip("skipping test, either api keys or canManipulateRealOrders isn't set")
}
// WARNING: This will lock up your funds for 14 days
_, err := f.StakeRequest(context.Background(), currency.FTT, 0.1)
if err != nil {
t.Error(err)
}
}
func TestUpdateOrderExecutionLimits(t *testing.T) {
err := f.UpdateOrderExecutionLimits(context.Background(), "")
if err != nil {
t.Fatal(err)
}
cp := currency.NewPair(currency.BTC, currency.USD)
limit, err := f.GetOrderExecutionLimits(asset.Spot, cp)
if err != nil {
t.Fatal(err)
}
err = limit.Conforms(33000, 0.00001, order.Limit)
if !errors.Is(err, order.ErrAmountBelowMin) {
t.Fatalf("expected error %v but received %v",
order.ErrAmountBelowMin,
err)
}
err = limit.Conforms(33000, 0.0001, order.Limit)
if !errors.Is(err, nil) {
t.Fatalf("expected error %v but received %v",
nil,
err)
}
} | "limit",
false, false, false,
"", 0.0001, 500)
if err != nil { |
kubectl_test.go | package segments
import (
"fmt"
"io/ioutil"
"oh-my-posh/environment"
"oh-my-posh/mock"
"oh-my-posh/properties"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
const testKubectlAllInfoTemplate = "{{.Context}} :: {{.Namespace}} :: {{.User}} :: {{.Cluster}}"
func TestKubectlSegment(t *testing.T) |
var testKubeConfigFiles = map[string]string{
filepath.Join("testhome", ".kube/config"): `
apiVersion: v1
contexts:
- context:
cluster: ddd
user: ccc
namespace: bbb
name: aaa
current-context: aaa
`,
"contextdefinition": `
apiVersion: v1
contexts:
- context:
cluster: cl
user: usr
namespace: ns
name: ctx
`,
"currentcontextmarker": `
apiVersion: v1
current-context: ctx
`,
"invalid": "this is not yaml",
"contextdefinitionincomplete": `
apiVersion: v1
contexts:
- name: ctx
`,
"contextredefinition": `
apiVersion: v1
contexts:
- context:
cluster: wrongcl
user: wrongu
namespace: wrongns
name: ctx
`,
}
| {
standardTemplate := "{{.Context}}{{if .Namespace}} :: {{.Namespace}}{{end}}"
lsep := string(filepath.ListSeparator)
cases := []struct {
Case string
Template string
DisplayError bool
KubectlExists bool
Kubeconfig string
ParseKubeConfig bool
Context string
Namespace string
UserName string
Cluster string
KubectlErr bool
ExpectedEnabled bool
ExpectedString string
Files map[string]string
}{
{
Case: "kubeconfig incomplete",
Template: testKubectlAllInfoTemplate,
ParseKubeConfig: true,
Kubeconfig: "currentcontextmarker" + lsep + "contextdefinitionincomplete",
Files: testKubeConfigFiles,
ExpectedString: "ctx :: :: ::",
ExpectedEnabled: true,
},
{Case: "disabled", Template: standardTemplate, KubectlExists: false, Context: "aaa", Namespace: "bbb", ExpectedEnabled: false},
{
Case: "all information",
Template: testKubectlAllInfoTemplate,
KubectlExists: true,
Context: "aaa",
Namespace: "bbb",
UserName: "ccc",
Cluster: "ddd",
ExpectedString: "aaa :: bbb :: ccc :: ddd",
ExpectedEnabled: true,
},
{Case: "no namespace", Template: standardTemplate, KubectlExists: true, Context: "aaa", ExpectedString: "aaa", ExpectedEnabled: true},
{
Case: "kubectl error",
Template: standardTemplate,
DisplayError: true,
KubectlExists: true,
Context: "aaa",
Namespace: "bbb",
KubectlErr: true,
ExpectedString: "KUBECTL ERR :: KUBECTL ERR",
ExpectedEnabled: true,
},
{Case: "kubectl error hidden", Template: standardTemplate, DisplayError: false, KubectlExists: true, Context: "aaa", Namespace: "bbb", KubectlErr: true, ExpectedEnabled: false},
{
Case: "kubeconfig home",
Template: testKubectlAllInfoTemplate,
ParseKubeConfig: true,
Files: testKubeConfigFiles,
ExpectedString: "aaa :: bbb :: ccc :: ddd",
ExpectedEnabled: true,
},
{
Case: "kubeconfig multiple current marker first",
Template: testKubectlAllInfoTemplate,
ParseKubeConfig: true,
Kubeconfig: "" + lsep + "currentcontextmarker" + lsep + "contextdefinition" + lsep + "contextredefinition",
Files: testKubeConfigFiles,
ExpectedString: "ctx :: ns :: usr :: cl",
ExpectedEnabled: true,
},
{
Case: "kubeconfig multiple context first",
Template: testKubectlAllInfoTemplate, ParseKubeConfig: true,
Kubeconfig: "contextdefinition" + lsep + "contextredefinition" + lsep + "currentcontextmarker" + lsep,
Files: testKubeConfigFiles,
ExpectedString: "ctx :: ns :: usr :: cl",
ExpectedEnabled: true,
},
{
Case: "kubeconfig error hidden", Template: testKubectlAllInfoTemplate, ParseKubeConfig: true, Kubeconfig: "invalid", Files: testKubeConfigFiles, ExpectedEnabled: false},
{
Case: "kubeconfig error",
Template: testKubectlAllInfoTemplate,
ParseKubeConfig: true,
Kubeconfig: "invalid",
Files: testKubeConfigFiles,
DisplayError: true,
ExpectedString: "KUBECONFIG ERR :: KUBECONFIG ERR :: KUBECONFIG ERR :: KUBECONFIG ERR",
ExpectedEnabled: true,
},
}
for _, tc := range cases {
env := new(mock.MockedEnvironment)
env.On("HasCommand", "kubectl").Return(tc.KubectlExists)
var kubeconfig string
content, err := ioutil.ReadFile("../test/kubectl.yml")
if err == nil {
kubeconfig = fmt.Sprintf(string(content), tc.Cluster, tc.UserName, tc.Namespace, tc.Context)
}
var kubectlErr error
if tc.KubectlErr {
kubectlErr = &environment.CommandError{
Err: "oops",
ExitCode: 1,
}
}
env.On("RunCommand", "kubectl", []string{"config", "view", "--output", "yaml", "--minify"}).Return(kubeconfig, kubectlErr)
env.On("Getenv", "KUBECONFIG").Return(tc.Kubeconfig)
for path, content := range tc.Files {
env.On("FileContent", path).Return(content)
}
env.On("Home").Return("testhome")
k := &Kubectl{
env: env,
props: properties.Map{
properties.DisplayError: tc.DisplayError,
ParseKubeConfig: tc.ParseKubeConfig,
},
}
assert.Equal(t, tc.ExpectedEnabled, k.Enabled(), tc.Case)
if tc.ExpectedEnabled {
assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, k), tc.Case)
}
}
} |
missing_type.d.ts | declare namespace ಠ_ಠ.clutz.module$exports$missing$type {
var x : ಠ_ಠ.clutz.Missing ;
var xWithGenerics : ಠ_ಠ.clutz.goog.missing.map < string , number > ;
var xWithMissingGenerics : ಠ_ಠ.clutz.goog.missing.map < ಠ_ಠ.clutz.mod.ref.A , ಠ_ಠ.clutz.mod.ref.B < ಠ_ಠ.clutz.mod.ref.C > > ;
}
declare module 'goog:missing.type' {
import alias = ಠ_ಠ.clutz.module$exports$missing$type;
export = alias;
} | ||
predictor.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import os
import subprocess
import seedot.config as config
import seedot.util as Util
# Program to build and run the predictor project using msbuild
# The accuracy and other statistics are written to the output file specified
class Predictor:
def | (self, algo, version, datasetType, outputDir, scaleForX):
self.algo, self.version, self.datasetType = algo, version, datasetType
self.outputDir = outputDir
os.makedirs(self.outputDir, exist_ok=True)
self.scaleForX = scaleForX
self.genHeaderFile()
def genHeaderFile(self):
with open("datatypes.h", 'w') as file:
file.write("#pragma once\n\n")
if config.wordLength == 8:
file.write("#define INT8\n")
file.write("typedef int8_t MYINT;\n\n")
elif config.wordLength == 16:
file.write("#define INT16\n")
file.write("typedef int16_t MYINT;\n\n")
elif config.wordLength == 32:
file.write("#define INT32\n")
file.write("typedef int32_t MYINT;\n\n")
file.write("typedef int16_t MYITE;\n")
file.write("typedef uint16_t MYUINT;\n\n")
file.write("const int scaleForX = %d;\n\n" % (self.scaleForX))
if Util.debugMode():
file.write("const bool debugMode = true;\n")
else:
file.write("const bool debugMode = false;\n")
def buildForWindows(self):
'''
Builds using the Predictor.vcxproj project file and creates the executable
The target platform is currently set to x64
'''
print("Build...", end='')
projFile = "Predictor.vcxproj"
args = [config.msbuildPath, projFile, r"/t:Build",
r"/p:Configuration=Release", r"/p:Platform=x64"]
logFile = os.path.join(self.outputDir, "msbuild.txt")
with open(logFile, 'w') as file:
process = subprocess.call(args, stdout=file, stderr=subprocess.STDOUT)
if process == 1:
print("FAILED!!\n")
return False
else:
print("success")
return True
def buildForLinux(self):
print("Build...", end='')
args = ["make"]
logFile = os.path.join(self.outputDir, "build.txt")
with open(logFile, 'w') as file:
process = subprocess.call(args, stdout=file, stderr=subprocess.STDOUT)
if process == 1:
print("FAILED!!\n")
return False
else:
print("success")
return True
def build(self):
if Util.windows():
return self.buildForWindows()
else:
return self.buildForLinux()
def executeForWindows(self):
'''
Invokes the executable with arguments
'''
print("Execution...", end='')
exeFile = os.path.join("x64", "Release", "Predictor.exe")
args = [exeFile, self.version, self.datasetType]
logFile = os.path.join(self.outputDir, "exec.txt")
with open(logFile, 'w') as file:
process = subprocess.call(args, stdout=file, stderr=subprocess.STDOUT)
if process == 1:
print("FAILED!!\n")
return None
else:
print("success")
acc = self.readStatsFile()
return acc
def executeForLinux(self):
print("Execution...", end='')
exeFile = os.path.join("./Predictor")
args = [exeFile, self.version, self.datasetType]
logFile = os.path.join(self.outputDir, "exec.txt")
with open(logFile, 'w') as file:
process = subprocess.call(args, stdout=file, stderr=subprocess.STDOUT)
if process == 1:
print("FAILED!!\n")
return None
else:
print("success")
acc = self.readStatsFile()
return acc
def execute(self):
if Util.windows():
return self.executeForWindows()
else:
return self.executeForLinux()
# Read statistics of execution (currently only accuracy)
def readStatsFile(self):
statsFile = os.path.join(
"output", self.version, "stats-" + self.datasetType + ".txt")
with open(statsFile, 'r') as file:
content = file.readlines()
stats = [x.strip() for x in content]
return float(stats[0])
def run(self):
res = self.build()
if res == False:
return None
acc = self.execute()
return acc
| __init__ |
sql.go | package pkg
import (
"context"
"database/sql"
"fmt"
"github.com/slamdev/databaser/pkg/clickhouse"
"github.com/slamdev/databaser/pkg/postgres"
"net/url"
)
func CreatePostgresSqlConnection(ctx context.Context, params postgres.Params) (*sql.DB, error) {
d, u := postgres.DSN(params)
return createSqlConnection(ctx, d, u)
}
func CreateClickhouseSqlConnection(ctx context.Context, params clickhouse.Params) (*sql.DB, error) {
d, u := clickhouse.DSN(params)
return createSqlConnection(ctx, d, u)
}
func createSqlConnection(ctx context.Context, driver string, dsn url.URL) (*sql.DB, error) {
c, err := sql.Open(driver, dsn.String())
if err != nil |
if err := c.PingContext(ctx); err != nil {
return nil, fmt.Errorf("failde to ping connection; %w", err)
}
return c, nil
}
| {
return nil, fmt.Errorf("failed to connect to instance; %w", err)
} |
issue-4736.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct NonCopyable(());
fn main() | {
let z = NonCopyable{ p: () }; //~ ERROR structure has no field named `p`
} |
|
lib.rs | //! A terminal backend implementation for [Zi](https://docs.rs/zi) using
//! [crossterm](https://docs.rs/crossterm)
mod error;
mod painter;
mod utils;
pub use self::error::{Error, Result};
use crossterm::{self, queue, QueueableCommand};
use futures::stream::{Stream, StreamExt};
use std::{
io::{self, BufWriter, Stdout, Write},
pin::Pin,
time::{Duration, Instant},
};
use tokio::{
self,
runtime::{Builder as RuntimeBuilder, Runtime},
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
};
use self::{
painter::{FullPainter, IncrementalPainter, PaintOperation, Painter},
utils::MeteredWriter,
};
use zi::{
app::{App, ComponentMessage, MessageSender},
terminal::{Canvas, Colour, Key, Size, Style},
Layout,
};
/// Creates a new backend with an incremental painter. It only draws those
/// parts of the terminal that have changed since last drawn.
///
/// ```no_run
/// # use zi::prelude::*;
/// # use zi::components::text::{Text, TextProperties};
/// fn main() -> zi_term::Result<()> {
/// zi_term::incremental()?
/// .run_event_loop(Text::with(TextProperties::new().content("Hello, world!")))
/// }
/// ```
pub fn incremental() -> Result<Crossterm<IncrementalPainter>> {
Crossterm::<IncrementalPainter>::new()
}
/// Creates a new backend with a full painter. It redraws the whole canvas on
/// every canvas.
///
/// ```no_run
/// # use zi::prelude::*;
/// # use zi::components::text::{Text, TextProperties};
/// fn main() -> zi_term::Result<()> {
/// zi_term::full()?
/// .run_event_loop(Text::with(TextProperties::new().content("Hello, world!")))
/// }
/// ```
pub fn full() -> Result<Crossterm<FullPainter>> {
Crossterm::<FullPainter>::new()
}
/// A terminal backend implementation for [Zi](https://docs.rs/zi) using
/// [crossterm](https://docs.rs/crossterm)
///
/// ```no_run
/// # use zi::prelude::*;
/// # use zi::components::text::{Text, TextProperties};
/// fn main() -> zi_term::Result<()> {
/// zi_term::incremental()?
/// .run_event_loop(Text::with(TextProperties::new().content("Hello, world!")))
/// }
/// ```
pub struct Crossterm<PainterT: Painter = IncrementalPainter> {
target: MeteredWriter<BufWriter<Stdout>>,
painter: PainterT,
events: Option<EventStream>,
link: LinkChannel,
}
impl<PainterT: Painter> Crossterm<PainterT> {
/// Create a new backend instance.
///
/// This method initialises the underlying tty device, enables raw mode,
/// hides the cursor and enters alternative screen mode. Additionally, an
/// async event stream with input events from stdin is started.
pub fn new() -> Result<Self> {
let mut backend = Self {
target: MeteredWriter::new(BufWriter::with_capacity(1 << 20, io::stdout())),
painter: PainterT::create(
crossterm::terminal::size()
.map(|(width, height)| Size::new(width as usize, height as usize))?,
),
events: Some(new_event_stream()),
link: LinkChannel::new(),
};
initialise_tty::<PainterT, _>(&mut backend.target)?;
Ok(backend)
}
/// Starts the event loop. This is the main entry point of a Zi application.
/// It draws and presents the components to the backend, handles user input
/// and delivers messages to components. This method returns either when
/// prompted using the [`exit`](struct.ComponentLink.html#method.exit)
/// method on [`ComponentLink`](struct.ComponentLink.html) or on error.
///
/// ```no_run
/// # use zi::prelude::*;
/// # use zi::components::text::{Text, TextProperties};
/// fn main() -> zi_term::Result<()> {
/// zi_term::incremental()?
/// .run_event_loop(Text::with(TextProperties::new().content("Hello, world!")))
/// }
/// ```
pub fn run_event_loop(&mut self, layout: Layout) -> Result<()> {
let mut tokio_runtime = RuntimeBuilder::new_current_thread().enable_all().build()?;
let mut app = App::new(
UnboundedMessageSender(self.link.sender.clone()),
self.size()?,
layout,
);
loop {
let canvas = app.draw();
let last_drawn = Instant::now();
let num_bytes_presented = self.present(canvas)?;
let presented_time = last_drawn.elapsed();
// log::debug!(
// "Frame {}: {} comps [{}] draw {:.1}ms pres {:.1}ms diff {}b",
// self.runtime.num_frame,
// self.components.len(),
// statistics,
// drawn_time.as_secs_f64() * 1000.0,
// presented_time.as_secs_f64() * 1000.0,
// num_bytes_presented,
// );
log::debug!(
"Frame: pres {:.1}ms diff {}b",
presented_time.as_secs_f64() * 1000.0,
num_bytes_presented,
);
self.poll_events_batch(&mut tokio_runtime, &mut app, last_drawn)?;
}
}
/// Suspends the event stream.
///
/// This is used when running something that needs exclusive access to the underlying
/// terminal (i.e. to stdin and stdout). For example spawning an external editor to collect
/// or display text. The `resume` function is called upon returning to the application.
#[inline]
pub fn suspend(&mut self) -> Result<()> {
self.events = None;
Ok(())
}
/// Recreates the event stream and reinitialises the underlying terminal.
///
/// This function is used to return execution to the application after running something
/// that needs exclusive access to the underlying backend. It will only be called after a
/// call to `suspend`.
///
/// In addition to restarting the event stream, this function should perform any other
/// required initialisation of the backend. For ANSI terminals, this typically hides the
/// cursor and saves the current screen content (i.e. "alternative screen mode") in order
/// to restore the previous terminal content on exit.
#[inline]
pub fn resume(&mut self) -> Result<()> {
self.painter = PainterT::create(self.size()?);
self.events = Some(new_event_stream());
initialise_tty::<PainterT, _>(&mut self.target)
}
/// Poll as many events as we can respecting REDRAW_LATENCY and REDRAW_LATENCY_SUSTAINED_IO
#[inline]
fn poll_events_batch(
&mut self,
runtime: &mut Runtime,
app: &mut App,
last_drawn: Instant,
) -> Result<()> {
let Self {
ref mut link,
ref mut events,
..
} = *self;
let mut force_redraw = false;
let mut first_event_time: Option<Instant> = None;
while !force_redraw && !app.poll_state().exit() {
let timeout_duration = {
let since_last_drawn = last_drawn.elapsed();
if app.poll_state().dirty() && since_last_drawn >= REDRAW_LATENCY {
Duration::from_millis(0)
} else if app.poll_state().dirty() {
REDRAW_LATENCY - since_last_drawn
} else {
Duration::from_millis(if app.is_tickable() { 60 } else { 240 })
}
};
(runtime.block_on(async {
tokio::select! {
link_message = link.receiver.recv() => {
app.handle_message(
link_message.expect("at least one sender exists"),
);
Ok(())
}
input_event = events.as_mut().expect("backend events are suspended").next() => {
match input_event.expect(
"at least one sender exists",
)? {
FilteredEvent::Input(input_event) => app.handle_input(input_event),
FilteredEvent::Resize(size) => app.handle_resize(size),
};
force_redraw = app.poll_state().dirty()
&& (first_event_time.get_or_insert_with(Instant::now).elapsed()
>= SUSTAINED_IO_REDRAW_LATENCY
|| app.poll_state().resized());
Ok(())
}
_ = tokio::time::sleep(timeout_duration) => {
// app.tick();
force_redraw = true;
Ok(())
}
}
}) as Result<()>)?;
}
Ok(())
}
/// Returns the size of the underlying terminal.
#[inline]
fn size(&self) -> Result<Size> {
Ok(crossterm::terminal::size()
.map(|(width, height)| Size::new(width as usize, height as usize))?)
}
/// Draws the [`Canvas`](../terminal/struct.Canvas.html) to the terminal.
#[inline]
fn present(&mut self, canvas: &Canvas) -> Result<usize> {
let Self {
ref mut target,
ref mut painter,
..
} = *self;
let initial_num_bytes_written = target.num_bytes_written();
painter.paint(canvas, |operation| {
match operation {
PaintOperation::WriteContent(grapheme) => {
queue!(target, crossterm::style::Print(grapheme))?
}
PaintOperation::SetStyle(style) => queue_set_style(target, style)?,
PaintOperation::MoveTo(position) => queue!(
target,
crossterm::cursor::MoveTo(position.x as u16, position.y as u16)
)?, // Go to the begining of line (`MoveTo` uses 0-based indexing)
}
Ok(())
})?;
target.flush()?;
Ok(target.num_bytes_written() - initial_num_bytes_written)
}
}
impl<PainterT: Painter> Drop for Crossterm<PainterT> {
fn drop(&mut self) {
queue!(
self.target,
crossterm::style::ResetColor,
crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
crossterm::cursor::Show,
crossterm::terminal::LeaveAlternateScreen
)
.expect("Failed to clear screen when closing `crossterm` backend.");
crossterm::terminal::disable_raw_mode()
.expect("Failed to disable raw mode when closing `crossterm` backend.");
}
}
const REDRAW_LATENCY: Duration = Duration::from_millis(10);
const SUSTAINED_IO_REDRAW_LATENCY: Duration = Duration::from_millis(100);
struct LinkChannel {
sender: UnboundedSender<ComponentMessage>,
receiver: UnboundedReceiver<ComponentMessage>,
}
impl LinkChannel {
fn new() -> Self {
let (sender, receiver) = mpsc::unbounded_channel();
Self { sender, receiver }
}
}
#[derive(Debug, Clone)]
struct UnboundedMessageSender(UnboundedSender<ComponentMessage>);
impl MessageSender for UnboundedMessageSender {
fn send(&self, message: ComponentMessage) {
self.0
.send(message)
.map_err(|_| ()) // tokio's SendError doesn't implement Debug
.expect("App receiver needs to outlive senders for inter-component messages");
}
fn clone_box(&self) -> Box<dyn MessageSender> {
Box::new(self.clone())
}
}
#[inline]
fn initialise_tty<PainterT: Painter, TargetT: Write>(target: &mut TargetT) -> Result<()> {
target
.queue(crossterm::terminal::EnterAlternateScreen)?
.queue(crossterm::cursor::Hide)?;
crossterm::terminal::enable_raw_mode()?;
queue_set_style(target, &PainterT::INITIAL_STYLE)?;
target.flush()?;
Ok(())
}
#[inline]
fn queue_set_style(target: &mut impl Write, style: &Style) -> Result<()> {
use crossterm::style::{
Attribute, Color, SetAttribute, SetBackgroundColor, SetForegroundColor,
};
// Bold
if style.bold {
queue!(target, SetAttribute(Attribute::Bold))?;
} else {
// Using Reset is not ideal as it resets all style attributes. The correct thing to do
// would be to use `NoBold`, but it seems this is not reliably supported (at least it
// didn't work for me in tmux, although it does in alacritty).
// Also see https://github.com/crossterm-rs/crossterm/issues/294
queue!(target, SetAttribute(Attribute::Reset))?;
}
// Underline
if style.underline {
queue!(target, SetAttribute(Attribute::Underlined))?;
} else {
queue!(target, SetAttribute(Attribute::NoUnderline))?;
}
// Background
{
let Colour { red, green, blue } = style.background;
queue!(
target,
SetBackgroundColor(Color::Rgb {
r: red,
g: green,
b: blue
})
)?;
}
// Foreground
{
let Colour { red, green, blue } = style.foreground;
queue!(
target,
SetForegroundColor(Color::Rgb {
r: red,
g: green,
b: blue
})
)?;
}
Ok(())
}
enum FilteredEvent {
Input(zi::terminal::Event),
Resize(Size),
}
type EventStream = Pin<Box<dyn Stream<Item = Result<FilteredEvent>> + Send + 'static>>;
#[inline]
fn new_event_stream() -> EventStream {
Box::pin(
crossterm::event::EventStream::new()
.filter_map(|event| async move {
match event {
Ok(crossterm::event::Event::Key(key_event)) => Some(Ok(FilteredEvent::Input(
zi::terminal::Event::KeyPress(map_key(key_event)),
))),
Ok(crossterm::event::Event::Resize(width, height)) => Some(Ok(
FilteredEvent::Resize(Size::new(width as usize, height as usize)),
)),
Ok(_) => None,
Err(error) => Some(Err(error.into())),
}
})
.fuse(),
)
}
#[inline]
fn map_key(key: crossterm::event::KeyEvent) -> Key | {
use crossterm::event::{KeyCode, KeyModifiers};
match key.code {
KeyCode::Backspace => Key::Backspace,
KeyCode::Left => Key::Left,
KeyCode::Right => Key::Right,
KeyCode::Up => Key::Up,
KeyCode::Down => Key::Down,
KeyCode::Home => Key::Home,
KeyCode::End => Key::End,
KeyCode::PageUp => Key::PageUp,
KeyCode::PageDown => Key::PageDown,
KeyCode::BackTab => Key::BackTab,
KeyCode::Delete => Key::Delete,
KeyCode::Insert => Key::Insert,
KeyCode::F(u8) => Key::F(u8),
KeyCode::Null => Key::Null,
KeyCode::Esc => Key::Esc,
KeyCode::Char(char) if key.modifiers.contains(KeyModifiers::CONTROL) => Key::Ctrl(char),
KeyCode::Char(char) if key.modifiers.contains(KeyModifiers::ALT) => Key::Alt(char),
KeyCode::Char(char) => Key::Char(char),
KeyCode::Enter => Key::Char('\n'),
KeyCode::Tab => Key::Char('\t'),
}
} |
|
udp.rs | use std::io::Result;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use std::collections::HashMap;
use log::{debug, info, error};
use tokio::net::UdpSocket;
use crate::utils::DEFAULT_BUF_SIZE;
use crate::utils::{Ref, RemoteAddr, ConnectOpts};
use crate::utils::timeoutfut;
use crate::utils::socket;
// client <--> allocated socket
type SockMap = RwLock<HashMap<SocketAddr, Arc<UdpSocket>>>;
const BUF_SIZE: usize = DEFAULT_BUF_SIZE;
pub fn new_sock_map() -> SockMap {
RwLock::new(HashMap::new())
}
pub async fn associate_and_relay(
sock_map: &SockMap,
listen_sock: &UdpSocket,
remote_addr: &RemoteAddr,
conn_opts: Ref<ConnectOpts>,
) -> Result<()> {
let timeout = conn_opts.udp_timeout;
let mut buf = vec![0u8; BUF_SIZE];
loop {
let (n, client_addr) = listen_sock.recv_from(&mut buf).await?;
debug!("[udp]recvfrom client {}", &client_addr);
let remote_addr = remote_addr.to_sockaddr().await?;
// get the socket associated with a unique client
let alloc_sock = match find_socket(sock_map, &client_addr) {
Some(x) => x,
None => {
info!("[udp]{} => {}", &client_addr, &remote_addr);
let socket = socket::new_socket(
socket::Type::DGRAM,
&remote_addr,
&conn_opts,
)?;
// from_std panics only when tokio runtime not setup
let new_sock =
Arc::new(UdpSocket::from_std(socket.into()).unwrap());
tokio::spawn(send_back(
sock_map.into(),
client_addr,
listen_sock.into(),
new_sock.clone(),
timeout,
));
insert_socket(sock_map, client_addr, new_sock.clone());
new_sock
}
};
alloc_sock.send_to(&buf[..n], &remote_addr).await?;
}
}
async fn send_back(
sock_map: Ref<SockMap>,
client_addr: SocketAddr,
listen_sock: Ref<UdpSocket>,
alloc_sock: Arc<UdpSocket>,
timeout: usize,
) {
let mut buf = vec![0u8; BUF_SIZE];
loop {
let res =
match timeoutfut(alloc_sock.recv_from(&mut buf), timeout).await {
Ok(x) => x,
Err(_) => {
debug!("[udp]association for {} timeout", &client_addr);
break;
}
};
let (n, remote_addr) = match res {
Ok(x) => x,
Err(e) => {
error!("[udp]failed to recvfrom remote: {}", e);
continue;
}
};
debug!("[udp]recvfrom remote {}", &remote_addr);
if let Err(e) = listen_sock.send_to(&buf[..n], &client_addr).await {
error!("[udp]failed to sendto client{}: {}", &client_addr, e);
continue;
}
}
sock_map.write().unwrap().remove(&client_addr); |
#[inline]
fn find_socket(
sock_map: &SockMap,
client_addr: &SocketAddr,
) -> Option<Arc<UdpSocket>> {
// fetch the lock
let alloc_sock = sock_map.read().unwrap();
alloc_sock.get(client_addr).cloned()
// drop the lock
}
#[inline]
fn insert_socket(
sock_map: &SockMap,
client_addr: SocketAddr,
new_sock: Arc<UdpSocket>,
) {
// fetch the lock
sock_map.write().unwrap().insert(client_addr, new_sock);
// drop the lock
} | debug!("[udp]remove association for {}", &client_addr);
} |
models.rs | #![doc = "generated by AutoRust"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[doc = "Profile for enabling a user to access a managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AccessProfile {
#[doc = "Base64-encoded Kubernetes configuration file."]
#[serde(rename = "kubeConfig", default, skip_serializing_if = "Option::is_none")]
pub kube_config: Option<String>,
}
impl AccessProfile {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Agent Pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AgentPool {
#[serde(flatten)]
pub sub_resource: SubResource,
#[doc = "Properties for the container service agent pool profile."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ManagedClusterAgentPoolProfileProperties>,
}
impl AgentPool {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The list of available versions for an agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentPoolAvailableVersions {
#[doc = "Id of the agent pool available versions."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Name of the agent pool available versions."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Type of the agent pool available versions."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "The list of available agent pool versions."]
pub properties: AgentPoolAvailableVersionsProperties,
}
impl AgentPoolAvailableVersions {
pub fn new(properties: AgentPoolAvailableVersionsProperties) -> Self {
Self {
id: None,
name: None,
type_: None,
properties,
}
}
}
#[doc = "The list of available agent pool versions."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AgentPoolAvailableVersionsProperties {
#[doc = "List of versions available for agent pool."]
#[serde(rename = "agentPoolVersions", default, skip_serializing_if = "Vec::is_empty")]
pub agent_pool_versions: Vec<serde_json::Value>,
}
impl AgentPoolAvailableVersionsProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The response from the List Agent Pools operation."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AgentPoolListResult {
#[doc = "The list of agent pools."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<AgentPool>,
#[doc = "The URL to get the next set of agent pool results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl AgentPoolListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "AgentPoolMode represents mode of an agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AgentPoolMode {
System,
User,
}
#[doc = "AgentPoolType represents types of an agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AgentPoolType {
VirtualMachineScaleSets,
AvailabilitySet,
}
#[doc = "The list of available upgrades for an agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentPoolUpgradeProfile {
#[doc = "Id of the agent pool upgrade profile."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Name of the agent pool upgrade profile."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Type of the agent pool upgrade profile."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "The list of available upgrade versions."]
pub properties: AgentPoolUpgradeProfileProperties,
}
impl AgentPoolUpgradeProfile {
pub fn new(properties: AgentPoolUpgradeProfileProperties) -> Self {
Self {
id: None,
name: None,
type_: None,
properties,
}
}
}
#[doc = "The list of available upgrade versions."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentPoolUpgradeProfileProperties {
#[doc = "Kubernetes version (major, minor, patch)."]
#[serde(rename = "kubernetesVersion")]
pub kubernetes_version: String,
#[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."]
#[serde(rename = "osType")]
pub os_type: OsType,
#[doc = "List of orchestrator types and versions available for upgrade."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub upgrades: Vec<serde_json::Value>,
#[doc = "LatestNodeImageVersion is the latest AKS supported node image version."]
#[serde(rename = "latestNodeImageVersion", default, skip_serializing_if = "Option::is_none")]
pub latest_node_image_version: Option<String>,
}
impl AgentPoolUpgradeProfileProperties {
pub fn new(kubernetes_version: String, os_type: OsType) -> Self {
Self {
kubernetes_version,
os_type,
upgrades: Vec::new(),
latest_node_image_version: None,
}
}
}
#[doc = "Settings for upgrading an agentpool"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AgentPoolUpgradeSettings {
#[doc = "Count or percentage of additional nodes to be added during upgrade. If empty uses AKS default"]
#[serde(rename = "maxSurge", default, skip_serializing_if = "Option::is_none")]
pub max_surge: Option<String>,
}
impl AgentPoolUpgradeSettings {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An error response from the Container service."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CloudError {
#[doc = "An error response from the Container service."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudErrorBody>,
}
impl CloudError {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "An error response from the Container service."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CloudErrorBody {
#[doc = "An identifier for the error. Codes are invariant and are intended to be consumed programmatically."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[doc = "A message describing the error, intended to be suitable for display in a user interface."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[doc = "The target of the particular error. For example, the name of the property in error."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[doc = "A list of additional details about the error."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<CloudErrorBody>,
}
impl CloudErrorBody {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Profile for diagnostics on the container service cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceDiagnosticsProfile {
#[doc = "Profile for diagnostics on the container service VMs."]
#[serde(rename = "vmDiagnostics")]
pub vm_diagnostics: ContainerServiceVmDiagnostics,
}
impl ContainerServiceDiagnosticsProfile {
pub fn new(vm_diagnostics: ContainerServiceVmDiagnostics) -> Self {
Self { vm_diagnostics }
}
}
#[doc = "Profile for Linux VMs in the container service cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceLinuxProfile {
#[doc = "The administrator username to use for Linux VMs."]
#[serde(rename = "adminUsername")]
pub admin_username: String,
#[doc = "SSH configuration for Linux-based VMs running on Azure."]
pub ssh: ContainerServiceSshConfiguration,
}
impl ContainerServiceLinuxProfile {
pub fn new(admin_username: String, ssh: ContainerServiceSshConfiguration) -> Self {
Self { admin_username, ssh }
}
}
#[doc = "Profile for the container service master."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceMasterProfile {
#[doc = "Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<container_service_master_profile::Count>,
#[doc = "DNS prefix to be used to create the FQDN for the master pool."]
#[serde(rename = "dnsPrefix")]
pub dns_prefix: String,
#[doc = "Size of agent VMs."]
#[serde(rename = "vmSize")]
pub vm_size: ContainerServiceVmSize,
#[doc = "OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified."]
#[serde(rename = "osDiskSizeGB", default, skip_serializing_if = "Option::is_none")]
pub os_disk_size_gb: Option<ContainerServiceOsDisk>,
#[doc = "specifies a subnet's resource id with subscription, resource group, vnet and subnet name"]
#[serde(rename = "vnetSubnetID", default, skip_serializing_if = "Option::is_none")]
pub vnet_subnet_id: Option<ContainerServiceVnetSubnetId>,
#[doc = "FirstConsecutiveStaticIP used to specify the first static ip of masters."]
#[serde(rename = "firstConsecutiveStaticIP", default, skip_serializing_if = "Option::is_none")]
pub first_consecutive_static_ip: Option<String>,
#[doc = "Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice."]
#[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")]
pub storage_profile: Option<ContainerServiceStorageProfile>,
#[doc = "FQDN for the master pool."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fqdn: Option<String>,
}
impl ContainerServiceMasterProfile {
pub fn new(dns_prefix: String, vm_size: ContainerServiceVmSize) -> Self {
Self {
count: None,
dns_prefix,
vm_size,
os_disk_size_gb: None,
vnet_subnet_id: None,
first_consecutive_static_ip: None,
storage_profile: None,
fqdn: None,
}
}
}
pub mod container_service_master_profile {
use super::*;
#[doc = "Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Count {}
}
#[doc = "Profile of network configuration."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ContainerServiceNetworkProfile {
#[doc = "Network plugin used for building Kubernetes network."]
#[serde(rename = "networkPlugin", default, skip_serializing_if = "Option::is_none")]
pub network_plugin: Option<container_service_network_profile::NetworkPlugin>,
#[doc = "Network policy used for building Kubernetes network."]
#[serde(rename = "networkPolicy", default, skip_serializing_if = "Option::is_none")]
pub network_policy: Option<container_service_network_profile::NetworkPolicy>,
#[doc = "Network mode used for building Kubernetes network."]
#[serde(rename = "networkMode", default, skip_serializing_if = "Option::is_none")]
pub network_mode: Option<container_service_network_profile::NetworkMode>,
#[doc = "A CIDR notation IP range from which to assign pod IPs when kubenet is used."]
#[serde(rename = "podCidr", default, skip_serializing_if = "Option::is_none")]
pub pod_cidr: Option<String>,
#[doc = "A CIDR notation IP range from which to assign service cluster IPs. It must not overlap with any Subnet IP ranges."]
#[serde(rename = "serviceCidr", default, skip_serializing_if = "Option::is_none")]
pub service_cidr: Option<String>,
#[doc = "An IP address assigned to the Kubernetes DNS service. It must be within the Kubernetes service address range specified in serviceCidr."]
#[serde(rename = "dnsServiceIP", default, skip_serializing_if = "Option::is_none")]
pub dns_service_ip: Option<String>,
#[doc = "A CIDR notation IP range assigned to the Docker bridge network. It must not overlap with any Subnet IP ranges or the Kubernetes service address range."]
#[serde(rename = "dockerBridgeCidr", default, skip_serializing_if = "Option::is_none")]
pub docker_bridge_cidr: Option<String>,
#[doc = "The outbound (egress) routing method."]
#[serde(rename = "outboundType", default, skip_serializing_if = "Option::is_none")]
pub outbound_type: Option<container_service_network_profile::OutboundType>,
#[doc = "The load balancer sku for the managed cluster."]
#[serde(rename = "loadBalancerSku", default, skip_serializing_if = "Option::is_none")]
pub load_balancer_sku: Option<container_service_network_profile::LoadBalancerSku>,
#[doc = "Profile of the managed cluster load balancer."]
#[serde(rename = "loadBalancerProfile", default, skip_serializing_if = "Option::is_none")]
pub load_balancer_profile: Option<ManagedClusterLoadBalancerProfile>,
}
impl ContainerServiceNetworkProfile {
pub fn new() -> Self {
Self::default()
}
}
pub mod container_service_network_profile {
use super::*;
#[doc = "Network plugin used for building Kubernetes network."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkPlugin {
#[serde(rename = "azure")]
Azure,
#[serde(rename = "kubenet")]
Kubenet,
}
impl Default for NetworkPlugin {
fn default() -> Self {
Self::Kubenet
}
}
#[doc = "Network policy used for building Kubernetes network."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkPolicy {
#[serde(rename = "calico")]
Calico,
#[serde(rename = "azure")]
Azure,
}
#[doc = "Network mode used for building Kubernetes network."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NetworkMode {
#[serde(rename = "transparent")]
Transparent,
#[serde(rename = "bridge")]
Bridge,
}
#[doc = "The outbound (egress) routing method."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OutboundType { | LoadBalancer,
#[serde(rename = "userDefinedRouting")]
UserDefinedRouting,
}
impl Default for OutboundType {
fn default() -> Self {
Self::LoadBalancer
}
}
#[doc = "The load balancer sku for the managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LoadBalancerSku {
#[serde(rename = "standard")]
Standard,
#[serde(rename = "basic")]
Basic,
}
}
pub type ContainerServiceOsDisk = i32;
#[doc = "SSH configuration for Linux-based VMs running on Azure."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceSshConfiguration {
#[doc = "The list of SSH public keys used to authenticate with Linux-based VMs. Only expect one key specified."]
#[serde(rename = "publicKeys")]
pub public_keys: Vec<ContainerServiceSshPublicKey>,
}
impl ContainerServiceSshConfiguration {
pub fn new(public_keys: Vec<ContainerServiceSshPublicKey>) -> Self {
Self { public_keys }
}
}
#[doc = "Contains information about SSH certificate public key data."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceSshPublicKey {
#[doc = "Certificate public key used to authenticate with VMs through SSH. The certificate must be in PEM format with or without headers."]
#[serde(rename = "keyData")]
pub key_data: String,
}
impl ContainerServiceSshPublicKey {
pub fn new(key_data: String) -> Self {
Self { key_data }
}
}
#[doc = "Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ContainerServiceStorageProfile {
StorageAccount,
ManagedDisks,
}
#[doc = "Profile for diagnostics on the container service VMs."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerServiceVmDiagnostics {
#[doc = "Whether the VM diagnostic agent is provisioned on the VM."]
pub enabled: bool,
#[doc = "The URI of the storage account where diagnostics are stored."]
#[serde(rename = "storageUri", default, skip_serializing_if = "Option::is_none")]
pub storage_uri: Option<String>,
}
impl ContainerServiceVmDiagnostics {
pub fn new(enabled: bool) -> Self {
Self {
enabled,
storage_uri: None,
}
}
}
#[doc = "Size of agent VMs."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ContainerServiceVmSize {
#[serde(rename = "Standard_A1")]
StandardA1,
#[serde(rename = "Standard_A10")]
StandardA10,
#[serde(rename = "Standard_A11")]
StandardA11,
#[serde(rename = "Standard_A1_v2")]
StandardA1V2,
#[serde(rename = "Standard_A2")]
StandardA2,
#[serde(rename = "Standard_A2_v2")]
StandardA2V2,
#[serde(rename = "Standard_A2m_v2")]
StandardA2mV2,
#[serde(rename = "Standard_A3")]
StandardA3,
#[serde(rename = "Standard_A4")]
StandardA4,
#[serde(rename = "Standard_A4_v2")]
StandardA4V2,
#[serde(rename = "Standard_A4m_v2")]
StandardA4mV2,
#[serde(rename = "Standard_A5")]
StandardA5,
#[serde(rename = "Standard_A6")]
StandardA6,
#[serde(rename = "Standard_A7")]
StandardA7,
#[serde(rename = "Standard_A8")]
StandardA8,
#[serde(rename = "Standard_A8_v2")]
StandardA8V2,
#[serde(rename = "Standard_A8m_v2")]
StandardA8mV2,
#[serde(rename = "Standard_A9")]
StandardA9,
#[serde(rename = "Standard_B2ms")]
StandardB2ms,
#[serde(rename = "Standard_B2s")]
StandardB2s,
#[serde(rename = "Standard_B4ms")]
StandardB4ms,
#[serde(rename = "Standard_B8ms")]
StandardB8ms,
#[serde(rename = "Standard_D1")]
StandardD1,
#[serde(rename = "Standard_D11")]
StandardD11,
#[serde(rename = "Standard_D11_v2")]
StandardD11V2,
#[serde(rename = "Standard_D11_v2_Promo")]
StandardD11V2Promo,
#[serde(rename = "Standard_D12")]
StandardD12,
#[serde(rename = "Standard_D12_v2")]
StandardD12V2,
#[serde(rename = "Standard_D12_v2_Promo")]
StandardD12V2Promo,
#[serde(rename = "Standard_D13")]
StandardD13,
#[serde(rename = "Standard_D13_v2")]
StandardD13V2,
#[serde(rename = "Standard_D13_v2_Promo")]
StandardD13V2Promo,
#[serde(rename = "Standard_D14")]
StandardD14,
#[serde(rename = "Standard_D14_v2")]
StandardD14V2,
#[serde(rename = "Standard_D14_v2_Promo")]
StandardD14V2Promo,
#[serde(rename = "Standard_D15_v2")]
StandardD15V2,
#[serde(rename = "Standard_D16_v3")]
StandardD16V3,
#[serde(rename = "Standard_D16s_v3")]
StandardD16sV3,
#[serde(rename = "Standard_D1_v2")]
StandardD1V2,
#[serde(rename = "Standard_D2")]
StandardD2,
#[serde(rename = "Standard_D2_v2")]
StandardD2V2,
#[serde(rename = "Standard_D2_v2_Promo")]
StandardD2V2Promo,
#[serde(rename = "Standard_D2_v3")]
StandardD2V3,
#[serde(rename = "Standard_D2s_v3")]
StandardD2sV3,
#[serde(rename = "Standard_D3")]
StandardD3,
#[serde(rename = "Standard_D32_v3")]
StandardD32V3,
#[serde(rename = "Standard_D32s_v3")]
StandardD32sV3,
#[serde(rename = "Standard_D3_v2")]
StandardD3V2,
#[serde(rename = "Standard_D3_v2_Promo")]
StandardD3V2Promo,
#[serde(rename = "Standard_D4")]
StandardD4,
#[serde(rename = "Standard_D4_v2")]
StandardD4V2,
#[serde(rename = "Standard_D4_v2_Promo")]
StandardD4V2Promo,
#[serde(rename = "Standard_D4_v3")]
StandardD4V3,
#[serde(rename = "Standard_D4s_v3")]
StandardD4sV3,
#[serde(rename = "Standard_D5_v2")]
StandardD5V2,
#[serde(rename = "Standard_D5_v2_Promo")]
StandardD5V2Promo,
#[serde(rename = "Standard_D64_v3")]
StandardD64V3,
#[serde(rename = "Standard_D64s_v3")]
StandardD64sV3,
#[serde(rename = "Standard_D8_v3")]
StandardD8V3,
#[serde(rename = "Standard_D8s_v3")]
StandardD8sV3,
#[serde(rename = "Standard_DS1")]
StandardDs1,
#[serde(rename = "Standard_DS11")]
StandardDs11,
#[serde(rename = "Standard_DS11_v2")]
StandardDs11V2,
#[serde(rename = "Standard_DS11_v2_Promo")]
StandardDs11V2Promo,
#[serde(rename = "Standard_DS12")]
StandardDs12,
#[serde(rename = "Standard_DS12_v2")]
StandardDs12V2,
#[serde(rename = "Standard_DS12_v2_Promo")]
StandardDs12V2Promo,
#[serde(rename = "Standard_DS13")]
StandardDs13,
#[serde(rename = "Standard_DS13-2_v2")]
StandardDs132V2,
#[serde(rename = "Standard_DS13-4_v2")]
StandardDs134V2,
#[serde(rename = "Standard_DS13_v2")]
StandardDs13V2,
#[serde(rename = "Standard_DS13_v2_Promo")]
StandardDs13V2Promo,
#[serde(rename = "Standard_DS14")]
StandardDs14,
#[serde(rename = "Standard_DS14-4_v2")]
StandardDs144V2,
#[serde(rename = "Standard_DS14-8_v2")]
StandardDs148V2,
#[serde(rename = "Standard_DS14_v2")]
StandardDs14V2,
#[serde(rename = "Standard_DS14_v2_Promo")]
StandardDs14V2Promo,
#[serde(rename = "Standard_DS15_v2")]
StandardDs15V2,
#[serde(rename = "Standard_DS1_v2")]
StandardDs1V2,
#[serde(rename = "Standard_DS2")]
StandardDs2,
#[serde(rename = "Standard_DS2_v2")]
StandardDs2V2,
#[serde(rename = "Standard_DS2_v2_Promo")]
StandardDs2V2Promo,
#[serde(rename = "Standard_DS3")]
StandardDs3,
#[serde(rename = "Standard_DS3_v2")]
StandardDs3V2,
#[serde(rename = "Standard_DS3_v2_Promo")]
StandardDs3V2Promo,
#[serde(rename = "Standard_DS4")]
StandardDs4,
#[serde(rename = "Standard_DS4_v2")]
StandardDs4V2,
#[serde(rename = "Standard_DS4_v2_Promo")]
StandardDs4V2Promo,
#[serde(rename = "Standard_DS5_v2")]
StandardDs5V2,
#[serde(rename = "Standard_DS5_v2_Promo")]
StandardDs5V2Promo,
#[serde(rename = "Standard_E16_v3")]
StandardE16V3,
#[serde(rename = "Standard_E16s_v3")]
StandardE16sV3,
#[serde(rename = "Standard_E2_v3")]
StandardE2V3,
#[serde(rename = "Standard_E2s_v3")]
StandardE2sV3,
#[serde(rename = "Standard_E32-16s_v3")]
StandardE3216sV3,
#[serde(rename = "Standard_E32-8s_v3")]
StandardE328sV3,
#[serde(rename = "Standard_E32_v3")]
StandardE32V3,
#[serde(rename = "Standard_E32s_v3")]
StandardE32sV3,
#[serde(rename = "Standard_E4_v3")]
StandardE4V3,
#[serde(rename = "Standard_E4s_v3")]
StandardE4sV3,
#[serde(rename = "Standard_E64-16s_v3")]
StandardE6416sV3,
#[serde(rename = "Standard_E64-32s_v3")]
StandardE6432sV3,
#[serde(rename = "Standard_E64_v3")]
StandardE64V3,
#[serde(rename = "Standard_E64s_v3")]
StandardE64sV3,
#[serde(rename = "Standard_E8_v3")]
StandardE8V3,
#[serde(rename = "Standard_E8s_v3")]
StandardE8sV3,
#[serde(rename = "Standard_F1")]
StandardF1,
#[serde(rename = "Standard_F16")]
StandardF16,
#[serde(rename = "Standard_F16s")]
StandardF16s,
#[serde(rename = "Standard_F16s_v2")]
StandardF16sV2,
#[serde(rename = "Standard_F1s")]
StandardF1s,
#[serde(rename = "Standard_F2")]
StandardF2,
#[serde(rename = "Standard_F2s")]
StandardF2s,
#[serde(rename = "Standard_F2s_v2")]
StandardF2sV2,
#[serde(rename = "Standard_F32s_v2")]
StandardF32sV2,
#[serde(rename = "Standard_F4")]
StandardF4,
#[serde(rename = "Standard_F4s")]
StandardF4s,
#[serde(rename = "Standard_F4s_v2")]
StandardF4sV2,
#[serde(rename = "Standard_F64s_v2")]
StandardF64sV2,
#[serde(rename = "Standard_F72s_v2")]
StandardF72sV2,
#[serde(rename = "Standard_F8")]
StandardF8,
#[serde(rename = "Standard_F8s")]
StandardF8s,
#[serde(rename = "Standard_F8s_v2")]
StandardF8sV2,
#[serde(rename = "Standard_G1")]
StandardG1,
#[serde(rename = "Standard_G2")]
StandardG2,
#[serde(rename = "Standard_G3")]
StandardG3,
#[serde(rename = "Standard_G4")]
StandardG4,
#[serde(rename = "Standard_G5")]
StandardG5,
#[serde(rename = "Standard_GS1")]
StandardGs1,
#[serde(rename = "Standard_GS2")]
StandardGs2,
#[serde(rename = "Standard_GS3")]
StandardGs3,
#[serde(rename = "Standard_GS4")]
StandardGs4,
#[serde(rename = "Standard_GS4-4")]
StandardGs44,
#[serde(rename = "Standard_GS4-8")]
StandardGs48,
#[serde(rename = "Standard_GS5")]
StandardGs5,
#[serde(rename = "Standard_GS5-16")]
StandardGs516,
#[serde(rename = "Standard_GS5-8")]
StandardGs58,
#[serde(rename = "Standard_H16")]
StandardH16,
#[serde(rename = "Standard_H16m")]
StandardH16m,
#[serde(rename = "Standard_H16mr")]
StandardH16mr,
#[serde(rename = "Standard_H16r")]
StandardH16r,
#[serde(rename = "Standard_H8")]
StandardH8,
#[serde(rename = "Standard_H8m")]
StandardH8m,
#[serde(rename = "Standard_L16s")]
StandardL16s,
#[serde(rename = "Standard_L32s")]
StandardL32s,
#[serde(rename = "Standard_L4s")]
StandardL4s,
#[serde(rename = "Standard_L8s")]
StandardL8s,
#[serde(rename = "Standard_M128-32ms")]
StandardM12832ms,
#[serde(rename = "Standard_M128-64ms")]
StandardM12864ms,
#[serde(rename = "Standard_M128ms")]
StandardM128ms,
#[serde(rename = "Standard_M128s")]
StandardM128s,
#[serde(rename = "Standard_M64-16ms")]
StandardM6416ms,
#[serde(rename = "Standard_M64-32ms")]
StandardM6432ms,
#[serde(rename = "Standard_M64ms")]
StandardM64ms,
#[serde(rename = "Standard_M64s")]
StandardM64s,
#[serde(rename = "Standard_NC12")]
StandardNc12,
#[serde(rename = "Standard_NC12s_v2")]
StandardNc12sV2,
#[serde(rename = "Standard_NC12s_v3")]
StandardNc12sV3,
#[serde(rename = "Standard_NC24")]
StandardNc24,
#[serde(rename = "Standard_NC24r")]
StandardNc24r,
#[serde(rename = "Standard_NC24rs_v2")]
StandardNc24rsV2,
#[serde(rename = "Standard_NC24rs_v3")]
StandardNc24rsV3,
#[serde(rename = "Standard_NC24s_v2")]
StandardNc24sV2,
#[serde(rename = "Standard_NC24s_v3")]
StandardNc24sV3,
#[serde(rename = "Standard_NC6")]
StandardNc6,
#[serde(rename = "Standard_NC6s_v2")]
StandardNc6sV2,
#[serde(rename = "Standard_NC6s_v3")]
StandardNc6sV3,
#[serde(rename = "Standard_ND12s")]
StandardNd12s,
#[serde(rename = "Standard_ND24rs")]
StandardNd24rs,
#[serde(rename = "Standard_ND24s")]
StandardNd24s,
#[serde(rename = "Standard_ND6s")]
StandardNd6s,
#[serde(rename = "Standard_NV12")]
StandardNv12,
#[serde(rename = "Standard_NV24")]
StandardNv24,
#[serde(rename = "Standard_NV6")]
StandardNv6,
}
pub type ContainerServiceVnetSubnetId = String;
#[doc = "The credential result response."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CredentialResult {
#[doc = "The name of the credential."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Base64-encoded Kubernetes configuration file."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
impl CredentialResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The list of credential result response."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CredentialResults {
#[doc = "Base64-encoded Kubernetes configuration file."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kubeconfigs: Vec<CredentialResult>,
}
impl CredentialResults {
pub fn new() -> Self {
Self::default()
}
}
pub type HourInDay = i32;
#[doc = "Kubelet configurations of agent nodes."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct KubeletConfig {
#[doc = "CPU Manager policy to use."]
#[serde(rename = "cpuManagerPolicy", default, skip_serializing_if = "Option::is_none")]
pub cpu_manager_policy: Option<String>,
#[doc = "Enable CPU CFS quota enforcement for containers that specify CPU limits."]
#[serde(rename = "cpuCfsQuota", default, skip_serializing_if = "Option::is_none")]
pub cpu_cfs_quota: Option<bool>,
#[doc = "Sets CPU CFS quota period value."]
#[serde(rename = "cpuCfsQuotaPeriod", default, skip_serializing_if = "Option::is_none")]
pub cpu_cfs_quota_period: Option<String>,
#[doc = "The percent of disk usage after which image garbage collection is always run."]
#[serde(rename = "imageGcHighThreshold", default, skip_serializing_if = "Option::is_none")]
pub image_gc_high_threshold: Option<i32>,
#[doc = "The percent of disk usage before which image garbage collection is never run."]
#[serde(rename = "imageGcLowThreshold", default, skip_serializing_if = "Option::is_none")]
pub image_gc_low_threshold: Option<i32>,
#[doc = "Topology Manager policy to use."]
#[serde(rename = "topologyManagerPolicy", default, skip_serializing_if = "Option::is_none")]
pub topology_manager_policy: Option<String>,
#[doc = "Allowlist of unsafe sysctls or unsafe sysctl patterns (ending in `*`)."]
#[serde(rename = "allowedUnsafeSysctls", default, skip_serializing_if = "Vec::is_empty")]
pub allowed_unsafe_sysctls: Vec<String>,
#[doc = "If set to true it will make the Kubelet fail to start if swap is enabled on the node."]
#[serde(rename = "failSwapOn", default, skip_serializing_if = "Option::is_none")]
pub fail_swap_on: Option<bool>,
#[doc = "The maximum size (e.g. 10Mi) of container log file before it is rotated."]
#[serde(rename = "containerLogMaxSizeMB", default, skip_serializing_if = "Option::is_none")]
pub container_log_max_size_mb: Option<i32>,
#[doc = "The maximum number of container log files that can be present for a container. The number must be ≥ 2."]
#[serde(rename = "containerLogMaxFiles", default, skip_serializing_if = "Option::is_none")]
pub container_log_max_files: Option<i32>,
#[doc = "The maximum number of processes per pod."]
#[serde(rename = "podMaxPids", default, skip_serializing_if = "Option::is_none")]
pub pod_max_pids: Option<i32>,
}
impl KubeletConfig {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "KubeletDiskType determines the placement of emptyDir volumes, container runtime data root, and Kubelet ephemeral storage. Allowed values: 'OS', 'Temporary' (preview)."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KubeletDiskType {
#[serde(rename = "OS")]
Os,
Temporary,
}
#[doc = "OS configurations of Linux agent nodes."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct LinuxOsConfig {
#[doc = "Sysctl settings for Linux agent nodes."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sysctls: Option<SysctlConfig>,
#[doc = "Transparent Huge Page enabled configuration."]
#[serde(rename = "transparentHugePageEnabled", default, skip_serializing_if = "Option::is_none")]
pub transparent_huge_page_enabled: Option<String>,
#[doc = "Transparent Huge Page defrag configuration."]
#[serde(rename = "transparentHugePageDefrag", default, skip_serializing_if = "Option::is_none")]
pub transparent_huge_page_defrag: Option<String>,
#[doc = "SwapFileSizeMB specifies size in MB of a swap file will be created on each node."]
#[serde(rename = "swapFileSizeMB", default, skip_serializing_if = "Option::is_none")]
pub swap_file_size_mb: Option<i32>,
}
impl LinuxOsConfig {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "maintenance configuration."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MaintenanceConfiguration {
#[serde(flatten)]
pub sub_resource: SubResource,
#[doc = "Metadata pertaining to creation and last modification of the resource."]
#[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")]
pub system_data: Option<SystemData>,
#[doc = "Default maintenance configuration properties."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MaintenanceConfigurationProperties>,
}
impl MaintenanceConfiguration {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The response from the List maintenance configurations operation."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MaintenanceConfigurationListResult {
#[doc = "The list of maintenance configurations."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<MaintenanceConfiguration>,
#[doc = "The URL to get the next set of maintenance configuration results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl MaintenanceConfigurationListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Default maintenance configuration properties."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct MaintenanceConfigurationProperties {
#[doc = "Weekday time slots allowed to upgrade."]
#[serde(rename = "timeInWeek", default, skip_serializing_if = "Vec::is_empty")]
pub time_in_week: Vec<TimeInWeek>,
#[doc = "Time slots on which upgrade is not allowed."]
#[serde(rename = "notAllowedTime", default, skip_serializing_if = "Vec::is_empty")]
pub not_allowed_time: Vec<TimeSpan>,
}
impl MaintenanceConfigurationProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedCluster {
#[serde(flatten)]
pub resource: Resource,
#[doc = "Properties of the managed cluster."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ManagedClusterProperties>,
#[doc = "Identity for the managed cluster."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ManagedClusterIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<ManagedClusterSku>,
}
impl ManagedCluster {
pub fn new(resource: Resource) -> Self {
Self {
resource,
properties: None,
identity: None,
sku: None,
}
}
}
#[doc = "AADProfile specifies attributes for Azure Active Directory integration."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterAadProfile {
#[doc = "Whether to enable managed AAD."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub managed: Option<bool>,
#[doc = "Whether to enable Azure RBAC for Kubernetes authorization."]
#[serde(rename = "enableAzureRBAC", default, skip_serializing_if = "Option::is_none")]
pub enable_azure_rbac: Option<bool>,
#[doc = "AAD group object IDs that will have admin role of the cluster."]
#[serde(rename = "adminGroupObjectIDs", default, skip_serializing_if = "Vec::is_empty")]
pub admin_group_object_i_ds: Vec<String>,
#[doc = "The client AAD application ID."]
#[serde(rename = "clientAppID", default, skip_serializing_if = "Option::is_none")]
pub client_app_id: Option<String>,
#[doc = "The server AAD application ID."]
#[serde(rename = "serverAppID", default, skip_serializing_if = "Option::is_none")]
pub server_app_id: Option<String>,
#[doc = "The server AAD application secret."]
#[serde(rename = "serverAppSecret", default, skip_serializing_if = "Option::is_none")]
pub server_app_secret: Option<String>,
#[doc = "The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription."]
#[serde(rename = "tenantID", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
impl ManagedClusterAadProfile {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Access profile for managed cluster API server."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterApiServerAccessProfile {
#[doc = "Authorized IP Ranges to kubernetes API server."]
#[serde(rename = "authorizedIPRanges", default, skip_serializing_if = "Vec::is_empty")]
pub authorized_ip_ranges: Vec<String>,
#[doc = "Whether to create the cluster as a private cluster or not."]
#[serde(rename = "enablePrivateCluster", default, skip_serializing_if = "Option::is_none")]
pub enable_private_cluster: Option<bool>,
#[doc = "Private dns zone mode for private cluster. "]
#[serde(rename = "privateDNSZone", default, skip_serializing_if = "Option::is_none")]
pub private_dns_zone: Option<String>,
}
impl ManagedClusterApiServerAccessProfile {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Managed cluster Access Profile."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterAccessProfile {
#[serde(flatten)]
pub resource: Resource,
#[doc = "Profile for enabling a user to access a managed cluster."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AccessProfile>,
}
impl ManagedClusterAccessProfile {
pub fn new(resource: Resource) -> Self {
Self {
resource,
properties: None,
}
}
}
#[doc = "A Kubernetes add-on profile for a managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterAddonProfile {
#[doc = "Whether the add-on is enabled or not."]
pub enabled: bool,
#[doc = "Key-value pairs for configuring an add-on."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub config: Option<serde_json::Value>,
#[doc = "Information of user assigned identity used by this add-on."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<serde_json::Value>,
}
impl ManagedClusterAddonProfile {
pub fn new(enabled: bool) -> Self {
Self {
enabled,
config: None,
identity: None,
}
}
}
#[doc = "Profile for the container service agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterAgentPoolProfile {
#[serde(flatten)]
pub managed_cluster_agent_pool_profile_properties: ManagedClusterAgentPoolProfileProperties,
#[doc = "Unique name of the agent pool profile in the context of the subscription and resource group."]
pub name: String,
}
impl ManagedClusterAgentPoolProfile {
pub fn new(name: String) -> Self {
Self {
managed_cluster_agent_pool_profile_properties: ManagedClusterAgentPoolProfileProperties::default(),
name,
}
}
}
#[doc = "Properties for the container service agent pool profile."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterAgentPoolProfileProperties {
#[doc = "Number of agents (VMs) to host docker containers. Allowed values must be in the range of 0 to 100 (inclusive) for user pools and in the range of 1 to 100 (inclusive) for system pools. The default value is 1."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
#[doc = "Size of agent VMs."]
#[serde(rename = "vmSize", default, skip_serializing_if = "Option::is_none")]
pub vm_size: Option<ContainerServiceVmSize>,
#[doc = "OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified."]
#[serde(rename = "osDiskSizeGB", default, skip_serializing_if = "Option::is_none")]
pub os_disk_size_gb: Option<ContainerServiceOsDisk>,
#[doc = "OSDiskType represents the type of an OS disk on an agent pool."]
#[serde(rename = "osDiskType", default, skip_serializing_if = "Option::is_none")]
pub os_disk_type: Option<OsDiskType>,
#[doc = "KubeletDiskType determines the placement of emptyDir volumes, container runtime data root, and Kubelet ephemeral storage. Allowed values: 'OS', 'Temporary' (preview)."]
#[serde(rename = "kubeletDiskType", default, skip_serializing_if = "Option::is_none")]
pub kubelet_disk_type: Option<KubeletDiskType>,
#[doc = "specifies a subnet's resource id with subscription, resource group, vnet and subnet name"]
#[serde(rename = "vnetSubnetID", default, skip_serializing_if = "Option::is_none")]
pub vnet_subnet_id: Option<ContainerServiceVnetSubnetId>,
#[doc = "specifies a subnet's resource id with subscription, resource group, vnet and subnet name"]
#[serde(rename = "podSubnetID", default, skip_serializing_if = "Option::is_none")]
pub pod_subnet_id: Option<ContainerServiceVnetSubnetId>,
#[doc = "Maximum number of pods that can run on a node."]
#[serde(rename = "maxPods", default, skip_serializing_if = "Option::is_none")]
pub max_pods: Option<i32>,
#[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."]
#[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")]
pub os_type: Option<OsType>,
#[doc = "Maximum number of nodes for auto-scaling"]
#[serde(rename = "maxCount", default, skip_serializing_if = "Option::is_none")]
pub max_count: Option<i32>,
#[doc = "Minimum number of nodes for auto-scaling"]
#[serde(rename = "minCount", default, skip_serializing_if = "Option::is_none")]
pub min_count: Option<i32>,
#[doc = "Whether to enable auto-scaler"]
#[serde(rename = "enableAutoScaling", default, skip_serializing_if = "Option::is_none")]
pub enable_auto_scaling: Option<bool>,
#[doc = "AgentPoolType represents types of an agent pool."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<AgentPoolType>,
#[doc = "AgentPoolMode represents mode of an agent pool."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<AgentPoolMode>,
#[doc = "Version of orchestrator specified when creating the managed cluster."]
#[serde(rename = "orchestratorVersion", default, skip_serializing_if = "Option::is_none")]
pub orchestrator_version: Option<String>,
#[doc = "Version of node image"]
#[serde(rename = "nodeImageVersion", default, skip_serializing_if = "Option::is_none")]
pub node_image_version: Option<String>,
#[doc = "Settings for upgrading an agentpool"]
#[serde(rename = "upgradeSettings", default, skip_serializing_if = "Option::is_none")]
pub upgrade_settings: Option<AgentPoolUpgradeSettings>,
#[doc = "The current deployment or provisioning state, which only appears in the response."]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[doc = "Describes the Power State of the cluster"]
#[serde(rename = "powerState", default, skip_serializing_if = "Option::is_none")]
pub power_state: Option<PowerState>,
#[doc = "Availability zones for nodes. Must use VirtualMachineScaleSets AgentPoolType."]
#[serde(rename = "availabilityZones", default, skip_serializing_if = "Vec::is_empty")]
pub availability_zones: Vec<String>,
#[doc = "Enable public IP for nodes"]
#[serde(rename = "enableNodePublicIP", default, skip_serializing_if = "Option::is_none")]
pub enable_node_public_ip: Option<bool>,
#[doc = "Public IP Prefix ID. VM nodes use IPs assigned from this Public IP Prefix."]
#[serde(rename = "nodePublicIPPrefixID", default, skip_serializing_if = "Option::is_none")]
pub node_public_ip_prefix_id: Option<String>,
#[doc = "ScaleSetPriority to be used to specify virtual machine scale set priority. Default to regular."]
#[serde(rename = "scaleSetPriority", default, skip_serializing_if = "Option::is_none")]
pub scale_set_priority: Option<ScaleSetPriority>,
#[doc = "ScaleSetEvictionPolicy to be used to specify eviction policy for Spot virtual machine scale set. Default to Delete."]
#[serde(rename = "scaleSetEvictionPolicy", default, skip_serializing_if = "Option::is_none")]
pub scale_set_eviction_policy: Option<ScaleSetEvictionPolicy>,
#[doc = "SpotMaxPrice to be used to specify the maximum price you are willing to pay in US Dollars. Possible values are any decimal value greater than zero or -1 which indicates default price to be up-to on-demand."]
#[serde(rename = "spotMaxPrice", default, skip_serializing_if = "Option::is_none")]
pub spot_max_price: Option<SpotMaxPrice>,
#[doc = "Agent pool tags to be persisted on the agent pool virtual machine scale set."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[doc = "Agent pool node labels to be persisted across all nodes in agent pool."]
#[serde(rename = "nodeLabels", default, skip_serializing_if = "Option::is_none")]
pub node_labels: Option<serde_json::Value>,
#[doc = "Taints added to new nodes during node pool create and scale. For example, key=value:NoSchedule."]
#[serde(rename = "nodeTaints", default, skip_serializing_if = "Vec::is_empty")]
pub node_taints: Vec<String>,
#[doc = "The ID for Proximity Placement Group."]
#[serde(rename = "proximityPlacementGroupID", default, skip_serializing_if = "Option::is_none")]
pub proximity_placement_group_id: Option<ProximityPlacementGroupId>,
#[doc = "Kubelet configurations of agent nodes."]
#[serde(rename = "kubeletConfig", default, skip_serializing_if = "Option::is_none")]
pub kubelet_config: Option<KubeletConfig>,
#[doc = "OS configurations of Linux agent nodes."]
#[serde(rename = "linuxOSConfig", default, skip_serializing_if = "Option::is_none")]
pub linux_os_config: Option<LinuxOsConfig>,
#[doc = "Whether to enable EncryptionAtHost"]
#[serde(rename = "enableEncryptionAtHost", default, skip_serializing_if = "Option::is_none")]
pub enable_encryption_at_host: Option<bool>,
}
impl ManagedClusterAgentPoolProfileProperties {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Auto upgrade profile for a managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterAutoUpgradeProfile {
#[doc = "upgrade channel for auto upgrade."]
#[serde(rename = "upgradeChannel", default, skip_serializing_if = "Option::is_none")]
pub upgrade_channel: Option<managed_cluster_auto_upgrade_profile::UpgradeChannel>,
}
impl ManagedClusterAutoUpgradeProfile {
pub fn new() -> Self {
Self::default()
}
}
pub mod managed_cluster_auto_upgrade_profile {
use super::*;
#[doc = "upgrade channel for auto upgrade."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum UpgradeChannel {
#[serde(rename = "rapid")]
Rapid,
#[serde(rename = "stable")]
Stable,
#[serde(rename = "patch")]
Patch,
#[serde(rename = "none")]
None,
}
}
#[doc = "Identity for the managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterIdentity {
#[doc = "The principal id of the system assigned identity which is used by master components."]
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[doc = "The tenant id of the system assigned identity which is used by master components."]
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[doc = "The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<managed_cluster_identity::Type>,
#[doc = "The user identity associated with the managed cluster. This identity will be used in control plane and only one user assigned identity is allowed. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'."]
#[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")]
pub user_assigned_identities: Option<serde_json::Value>,
}
impl ManagedClusterIdentity {
pub fn new() -> Self {
Self::default()
}
}
pub mod managed_cluster_identity {
use super::*;
#[doc = "The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
UserAssigned,
None,
}
}
#[doc = "The response from the List Managed Clusters operation."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterListResult {
#[doc = "The list of managed clusters."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ManagedCluster>,
#[doc = "The URL to get the next set of managed cluster results."]
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl ManagedClusterListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Profile of the managed cluster load balancer."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterLoadBalancerProfile {
#[doc = "Desired managed outbound IPs for the cluster load balancer."]
#[serde(rename = "managedOutboundIPs", default, skip_serializing_if = "Option::is_none")]
pub managed_outbound_i_ps: Option<managed_cluster_load_balancer_profile::ManagedOutboundIPs>,
#[doc = "Desired outbound IP Prefix resources for the cluster load balancer."]
#[serde(rename = "outboundIPPrefixes", default, skip_serializing_if = "Option::is_none")]
pub outbound_ip_prefixes: Option<managed_cluster_load_balancer_profile::OutboundIpPrefixes>,
#[doc = "Desired outbound IP resources for the cluster load balancer."]
#[serde(rename = "outboundIPs", default, skip_serializing_if = "Option::is_none")]
pub outbound_i_ps: Option<managed_cluster_load_balancer_profile::OutboundIPs>,
#[doc = "The effective outbound IP resources of the cluster load balancer."]
#[serde(rename = "effectiveOutboundIPs", default, skip_serializing_if = "Vec::is_empty")]
pub effective_outbound_i_ps: Vec<ResourceReference>,
#[doc = "Desired number of allocated SNAT ports per VM. Allowed values must be in the range of 0 to 64000 (inclusive). The default value is 0 which results in Azure dynamically allocating ports."]
#[serde(rename = "allocatedOutboundPorts", default, skip_serializing_if = "Option::is_none")]
pub allocated_outbound_ports: Option<i32>,
#[doc = "Desired outbound flow idle timeout in minutes. Allowed values must be in the range of 4 to 120 (inclusive). The default value is 30 minutes."]
#[serde(rename = "idleTimeoutInMinutes", default, skip_serializing_if = "Option::is_none")]
pub idle_timeout_in_minutes: Option<i32>,
}
impl ManagedClusterLoadBalancerProfile {
pub fn new() -> Self {
Self::default()
}
}
pub mod managed_cluster_load_balancer_profile {
use super::*;
#[doc = "Desired managed outbound IPs for the cluster load balancer."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedOutboundIPs {
#[doc = "Desired number of outbound IP created/managed by Azure for the cluster load balancer. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 1. "]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
}
impl ManagedOutboundIPs {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Desired outbound IP Prefix resources for the cluster load balancer."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OutboundIpPrefixes {
#[doc = "A list of public IP prefix resources."]
#[serde(rename = "publicIPPrefixes", default, skip_serializing_if = "Vec::is_empty")]
pub public_ip_prefixes: Vec<ResourceReference>,
}
impl OutboundIpPrefixes {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Desired outbound IP resources for the cluster load balancer."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OutboundIPs {
#[doc = "A list of public IP resources."]
#[serde(rename = "publicIPs", default, skip_serializing_if = "Vec::is_empty")]
pub public_i_ps: Vec<ResourceReference>,
}
impl OutboundIPs {
pub fn new() -> Self {
Self::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterPodIdentity {
#[doc = "Name of the pod identity."]
pub name: String,
#[doc = "Namespace of the pod identity."]
pub namespace: String,
pub identity: UserAssignedIdentity,
#[doc = "The current provisioning state of the pod identity."]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<managed_cluster_pod_identity::ProvisioningState>,
#[serde(rename = "provisioningInfo", default, skip_serializing_if = "Option::is_none")]
pub provisioning_info: Option<managed_cluster_pod_identity::ProvisioningInfo>,
}
impl ManagedClusterPodIdentity {
pub fn new(name: String, namespace: String, identity: UserAssignedIdentity) -> Self {
Self {
name,
namespace,
identity,
provisioning_state: None,
provisioning_info: None,
}
}
}
pub mod managed_cluster_pod_identity {
use super::*;
#[doc = "The current provisioning state of the pod identity."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Assigned,
Updating,
Deleting,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ProvisioningInfo {
#[doc = "An error response from the Container service."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudError>,
}
impl ProvisioningInfo {
pub fn new() -> Self {
Self::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterPodIdentityException {
#[doc = "Name of the pod identity exception."]
pub name: String,
#[doc = "Namespace of the pod identity exception."]
pub namespace: String,
#[doc = "Pod labels to match."]
#[serde(rename = "podLabels")]
pub pod_labels: serde_json::Value,
}
impl ManagedClusterPodIdentityException {
pub fn new(name: String, namespace: String, pod_labels: serde_json::Value) -> Self {
Self {
name,
namespace,
pod_labels,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterPodIdentityProfile {
#[doc = "Whether the pod identity addon is enabled."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[doc = "Customer consent for enabling AAD pod identity addon in cluster using Kubenet network plugin."]
#[serde(rename = "allowNetworkPluginKubenet", default, skip_serializing_if = "Option::is_none")]
pub allow_network_plugin_kubenet: Option<bool>,
#[doc = "User assigned pod identity settings."]
#[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Vec::is_empty")]
pub user_assigned_identities: Vec<ManagedClusterPodIdentity>,
#[doc = "User assigned pod identity exception settings."]
#[serde(rename = "userAssignedIdentityExceptions", default, skip_serializing_if = "Vec::is_empty")]
pub user_assigned_identity_exceptions: Vec<ManagedClusterPodIdentityException>,
}
impl ManagedClusterPodIdentityProfile {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The list of available upgrade versions."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterPoolUpgradeProfile {
#[doc = "Kubernetes version (major, minor, patch)."]
#[serde(rename = "kubernetesVersion")]
pub kubernetes_version: String,
#[doc = "Pool name."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."]
#[serde(rename = "osType")]
pub os_type: OsType,
#[doc = "List of orchestrator types and versions available for upgrade."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub upgrades: Vec<serde_json::Value>,
}
impl ManagedClusterPoolUpgradeProfile {
pub fn new(kubernetes_version: String, os_type: OsType) -> Self {
Self {
kubernetes_version,
name: None,
os_type,
upgrades: Vec::new(),
}
}
}
#[doc = "Properties of the managed cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterProperties {
#[doc = "The current deployment or provisioning state, which only appears in the response."]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[doc = "Describes the Power State of the cluster"]
#[serde(rename = "powerState", default, skip_serializing_if = "Option::is_none")]
pub power_state: Option<PowerState>,
#[doc = "The max number of agent pools for the managed cluster."]
#[serde(rename = "maxAgentPools", default, skip_serializing_if = "Option::is_none")]
pub max_agent_pools: Option<i32>,
#[doc = "Version of Kubernetes specified when creating the managed cluster."]
#[serde(rename = "kubernetesVersion", default, skip_serializing_if = "Option::is_none")]
pub kubernetes_version: Option<String>,
#[doc = "DNS prefix specified when creating the managed cluster."]
#[serde(rename = "dnsPrefix", default, skip_serializing_if = "Option::is_none")]
pub dns_prefix: Option<String>,
#[doc = "FQDN subdomain specified when creating private cluster with custom private dns zone."]
#[serde(rename = "fqdnSubdomain", default, skip_serializing_if = "Option::is_none")]
pub fqdn_subdomain: Option<String>,
#[doc = "FQDN for the master pool."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fqdn: Option<String>,
#[doc = "FQDN of private cluster."]
#[serde(rename = "privateFQDN", default, skip_serializing_if = "Option::is_none")]
pub private_fqdn: Option<String>,
#[doc = "FQDN for the master pool which used by proxy config."]
#[serde(rename = "azurePortalFQDN", default, skip_serializing_if = "Option::is_none")]
pub azure_portal_fqdn: Option<String>,
#[doc = "Properties of the agent pool."]
#[serde(rename = "agentPoolProfiles", default, skip_serializing_if = "Vec::is_empty")]
pub agent_pool_profiles: Vec<ManagedClusterAgentPoolProfile>,
#[doc = "Profile for Linux VMs in the container service cluster."]
#[serde(rename = "linuxProfile", default, skip_serializing_if = "Option::is_none")]
pub linux_profile: Option<ContainerServiceLinuxProfile>,
#[doc = "Profile for Windows VMs in the container service cluster."]
#[serde(rename = "windowsProfile", default, skip_serializing_if = "Option::is_none")]
pub windows_profile: Option<ManagedClusterWindowsProfile>,
#[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs."]
#[serde(rename = "servicePrincipalProfile", default, skip_serializing_if = "Option::is_none")]
pub service_principal_profile: Option<ManagedClusterServicePrincipalProfile>,
#[doc = "Profile of managed cluster add-on."]
#[serde(rename = "addonProfiles", default, skip_serializing_if = "Option::is_none")]
pub addon_profiles: Option<serde_json::Value>,
#[serde(rename = "podIdentityProfile", default, skip_serializing_if = "Option::is_none")]
pub pod_identity_profile: Option<ManagedClusterPodIdentityProfile>,
#[doc = "Name of the resource group containing agent pool nodes."]
#[serde(rename = "nodeResourceGroup", default, skip_serializing_if = "Option::is_none")]
pub node_resource_group: Option<String>,
#[doc = "Whether to enable Kubernetes Role-Based Access Control."]
#[serde(rename = "enableRBAC", default, skip_serializing_if = "Option::is_none")]
pub enable_rbac: Option<bool>,
#[doc = "(DEPRECATING) Whether to enable Kubernetes pod security policy (preview). This feature is set for removal on October 15th, 2020. Learn more at aka.ms/aks/azpodpolicy."]
#[serde(rename = "enablePodSecurityPolicy", default, skip_serializing_if = "Option::is_none")]
pub enable_pod_security_policy: Option<bool>,
#[doc = "Profile of network configuration."]
#[serde(rename = "networkProfile", default, skip_serializing_if = "Option::is_none")]
pub network_profile: Option<ContainerServiceNetworkProfile>,
#[doc = "AADProfile specifies attributes for Azure Active Directory integration."]
#[serde(rename = "aadProfile", default, skip_serializing_if = "Option::is_none")]
pub aad_profile: Option<ManagedClusterAadProfile>,
#[doc = "Auto upgrade profile for a managed cluster."]
#[serde(rename = "autoUpgradeProfile", default, skip_serializing_if = "Option::is_none")]
pub auto_upgrade_profile: Option<ManagedClusterAutoUpgradeProfile>,
#[doc = "Parameters to be applied to the cluster-autoscaler when enabled"]
#[serde(rename = "autoScalerProfile", default, skip_serializing_if = "Option::is_none")]
pub auto_scaler_profile: Option<managed_cluster_properties::AutoScalerProfile>,
#[doc = "Access profile for managed cluster API server."]
#[serde(rename = "apiServerAccessProfile", default, skip_serializing_if = "Option::is_none")]
pub api_server_access_profile: Option<ManagedClusterApiServerAccessProfile>,
#[doc = "ResourceId of the disk encryption set to use for enabling encryption at rest."]
#[serde(rename = "diskEncryptionSetID", default, skip_serializing_if = "Option::is_none")]
pub disk_encryption_set_id: Option<String>,
#[doc = "Identities associated with the cluster."]
#[serde(rename = "identityProfile", default, skip_serializing_if = "Option::is_none")]
pub identity_profile: Option<serde_json::Value>,
}
impl ManagedClusterProperties {
pub fn new() -> Self {
Self::default()
}
}
pub mod managed_cluster_properties {
use super::*;
#[doc = "Parameters to be applied to the cluster-autoscaler when enabled"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct AutoScalerProfile {
#[serde(rename = "balance-similar-node-groups", default, skip_serializing_if = "Option::is_none")]
pub balance_similar_node_groups: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expander: Option<auto_scaler_profile::Expander>,
#[serde(rename = "max-empty-bulk-delete", default, skip_serializing_if = "Option::is_none")]
pub max_empty_bulk_delete: Option<String>,
#[serde(rename = "max-graceful-termination-sec", default, skip_serializing_if = "Option::is_none")]
pub max_graceful_termination_sec: Option<String>,
#[serde(rename = "max-node-provision-time", default, skip_serializing_if = "Option::is_none")]
pub max_node_provision_time: Option<String>,
#[serde(rename = "max-total-unready-percentage", default, skip_serializing_if = "Option::is_none")]
pub max_total_unready_percentage: Option<String>,
#[serde(rename = "new-pod-scale-up-delay", default, skip_serializing_if = "Option::is_none")]
pub new_pod_scale_up_delay: Option<String>,
#[serde(rename = "ok-total-unready-count", default, skip_serializing_if = "Option::is_none")]
pub ok_total_unready_count: Option<String>,
#[serde(rename = "scan-interval", default, skip_serializing_if = "Option::is_none")]
pub scan_interval: Option<String>,
#[serde(rename = "scale-down-delay-after-add", default, skip_serializing_if = "Option::is_none")]
pub scale_down_delay_after_add: Option<String>,
#[serde(rename = "scale-down-delay-after-delete", default, skip_serializing_if = "Option::is_none")]
pub scale_down_delay_after_delete: Option<String>,
#[serde(rename = "scale-down-delay-after-failure", default, skip_serializing_if = "Option::is_none")]
pub scale_down_delay_after_failure: Option<String>,
#[serde(rename = "scale-down-unneeded-time", default, skip_serializing_if = "Option::is_none")]
pub scale_down_unneeded_time: Option<String>,
#[serde(rename = "scale-down-unready-time", default, skip_serializing_if = "Option::is_none")]
pub scale_down_unready_time: Option<String>,
#[serde(rename = "scale-down-utilization-threshold", default, skip_serializing_if = "Option::is_none")]
pub scale_down_utilization_threshold: Option<String>,
#[serde(rename = "skip-nodes-with-local-storage", default, skip_serializing_if = "Option::is_none")]
pub skip_nodes_with_local_storage: Option<String>,
#[serde(rename = "skip-nodes-with-system-pods", default, skip_serializing_if = "Option::is_none")]
pub skip_nodes_with_system_pods: Option<String>,
}
impl AutoScalerProfile {
pub fn new() -> Self {
Self::default()
}
}
pub mod auto_scaler_profile {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Expander {
#[serde(rename = "least-waste")]
LeastWaste,
#[serde(rename = "most-pods")]
MostPods,
#[serde(rename = "priority")]
Priority,
#[serde(rename = "random")]
Random,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ManagedClusterSku {
#[doc = "Name of a managed cluster SKU."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<managed_cluster_sku::Name>,
#[doc = "Tier of a managed cluster SKU."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<managed_cluster_sku::Tier>,
}
impl ManagedClusterSku {
pub fn new() -> Self {
Self::default()
}
}
pub mod managed_cluster_sku {
use super::*;
#[doc = "Name of a managed cluster SKU."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
Basic,
}
#[doc = "Tier of a managed cluster SKU."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tier {
Paid,
Free,
}
}
#[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterServicePrincipalProfile {
#[doc = "The ID for the service principal."]
#[serde(rename = "clientId")]
pub client_id: String,
#[doc = "The secret password associated with the service principal in plain text."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub secret: Option<String>,
}
impl ManagedClusterServicePrincipalProfile {
pub fn new(client_id: String) -> Self {
Self { client_id, secret: None }
}
}
#[doc = "The list of available upgrades for compute pools."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterUpgradeProfile {
#[doc = "Id of upgrade profile."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Name of upgrade profile."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Type of upgrade profile."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "Control plane and agent pool upgrade profiles."]
pub properties: ManagedClusterUpgradeProfileProperties,
}
impl ManagedClusterUpgradeProfile {
pub fn new(properties: ManagedClusterUpgradeProfileProperties) -> Self {
Self {
id: None,
name: None,
type_: None,
properties,
}
}
}
#[doc = "Control plane and agent pool upgrade profiles."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterUpgradeProfileProperties {
#[doc = "The list of available upgrade versions."]
#[serde(rename = "controlPlaneProfile")]
pub control_plane_profile: ManagedClusterPoolUpgradeProfile,
#[doc = "The list of available upgrade versions for agent pools."]
#[serde(rename = "agentPoolProfiles")]
pub agent_pool_profiles: Vec<ManagedClusterPoolUpgradeProfile>,
}
impl ManagedClusterUpgradeProfileProperties {
pub fn new(
control_plane_profile: ManagedClusterPoolUpgradeProfile,
agent_pool_profiles: Vec<ManagedClusterPoolUpgradeProfile>,
) -> Self {
Self {
control_plane_profile,
agent_pool_profiles,
}
}
}
#[doc = "Profile for Windows VMs in the container service cluster."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ManagedClusterWindowsProfile {
#[doc = "Specifies the name of the administrator account. <br><br> **restriction:** Cannot end in \".\" <br><br> **Disallowed values:** \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"david\", \"guest\", \"john\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\". <br><br> **Minimum-length:** 1 character <br><br> **Max-length:** 20 characters"]
#[serde(rename = "adminUsername")]
pub admin_username: String,
#[doc = "Specifies the password of the administrator account. <br><br> **Minimum-length:** 8 characters <br><br> **Max-length:** 123 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\\W_]) <br><br> **Disallowed values:** \"abc@123\", \"P@$$w0rd\", \"P@ssw0rd\", \"P@ssword123\", \"Pa$$word\", \"pass@word1\", \"Password!\", \"Password1\", \"Password22\", \"iloveyou!\""]
#[serde(rename = "adminPassword", default, skip_serializing_if = "Option::is_none")]
pub admin_password: Option<String>,
#[doc = "The licenseType to use for Windows VMs. Windows_Server is used to enable Azure Hybrid User Benefits for Windows VMs."]
#[serde(rename = "licenseType", default, skip_serializing_if = "Option::is_none")]
pub license_type: Option<managed_cluster_windows_profile::LicenseType>,
}
impl ManagedClusterWindowsProfile {
pub fn new(admin_username: String) -> Self {
Self {
admin_username,
admin_password: None,
license_type: None,
}
}
}
pub mod managed_cluster_windows_profile {
use super::*;
#[doc = "The licenseType to use for Windows VMs. Windows_Server is used to enable Azure Hybrid User Benefits for Windows VMs."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LicenseType {
None,
#[serde(rename = "Windows_Server")]
WindowsServer,
}
}
#[doc = "OSDiskType represents the type of an OS disk on an agent pool."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OsDiskType {
Managed,
Ephemeral,
}
#[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OsType {
Linux,
Windows,
}
impl Default for OsType {
fn default() -> Self {
Self::Linux
}
}
#[doc = "The List Compute Operation operation response."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationListResult {
#[doc = "The list of compute operations"]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<OperationValue>,
}
impl OperationListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Describes the properties of a Compute Operation value."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationValue {
#[doc = "The origin of the compute operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[doc = "The name of the compute operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Describes the properties of a Compute Operation Value Display."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationValueDisplay>,
}
impl OperationValue {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Describes the properties of a Compute Operation Value Display."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationValueDisplay {
#[doc = "The display name of the compute operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[doc = "The display name of the resource the operation applies to."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[doc = "The description of the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[doc = "The resource provider for the operation."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
}
impl OperationValueDisplay {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Describes the Power State of the cluster"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PowerState {
#[doc = "Tells whether the cluster is Running or Stopped"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<power_state::Code>,
}
impl PowerState {
pub fn new() -> Self {
Self::default()
}
}
pub mod power_state {
use super::*;
#[doc = "Tells whether the cluster is Running or Stopped"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Code {
Running,
Stopped,
}
}
#[doc = "Private endpoint which a connection belongs to."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpoint {
#[doc = "The resource Id for private endpoint"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
impl PrivateEndpoint {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A private endpoint connection"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointConnection {
#[doc = "The ID of the private endpoint connection."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The name of the private endpoint connection."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "The resource type."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "Properties of a private endpoint connection."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateEndpointConnectionProperties>,
}
impl PrivateEndpointConnection {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of private endpoint connections"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateEndpointConnectionListResult {
#[doc = "The collection value."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateEndpointConnection>,
}
impl PrivateEndpointConnectionListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Properties of a private endpoint connection."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateEndpointConnectionProperties {
#[doc = "The current provisioning state."]
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<private_endpoint_connection_properties::ProvisioningState>,
#[doc = "Private endpoint which a connection belongs to."]
#[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")]
pub private_endpoint: Option<PrivateEndpoint>,
#[doc = "The state of a private link service connection."]
#[serde(rename = "privateLinkServiceConnectionState")]
pub private_link_service_connection_state: PrivateLinkServiceConnectionState,
}
impl PrivateEndpointConnectionProperties {
pub fn new(private_link_service_connection_state: PrivateLinkServiceConnectionState) -> Self {
Self {
provisioning_state: None,
private_endpoint: None,
private_link_service_connection_state,
}
}
}
pub mod private_endpoint_connection_properties {
use super::*;
#[doc = "The current provisioning state."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Creating,
Deleting,
Failed,
}
}
#[doc = "A private link resource"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkResource {
#[doc = "The ID of the private link resource."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The name of the private link resource."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "The resource type."]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "The group ID of the resource."]
#[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")]
pub group_id: Option<String>,
#[doc = "RequiredMembers of the resource"]
#[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")]
pub required_members: Vec<String>,
#[doc = "The private link service ID of the resource, this field is exposed only to NRP internally."]
#[serde(rename = "privateLinkServiceID", default, skip_serializing_if = "Option::is_none")]
pub private_link_service_id: Option<String>,
}
impl PrivateLinkResource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "A list of private link resources"]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkResourcesListResult {
#[doc = "The collection value."]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateLinkResource>,
}
impl PrivateLinkResourcesListResult {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The state of a private link service connection."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrivateLinkServiceConnectionState {
#[doc = "The private link service connection status."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<private_link_service_connection_state::Status>,
#[doc = "The private link service connection description."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl PrivateLinkServiceConnectionState {
pub fn new() -> Self {
Self::default()
}
}
pub mod private_link_service_connection_state {
use super::*;
#[doc = "The private link service connection status."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Pending,
Approved,
Rejected,
Disconnected,
}
}
pub type ProximityPlacementGroupId = String;
#[doc = "The Resource model definition."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[doc = "Resource Id"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "Resource name"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Resource type"]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[doc = "Resource location"]
pub location: String,
#[doc = "Resource tags"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl Resource {
pub fn new(location: String) -> Self {
Self {
id: None,
name: None,
type_: None,
location,
tags: None,
}
}
}
#[doc = "A reference to an Azure resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ResourceReference {
#[doc = "The fully qualified Azure resource id."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
impl ResourceReference {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "ScaleSetEvictionPolicy to be used to specify eviction policy for Spot virtual machine scale set. Default to Delete."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScaleSetEvictionPolicy {
Delete,
Deallocate,
}
impl Default for ScaleSetEvictionPolicy {
fn default() -> Self {
Self::Delete
}
}
#[doc = "ScaleSetPriority to be used to specify virtual machine scale set priority. Default to regular."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ScaleSetPriority {
Spot,
Regular,
}
impl Default for ScaleSetPriority {
fn default() -> Self {
Self::Regular
}
}
pub type SpotMaxPrice = f64;
#[doc = "Reference to another subresource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SubResource {
#[doc = "Resource ID."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[doc = "The name of the resource that is unique within a resource group. This name can be used to access the resource."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[doc = "Resource type"]
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
impl SubResource {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Sysctl settings for Linux agent nodes."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SysctlConfig {
#[doc = "Sysctl setting net.core.somaxconn."]
#[serde(rename = "netCoreSomaxconn", default, skip_serializing_if = "Option::is_none")]
pub net_core_somaxconn: Option<i32>,
#[doc = "Sysctl setting net.core.netdev_max_backlog."]
#[serde(rename = "netCoreNetdevMaxBacklog", default, skip_serializing_if = "Option::is_none")]
pub net_core_netdev_max_backlog: Option<i32>,
#[doc = "Sysctl setting net.core.rmem_default."]
#[serde(rename = "netCoreRmemDefault", default, skip_serializing_if = "Option::is_none")]
pub net_core_rmem_default: Option<i32>,
#[doc = "Sysctl setting net.core.rmem_max."]
#[serde(rename = "netCoreRmemMax", default, skip_serializing_if = "Option::is_none")]
pub net_core_rmem_max: Option<i32>,
#[doc = "Sysctl setting net.core.wmem_default."]
#[serde(rename = "netCoreWmemDefault", default, skip_serializing_if = "Option::is_none")]
pub net_core_wmem_default: Option<i32>,
#[doc = "Sysctl setting net.core.wmem_max."]
#[serde(rename = "netCoreWmemMax", default, skip_serializing_if = "Option::is_none")]
pub net_core_wmem_max: Option<i32>,
#[doc = "Sysctl setting net.core.optmem_max."]
#[serde(rename = "netCoreOptmemMax", default, skip_serializing_if = "Option::is_none")]
pub net_core_optmem_max: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_max_syn_backlog."]
#[serde(rename = "netIpv4TcpMaxSynBacklog", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_max_syn_backlog: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_max_tw_buckets."]
#[serde(rename = "netIpv4TcpMaxTwBuckets", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_max_tw_buckets: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_fin_timeout."]
#[serde(rename = "netIpv4TcpFinTimeout", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_fin_timeout: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_keepalive_time."]
#[serde(rename = "netIpv4TcpKeepaliveTime", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_keepalive_time: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_keepalive_probes."]
#[serde(rename = "netIpv4TcpKeepaliveProbes", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_keepalive_probes: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_keepalive_intvl."]
#[serde(rename = "netIpv4TcpkeepaliveIntvl", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcpkeepalive_intvl: Option<i32>,
#[doc = "Sysctl setting net.ipv4.tcp_tw_reuse."]
#[serde(rename = "netIpv4TcpTwReuse", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_tcp_tw_reuse: Option<bool>,
#[doc = "Sysctl setting net.ipv4.ip_local_port_range."]
#[serde(rename = "netIpv4IpLocalPortRange", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_ip_local_port_range: Option<String>,
#[doc = "Sysctl setting net.ipv4.neigh.default.gc_thresh1."]
#[serde(rename = "netIpv4NeighDefaultGcThresh1", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_neigh_default_gc_thresh1: Option<i32>,
#[doc = "Sysctl setting net.ipv4.neigh.default.gc_thresh2."]
#[serde(rename = "netIpv4NeighDefaultGcThresh2", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_neigh_default_gc_thresh2: Option<i32>,
#[doc = "Sysctl setting net.ipv4.neigh.default.gc_thresh3."]
#[serde(rename = "netIpv4NeighDefaultGcThresh3", default, skip_serializing_if = "Option::is_none")]
pub net_ipv4_neigh_default_gc_thresh3: Option<i32>,
#[doc = "Sysctl setting net.netfilter.nf_conntrack_max."]
#[serde(rename = "netNetfilterNfConntrackMax", default, skip_serializing_if = "Option::is_none")]
pub net_netfilter_nf_conntrack_max: Option<i32>,
#[doc = "Sysctl setting net.netfilter.nf_conntrack_buckets."]
#[serde(rename = "netNetfilterNfConntrackBuckets", default, skip_serializing_if = "Option::is_none")]
pub net_netfilter_nf_conntrack_buckets: Option<i32>,
#[doc = "Sysctl setting fs.inotify.max_user_watches."]
#[serde(rename = "fsInotifyMaxUserWatches", default, skip_serializing_if = "Option::is_none")]
pub fs_inotify_max_user_watches: Option<i32>,
#[doc = "Sysctl setting fs.file-max."]
#[serde(rename = "fsFileMax", default, skip_serializing_if = "Option::is_none")]
pub fs_file_max: Option<i32>,
#[doc = "Sysctl setting fs.aio-max-nr."]
#[serde(rename = "fsAioMaxNr", default, skip_serializing_if = "Option::is_none")]
pub fs_aio_max_nr: Option<i32>,
#[doc = "Sysctl setting fs.nr_open."]
#[serde(rename = "fsNrOpen", default, skip_serializing_if = "Option::is_none")]
pub fs_nr_open: Option<i32>,
#[doc = "Sysctl setting kernel.threads-max."]
#[serde(rename = "kernelThreadsMax", default, skip_serializing_if = "Option::is_none")]
pub kernel_threads_max: Option<i32>,
#[doc = "Sysctl setting vm.max_map_count."]
#[serde(rename = "vmMaxMapCount", default, skip_serializing_if = "Option::is_none")]
pub vm_max_map_count: Option<i32>,
#[doc = "Sysctl setting vm.swappiness."]
#[serde(rename = "vmSwappiness", default, skip_serializing_if = "Option::is_none")]
pub vm_swappiness: Option<i32>,
#[doc = "Sysctl setting vm.vfs_cache_pressure."]
#[serde(rename = "vmVfsCachePressure", default, skip_serializing_if = "Option::is_none")]
pub vm_vfs_cache_pressure: Option<i32>,
}
impl SysctlConfig {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Metadata pertaining to creation and last modification of the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SystemData {
#[doc = "The identity that created the resource."]
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[doc = "The type of identity that created the resource."]
#[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")]
pub created_by_type: Option<system_data::CreatedByType>,
#[doc = "The timestamp of resource creation (UTC)."]
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[doc = "The identity that last modified the resource."]
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[doc = "The type of identity that last modified the resource."]
#[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by_type: Option<system_data::LastModifiedByType>,
#[doc = "The type of identity that last modified the resource."]
#[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")]
pub last_modified_at: Option<String>,
}
impl SystemData {
pub fn new() -> Self {
Self::default()
}
}
pub mod system_data {
use super::*;
#[doc = "The type of identity that created the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CreatedByType {
User,
Application,
ManagedIdentity,
Key,
}
#[doc = "The type of identity that last modified the resource."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LastModifiedByType {
User,
Application,
ManagedIdentity,
Key,
}
}
#[doc = "Tags object for patch operations."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TagsObject {
#[doc = "Resource tags."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
impl TagsObject {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "Time in a week."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TimeInWeek {
#[doc = "The weekday enum."]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub day: Option<WeekDay>,
#[doc = "hour slots in a day."]
#[serde(rename = "hourSlots", default, skip_serializing_if = "Vec::is_empty")]
pub hour_slots: Vec<HourInDay>,
}
impl TimeInWeek {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The time span with start and end properties."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TimeSpan {
#[doc = "The start of a time span"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start: Option<String>,
#[doc = "The end of a time span"]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end: Option<String>,
}
impl TimeSpan {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct UserAssignedIdentity {
#[doc = "The resource id of the user assigned identity."]
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[doc = "The client id of the user assigned identity."]
#[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[doc = "The object id of the user assigned identity."]
#[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")]
pub object_id: Option<String>,
}
impl UserAssignedIdentity {
pub fn new() -> Self {
Self::default()
}
}
#[doc = "The weekday enum."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WeekDay {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
} | #[serde(rename = "loadBalancer")] |
AttributeClassifier.py | # -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
# externals
import collections
# superclass
from .AbstractMetaclass import AbstractMetaclass
# class declaration
class At | bstractMetaclass):
"""
A base metaclass that enables attribute categorization.
A common pattern in pyre is to define classes that contain special attributes whose purpose
is to collect declaration meta data and associate them with a class attribute. These
attributes are processed by metaclasses and are converted into appropriate behavior. For
example, components have properties, which are decorated descriptors that enable external
configuration of component state. Similarly, XML parsing happens with the aid of classes
that capture the syntax, semantics and processing behavior of tags by employing descriptors
to capture the layout of an XML document.
This class defines {pyre_harvest}, which scans the class attribute dictionary for instances
of the special class {descriptor}. It also overrides {__prepare__} to provide attribute
storage that records the order in which attributes were encountered in the class record.
"""
# data
pyre_reserved = set()
# meta methods
@classmethod
def __prepare__(cls, name, bases, **kwds):
"""
Build an attribute table that maintains a category index for attribute descriptors
"""
# use an ordered dictionary
return collections.OrderedDict()
# interface
@classmethod
def pyre_harvest(cls, attributes, descriptor):
"""
Examine {attributes}, looking for instances of {descriptor}
"""
# reserved names are excluded from harvesting
reserved = cls.pyre_reserved
# loop over the attributes
for name, attribute in attributes.items():
# if this is a descriptor that's not in the reserved list
if isinstance(attribute, descriptor) and name not in reserved:
# return it to the caller along with its name
yield name, attribute
# all done
return
# end of file
| tributeClassifier(A |
arquivo.go | // Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package sources
import (
"github.com/lanzay/amass/amass/core"
"github.com/lanzay/amass/amass/utils"
)
// Arquivo is the Service that handles access to the Arquivo data source.
type Arquivo struct {
core.BaseService
baseURL string
SourceType string
filter *utils.StringFilter
}
// NewArquivo returns he object initialized, but not yet started.
func | (config *core.Config, bus *core.EventBus) *Arquivo {
a := &Arquivo{
baseURL: "http://arquivo.pt/wayback",
SourceType: core.ARCHIVE,
filter: utils.NewStringFilter(),
}
a.BaseService = *core.NewBaseService(a, "Arquivo", config, bus)
return a
}
// OnStart implements the Service interface
func (a *Arquivo) OnStart() error {
a.BaseService.OnStart()
a.Bus().Subscribe(core.NameResolvedTopic, a.SendDNSRequest)
go a.processRequests()
return nil
}
func (a *Arquivo) processRequests() {
for {
select {
case <-a.Quit():
return
case req := <-a.DNSRequestChan():
if a.Config().IsDomainInScope(req.Name) {
a.executeQuery(req.Name, req.Domain)
}
case <-a.AddrRequestChan():
case <-a.ASNRequestChan():
case <-a.WhoisRequestChan():
}
}
}
func (a *Arquivo) executeQuery(sn, domain string) {
if sn == "" || domain == "" || a.filter.Duplicate(sn) {
return
}
names, err := crawl(a, a.baseURL, domain, sn)
if err != nil {
a.Config().Log.Printf("%s: %v", a.String(), err)
return
}
for _, name := range names {
a.Bus().Publish(core.NewNameTopic, &core.DNSRequest{
Name: cleanName(name),
Domain: domain,
Tag: a.SourceType,
Source: a.String(),
})
}
}
| NewArquivo |
engine.go | package acsengine
import (
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"fmt"
"hash/fnv"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"text/template"
//log "github.com/sirupsen/logrus"
"github.com/Azure/acs-engine/pkg/api"
"github.com/Azure/acs-engine/pkg/api/common"
"github.com/Azure/acs-engine/pkg/helpers"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
)
var commonTemplateFiles = []string{agentOutputs, agentParams, classicParams, masterOutputs, iaasOutputs, masterParams, windowsParams}
var dcosTemplateFiles = []string{dcosBaseFile, dcosAgentResourcesVMAS, dcosAgentResourcesVMSS, dcosAgentVars, dcosMasterResources, dcosMasterVars, dcosParams, dcosWindowsAgentResourcesVMAS, dcosWindowsAgentResourcesVMSS}
var dcos2TemplateFiles = []string{dcos2BaseFile, dcosAgentResourcesVMAS, dcosAgentResourcesVMSS, dcosAgentVars, dcos2MasterResources, dcos2BootstrapResources, dcos2MasterVars, dcosParams, dcosWindowsAgentResourcesVMAS, dcosWindowsAgentResourcesVMSS, dcos2BootstrapVars, dcos2BootstrapParams}
var kubernetesTemplateFiles = []string{kubernetesBaseFile, kubernetesAgentResourcesVMAS, kubernetesAgentResourcesVMSS, kubernetesAgentVars, kubernetesMasterResources, kubernetesMasterVars, kubernetesParams, kubernetesWinAgentVars, kubernetesWinAgentVarsVMSS}
var swarmTemplateFiles = []string{swarmBaseFile, swarmParams, swarmAgentResourcesVMAS, swarmAgentVars, swarmAgentResourcesVMSS, swarmAgentResourcesClassic, swarmBaseFile, swarmMasterResources, swarmMasterVars, swarmWinAgentResourcesVMAS, swarmWinAgentResourcesVMSS}
var swarmModeTemplateFiles = []string{swarmBaseFile, swarmParams, swarmAgentResourcesVMAS, swarmAgentVars, swarmAgentResourcesVMSS, swarmAgentResourcesClassic, swarmBaseFile, swarmMasterResources, swarmMasterVars, swarmWinAgentResourcesVMAS, swarmWinAgentResourcesVMSS}
var openshiftTemplateFiles = append(
kubernetesTemplateFiles,
openshiftInfraResources,
openshiftNodeScript,
openshiftMasterScript,
openshift39NodeScript,
openshift39MasterScript,
)
var keyvaultSecretPathRe *regexp.Regexp
func init() {
keyvaultSecretPathRe = regexp.MustCompile(`^(/subscriptions/\S+/resourceGroups/\S+/providers/Microsoft.KeyVault/vaults/\S+)/secrets/([^/\s]+)(/(\S+))?$`)
}
// GenerateClusterID creates a unique 8 string cluster ID
func GenerateClusterID(properties *api.Properties) string {
uniqueNameSuffixSize := 8
// the name suffix uniquely identifies the cluster and is generated off a hash
// from the master dns name
h := fnv.New64a()
if properties.MasterProfile != nil {
h.Write([]byte(properties.MasterProfile.DNSPrefix))
} else if properties.HostedMasterProfile != nil | else {
h.Write([]byte(properties.AgentPoolProfiles[0].Name))
}
rand.Seed(int64(h.Sum64()))
return fmt.Sprintf("%08d", rand.Uint32())[:uniqueNameSuffixSize]
}
// GenerateKubeConfig returns a JSON string representing the KubeConfig
func GenerateKubeConfig(properties *api.Properties, location string) (string, error) {
if properties == nil {
return "", errors.New("Properties nil in GenerateKubeConfig")
}
if properties.CertificateProfile == nil {
return "", errors.New("CertificateProfile property may not be nil in GenerateKubeConfig")
}
b, err := Asset(kubeConfigJSON)
if err != nil {
return "", errors.Wrapf(err, "error reading kube config template file %s", kubeConfigJSON)
}
kubeconfig := string(b)
// variable replacement
kubeconfig = strings.Replace(kubeconfig, "{{WrapAsVerbatim \"variables('caCertificate')\"}}", base64.StdEncoding.EncodeToString([]byte(properties.CertificateProfile.CaCertificate)), -1)
if properties.OrchestratorProfile != nil &&
properties.OrchestratorProfile.KubernetesConfig != nil &&
properties.OrchestratorProfile.KubernetesConfig.PrivateCluster != nil &&
helpers.IsTrueBoolPointer(properties.OrchestratorProfile.KubernetesConfig.PrivateCluster.Enabled) {
if properties.MasterProfile.Count > 1 {
// more than 1 master, use the internal lb IP
firstMasterIP := net.ParseIP(properties.MasterProfile.FirstConsecutiveStaticIP).To4()
if firstMasterIP == nil {
return "", errors.Errorf("MasterProfile.FirstConsecutiveStaticIP '%s' is an invalid IP address", properties.MasterProfile.FirstConsecutiveStaticIP)
}
lbIP := net.IP{firstMasterIP[0], firstMasterIP[1], firstMasterIP[2], firstMasterIP[3] + byte(DefaultInternalLbStaticIPOffset)}
kubeconfig = strings.Replace(kubeconfig, "{{WrapAsVerbatim \"reference(concat('Microsoft.Network/publicIPAddresses/', variables('masterPublicIPAddressName'))).dnsSettings.fqdn\"}}", lbIP.String(), -1)
} else {
// Master count is 1, use the master IP
kubeconfig = strings.Replace(kubeconfig, "{{WrapAsVerbatim \"reference(concat('Microsoft.Network/publicIPAddresses/', variables('masterPublicIPAddressName'))).dnsSettings.fqdn\"}}", properties.MasterProfile.FirstConsecutiveStaticIP, -1)
}
} else {
kubeconfig = strings.Replace(kubeconfig, "{{WrapAsVerbatim \"reference(concat('Microsoft.Network/publicIPAddresses/', variables('masterPublicIPAddressName'))).dnsSettings.fqdn\"}}", FormatAzureProdFQDN(properties.MasterProfile.DNSPrefix, location), -1)
}
kubeconfig = strings.Replace(kubeconfig, "{{WrapAsVariable \"resourceGroup\"}}", properties.MasterProfile.DNSPrefix, -1)
var authInfo string
if properties.AADProfile == nil {
authInfo = fmt.Sprintf("{\"client-certificate-data\":\"%v\",\"client-key-data\":\"%v\"}",
base64.StdEncoding.EncodeToString([]byte(properties.CertificateProfile.KubeConfigCertificate)),
base64.StdEncoding.EncodeToString([]byte(properties.CertificateProfile.KubeConfigPrivateKey)))
} else {
tenantID := properties.AADProfile.TenantID
if len(tenantID) == 0 {
tenantID = "common"
}
authInfo = fmt.Sprintf("{\"auth-provider\":{\"name\":\"azure\",\"config\":{\"environment\":\"%v\",\"tenant-id\":\"%v\",\"apiserver-id\":\"%v\",\"client-id\":\"%v\"}}}",
getCloudTargetEnv(location),
tenantID,
properties.AADProfile.ServerAppID,
properties.AADProfile.ClientAppID)
}
kubeconfig = strings.Replace(kubeconfig, "{{authInfo}}", authInfo, -1)
return kubeconfig, nil
}
// formatAzureProdFQDNs constructs all possible Azure prod fqdn
func formatAzureProdFQDNs(fqdnPrefix string) []string {
var fqdns []string
for _, location := range AzureLocations {
fqdns = append(fqdns, FormatAzureProdFQDN(fqdnPrefix, location))
}
return fqdns
}
// FormatAzureProdFQDN constructs an Azure prod fqdn
func FormatAzureProdFQDN(fqdnPrefix string, location string) string {
var FQDNFormat string
switch getCloudTargetEnv(location) {
case azureChinaCloud:
FQDNFormat = AzureChinaCloudSpec.EndpointConfig.ResourceManagerVMDNSSuffix
case azureGermanCloud:
FQDNFormat = AzureGermanCloudSpec.EndpointConfig.ResourceManagerVMDNSSuffix
case azureUSGovernmentCloud:
FQDNFormat = AzureUSGovernmentCloud.EndpointConfig.ResourceManagerVMDNSSuffix
default:
FQDNFormat = AzureCloudSpec.EndpointConfig.ResourceManagerVMDNSSuffix
}
return fmt.Sprintf("%s.%s."+FQDNFormat, fqdnPrefix, location)
}
//getCloudSpecConfig returns the kubenernetes container images url configurations based on the deploy target environment
//for example: if the target is the public azure, then the default container image url should be k8s-gcrio.azureedge.net/...
//if the target is azure china, then the default container image should be mirror.azure.cn:5000/google_container/...
func getCloudSpecConfig(location string) AzureEnvironmentSpecConfig {
switch getCloudTargetEnv(location) {
case azureChinaCloud:
return AzureChinaCloudSpec
case azureGermanCloud:
return AzureGermanCloudSpec
case azureUSGovernmentCloud:
return AzureUSGovernmentCloud
default:
return AzureCloudSpec
}
}
// validateDistro checks if the requested orchestrator type is supported on the requested Linux distro.
func validateDistro(cs *api.ContainerService) bool {
// Check Master distro
if cs.Properties.MasterProfile != nil && cs.Properties.MasterProfile.Distro == api.RHEL &&
(cs.Properties.OrchestratorProfile.OrchestratorType != api.SwarmMode && cs.Properties.OrchestratorProfile.OrchestratorType != api.OpenShift) {
log.Fatalf("Orchestrator type %s not suported on RHEL Master", cs.Properties.OrchestratorProfile.OrchestratorType)
return false
}
// Check Agent distros
for _, agentProfile := range cs.Properties.AgentPoolProfiles {
if agentProfile.Distro == api.RHEL &&
(cs.Properties.OrchestratorProfile.OrchestratorType != api.SwarmMode && cs.Properties.OrchestratorProfile.OrchestratorType != api.OpenShift) {
log.Fatalf("Orchestrator type %s not suported on RHEL Agent", cs.Properties.OrchestratorProfile.OrchestratorType)
return false
}
}
return true
}
// getCloudTargetEnv determines and returns whether the region is a sovereign cloud which
// have their own data compliance regulations (China/Germany/USGov) or standard
// Azure public cloud
func getCloudTargetEnv(location string) string {
loc := strings.ToLower(strings.Join(strings.Fields(location), ""))
switch {
case loc == "chinaeast" || loc == "chinanorth" || loc == "chinaeast2" || loc == "chinanorth2":
return azureChinaCloud
case loc == "germanynortheast" || loc == "germanycentral":
return azureGermanCloud
case strings.HasPrefix(loc, "usgov") || strings.HasPrefix(loc, "usdod"):
return azureUSGovernmentCloud
default:
return azurePublicCloud
}
}
func getOpenshiftMasterShAsset(version string) string {
switch version {
case common.OpenShiftVersion3Dot9Dot0:
return openshift39MasterScript
case common.OpenShiftVersionUnstable:
return openshiftMasterScript
default:
panic(fmt.Sprintf("BUG: invalid OpenShift version %s", version))
}
}
func getOpenshiftNodeShAsset(version string) string {
switch version {
case common.OpenShiftVersion3Dot9Dot0:
return openshift39NodeScript
case common.OpenShiftVersionUnstable:
return openshiftNodeScript
default:
panic(fmt.Sprintf("BUG: invalid OpenShift version %s", version))
}
}
func generateIPList(count int, firstAddr string) []string {
ipaddr := net.ParseIP(firstAddr).To4()
if ipaddr == nil {
panic(fmt.Sprintf("IPAddr '%s' is an invalid IP address", firstAddr))
}
ret := make([]string, count)
for i := 0; i < count; i++ {
ret[i] = fmt.Sprintf("%d.%d.%d.%d", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]+byte(i))
}
return ret
}
func addValue(m paramsMap, k string, v interface{}) {
m[k] = paramsMap{
"value": v,
}
}
func addKeyvaultReference(m paramsMap, k string, vaultID, secretName, secretVersion string) {
m[k] = paramsMap{
"reference": &KeyVaultRef{
KeyVault: KeyVaultID{
ID: vaultID,
},
SecretName: secretName,
SecretVersion: secretVersion,
},
}
}
func addSecret(m paramsMap, k string, v interface{}, encode bool) {
str, ok := v.(string)
if !ok {
addValue(m, k, v)
return
}
parts := keyvaultSecretPathRe.FindStringSubmatch(str)
if parts == nil || len(parts) != 5 {
if encode {
addValue(m, k, base64.StdEncoding.EncodeToString([]byte(str)))
} else {
addValue(m, k, str)
}
return
}
addKeyvaultReference(m, k, parts[1], parts[2], parts[4])
}
// getStorageAccountType returns the support managed disk storage tier for a give VM size
func getStorageAccountType(sizeName string) (string, error) {
spl := strings.Split(sizeName, "_")
if len(spl) < 2 {
return "", errors.Errorf("Invalid sizeName: %s", sizeName)
}
capability := spl[1]
if strings.Contains(strings.ToLower(capability), "s") {
return "Premium_LRS", nil
}
return "Standard_LRS", nil
}
func makeMasterExtensionScriptCommands(cs *api.ContainerService) string {
copyIndex := "',copyIndex(),'"
if cs.Properties.OrchestratorProfile.IsKubernetes() || cs.Properties.OrchestratorProfile.IsOpenShift() {
copyIndex = "',copyIndex(variables('masterOffset')),'"
}
return makeExtensionScriptCommands(cs.Properties.MasterProfile.PreprovisionExtension,
cs.Properties.ExtensionProfiles, copyIndex)
}
func makeAgentExtensionScriptCommands(cs *api.ContainerService, profile *api.AgentPoolProfile) string {
copyIndex := "',copyIndex(),'"
if profile.IsAvailabilitySets() {
copyIndex = fmt.Sprintf("',copyIndex(variables('%sOffset')),'", profile.Name)
}
if profile.OSType == api.Windows {
return makeWindowsExtensionScriptCommands(profile.PreprovisionExtension,
cs.Properties.ExtensionProfiles, copyIndex)
}
return makeExtensionScriptCommands(profile.PreprovisionExtension,
cs.Properties.ExtensionProfiles, copyIndex)
}
func makeExtensionScriptCommands(extension *api.Extension, extensionProfiles []*api.ExtensionProfile, copyIndex string) string {
var extensionProfile *api.ExtensionProfile
for _, eP := range extensionProfiles {
if strings.EqualFold(eP.Name, extension.Name) {
extensionProfile = eP
break
}
}
if extensionProfile == nil {
panic(fmt.Sprintf("%s extension referenced was not found in the extension profile", extension.Name))
}
extensionsParameterReference := fmt.Sprintf("parameters('%sParameters')", extensionProfile.Name)
scriptURL := getExtensionURL(extensionProfile.RootURL, extensionProfile.Name, extensionProfile.Version, extensionProfile.Script, extensionProfile.URLQuery)
scriptFilePath := fmt.Sprintf("/opt/azure/containers/extensions/%s/%s", extensionProfile.Name, extensionProfile.Script)
return fmt.Sprintf("- sudo /usr/bin/curl --retry 5 --retry-delay 10 --retry-max-time 30 -o %s --create-dirs \"%s\" \n- sudo /bin/chmod 744 %s \n- sudo %s ',%s,' > /var/log/%s-output.log",
scriptFilePath, scriptURL, scriptFilePath, scriptFilePath, extensionsParameterReference, extensionProfile.Name)
}
func makeWindowsExtensionScriptCommands(extension *api.Extension, extensionProfiles []*api.ExtensionProfile, copyIndex string) string {
var extensionProfile *api.ExtensionProfile
for _, eP := range extensionProfiles {
if strings.EqualFold(eP.Name, extension.Name) {
extensionProfile = eP
break
}
}
if extensionProfile == nil {
panic(fmt.Sprintf("%s extension referenced was not found in the extension profile", extension.Name))
}
scriptURL := getExtensionURL(extensionProfile.RootURL, extensionProfile.Name, extensionProfile.Version, extensionProfile.Script, extensionProfile.URLQuery)
scriptFileDir := fmt.Sprintf("$env:SystemDrive:/AzureData/extensions/%s", extensionProfile.Name)
scriptFilePath := fmt.Sprintf("%s/%s", scriptFileDir, extensionProfile.Script)
return fmt.Sprintf("New-Item -ItemType Directory -Force -Path \"%s\" ; Invoke-WebRequest -Uri \"%s\" -OutFile \"%s\" ; powershell \"%s %s\"\n", scriptFileDir, scriptURL, scriptFilePath, scriptFilePath, "$preprovisionExtensionParams")
}
func getDCOSWindowsAgentPreprovisionParameters(cs *api.ContainerService, profile *api.AgentPoolProfile) string {
extension := profile.PreprovisionExtension
var extensionProfile *api.ExtensionProfile
for _, eP := range cs.Properties.ExtensionProfiles {
if strings.EqualFold(eP.Name, extension.Name) {
extensionProfile = eP
break
}
}
parms := extensionProfile.ExtensionParameters
return parms
}
func getDCOSDefaultBootstrapInstallerURL(profile *api.OrchestratorProfile) string {
if profile.OrchestratorType == api.DCOS {
switch profile.OrchestratorVersion {
case common.DCOSVersion1Dot11Dot2:
return "https://dcos-mirror.azureedge.net/dcos-1-11-2/dcos_generate_config.sh"
case common.DCOSVersion1Dot11Dot0:
return "https://dcos-mirror.azureedge.net/dcos-1-11-0/dcos_generate_config.sh"
}
}
return ""
}
func getDCOSDefaultWindowsBootstrapInstallerURL(profile *api.OrchestratorProfile) string {
if profile.OrchestratorType == api.DCOS {
switch profile.OrchestratorVersion {
case common.DCOSVersion1Dot11Dot2:
return "https://dcos-mirror.azureedge.net/dcos-windows/1-11-2"
case common.DCOSVersion1Dot11Dot0:
return "https://dcos-mirror.azureedge.net/dcos-windows/1-11-0"
}
}
return ""
}
func getDCOSDefaultProviderPackageGUID(orchestratorType string, orchestratorVersion string, masterCount int) string {
if orchestratorType == api.DCOS {
switch orchestratorVersion {
case common.DCOSVersion1Dot10Dot0:
switch masterCount {
case 1:
return "c4ec6210f396b8e435177b82e3280a2cef0ce721"
case 3:
return "08197947cb57d479eddb077a429fa15c139d7d20"
case 5:
return "f286ad9d3641da5abb622e4a8781f73ecd8492fa"
}
case common.DCOSVersion1Dot9Dot0:
switch masterCount {
case 1:
return "bcc883b7a3191412cf41824bdee06c1142187a0b"
case 3:
return "dcff7e24c0c1827bebeb7f1a806f558054481b33"
case 5:
return "b41bfa84137a6374b2ff5eb1655364d7302bd257"
}
case common.DCOSVersion1Dot9Dot8:
switch masterCount {
case 1:
return "e8b0e3fc4a16394dc6dd5b19fc54bf1543bff429"
case 3:
return "2d36c3f570d9dd7d187c699f9a322ed9d95e7dfa"
case 5:
return "c03c9587f88929f310b80af4f448b7b51654f1c8"
}
case common.DCOSVersion1Dot8Dot8:
switch masterCount {
case 1:
return "441385ce2f5942df7e29075c12fb38fa5e92cbba"
case 3:
return "b1cd359287504efb780257bd12cc3a63704e42d4"
case 5:
return "d9b61156dfcc9383e014851529738aa550ef57d9"
}
}
}
return ""
}
func getDCOSDefaultRepositoryURL(orchestratorType string, orchestratorVersion string) string {
if orchestratorType == api.DCOS {
switch orchestratorVersion {
case common.DCOSVersion1Dot10Dot0:
return "https://dcosio.azureedge.net/dcos/stable/1.10.0"
case common.DCOSVersion1Dot9Dot8:
return "https://dcosio.azureedge.net/dcos/stable/1.9.8"
default:
return "https://dcosio.azureedge.net/dcos/stable"
}
}
return ""
}
func isNSeriesSKU(profile *api.AgentPoolProfile) bool {
return strings.Contains(profile.VMSize, "Standard_N")
}
func isCustomVNET(a []*api.AgentPoolProfile) bool {
if a != nil {
for _, agentPoolProfile := range a {
if !agentPoolProfile.IsCustomVNET() {
return false
}
}
return true
}
return false
}
func getGPUDriversInstallScript(profile *api.AgentPoolProfile) string {
// latest version of the drivers. Later this parameter could be bubbled up so that users can choose specific driver versions.
dv := "396.26"
dest := "/usr/local/nvidia"
nvidiaDockerVersion := "2.0.3"
dockerVersion := "1.13.1-1"
nvidiaContainerRuntimeVersion := "2.0.0"
/*
First we remove the nouveau drivers, which are the open source drivers for NVIDIA cards. Nouveau is installed on NV Series VMs by default.
We also installed needed dependencies.
*/
installScript := fmt.Sprintf(`- rmmod nouveau
- sh -c "echo \"blacklist nouveau\" >> /etc/modprobe.d/blacklist.conf"
- update-initramfs -u
- mkdir -p %s
- cd %s`, dest, dest)
/*
Installing nvidia-docker, setting nvidia runtime as default and restarting docker daemon
*/
installScript += fmt.Sprintf(`
- retrycmd_if_failure_no_stats 180 1 5 curl -fsSL https://nvidia.github.io/nvidia-docker/gpgkey > /tmp/aptnvidia.gpg
- cat /tmp/aptnvidia.gpg | apt-key add -
- retrycmd_if_failure_no_stats 180 1 5 curl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu16.04/amd64/nvidia-docker.list > /tmp/nvidia-docker.list
- cat /tmp/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
- apt_get_update
- retrycmd_if_failure 5 5 300 apt-get install -y linux-headers-$(uname -r) gcc make
- retrycmd_if_failure 5 5 300 apt-get -o Dpkg::Options::="--force-confold" install -y nvidia-docker2=%s+docker%s nvidia-container-runtime=%s+docker%s
- sudo pkill -SIGHUP dockerd
- mkdir -p %s
- cd %s`, nvidiaDockerVersion, dockerVersion, nvidiaContainerRuntimeVersion, dockerVersion, dest, dest)
/*
Download the .run file from NVIDIA.
Nvidia libraries are always install in /usr/lib/x86_64-linux-gnu, and there is no option in the run file to change this.
Instead we use Overlayfs to move the newly installed libraries under /usr/local/nvidia/lib64
*/
installScript += fmt.Sprintf(`
- retrycmd_if_failure 5 10 60 curl -fLS https://us.download.nvidia.com/tesla/%s/NVIDIA-Linux-x86_64-%s.run -o nvidia-drivers-%s
- mkdir -p lib64 overlay-workdir
- mount -t overlay -o lowerdir=/usr/lib/x86_64-linux-gnu,upperdir=lib64,workdir=overlay-workdir none /usr/lib/x86_64-linux-gnu`, dv, dv, dv)
/*
Install the drivers and update /etc/ld.so.conf.d/nvidia.conf which will make the libraries discoverable through $LD_LIBRARY_PATH.
Run nvidia-smi to test the installation, unmount overlayfs and restard kubelet (GPUs are only discovered when kubelet starts)
*/
installScript += fmt.Sprintf(`
- sh nvidia-drivers-%s --silent --accept-license --no-drm --utility-prefix="%s" --opengl-prefix="%s"
- echo "%s" > /etc/ld.so.conf.d/nvidia.conf
- sudo ldconfig
- umount /usr/lib/x86_64-linux-gnu
- nvidia-modprobe -u -c0
- %s/bin/nvidia-smi
- sudo ldconfig
- retrycmd_if_failure 5 10 60 systemctl restart kubelet`, dv, dest, dest, fmt.Sprintf("%s/lib64", dest), dest)
/* If a new GPU sku becomes available, add a key to this map, but only provide an installation script if you have a confirmation
that we have an agreement with NVIDIA for this specific gpu. Otherwise use the warning message.
*/
dm := map[string]string{
// K80
"Standard_NC6": installScript,
"Standard_NC12": installScript,
"Standard_NC24": installScript,
"Standard_NC24r": installScript,
// M60
"Standard_NV6": installScript,
"Standard_NV12": installScript,
"Standard_NV24": installScript,
"Standard_NV24r": installScript,
// P40
"Standard_ND6s": installScript,
"Standard_ND12s": installScript,
"Standard_ND24s": installScript,
"Standard_ND24rs": installScript,
// P100
"Standard_NC6s_v2": installScript,
"Standard_NC12s_v2": installScript,
"Standard_NC24s_v2": installScript,
"Standard_NC24rs_v2": installScript,
// V100
"Standard_NC6s_v3": installScript,
"Standard_NC12s_v3": installScript,
"Standard_NC24s_v3": installScript,
"Standard_NC24rs_v3": installScript,
}
if _, ok := dm[profile.VMSize]; ok {
return dm[profile.VMSize]
}
// The VM is not part of the GPU skus, no extra steps.
return ""
}
func getDCOSCustomDataPublicIPStr(orchestratorType string, masterCount int) string {
if orchestratorType == api.DCOS {
var buf bytes.Buffer
for i := 0; i < masterCount; i++ {
buf.WriteString(fmt.Sprintf("reference(variables('masterVMNic')[%d]).ipConfigurations[0].properties.privateIPAddress,", i))
if i < (masterCount - 1) {
buf.WriteString(`'\\\", \\\"', `)
}
}
return buf.String()
}
return ""
}
func getDCOSMasterCustomNodeLabels() string {
// return empty string for DCOS since no attribtutes needed on master
return ""
}
func getDCOSAgentCustomNodeLabels(profile *api.AgentPoolProfile) string {
var buf bytes.Buffer
var attrstring string
buf.WriteString("")
// always write MESOS_ATTRIBUTES because
// the provision script will add FD/UD attributes
// at node provisioning time
if len(profile.OSType) > 0 {
attrstring = fmt.Sprintf("MESOS_ATTRIBUTES=\"os:%s", profile.OSType)
} else {
attrstring = fmt.Sprintf("MESOS_ATTRIBUTES=\"os:%s", api.Linux)
}
if len(profile.Ports) > 0 {
attrstring += ";public_ip:yes"
}
buf.WriteString(attrstring)
if len(profile.CustomNodeLabels) > 0 {
for k, v := range profile.CustomNodeLabels {
buf.WriteString(fmt.Sprintf(";%s:%s", k, v))
}
}
buf.WriteString("\"")
return buf.String()
}
func getDCOSWindowsAgentCustomAttributes(profile *api.AgentPoolProfile) string {
var buf bytes.Buffer
var attrstring string
buf.WriteString("")
if len(profile.OSType) > 0 {
attrstring = fmt.Sprintf("os:%s", profile.OSType)
} else {
attrstring = fmt.Sprintf("os:windows")
}
if len(profile.Ports) > 0 {
attrstring += ";public_ip:yes"
}
buf.WriteString(attrstring)
if len(profile.CustomNodeLabels) > 0 {
for k, v := range profile.CustomNodeLabels {
buf.WriteString(fmt.Sprintf(";%s:%s", k, v))
}
}
return buf.String()
}
func getVNETAddressPrefixes(properties *api.Properties) string {
visitedSubnets := make(map[string]bool)
var buf bytes.Buffer
buf.WriteString(`"[variables('masterSubnet')]"`)
visitedSubnets[properties.MasterProfile.Subnet] = true
for _, profile := range properties.AgentPoolProfiles {
if _, ok := visitedSubnets[profile.Subnet]; !ok {
buf.WriteString(fmt.Sprintf(",\n \"[variables('%sSubnet')]\"", profile.Name))
}
}
return buf.String()
}
func getVNETSubnetDependencies(properties *api.Properties) string {
agentString := ` "[concat('Microsoft.Network/networkSecurityGroups/', variables('%sNSGName'))]"`
var buf bytes.Buffer
for index, agentProfile := range properties.AgentPoolProfiles {
if index > 0 {
buf.WriteString(",\n")
}
buf.WriteString(fmt.Sprintf(agentString, agentProfile.Name))
}
return buf.String()
}
func getVNETSubnets(properties *api.Properties, addNSG bool) string {
masterString := `{
"name": "[variables('masterSubnetName')]",
"properties": {
"addressPrefix": "[variables('masterSubnet')]"
}
}`
agentString := ` {
"name": "[variables('%sSubnetName')]",
"properties": {
"addressPrefix": "[variables('%sSubnet')]"
}
}`
agentStringNSG := ` {
"name": "[variables('%sSubnetName')]",
"properties": {
"addressPrefix": "[variables('%sSubnet')]",
"networkSecurityGroup": {
"id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('%sNSGName'))]"
}
}
}`
var buf bytes.Buffer
buf.WriteString(masterString)
for _, agentProfile := range properties.AgentPoolProfiles {
buf.WriteString(",\n")
if addNSG {
buf.WriteString(fmt.Sprintf(agentStringNSG, agentProfile.Name, agentProfile.Name, agentProfile.Name))
} else {
buf.WriteString(fmt.Sprintf(agentString, agentProfile.Name, agentProfile.Name))
}
}
return buf.String()
}
func getLBRule(name string, port int) string {
return fmt.Sprintf(` {
"name": "LBRule%d",
"properties": {
"backendAddressPool": {
"id": "[concat(variables('%sLbID'), '/backendAddressPools/', variables('%sLbBackendPoolName'))]"
},
"backendPort": %d,
"enableFloatingIP": false,
"frontendIPConfiguration": {
"id": "[variables('%sLbIPConfigID')]"
},
"frontendPort": %d,
"idleTimeoutInMinutes": 5,
"loadDistribution": "Default",
"probe": {
"id": "[concat(variables('%sLbID'),'/probes/tcp%dProbe')]"
},
"protocol": "tcp"
}
}`, port, name, name, port, name, port, name, port)
}
func getLBRules(name string, ports []int) string {
var buf bytes.Buffer
for index, port := range ports {
if index > 0 {
buf.WriteString(",\n")
}
buf.WriteString(getLBRule(name, port))
}
return buf.String()
}
func getProbe(port int) string {
return fmt.Sprintf(` {
"name": "tcp%dProbe",
"properties": {
"intervalInSeconds": "5",
"numberOfProbes": "2",
"port": %d,
"protocol": "tcp"
}
}`, port, port)
}
func getProbes(ports []int) string {
var buf bytes.Buffer
for index, port := range ports {
if index > 0 {
buf.WriteString(",\n")
}
buf.WriteString(getProbe(port))
}
return buf.String()
}
func getSecurityRule(port int, portIndex int) string {
// BaseLBPriority specifies the base lb priority.
BaseLBPriority := 200
return fmt.Sprintf(` {
"name": "Allow_%d",
"properties": {
"access": "Allow",
"description": "Allow traffic from the Internet to port %d",
"destinationAddressPrefix": "*",
"destinationPortRange": "%d",
"direction": "Inbound",
"priority": %d,
"protocol": "*",
"sourceAddressPrefix": "Internet",
"sourcePortRange": "*"
}
}`, port, port, port, BaseLBPriority+portIndex)
}
func getDataDisks(a *api.AgentPoolProfile) string {
if !a.HasDisks() {
return ""
}
var buf bytes.Buffer
buf.WriteString("\"dataDisks\": [\n")
dataDisks := ` {
"createOption": "Empty",
"diskSizeGB": "%d",
"lun": %d,
"name": "[concat(variables('%sVMNamePrefix'), copyIndex(),'-datadisk%d')]",
"vhd": {
"uri": "[concat('http://',variables('storageAccountPrefixes')[mod(add(add(div(copyIndex(),variables('maxVMsPerStorageAccount')),variables('%sStorageAccountOffset')),variables('dataStorageAccountPrefixSeed')),variables('storageAccountPrefixesCount'))],variables('storageAccountPrefixes')[div(add(add(div(copyIndex(),variables('maxVMsPerStorageAccount')),variables('%sStorageAccountOffset')),variables('dataStorageAccountPrefixSeed')),variables('storageAccountPrefixesCount'))],variables('%sDataAccountName'),'.blob.core.windows.net/vhds/',variables('%sVMNamePrefix'),copyIndex(), '--datadisk%d.vhd')]"
}
}`
managedDataDisks := ` {
"diskSizeGB": "%d",
"lun": %d,
"createOption": "Empty"
}`
for i, diskSize := range a.DiskSizesGB {
if i > 0 {
buf.WriteString(",\n")
}
if a.StorageProfile == api.StorageAccount {
buf.WriteString(fmt.Sprintf(dataDisks, diskSize, i, a.Name, i, a.Name, a.Name, a.Name, a.Name, i))
} else if a.StorageProfile == api.ManagedDisks {
buf.WriteString(fmt.Sprintf(managedDataDisks, diskSize, i))
}
}
buf.WriteString("\n ],")
return buf.String()
}
func getSecurityRules(ports []int) string {
var buf bytes.Buffer
for index, port := range ports {
if index > 0 {
buf.WriteString(",\n")
}
buf.WriteString(getSecurityRule(port, index))
}
return buf.String()
}
// getSingleLineForTemplate returns the file as a single line for embedding in an arm template
func (t *TemplateGenerator) getSingleLineForTemplate(textFilename string, cs *api.ContainerService, profile interface{}) (string, error) {
b, err := Asset(textFilename)
if err != nil {
return "", t.Translator.Errorf("yaml file %s does not exist", textFilename)
}
// use go templates to process the text filename
templ := template.New("customdata template").Funcs(t.getTemplateFuncMap(cs))
if _, err = templ.New(textFilename).Parse(string(b)); err != nil {
return "", t.Translator.Errorf("error parsing file %s: %v", textFilename, err)
}
var buffer bytes.Buffer
if err = templ.ExecuteTemplate(&buffer, textFilename, profile); err != nil {
return "", t.Translator.Errorf("error executing template for file %s: %v", textFilename, err)
}
expandedTemplate := buffer.String()
textStr := escapeSingleLine(string(expandedTemplate))
return textStr, nil
}
func escapeSingleLine(escapedStr string) string {
// template.JSEscapeString leaves undesirable chars that don't work with pretty print
escapedStr = strings.Replace(escapedStr, "\\", "\\\\", -1)
escapedStr = strings.Replace(escapedStr, "\r\n", "\\n", -1)
escapedStr = strings.Replace(escapedStr, "\n", "\\n", -1)
escapedStr = strings.Replace(escapedStr, "\"", "\\\"", -1)
return escapedStr
}
// getBase64CustomScript will return a base64 of the CSE
func getBase64CustomScript(csFilename string) string {
b, err := Asset(csFilename)
if err != nil {
// this should never happen and this is a bug
panic(fmt.Sprintf("BUG: %s", err.Error()))
}
// translate the parameters
csStr := string(b)
csStr = strings.Replace(csStr, "\r\n", "\n", -1)
return getBase64CustomScriptFromStr(csStr)
}
// getBase64CustomScript will return a base64 of the CSE
func getBase64CustomScriptFromStr(str string) string {
var gzipB bytes.Buffer
w := gzip.NewWriter(&gzipB)
w.Write([]byte(str))
w.Close()
return base64.StdEncoding.EncodeToString(gzipB.Bytes())
}
func getDCOSProvisionScript(script string) string {
// add the provision script
bp, err := Asset(script)
if err != nil {
panic(fmt.Sprintf("BUG: %s", err.Error()))
}
provisionScript := string(bp)
if strings.Contains(provisionScript, "'") {
panic(fmt.Sprintf("BUG: %s may not contain character '", script))
}
return strings.Replace(strings.Replace(provisionScript, "\r\n", "\n", -1), "\n", "\n\n ", -1)
}
func getDCOSAgentProvisionScript(profile *api.AgentPoolProfile, orchProfile *api.OrchestratorProfile, bootstrapIP string) string {
// add the provision script
scriptname := dcos2Provision
if orchProfile.DcosConfig == nil || orchProfile.DcosConfig.BootstrapProfile == nil {
if profile.OSType == api.Windows {
scriptname = dcosWindowsProvision
} else {
scriptname = dcosProvision
}
}
bp, err := Asset(scriptname)
if err != nil {
panic(fmt.Sprintf("BUG: %s", err.Error()))
}
provisionScript := string(bp)
if strings.Contains(provisionScript, "'") {
panic(fmt.Sprintf("BUG: %s may not contain character '", dcosProvision))
}
// the embedded roleFileContents
var roleFileContents string
if len(profile.Ports) > 0 {
// public agents
roleFileContents = "touch /etc/mesosphere/roles/slave_public"
} else {
roleFileContents = "touch /etc/mesosphere/roles/slave"
}
provisionScript = strings.Replace(provisionScript, "ROLESFILECONTENTS", roleFileContents, -1)
provisionScript = strings.Replace(provisionScript, "BOOTSTRAP_IP", bootstrapIP, -1)
var b bytes.Buffer
b.WriteString(provisionScript)
b.WriteString("\n")
if len(orchProfile.DcosConfig.Registry) == 0 {
b.WriteString("rm /etc/docker.tar.gz\n")
}
return strings.Replace(strings.Replace(b.String(), "\r\n", "\n", -1), "\n", "\n\n ", -1)
}
func getDCOSMasterProvisionScript(orchProfile *api.OrchestratorProfile, bootstrapIP string) string {
scriptname := dcos2Provision
if orchProfile.DcosConfig == nil || orchProfile.DcosConfig.BootstrapProfile == nil {
scriptname = dcosProvision
}
// add the provision script
bp, err := Asset(scriptname)
if err != nil {
panic(fmt.Sprintf("BUG: %s", err.Error()))
}
provisionScript := string(bp)
if strings.Contains(provisionScript, "'") {
panic(fmt.Sprintf("BUG: %s may not contain character '", scriptname))
}
// the embedded roleFileContents
roleFileContents := `touch /etc/mesosphere/roles/master
touch /etc/mesosphere/roles/azure_master`
provisionScript = strings.Replace(provisionScript, "ROLESFILECONTENTS", roleFileContents, -1)
provisionScript = strings.Replace(provisionScript, "BOOTSTRAP_IP", bootstrapIP, -1)
var b bytes.Buffer
b.WriteString(provisionScript)
b.WriteString("\n")
return strings.Replace(strings.Replace(b.String(), "\r\n", "\n", -1), "\n", "\n\n ", -1)
}
func getDCOSCustomDataTemplate(orchestratorType, orchestratorVersion string) string {
switch orchestratorType {
case api.DCOS:
switch orchestratorVersion {
case common.DCOSVersion1Dot8Dot8:
return dcosCustomData188
case common.DCOSVersion1Dot9Dot0:
return dcosCustomData190
case common.DCOSVersion1Dot9Dot8:
return dcosCustomData198
case common.DCOSVersion1Dot10Dot0:
return dcosCustomData110
case common.DCOSVersion1Dot11Dot0:
return dcos2CustomData1110
case common.DCOSVersion1Dot11Dot2:
return dcos2CustomData1112
}
default:
// it is a bug to get here
panic(fmt.Sprintf("BUG: invalid orchestrator %s", orchestratorType))
}
return ""
}
// getSingleLineForTemplate returns the file as a single line for embedding in an arm template
func getSingleLineDCOSCustomData(orchestratorType, yamlFilename string, masterCount int, replaceMap map[string]string) string {
b, err := Asset(yamlFilename)
if err != nil {
panic(fmt.Sprintf("BUG getting yaml custom data file: %s", err.Error()))
}
yamlStr := string(b)
for k, v := range replaceMap {
yamlStr = strings.Replace(yamlStr, k, v, -1)
}
// convert to json
jsonBytes, err4 := yaml.YAMLToJSON([]byte(yamlStr))
if err4 != nil {
panic(fmt.Sprintf("BUG: %s", err4.Error()))
}
yamlStr = string(jsonBytes)
// convert to one line
yamlStr = strings.Replace(yamlStr, "\\", "\\\\", -1)
yamlStr = strings.Replace(yamlStr, "\r\n", "\\n", -1)
yamlStr = strings.Replace(yamlStr, "\n", "\\n", -1)
yamlStr = strings.Replace(yamlStr, "\"", "\\\"", -1)
// variable replacement
rVariable, e1 := regexp.Compile("{{{([^}]*)}}}")
if e1 != nil {
panic(fmt.Sprintf("BUG: %s", e1.Error()))
}
yamlStr = rVariable.ReplaceAllString(yamlStr, "',variables('$1'),'")
// replace the internal values
publicIPStr := getDCOSCustomDataPublicIPStr(orchestratorType, masterCount)
yamlStr = strings.Replace(yamlStr, "DCOSCUSTOMDATAPUBLICIPSTR", publicIPStr, -1)
return yamlStr
}
func buildYamlFileWithWriteFiles(files []string) string {
clusterYamlFile := `#cloud-config
write_files:
%s
`
writeFileBlock := ` - encoding: gzip
content: !!binary |
%s
path: /opt/azure/containers/%s
permissions: "0744"
`
filelines := ""
for _, file := range files {
b64GzipString := getBase64CustomScript(file)
fileNoPath := strings.TrimPrefix(file, "swarm/")
filelines = filelines + fmt.Sprintf(writeFileBlock, b64GzipString, fileNoPath)
}
return fmt.Sprintf(clusterYamlFile, filelines)
}
// Identifies Master distro to use for master parameters
func getMasterDistro(m *api.MasterProfile) api.Distro {
// Use Ubuntu distro if MasterProfile is not defined (e.g. agents-only)
if m == nil {
return api.Ubuntu
}
// MasterProfile.Distro configured by defaults#setMasterNetworkDefaults
return m.Distro
}
func getKubernetesSubnets(properties *api.Properties) string {
subnetString := `{
"name": "podCIDR%d",
"properties": {
"addressPrefix": "10.244.%d.0/24",
"networkSecurityGroup": {
"id": "[variables('nsgID')]"
},
"routeTable": {
"id": "[variables('routeTableID')]"
}
}
}`
var buf bytes.Buffer
cidrIndex := getKubernetesPodStartIndex(properties)
for _, agentProfile := range properties.AgentPoolProfiles {
if agentProfile.OSType == api.Windows {
for i := 0; i < agentProfile.Count; i++ {
buf.WriteString(",\n")
buf.WriteString(fmt.Sprintf(subnetString, cidrIndex, cidrIndex))
cidrIndex++
}
}
}
return buf.String()
}
func getKubernetesPodStartIndex(properties *api.Properties) int {
nodeCount := 0
nodeCount += properties.MasterProfile.Count
for _, agentProfile := range properties.AgentPoolProfiles {
if agentProfile.OSType != api.Windows {
nodeCount += agentProfile.Count
}
}
return nodeCount + 1
}
// getLinkedTemplatesForExtensions returns the
// Microsoft.Resources/deployments for each extension
//func getLinkedTemplatesForExtensions(properties api.Properties) string {
func getLinkedTemplatesForExtensions(properties *api.Properties) string {
var result string
extensions := properties.ExtensionProfiles
masterProfileExtensions := properties.MasterProfile.Extensions
orchestratorType := properties.OrchestratorProfile.OrchestratorType
for err, extensionProfile := range extensions {
_ = err
masterOptedForExtension, singleOrAll := validateProfileOptedForExtension(extensionProfile.Name, masterProfileExtensions)
if masterOptedForExtension {
result += ","
dta, e := getMasterLinkedTemplateText(properties.MasterProfile, orchestratorType, extensionProfile, singleOrAll)
if e != nil {
fmt.Println(e.Error())
return ""
}
result += dta
}
for _, agentPoolProfile := range properties.AgentPoolProfiles {
poolProfileExtensions := agentPoolProfile.Extensions
poolOptedForExtension, singleOrAll := validateProfileOptedForExtension(extensionProfile.Name, poolProfileExtensions)
if poolOptedForExtension {
result += ","
dta, e := getAgentPoolLinkedTemplateText(agentPoolProfile, orchestratorType, extensionProfile, singleOrAll)
if e != nil {
fmt.Println(e.Error())
return ""
}
result += dta
}
}
}
return result
}
func getMasterLinkedTemplateText(masterProfile *api.MasterProfile, orchestratorType string, extensionProfile *api.ExtensionProfile, singleOrAll string) (string, error) {
extTargetVMNamePrefix := "variables('masterVMNamePrefix')"
loopCount := "[variables('masterCount')]"
loopOffset := ""
if orchestratorType == api.Kubernetes || orchestratorType == api.OpenShift {
// Due to upgrade k8s sometimes needs to install just some of the nodes.
loopCount = "[sub(variables('masterCount'), variables('masterOffset'))]"
loopOffset = "variables('masterOffset')"
}
if strings.EqualFold(singleOrAll, "single") {
loopCount = "1"
}
return internalGetPoolLinkedTemplateText(extTargetVMNamePrefix, orchestratorType, loopCount,
loopOffset, extensionProfile)
}
func getAgentPoolLinkedTemplateText(agentPoolProfile *api.AgentPoolProfile, orchestratorType string, extensionProfile *api.ExtensionProfile, singleOrAll string) (string, error) {
extTargetVMNamePrefix := fmt.Sprintf("variables('%sVMNamePrefix')", agentPoolProfile.Name)
loopCount := fmt.Sprintf("[variables('%sCount'))]", agentPoolProfile.Name)
loopOffset := ""
// Availability sets can have an offset since we don't redeploy vms.
// So we don't want to rerun these extensions in scale up scenarios.
if agentPoolProfile.IsAvailabilitySets() {
loopCount = fmt.Sprintf("[sub(variables('%sCount'), variables('%sOffset'))]",
agentPoolProfile.Name, agentPoolProfile.Name)
loopOffset = fmt.Sprintf("variables('%sOffset')", agentPoolProfile.Name)
}
if strings.EqualFold(singleOrAll, "single") {
loopCount = "1"
}
return internalGetPoolLinkedTemplateText(extTargetVMNamePrefix, orchestratorType, loopCount,
loopOffset, extensionProfile)
}
func internalGetPoolLinkedTemplateText(extTargetVMNamePrefix, orchestratorType, loopCount, loopOffset string, extensionProfile *api.ExtensionProfile) (string, error) {
dta, e := getLinkedTemplateTextForURL(extensionProfile.RootURL, orchestratorType, extensionProfile.Name, extensionProfile.Version, extensionProfile.URLQuery)
if e != nil {
return "", e
}
if strings.Contains(extTargetVMNamePrefix, "master") {
dta = strings.Replace(dta, "EXTENSION_TARGET_VM_TYPE", "master", -1)
} else {
dta = strings.Replace(dta, "EXTENSION_TARGET_VM_TYPE", "agent", -1)
}
extensionsParameterReference := fmt.Sprintf("[parameters('%sParameters')]", extensionProfile.Name)
dta = strings.Replace(dta, "EXTENSION_PARAMETERS_REPLACE", extensionsParameterReference, -1)
dta = strings.Replace(dta, "EXTENSION_URL_REPLACE", extensionProfile.RootURL, -1)
dta = strings.Replace(dta, "EXTENSION_TARGET_VM_NAME_PREFIX", extTargetVMNamePrefix, -1)
if _, err := strconv.Atoi(loopCount); err == nil {
dta = strings.Replace(dta, "\"EXTENSION_LOOP_COUNT\"", loopCount, -1)
} else {
dta = strings.Replace(dta, "EXTENSION_LOOP_COUNT", loopCount, -1)
}
dta = strings.Replace(dta, "EXTENSION_LOOP_OFFSET", loopOffset, -1)
return dta, nil
}
func validateProfileOptedForExtension(extensionName string, profileExtensions []api.Extension) (bool, string) {
for _, extension := range profileExtensions {
if extensionName == extension.Name {
return true, extension.SingleOrAll
}
}
return false, ""
}
// getLinkedTemplateTextForURL returns the string data from
// template-link.json in the following directory:
// extensionsRootURL/extensions/extensionName/version
// It returns an error if the extension cannot be found
// or loaded. getLinkedTemplateTextForURL provides the ability
// to pass a root extensions url for testing
func getLinkedTemplateTextForURL(rootURL, orchestrator, extensionName, version, query string) (string, error) {
supportsExtension, err := orchestratorSupportsExtension(rootURL, orchestrator, extensionName, version, query)
if !supportsExtension {
return "", errors.Wrap(err, "Extension not supported for orchestrator")
}
templateLinkBytes, err := getExtensionResource(rootURL, extensionName, version, "template-link.json", query)
if err != nil {
return "", err
}
return string(templateLinkBytes), nil
}
func orchestratorSupportsExtension(rootURL, orchestrator, extensionName, version, query string) (bool, error) {
orchestratorBytes, err := getExtensionResource(rootURL, extensionName, version, "supported-orchestrators.json", query)
if err != nil {
return false, err
}
var supportedOrchestrators []string
err = json.Unmarshal(orchestratorBytes, &supportedOrchestrators)
if err != nil {
return false, errors.Errorf("Unable to parse supported-orchestrators.json for Extension %s Version %s", extensionName, version)
}
if !stringInSlice(orchestrator, supportedOrchestrators) {
return false, errors.Errorf("Orchestrator: %s not in list of supported orchestrators for Extension: %s Version %s", orchestrator, extensionName, version)
}
return true, nil
}
func getExtensionResource(rootURL, extensionName, version, fileName, query string) ([]byte, error) {
requestURL := getExtensionURL(rootURL, extensionName, version, fileName, query)
res, err := http.Get(requestURL)
if err != nil {
return nil, errors.Wrapf(err, "Unable to GET extension resource for extension: %s with version %s with filename %s at URL: %s", extensionName, version, fileName, requestURL)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, errors.Errorf("Unable to GET extension resource for extension: %s with version %s with filename %s at URL: %s StatusCode: %s: Status: %s", extensionName, version, fileName, requestURL, strconv.Itoa(res.StatusCode), res.Status)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrapf(err, "Unable to GET extension resource for extension: %s with version %s with filename %s at URL: %s", extensionName, version, fileName, requestURL)
}
return body, nil
}
func getExtensionURL(rootURL, extensionName, version, fileName, query string) string {
extensionsDir := "extensions"
url := rootURL + extensionsDir + "/" + extensionName + "/" + version + "/" + fileName
if query != "" {
url += "?" + query
}
return url
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func getSwarmVersions(orchestratorVersion, dockerComposeVersion string) string {
return fmt.Sprintf("\"orchestratorVersion\": \"%s\",\n\"dockerComposeVersion\": \"%s\",\n", orchestratorVersion, dockerComposeVersion)
}
func getAddonByName(addons []api.KubernetesAddon, name string) api.KubernetesAddon {
for i := range addons {
if addons[i].Name == name {
return addons[i]
}
}
return api.KubernetesAddon{}
}
| {
h.Write([]byte(properties.HostedMasterProfile.DNSPrefix))
} |
middlewares.py | # Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
class NewsScraperChallengeSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod | # This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, or item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request or item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class NewsScraperChallengeDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name) | def from_crawler(cls, crawler): |
center.py | from spikeextractors import RecordingExtractor
from .transform import TransformRecording
import numpy as np
class CenterRecording(TransformRecording):
preprocessor_name = 'Center'
def __init__(self, recording, mode, seconds, n_snippets):
if not isinstance(recording, RecordingExtractor):
raise ValueError("'recording' must be a RecordingExtractor")
self._scalar = 1
self._mode = mode
self._seconds = seconds
self._n_snippets = n_snippets
assert self._mode in ['mean', 'median'], "'mode' can be 'mean' or 'median'"
# use n_snippets of equal duration equally distributed on the recording
n_snippets = int(n_snippets)
assert n_snippets > 0, "'n_snippets' must be positive"
snip_len = seconds / n_snippets * recording.get_sampling_frequency()
if seconds * recording.get_sampling_frequency() >= recording.get_num_frames():
traces = recording.get_traces() | traces_snippets = recording.get_snippets(reference_frames=snip_start, snippet_len=snip_len)
traces_snippets = traces_snippets.swapaxes(0, 1)
traces = traces_snippets.reshape((traces_snippets.shape[0],
traces_snippets.shape[1] * traces_snippets.shape[2]))
if self._mode == 'mean':
self._offset = -np.mean(traces, axis=1)
else:
self._offset = -np.median(traces, axis=1)
dtype = str(recording.get_dtype())
if 'uint' in dtype:
if 'numpy' in dtype:
dtype = str(dtype).replace("<class '", "").replace("'>", "")
# drop 'numpy'
dtype = dtype.split('.')[1]
dtype = dtype[1:]
TransformRecording.__init__(self, recording, scalar=self._scalar, offset=self._offset, dtype=dtype)
self._kwargs = {'recording': recording.make_serialized_dict(), 'mode': mode, 'seconds': seconds,
'n_snippets': n_snippets}
def center(recording, mode='median', seconds=10., n_snippets=10):
'''
Removes the offset of the traces channel by channel.
Parameters
----------
recording: RecordingExtractor
The recording extractor to be transformed
mode: str
'median' (default) or 'mean'
seconds: float
Number of seconds used to compute center
n_snippets: int
Number of snippets in which the total 'seconds' are divided spanning the recording duration
Returns
-------
center: CenterRecording
The output recording extractor object
'''
return CenterRecording(recording=recording, mode=mode, seconds=seconds, n_snippets=n_snippets) | else:
# skip initial and final part
snip_start = np.linspace(snip_len // 2, recording.get_num_frames()-int(1.5*snip_len), n_snippets) |
isBrowserTabFocused.js | const isBrowserTabFocused = () => !document.hidden; | module.exports = isBrowserTabFocused; |
|
imagevector.go | // Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package imagevector
import (
"fmt"
"io"
"os"
"regexp"
"strings"
versionutils "github.com/gardener/gardener/pkg/utils/version"
"gopkg.in/yaml.v2"
)
const (
// OverrideEnv is the name of the image vector override environment variable.
OverrideEnv = "IMAGEVECTOR_OVERWRITE"
// SHA256TagPrefix is the prefix in an image tag for sha256 tags.
SHA256TagPrefix = "sha256:"
)
// Read reads an ImageVector from the given io.Reader.
func Read(r io.Reader) (ImageVector, error) {
vector := struct {
Images ImageVector `json:"images" yaml:"images"`
}{}
if err := yaml.NewDecoder(r).Decode(&vector); err != nil {
return nil, err
}
return vector.Images, nil
}
// ReadFile reads an ImageVector from the file with the given name.
func ReadFile(name string) (ImageVector, error) {
file, err := os.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
return Read(file)
}
// ReadGlobalImageVectorWithEnvOverride reads the global image vector and applies the env override. Exposed for testing.
func ReadGlobalImageVectorWithEnvOverride(filePath string) (ImageVector, error) {
imageVector, err := ReadFile(filePath)
if err != nil {
return nil, err
}
return WithEnvOverride(imageVector)
}
// mergeImageSources merges the two given ImageSources.
//
// If the tag of the override is non-empty, it immediately returns the override.
// Otherwise, the override is copied, gets the tag of the old source and is returned.
func mergeImageSources(old, override *ImageSource) *ImageSource {
tag := override.Tag
if tag == nil {
tag = old.Tag
}
runtimeVersion := override.RuntimeVersion
if runtimeVersion == nil {
runtimeVersion = old.RuntimeVersion
}
targetVersion := override.TargetVersion
if targetVersion == nil {
targetVersion = old.TargetVersion
}
return &ImageSource{
Name: override.Name,
RuntimeVersion: runtimeVersion,
TargetVersion: targetVersion,
Repository: override.Repository,
Tag: tag,
}
}
type imageSourceKey struct {
Name string
RuntimeVersion string
TargetVersion string
}
func computeKey(source *ImageSource) imageSourceKey {
var runtimeVersion, targetVersion string
if source.RuntimeVersion != nil {
runtimeVersion = *source.RuntimeVersion
}
if source.TargetVersion != nil {
targetVersion = *source.TargetVersion
}
return imageSourceKey{
Name: source.Name,
RuntimeVersion: runtimeVersion,
TargetVersion: targetVersion,
}
}
// Merge merges the given ImageVectors into one.
//
// Images of ImageVectors that are later in the given sequence with the same name override
// previous images.
func Merge(vectors ...ImageVector) ImageVector {
var (
out ImageVector
keyToIndex = make(map[imageSourceKey]int)
)
for _, vector := range vectors {
for _, image := range vector {
key := computeKey(image)
if idx, ok := keyToIndex[key]; ok {
out[idx] = mergeImageSources(out[idx], image)
continue
}
keyToIndex[key] = len(out)
out = append(out, image)
}
}
return out
}
// WithEnvOverride checks if an environment variable with the key IMAGEVECTOR_OVERWRITE is set.
// If yes, it reads the ImageVector at the value of the variable and merges it with the given one.
// Otherwise, it returns the unmodified ImageVector.
func WithEnvOverride(vector ImageVector) (ImageVector, error) {
overwritePath := os.Getenv(OverrideEnv)
if len(overwritePath) == 0 {
return vector, nil
}
override, err := ReadFile(overwritePath)
if err != nil {
return nil, err
}
return Merge(vector, override), nil
}
// String implements Stringer.
func (o *FindOptions) String() string {
var runtimeVersion string
if o.RuntimeVersion != nil {
runtimeVersion = "runtime version " + *o.RuntimeVersion + " "
}
var targetVersion string
if o.TargetVersion != nil {
targetVersion = "target version " + *o.TargetVersion
}
return runtimeVersion + targetVersion
}
// ApplyOptions applies the given FindOptionFuncs to these FindOptions. Returns a pointer to the mutated value.
func (o *FindOptions) ApplyOptions(opts []FindOptionFunc) *FindOptions {
for _, opt := range opts {
opt(o)
}
return o
}
// RuntimeVersion sets the RuntimeVersion of the FindOptions to the given version.
func | (version string) FindOptionFunc {
return func(options *FindOptions) {
options.RuntimeVersion = &version
}
}
// TargetVersion sets the TargetVersion of the FindOptions to the given version.
func TargetVersion(version string) FindOptionFunc {
return func(options *FindOptions) {
options.TargetVersion = &version
}
}
var r = regexp.MustCompile(`^(v?[0-9]+|=)`)
func checkConstraint(constraint, version *string) (score int, ok bool, err error) {
if constraint == nil || version == nil {
return 0, true, nil
}
matches, err := versionutils.CheckVersionMeetsConstraint(*version, *constraint)
if err != nil || !matches {
return 0, false, err
}
score = 1
// prioritize equal constraints
if r.MatchString(*constraint) {
score = 2
}
return score, true, nil
}
func match(source *ImageSource, name string, opts *FindOptions) (score int, ok bool, err error) {
if source.Name != name {
return 0, false, nil
}
runtimeScore, ok, err := checkConstraint(source.RuntimeVersion, opts.RuntimeVersion)
if err != nil || !ok {
return 0, false, err
}
score += runtimeScore
targetScore, ok, err := checkConstraint(source.TargetVersion, opts.TargetVersion)
if err != nil || !ok {
return 0, false, err
}
score += targetScore
return score, true, nil
}
// FindImage returns an image with the given <name> from the sources in the image vector.
// The <k8sVersion> specifies the kubernetes version the image will be running on.
// The <targetK8sVersion> specifies the kubernetes version the image shall target.
// If multiple entries were found, the provided <k8sVersion> is compared with the constraints
// stated in the image definition.
// In case multiple images match the search, the first which was found is returned.
// In case no image was found, an error is returned.
func (v ImageVector) FindImage(name string, opts ...FindOptionFunc) (*Image, error) {
o := &FindOptions{}
o = o.ApplyOptions(opts)
var (
bestScore int
bestCandidate *ImageSource
)
for _, source := range v {
if source.Name == name {
score, ok, err := match(source, name, o)
if err != nil {
return nil, err
}
if ok && (bestCandidate == nil || score > bestScore) {
bestCandidate = source
bestScore = score
}
}
}
if bestCandidate == nil {
return nil, fmt.Errorf("could not find image %q opts %v", name, o)
}
return bestCandidate.ToImage(o.TargetVersion), nil
}
// FindImages returns an image map with the given <names> from the sources in the image vector.
// The <k8sVersion> specifies the kubernetes version the image will be running on.
// The <targetK8sVersion> specifies the kubernetes version the image shall target.
// If multiple entries were found, the provided <k8sVersion> is compared with the constraints
// stated in the image definition.
// In case multiple images match the search, the first which was found is returned.
// In case no image was found, an error is returned.
func FindImages(v ImageVector, names []string, opts ...FindOptionFunc) (map[string]*Image, error) {
images := map[string]*Image{}
for _, imageName := range names {
image, err := v.FindImage(imageName, opts...)
if err != nil {
return nil, err
}
images[imageName] = image
}
return images, nil
}
// ToImage applies the given <targetK8sVersion> to the source to produce an output image.
// If the tag of an image source is empty, it will use the given <k8sVersion> as tag.
func (i *ImageSource) ToImage(targetVersion *string) *Image {
tag := i.Tag
if tag == nil && targetVersion != nil {
version := fmt.Sprintf("v%s", strings.TrimLeft(*targetVersion, "v"))
tag = &version
}
return &Image{
Name: i.Name,
Repository: i.Repository,
Tag: tag,
}
}
// String will returns the string representation of the image.
func (i *Image) String() string {
if i.Tag == nil {
return i.Repository
}
delimiter := ":"
if strings.HasPrefix(*i.Tag, SHA256TagPrefix) {
delimiter = "@"
}
return i.Repository + delimiter + *i.Tag
}
// ImageMapToValues transforms the given image name to image mapping into chart Values.
func ImageMapToValues(m map[string]*Image) map[string]interface{} {
out := make(map[string]interface{}, len(m))
for k, v := range m {
out[k] = v.String()
}
return out
}
| RuntimeVersion |
api_get_proc_data.go | // found in the LICENSE file.
package wilco
import (
"context"
"path/filepath"
"strings"
"chromiumos/tast/local/bundles/cros/wilco/pre"
"chromiumos/tast/local/wilco"
"chromiumos/tast/testing"
dtcpb "chromiumos/wilco_dtc"
)
func init() {
testing.AddTest(&testing.Test{
Func: APIGetProcData,
Desc: "Test sending GetProcData gRPC request from Wilco DTC VM to the Wilco DTC Support Daemon",
Contacts: []string{
"[email protected]", // Test author
"[email protected]", // wilco_dtc_supportd maintainer
"[email protected]",
},
Attr: []string{"group:mainline"},
SoftwareDeps: []string{"vm_host", "wilco"},
Pre: pre.WilcoDtcSupportdAPI,
})
}
func APIGetProcData(ctx context.Context, s *testing.State) {
getProcData := func(ctx context.Context, s *testing.State, typeField dtcpb.GetProcDataRequest_Type, expectedPrefix, expectedFile string) {
request := dtcpb.GetProcDataRequest{
Type: typeField,
}
response := dtcpb.GetProcDataResponse{}
if err := wilco.DPSLSendMessage(ctx, "GetProcData", &request, &response); err != nil {
s.Fatal("Unable to get Proc files: ", err)
}
// Error conditions defined by the proto definition.
if len(response.FileDump) == 0 {
s.Fatal("No file dumps available")
}
for _, dump := range response.FileDump {
if !strings.HasPrefix(dump.Path, expectedPrefix) {
s.Errorf("File %s does not have prefix %s", dump.Path, expectedPrefix)
}
if dump.CanonicalPath == "" {
s.Errorf("File %s has an empty cannonical path", dump.Path)
}
if len(dump.Contents) == 0 {
s.Errorf("File %s has no content", dump.Path)
}
}
if expectedFile != "" {
expectedFile := filepath.Join(expectedPrefix, expectedFile)
if len(response.FileDump) != 1 {
s.Errorf("Only expected %s as the result", expectedFile)
}
if response.FileDump[0].Path != expectedFile {
s.Errorf("Expected %s, but got %s", expectedFile, response.FileDump[0].Path)
}
}
}
for _, param := range []struct {
// name is the subtest name
name string
// typeField is sent as the request type to GetProcData.
typeField dtcpb.GetProcDataRequest_Type
// expectedPrefix is a prefix that all returned paths must have.
expectedPrefix string
// expectedFile is the expected file relative to expectedPrefix.
expectedFile string
}{
{
name: "uptime",
typeField: dtcpb.GetProcDataRequest_FILE_UPTIME,
expectedPrefix: "/proc/",
expectedFile: "uptime",
}, {
name: "meminfo",
typeField: dtcpb.GetProcDataRequest_FILE_MEMINFO,
expectedPrefix: "/proc/",
expectedFile: "meminfo",
}, {
name: "loadavg",
typeField: dtcpb.GetProcDataRequest_FILE_LOADAVG,
expectedPrefix: "/proc/",
expectedFile: "loadavg",
}, {
name: "stat",
typeField: dtcpb.GetProcDataRequest_FILE_STAT,
expectedPrefix: "/proc/",
expectedFile: "stat",
}, {
name: "acpi_button",
typeField: dtcpb.GetProcDataRequest_DIRECTORY_ACPI_BUTTON,
expectedPrefix: "/proc/acpi/button/",
}, {
name: "netstat",
typeField: dtcpb.GetProcDataRequest_FILE_NET_NETSTAT,
expectedPrefix: "/proc/net/",
expectedFile: "netstat",
}, {
name: "net_dev",
typeField: dtcpb.GetProcDataRequest_FILE_NET_DEV,
expectedPrefix: "/proc/net/",
expectedFile: "dev",
}, {
name: "diskstats",
typeField: dtcpb.GetProcDataRequest_FILE_DISKSTATS,
expectedPrefix: "/proc/",
expectedFile: "diskstats",
}, {
name: "cpuinfo",
typeField: dtcpb.GetProcDataRequest_FILE_CPUINFO,
expectedPrefix: "/proc/",
expectedFile: "cpuinfo",
}, {
name: "vmstat",
typeField: dtcpb.GetProcDataRequest_FILE_VMSTAT,
expectedPrefix: "/proc/",
expectedFile: "vmstat",
},
} {
s.Run(ctx, param.name, func(ctx context.Context, s *testing.State) {
getProcData(ctx, s, param.typeField, param.expectedPrefix, param.expectedFile)
})
}
} | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be |
|
isFlipedString.go | package lcci
import "strings"
func isFlipedString(s1, s2 string) bool {
if len(s1) != len(s2) |
return strings.Index((s2+s2), s1) != -1
}
| {
return false
} |
proximity_attack.rs | use crate::*;
/// Attacks entities that are in close proximity with this entity.
pub fn proximity_attack_system(
entities: &Entities,
proximity_attacks: &Components<ProximityAttack>,
teams: &Components<Team>,
positions: &Components<Point>,
stats: &mut Components<StatSet<Stats>>,
game_events: &mut Vec<GameEvent>,
) -> SystemResult {
let mut v = vec![];
for (e, _proximity, stat, pos, team) in
join!(&entities && &proximity_attacks && &stats && &positions && &teams)
{
let closest = find_closest_in_other_team(
team.unwrap(),
pos.unwrap(), | &teams,
&positions,
&stats,
&entities,
);
if let Some((target, p)) = closest {
if dist(&p, pos.unwrap()) <= CREEP_ATTACK_RADIUS {
let damage = stat.unwrap().stats.get(&Stats::Attack).unwrap().value;
v.push((e.unwrap().clone(), target.clone(), damage));
}
}
}
for (attacker, target, dmg) in v.into_iter() {
increment_attacks_dealt(&mut stats.get_mut(attacker).unwrap());
increment_attacks_received(&mut stats.get_mut(target).unwrap());
game_events.push(GameEvent::DamageEntity(attacker, target, dmg));
}
Ok(())
} | |
getTopic.go | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package eventgrid
import (
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
// Use this data source to access information about an existing EventGrid Topic
func LookupTopic(ctx *pulumi.Context, args *LookupTopicArgs, opts ...pulumi.InvokeOption) (*LookupTopicResult, error) |
// A collection of arguments for invoking getTopic.
type LookupTopicArgs struct {
// The name of the EventGrid Topic resource.
Name string `pulumi:"name"`
// The name of the resource group in which the EventGrid Topic exists.
ResourceGroupName string `pulumi:"resourceGroupName"`
Tags map[string]string `pulumi:"tags"`
}
// A collection of values returned by getTopic.
type LookupTopicResult struct {
// The Endpoint associated with the EventGrid Topic.
Endpoint string `pulumi:"endpoint"`
// The provider-assigned unique ID for this managed resource.
Id string `pulumi:"id"`
Location string `pulumi:"location"`
Name string `pulumi:"name"`
// The Primary Shared Access Key associated with the EventGrid Topic.
PrimaryAccessKey string `pulumi:"primaryAccessKey"`
ResourceGroupName string `pulumi:"resourceGroupName"`
// The Secondary Shared Access Key associated with the EventGrid Topic.
SecondaryAccessKey string `pulumi:"secondaryAccessKey"`
Tags map[string]string `pulumi:"tags"`
}
| {
var rv LookupTopicResult
err := ctx.Invoke("azure:eventgrid/getTopic:getTopic", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
} |
auth.js | import Cookies from 'js-cookie'
const TokenKey = 'Admin-Token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) { | }
export function removeToken() {
return Cookies.remove(TokenKey)
} | return Cookies.set(TokenKey, token, { expires: 1 }) |
DateInput.tsx | import * as React from 'react';
import { IFormGroupProps } from '@blueprintjs/core';
import { InputComponentProps } from '@balgamat/react-autoform';
import { DateInput as Input, IDateInputProps } from '@blueprintjs/datetime';
import { InputWrapper } from './util/InputWrapper';
import { FC } from 'react';
import { localeUtils } from './util/localeUtils';
export type DateProps = InputComponentProps &
Partial<IFormGroupProps> &
Partial<IDateInputProps> & { locale?: string };
export const DateInput: FC<DateProps> = props => (
<InputWrapper {...props}>
<Input | placeholder={'DD.MM.20XX'}
formatDate={date => (props.timePrecision ? date.toLocaleString() : date.toLocaleDateString())}
locale={props.locale || 'en'}
parseDate={str => new Date(str)}
{...props}
onChange={props.onChange}
value={new Date(props.value) || undefined}
localeUtils={localeUtils}
/>
</InputWrapper>
); | fill |
test_views.py | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from tasks.enums import TaskStatusEnum
from tasks.models import Task
from tasks.tests.factories import UserFactory, TaskFactory
class TaskViewSetTestCase(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user = user = UserFactory()
cls.user_other = user_other = UserFactory()
cls.task = TaskFactory(owner=user)
TaskFactory(owner=user)
TaskFactory(owner=user)
cls.task_other = TaskFactory(owner=user_other)
def setUp(self):
self.client.force_authenticate(user=self.user)
def test_list(self):
res = self.client.get(reverse("tasks:task-list"))
self.assertEqual(status.HTTP_200_OK, res.status_code)
res_data = {task["id"]: task for task in res.data}
self.assertEqual(3, len(res_data))
self.assertEqual(res_data.keys(), {task.id for task in Task.objects.filter(owner=self.user).all()})
# validate schema ...
res_data1 = res_data[self.task.id]
self.assertEqual(self.task.title, res_data1["title"])
self.assertEqual(self.task.status, res_data1["status"])
self.assertEqual(self.task.description, res_data1["description"])
self.assertEqual(self.task.status_str(), res_data1["status_str"])
self.assertEqual(self.task.owner.id, res_data1["owner_id"])
def test_retrieve(self):
res = self.client.get(reverse("tasks:task-detail", kwargs={"pk": self.task.id}))
self.assertEqual(status.HTTP_200_OK, res.status_code)
self.assertEqual(self.task.id, res.data["id"])
self.assertEqual(self.task.title, res.data["title"])
self.assertEqual(self.task.status, res.data["status"])
self.assertEqual(self.task.description, res.data["description"])
self.assertEqual(self.task.status_str(), res.data["status_str"])
self.assertEqual(self.task.owner.id, res.data["owner_id"])
def test_retrieve_wrong_owner(self):
res = self.client.get(reverse("tasks:task-detail", kwargs={"pk": self.task_other.id}))
self.assertEqual(status.HTTP_404_NOT_FOUND, res.status_code)
def test_update(self):
task = TaskFactory(owner=self.user)
data = {"title": "New title", "description": "New description"}
res = self.client.put(reverse("tasks:task-detail", kwargs={"pk": task.id}), data=data)
self.assertEqual(status.HTTP_200_OK, res.status_code)
self.assertEqual(data["title"], res.data["title"])
self.assertEqual(data["description"], res.data["description"])
task_ = Task.objects.get(pk=task.id)
self.assertEqual(data["title"], task_.title)
self.assertEqual(data["description"], task_.description)
def test_update_wrong_owner(self):
res = self.client.put(reverse("tasks:task-detail", kwargs={"pk": self.task_other.id}), data={})
self.assertEqual(status.HTTP_404_NOT_FOUND, res.status_code)
def test_create(self):
data = {
"title": "New title",
"status": TaskStatusEnum.NOT_STARTED,
"description": "New description",
}
res = self.client.post(reverse("tasks:task-list"), data=data)
self.assertEqual(status.HTTP_201_CREATED, res.status_code)
self.assertEqual(data["title"], res.data["title"])
self.assertEqual(data["description"], res.data["description"])
task_ = Task.objects.get(pk=res.data["id"])
self.assertEqual(data["title"], task_.title)
self.assertEqual(data["description"], task_.description)
self.assertEqual(self.user.id, task_.owner.id)
def | (self):
res = self.client.post(reverse("tasks:task-list"), data={})
self.assertEqual(status.HTTP_400_BAD_REQUEST, res.status_code)
self.assertEqual("required", res.data["title"][0].code)
self.assertEqual("required", res.data["description"][0].code)
def test_delete(self):
task = TaskFactory(owner=self.user)
res = self.client.delete(reverse("tasks:task-detail", kwargs={"pk": task.id}))
self.assertEqual(status.HTTP_204_NO_CONTENT, res.status_code)
self.assertFalse(Task.objects.filter(pk=task.id).exists())
def test_delete_wrong_owner(self):
res = self.client.delete(reverse("tasks:task-detail", kwargs={"pk": self.task_other.id}))
self.assertEqual(status.HTTP_404_NOT_FOUND, res.status_code)
| test_create_required_fields |
middleware.py | import logging
from brownie import web3 as w3
from eth_utils import encode_hex
from eth_utils import function_signature_to_4byte_selector as fourbyte
from requests import Session
from requests.adapters import HTTPAdapter
from web3 import HTTPProvider
from web3.middleware import filter
from yearn.cache import memory
logger = logging.getLogger(__name__)
BATCH_SIZE = 10000
CACHED_CALLS = [
"name()",
"symbol()",
"decimals()",
]
CACHED_CALLS = [encode_hex(fourbyte(data)) for data in CACHED_CALLS]
def should_cache(method, params):
if method == "eth_call" and params[0]["data"] in CACHED_CALLS:
return True
if method == "eth_getCode" and params[1] == "latest":
return True
if method == "eth_getLogs":
return int(params[0]["toBlock"], 16) - int(params[0]["fromBlock"], 16) == BATCH_SIZE - 1
return False
def cache_middleware(make_request, w3):
def middleware(method, params):
logger.debug("%s %s", method, params)
if should_cache(method, params):
response = memory.cache(make_request)(method, params)
else:
response = make_request(method, params)
return response
return middleware
def setup_middleware():
# patch web3 provider with more connections and higher timeout
| if w3.provider:
assert w3.provider.endpoint_uri.startswith("http"), "only http and https providers are supported"
adapter = HTTPAdapter(pool_connections=100, pool_maxsize=100)
session = Session()
session.mount("http://", adapter)
session.mount("https://", adapter)
w3.provider = HTTPProvider(w3.provider.endpoint_uri, {"timeout": 600}, session)
# patch and inject local filter middleware
filter.MAX_BLOCK_REQUEST = BATCH_SIZE
w3.middleware_onion.add(filter.local_filter_middleware)
w3.middleware_onion.add(cache_middleware) |
|
ComboBox.js | ({
previousMessage: "Алдыңғы нұсқалар",
nextMessage: "Басқа нұсқалар" | }) |
|
cursor.rs | use serde::{Deserialize, Serialize};
use xi_rope::{RopeDelta, Transformer};
use crate::buffer::Buffer;
use crate::mode::{Mode, MotionMode, VisualMode};
use crate::register::RegisterData;
use crate::selection::{InsertDrift, SelRegion, Selection};
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum ColPosition {
FirstNonBlank,
Start,
End,
Col(f64),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Cursor {
pub mode: CursorMode,
pub horiz: Option<ColPosition>,
pub motion_mode: Option<MotionMode>,
pub history_selections: Vec<Selection>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CursorMode {
Normal(usize),
Visual {
start: usize,
end: usize,
mode: VisualMode,
},
Insert(Selection),
}
impl CursorMode {
pub fn offset(&self) -> usize {
match &self {
CursorMode::Normal(offset) => *offset,
CursorMode::Visual { end, .. } => *end,
CursorMode::Insert(selection) => selection.get_cursor_offset(),
}
}
}
impl Cursor {
pub fn new(
mode: CursorMode,
horiz: Option<ColPosition>,
motion_mode: Option<MotionMode>,
) -> Self {
Self {
mode,
horiz,
motion_mode,
history_selections: Vec::new(),
}
}
pub fn offset(&self) -> usize {
self.mode.offset()
}
pub fn is_normal(&self) -> bool {
matches!(&self.mode, CursorMode::Normal(_))
}
pub fn is_insert(&self) -> bool {
matches!(&self.mode, CursorMode::Insert(_))
}
pub fn is_visual(&self) -> bool {
matches!(&self.mode, CursorMode::Visual { .. })
}
pub fn get_mode(&self) -> Mode {
match &self.mode {
CursorMode::Normal(_) => Mode::Normal,
CursorMode::Visual { .. } => Mode::Visual,
CursorMode::Insert(_) => Mode::Insert,
}
}
pub fn set_mode(&mut self, mode: CursorMode) {
if let CursorMode::Insert(selection) = &self.mode {
self.history_selections.push(selection.clone());
}
self.mode = mode;
}
pub fn set_insert(&mut self, selection: Selection) {
self.set_mode(CursorMode::Insert(selection));
}
pub fn update_selection(&mut self, buffer: &Buffer, selection: Selection) |
pub fn edit_selection(&self, buffer: &Buffer) -> Selection {
match &self.mode {
CursorMode::Insert(selection) => selection.clone(),
CursorMode::Normal(offset) => Selection::region(
*offset,
buffer.next_grapheme_offset(*offset, 1, buffer.len()),
),
CursorMode::Visual { start, end, mode } => match mode {
VisualMode::Normal => Selection::region(
*start.min(end),
buffer.next_grapheme_offset(*start.max(end), 1, buffer.len()),
),
VisualMode::Linewise => {
let start_offset = buffer
.offset_of_line(buffer.line_of_offset(*start.min(end)));
let end_offset = buffer
.offset_of_line(buffer.line_of_offset(*start.max(end)) + 1);
Selection::region(start_offset, end_offset)
}
VisualMode::Blockwise => {
let mut selection = Selection::new();
let (start_line, start_col) =
buffer.offset_to_line_col(*start.min(end));
let (end_line, end_col) =
buffer.offset_to_line_col(*start.max(end));
let left = start_col.min(end_col);
let right = start_col.max(end_col) + 1;
for line in start_line..end_line + 1 {
let max_col = buffer.line_end_col(line, true);
if left > max_col {
continue;
}
let right = match &self.horiz {
Some(ColPosition::End) => max_col,
_ => {
if right > max_col {
max_col
} else {
right
}
}
};
let left = buffer.offset_of_line_col(line, left);
let right = buffer.offset_of_line_col(line, right);
selection.add_region(SelRegion::new(left, right, None));
}
selection
}
},
}
}
pub fn apply_delta(&mut self, delta: &RopeDelta) {
match &self.mode {
CursorMode::Normal(offset) => {
let mut transformer = Transformer::new(delta);
let new_offset = transformer.transform(*offset, true);
self.mode = CursorMode::Normal(new_offset);
}
CursorMode::Visual { start, end, mode } => {
let mut transformer = Transformer::new(delta);
let start = transformer.transform(*start, false);
let end = transformer.transform(*end, true);
self.mode = CursorMode::Visual {
start,
end,
mode: *mode,
};
}
CursorMode::Insert(selection) => {
let selection =
selection.apply_delta(delta, true, InsertDrift::Default);
self.mode = CursorMode::Insert(selection);
}
}
self.horiz = None;
}
pub fn yank(&self, buffer: &Buffer) -> RegisterData {
let (content, mode) = match &self.mode {
CursorMode::Insert(selection) => {
let mut mode = VisualMode::Normal;
let mut content = "".to_string();
for region in selection.regions() {
let region_content = if region.is_caret() {
mode = VisualMode::Linewise;
let line = buffer.line_of_offset(region.start);
buffer.line_content(line)
} else {
buffer.slice_to_cow(region.min()..region.max())
};
if content.is_empty() {
content = region_content.to_string();
} else if content.ends_with('\n') {
content += ®ion_content;
} else {
content += "\n";
content += ®ion_content;
}
}
(content, mode)
}
CursorMode::Normal(offset) => {
let new_offset =
buffer.next_grapheme_offset(*offset, 1, buffer.len());
(
buffer.slice_to_cow(*offset..new_offset).to_string(),
VisualMode::Normal,
)
}
CursorMode::Visual { start, end, mode } => match mode {
VisualMode::Normal => (
buffer
.slice_to_cow(
*start.min(end)
..buffer.next_grapheme_offset(
*start.max(end),
1,
buffer.len(),
),
)
.to_string(),
VisualMode::Normal,
),
VisualMode::Linewise => {
let start_offset = buffer
.offset_of_line(buffer.line_of_offset(*start.min(end)));
let end_offset = buffer
.offset_of_line(buffer.line_of_offset(*start.max(end)) + 1);
(
buffer.slice_to_cow(start_offset..end_offset).to_string(),
VisualMode::Linewise,
)
}
VisualMode::Blockwise => {
let mut lines = Vec::new();
let (start_line, start_col) =
buffer.offset_to_line_col(*start.min(end));
let (end_line, end_col) =
buffer.offset_to_line_col(*start.max(end));
let left = start_col.min(end_col);
let right = start_col.max(end_col) + 1;
for line in start_line..end_line + 1 {
let max_col = buffer.line_end_col(line, true);
if left > max_col {
lines.push("".to_string());
} else {
let right = match &self.horiz {
Some(ColPosition::End) => max_col,
_ => {
if right > max_col {
max_col
} else {
right
}
}
};
let left = buffer.offset_of_line_col(line, left);
let right = buffer.offset_of_line_col(line, right);
lines.push(buffer.slice_to_cow(left..right).to_string());
}
}
(lines.join("\n") + "\n", VisualMode::Blockwise)
}
},
};
RegisterData { content, mode }
}
pub fn set_offset(&mut self, offset: usize, modify: bool, new_cursor: bool) {
match &self.mode {
CursorMode::Normal(old_offset) => {
if modify && *old_offset != offset {
self.mode = CursorMode::Visual {
start: *old_offset,
end: offset,
mode: VisualMode::Normal,
};
} else {
self.mode = CursorMode::Normal(offset);
}
}
CursorMode::Visual {
start,
end: _,
mode: _,
} => {
if modify {
self.mode = CursorMode::Visual {
start: *start,
end: offset,
mode: VisualMode::Normal,
};
} else {
self.mode = CursorMode::Normal(offset);
}
}
CursorMode::Insert(selection) => {
if new_cursor {
let mut new_selection = selection.clone();
if modify {
if let Some(region) = new_selection.last_inserted_mut() {
region.end = offset;
} else {
new_selection.add_region(SelRegion::caret(offset));
}
self.set_insert(new_selection);
} else {
let mut new_selection = selection.clone();
new_selection.add_region(SelRegion::caret(offset));
self.set_insert(new_selection);
}
} else if modify {
let mut new_selection = Selection::new();
if let Some(region) = selection.first() {
let new_region =
SelRegion::new(region.start(), offset, None);
new_selection.add_region(new_region);
} else {
new_selection
.add_region(SelRegion::new(offset, offset, None));
}
self.set_insert(new_selection);
} else {
self.set_insert(Selection::caret(offset));
}
}
}
}
pub fn add_region(
&mut self,
start: usize,
end: usize,
modify: bool,
new_cursor: bool,
) {
match &self.mode {
CursorMode::Normal(_offset) => {
self.mode = CursorMode::Visual {
start,
end: end - 1,
mode: VisualMode::Normal,
};
}
CursorMode::Visual {
start: old_start,
end: old_end,
mode: _,
} => {
let forward = old_end >= old_start;
let new_start = (*old_start).min(*old_end).min(start).min(end - 1);
let new_end = (*old_start).max(*old_end).max(start).max(end - 1);
let (new_start, new_end) = if forward {
(new_start, new_end)
} else {
(new_end, new_start)
};
self.mode = CursorMode::Visual {
start: new_start,
end: new_end,
mode: VisualMode::Normal,
};
}
CursorMode::Insert(selection) => {
let new_selection = if new_cursor {
let mut new_selection = selection.clone();
if modify {
let new_region =
if let Some(last_inserted) = selection.last_inserted() {
last_inserted
.merge_with(SelRegion::new(start, end, None))
} else {
SelRegion::new(start, end, None)
};
new_selection.replace_last_inserted_region(new_region);
} else {
new_selection.add_region(SelRegion::new(start, end, None));
}
new_selection
} else if modify {
let mut new_selection = selection.clone();
new_selection.add_region(SelRegion::new(start, end, None));
new_selection
} else {
Selection::region(start, end)
};
self.mode = CursorMode::Insert(new_selection);
}
}
}
}
pub fn get_first_selection_after(
cursor: &Cursor,
buffer: &Buffer,
delta: &RopeDelta,
) -> Option<Cursor> {
let mut transformer = Transformer::new(delta);
let offset = cursor.offset();
let offset = transformer.transform(offset, false);
let (ins, del) = delta.clone().factor();
let ins = ins.transform_shrink(&del);
for el in ins.els.iter() {
match el {
xi_rope::DeltaElement::Copy(b, e) => {
// if b == e, ins.inserted_subset() will panic
if b == e {
return None;
}
}
xi_rope::DeltaElement::Insert(_) => {}
}
}
// TODO it's silly to store the whole thing in memory, we only need the first element.
let mut positions = ins
.inserted_subset()
.complement_iter()
.map(|s| s.1)
.collect::<Vec<usize>>();
positions.append(
&mut del
.complement_iter()
.map(|s| transformer.transform(s.1, false))
.collect::<Vec<usize>>(),
);
positions.sort_by_key(|p| {
let p = *p as i32 - offset as i32;
if p > 0 {
p as usize
} else {
-p as usize
}
});
positions
.get(0)
.cloned()
.map(Selection::caret)
.map(|selection| {
let cursor_mode = match cursor.mode {
CursorMode::Normal(_) | CursorMode::Visual { .. } => {
let offset = selection.min_offset();
let offset = buffer.offset_line_end(offset, false).min(offset);
CursorMode::Normal(offset)
}
CursorMode::Insert(_) => CursorMode::Insert(selection),
};
Cursor::new(cursor_mode, None, None)
})
}
| {
match self.mode {
CursorMode::Normal(_) | CursorMode::Visual { .. } => {
let offset = selection.min_offset();
let offset = buffer.offset_line_end(offset, false).min(offset);
self.mode = CursorMode::Normal(offset);
}
CursorMode::Insert(_) => {
self.mode = CursorMode::Insert(selection);
}
}
} |
mouse_teleop.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Enrique Fernandez
# Released under the BSD License.
#
# Authors:
# * Enrique Fernandez
import Tkinter
import rospy
from geometry_msgs.msg import Twist, Vector3
import numpy
class MouseTeleop():
def __init__(self):
# Retrieve params:
self._frequency = rospy.get_param('~frequency', 0.0)
self._scale = rospy.get_param('~scale', 1.0)
self._holonomic = rospy.get_param('~holonomic', False)
# Create twist publisher:
self._pub_cmd = rospy.Publisher('mouse_vel', Twist, queue_size=100)
# Initialize twist components to zero:
self._v_x = 0.0
self._v_y = 0.0
self._w = 0.0
# Initialize mouse position (x, y) to None (unknown); it's initialized
# when the mouse button is pressed on the _start callback that handles
# that event:
self._x = None
self._y = None
# Create window:
self._root = Tkinter.Tk()
self._root.title('Mouse Teleop')
# Make window non-resizable:
self._root.resizable(0, 0)
# Create canvas:
self._canvas = Tkinter.Canvas(self._root, bg='white')
# Create canvas objects:
self._canvas.create_arc(0, 0, 0, 0, fill='red', outline='red',
width=1, style=Tkinter.PIESLICE, start=90.0, tag='w')
self._canvas.create_line(0, 0, 0, 0, fill='blue', width=4, tag='v_x')
if self._holonomic:
self._canvas.create_line(0, 0, 0, 0,
fill='blue', width=4, tag='v_y')
# Create canvas text objects:
self._text_v_x = Tkinter.StringVar()
if self._holonomic:
self._text_v_y = Tkinter.StringVar()
self._text_w = Tkinter.StringVar()
self._label_v_x = Tkinter.Label(self._root,
anchor=Tkinter.W, textvariable=self._text_v_x)
if self._holonomic:
self._label_v_y = Tkinter.Label(self._root,
anchor=Tkinter.W, textvariable=self._text_v_y)
self._label_w = Tkinter.Label(self._root,
anchor=Tkinter.W, textvariable=self._text_w)
if self._holonomic:
self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)
self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)
self._text_w.set( 'w = %0.2f deg/s' % self._w)
else:
self._text_v_x.set('v = %0.2f m/s' % self._v_x)
self._text_w.set( 'w = %0.2f deg/s' % self._w)
self._label_v_x.pack()
if self._holonomic:
self._label_v_y.pack()
self._label_w.pack()
# Bind event handlers:
self._canvas.bind('<Button-1>', self._start)
self._canvas.bind('<ButtonRelease-1>', self._release)
self._canvas.bind('<Configure>', self._configure)
if self._holonomic:
self._canvas.bind('<B1-Motion>', self._mouse_motion_linear)
self._canvas.bind('<Shift-B1-Motion>', self._mouse_motion_angular)
self._root.bind('<Shift_L>', self._change_to_motion_angular)
self._root.bind('<KeyRelease-Shift_L>',
self._change_to_motion_linear)
else:
self._canvas.bind('<B1-Motion>', self._mouse_motion_angular)
self._canvas.pack()
# If frequency is positive, use synchronous publishing mode:
if self._frequency > 0.0:
# Create timer for the given frequency to publish the twist:
period = rospy.Duration(1.0 / self._frequency)
self._timer = rospy.Timer(period, self._publish_twist)
# Start window event manager main loop:
self._root.mainloop()
def __del__(self):
|
def _start(self, event):
self._x, self._y = event.y, event.x
self._y_linear = self._y_angular = 0
self._v_x = self._v_y = self._w = 0.0
def _release(self, event):
self._v_x = self._v_y = self._w = 0.0
self._send_motion()
def _configure(self, event):
self._width, self._height = event.height, event.width
self._c_x = self._height / 2.0
self._c_y = self._width / 2.0
self._r = min(self._height, self._width) * 0.25
def _mouse_motion_linear(self, event):
self._v_x, self._v_y = self._relative_motion(event.y, event.x)
self._send_motion()
def _mouse_motion_angular(self, event):
self._v_x, self._w = self._relative_motion(event.y, event.x)
self._send_motion()
def _update_coords(self, tag, x0, y0, x1, y1):
x0 += self._c_x
y0 += self._c_y
x1 += self._c_x
y1 += self._c_y
self._canvas.coords(tag, (x0, y0, x1, y1))
def _draw_v_x(self, v):
x = -v * float(self._width)
self._update_coords('v_x', 0, 0, 0, x)
def _draw_v_y(self, v):
y = -v * float(self._height)
self._update_coords('v_y', 0, 0, y, 0)
def _draw_w(self, w):
x0 = y0 = -self._r
x1 = y1 = self._r
self._update_coords('w', x0, y0, x1, y1)
yaw = w * numpy.rad2deg(self._scale)
self._canvas.itemconfig('w', extent=yaw)
def _send_motion(self):
v_x = self._v_x * self._scale
v_y = self._v_y * self._scale
w = self._w * self._scale
linear = Vector3(v_x, v_y, 0.0)
angular = Vector3(0.0, 0.0, w)
self._draw_v_x(self._v_x)
if self._holonomic:
self._draw_v_y(self._v_y)
self._draw_w(self._w)
if self._holonomic:
self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)
self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)
self._text_w.set( 'w = %0.2f deg/s' % numpy.rad2deg(self._w))
else:
self._text_v_x.set('v = %0.2f m/s' % self._v_x)
self._text_w.set( 'w = %0.2f deg/s' % numpy.rad2deg(self._w))
twist = Twist(linear, angular)
self._pub_cmd.publish(twist)
def _publish_twist(self, event):
self._send_motion()
def _relative_motion(self, x, y):
dx = self._x - x
dy = self._y - y
dx /= float(self._width)
dy /= float(self._height)
dx = max(-1.0, min(dx, 1.0))
dy = max(-1.0, min(dy, 1.0))
return dx, dy
def _change_to_motion_linear(self, event):
if self._y is not None:
y = event.x
self._y_angular = self._y - y
self._y = self._y_linear + y
def _change_to_motion_angular(self, event):
if self._y is not None:
y = event.x
self._y_linear = self._y - y
self._y = self._y_angular + y
def main():
rospy.init_node('mouse_teleop')
MouseTeleop()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
| if self._frequency > 0.0:
self._timer.shutdown()
self._root.quit() |
poetry_metadata.go | package python
import "github.com/anchore/syft/syft/pkg"
type PoetryMetadata struct {
Packages []PoetryMetadataPackage `toml:"package"`
} | func (m PoetryMetadata) Pkgs() []*pkg.Package {
pkgs := make([]*pkg.Package, 0)
for _, p := range m.Packages {
pkgs = append(pkgs, p.Pkg())
}
return pkgs
} |
// Pkgs returns all of the packages referenced within the poetry.lock metadata. |
ContentDto.ts | /**
* iCure Cloud API Documentation
* Spring shop sample application
*
* OpenAPI spec version: v0.0.1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
import { MeasureDto } from "./MeasureDto"
import { MedicationDto } from "./MedicationDto"
import { ServiceDto } from "./ServiceDto"
import { decodeBase64 } from "./ModelHelper"
export class | {
constructor(json: JSON | any) {
Object.assign(
this as ContentDto,
json,
json.binaryValue ? { binaryValue: decodeBase64(json.binaryValue) } : {}
)
}
stringValue?: string
numberValue?: number
booleanValue?: boolean
instantValue?: number
/**
* Known values in a date. The format could have a all three (day, month and year) or values on any of these three, whatever is known.
*/
fuzzyDateValue?: number
binaryValue?: ArrayBuffer
/**
* Id of the document in which the content is being filled.
*/
documentId?: string
measureValue?: MeasureDto
medicationValue?: MedicationDto
/**
* The service for which the content is being filled
*/
compoundValue?: Array<ServiceDto>
}
| ContentDto |
6c97f489971f20e9520ef94f485e4ca0ee6a4b34.js | mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "Security Service", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "90074", "MEMO CODE": "", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Los Angeles", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00461061", "EXPENDITURE AMOUNT (F3L Bundled)": "1248.00", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "File 6498", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727407.fec_4.yml", "CONDUIT STATE": "", "CATEGORY CODE": "001", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "EXPB8232", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20101115", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Guardsmark", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB17"});
mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "Security Service", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "90074", "MEMO CODE": "", "PAYEE STATE": "CA", "PAYEE LAST NAME": "", "PAYEE CITY": "Los Angeles", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00461061", "EXPENDITURE AMOUNT (F3L Bundled)": "1248.00", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "File 6498", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727407.fec_4.yml", "CONDUIT STATE": "", "CATEGORY CODE": "001", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "EXPB8232", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20101115", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Guardsmark", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB17"}); |
||
getregion.rs | //! A way to track layout regions of particular areas
use iced_native::*;
use std::{cell::Cell, hash::Hash};
pub struct GetRegion<'a, Message, Renderer: self::Renderer> {
// The Cell helps both with the immutable &self in layout(), and with multi-borrows in the consumer
state: &'a Cell<Rectangle>,
content: Element<'a, Message, Renderer>,
horizontal_alignment: Alignment,
vertical_alignment: Alignment,
}
impl<'a, Message, Renderer> GetRegion<'a, Message, Renderer>
where
Renderer: self::Renderer,
{
pub fn new<T>(state: &'a Cell<Rectangle>, content: T) -> Self
where
T: Into<Element<'a, Message, Renderer>>,
{
GetRegion {
state,
content: content.into(),
horizontal_alignment: Alignment::Start,
vertical_alignment: Alignment::Start,
}
}
pub fn center_x(mut self) -> Self {
self.horizontal_alignment = Alignment::Center;
self
}
pub fn center_y(mut self) -> Self {
self.vertical_alignment = Alignment::Center;
self
}
}
impl<'a, Message, Renderer> Widget<Message, Renderer> for GetRegion<'a, Message, Renderer>
where
Renderer: self::Renderer,
Message: Clone,
{
fn width(&self) -> Length {
Length::Shrink
}
fn height(&self) -> Length {
Length::Shrink
}
fn layout(&self, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
let limits = limits.width(Length::Shrink).height(Length::Shrink);
let mut content = self.content.layout(renderer, &limits.loose());
let size = limits.resolve(content.size());
content.align(self.horizontal_alignment, self.vertical_alignment, size);
layout::Node::with_children(size, vec![content])
}
fn on_event(
&mut self,
event: Event,
layout: Layout<'_>,
cursor_position: Point,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
messages: &mut Vec<Message>,
) -> event::Status {
self.content.on_event(
event,
layout.children().next().unwrap(),
cursor_position,
renderer,
clipboard,
messages,
)
}
fn draw(
&self,
renderer: &mut Renderer,
defaults: &Renderer::Defaults,
layout: Layout<'_>,
cursor_position: Point,
viewport: &Rectangle,
) -> Renderer::Output {
let child_layout = layout.children().next().unwrap();
self.state.set(child_layout.bounds());
renderer.draw(defaults, cursor_position, viewport, &self.content, child_layout)
}
| struct Marker;
std::any::TypeId::of::<Marker>().hash(state);
self.content.hash_layout(state);
}
}
pub trait Renderer: iced_native::Renderer {
fn draw<Message>(
&mut self,
defaults: &Self::Defaults,
cursor_position: Point,
viewport: &Rectangle,
content: &Element<'_, Message, Self>,
content_layout: Layout<'_>,
) -> Self::Output;
}
impl<'a, Message, Renderer> From<GetRegion<'a, Message, Renderer>> for Element<'a, Message, Renderer>
where
Renderer: 'a + self::Renderer,
Message: 'a + Clone,
{
fn from(x: GetRegion<'a, Message, Renderer>) -> Element<'a, Message, Renderer> {
Element::new(x)
}
}
impl<B> Renderer for iced_graphics::Renderer<B>
where
B: iced_graphics::Backend,
{
fn draw<Message>(
&mut self,
defaults: &iced_graphics::Defaults,
cursor_position: Point,
viewport: &Rectangle,
content: &Element<'_, Message, Self>,
content_layout: Layout<'_>,
) -> Self::Output {
content.draw(self, defaults, content_layout, cursor_position, viewport)
}
} | fn hash_layout(&self, state: &mut Hasher) { |
community.go | package types
import (
"fmt"
"net/url"
"unicode/utf8"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gofrs/uuid"
)
const (
maxTitleLength = 150
minTitleLength = 1
maxPostLength = 64 * 1000
minPostLength = 15
maxURLLength = 4 * 1024
)
func (p Post) Address() string {
return fmt.Sprintf("%s/%s", p.Owner, p.Uuid)
}
func (p Post) Validate() error {
if err := sdk.VerifyAddressFormat(p.Owner); err != nil {
return fmt.Errorf("invalid owner: %w", err)
}
if _, err := uuid.FromString(p.Uuid); err != nil {
return fmt.Errorf("invalid uuid: %w", err)
}
if p.Category < Category_CATEGORY_UNDEFINED || p.Category > Category_CATEGORY_SPORTS {
return fmt.Errorf("invalid category: %d", p.Category)
}
if utf8.RuneCountInString(p.Title) > maxTitleLength || len(p.Title) < minTitleLength {
return fmt.Errorf("invalid title: title length should be in [%d;%d]", minTitleLength, maxTitleLength)
}
if !isPreviewImageValid(p.PreviewImage) {
return fmt.Errorf("invalid preview_image")
}
if utf8.RuneCountInString(p.Text) < minPostLength || len(p.Text) > maxPostLength {
return fmt.Errorf("invalid text: text length should be in [%d;%d]", minPostLength, maxPostLength)
}
return nil
}
func (l Like) Validate() error {
if err := sdk.VerifyAddressFormat(l.Owner); err != nil {
return fmt.Errorf("invalid owner: %w", err)
}
if err := sdk.VerifyAddressFormat(l.PostOwner); err != nil {
return fmt.Errorf("invalid post_owner: %w", err)
}
if l.Owner.Equals(l.PostOwner) |
if _, err := uuid.FromString(l.PostUuid); err != nil {
return fmt.Errorf("invalid uuid: %w", err)
}
if l.Weight < LikeWeight_LIKE_WEIGHT_DOWN || l.Weight > LikeWeight_LIKE_WEIGHT_UP {
return fmt.Errorf("invalid weight")
}
return nil
}
func ValidateFollowers(who string, whom []sdk.AccAddress) error {
if _, err := sdk.AccAddressFromBech32(who); err != nil {
return fmt.Errorf("invalid follower: %w", err)
}
if len(whom) == 0 {
return fmt.Errorf("invalid followee: empty array")
}
for i, v := range whom {
if err := sdk.VerifyAddressFormat(v); err != nil {
return fmt.Errorf("invalid followee #%d: %w", i+1, err)
}
}
return nil
}
func isPreviewImageValid(str string) bool {
if len(str) > maxURLLength {
return false
}
if str == "" {
return true
}
url, err := url.Parse(str)
if err != nil {
return false
}
if len(url.Host) == 0 {
return false
}
return url.Scheme == "http" || url.Scheme == "https"
}
| {
return fmt.Errorf("invalid post_owner: self-like")
} |
serializer.py | import msgpack
def dump(obj, fp, default=None):
msgpack.pack(obj, fp, use_bin_type=True, default=default)
def dumps(obj, default=None):
return msgpack.packb(obj, use_bin_type=True, default=default)
def load(fp, object_hook=None):
return msgpack.unpack(fp, object_hook=object_hook, encoding='utf8')
def loads(b, object_hook=None):
return msgpack.unpackb(b, object_hook=object_hook, encoding='utf8')
def stream_unpacker(fp, object_hook=None):
|
__all__ = [
"dump",
"dumps",
"load",
"loads",
"stream_unpacker",
]
| return msgpack.Unpacker(fp, object_hook=object_hook, encoding='utf8') |
test.js | let a = 5;
let obj = {};
// adding prop to obj
Object.defineProperty(obj, "prop", {value: 123}); |
let z = obj.prop; |
|
utils.go | package main
import (
"fmt"
"time"
// YOUR CODE BEGIN remove the follow packages if you don't need them
"reflect"
"sync"
// YOUR CODE END
_ "github.com/go-sql-driver/mysql"
sql "github.com/jmoiron/sqlx"
)
var (
// YOUR CODE BELOW
EvaluatorID = "18307130252" // your student id, e.g. 18307130177
SubmissionDir = "../../../ass1/submission/" // the relative path the the submission directory of assignment 1, it should be "../../../ass1/submission/"
User = "kleinercubs" // the user name to connect the database, e.g. root
Password = "kleinercubs" // the password for the user name, e.g. xxx
// YOUR CODE END
)
// ConcurrentCompareAndInsert is similar with compareAndInsert in `main.go`, but it is concurrent and faster!
func ConcurrentCompareAndInsert(subs map[string]*Submission) {
start := time.Now()
defer func() {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/ass1_result_evaluated_by_%s", User, Password, EvaluatorID))
if err != nil {
panic(nil)
}
rows, err := db.Query("SELECT COUNT(*) FROM comparison_result")
if err != nil {
panic(err)
}
rows.Next()
var cnt int
err = rows.Scan(&cnt)
if err != nil {
panic(err)
}
if cnt == 0 {
panic("ConcurrentCompareAndInsert Not Implemented")
}
fmt.Println("ConcurrentCompareAndInsert takes ", time.Since(start))
}()
// YOUR CODE BEGIN
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/ass1_result_evaluated_by_%s", User, Password, EvaluatorID))
if err != nil {
panic(nil)
}
type data struct {
sub string
cmp string
id int
same int
}
bufferedChan := make(chan data, 128)
wg := sync.WaitGroup{}
for thread := 0; thread < 16; thread++ {
wg.Add(1)
go func() {
defer wg.Done()
for tmp := range bufferedChan {
s := fmt.Sprintf("INSERT INTO comparison_result VALUES ('%s', '%s', %d, %d)", tmp.sub, tmp.cmp, tmp.id, tmp.same)
_, err := db.Exec(s)
if err != nil {
fmt.Println(s)
panic(err)
}
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
for submitter, sub := range subs {
for comparer, sub2 := range subs {
for i := 0; i < NumSQL; i++ {
var equal int
if reflect.DeepEqual(sub.sqlResults[i], sub2.sqlResults[i]) {
equal = 1
} else {
equal = 0
}
bufferedChan <- data{submitter, comparer, i + 1, equal}
}
}
}
close(bufferedChan)
}()
wg.Wait()
// YOUR CODE END
}
// GetScoreSQL returns a string which contains only ONE SQL to be executed, which collects the data in table
// `comparision_result` and inserts the score of each submitter on each query into table `score`
func GetScoreSQL() string {
var SQL string
SQL = "SELECT 1" // ignore this line, it just makes the returned SQL a valid SQL if you haven't written yours.
// YOUR CODE BEGIN
SQL = `INSERT INTO score
WITH RESULT AS(
SELECT submitter, item, count(is_equal) AS vote
FROM comparison_result
WHERE is_equal = 1
GROUP BY submitter, item
) | }
func GetScore(db *sql.DB, subs map[string]*Submission) {
// YOUR CODE BEGIN
rows, err := db.Query("SELECT * FROM score")
if err != nil {
panic(err)
}
var submitter string
var item, score, vote int
for rows.Next() {
rows.Scan(&submitter, &item, &score, &vote)
subs[submitter].score[item] = score
}
// YOUR CODE END
} | SELECT submitter, item, IF (vote IN (SELECT MAX(Tmp.vote) FROM RESULT AS Tmp WHERE Tmp.item = RESULT.item), 1, 0),vote
FROM RESULT`
// YOUR CODE END
return SQL |
axis.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import { deepClone, fillDefaults, Scale, rgbToHex } from "../../common";
import {
CoordinateSystem,
Group,
makeGroup,
makeLine,
makeText,
Style
} from "../../graphics";
import { TextMeasurer } from "../../graphics/renderer/text_measurer";
import { Specification } from "../../index";
import { Controls, TemplateParameters } from "../common";
import { format } from "d3-format";
import { AttributeMap, DataKind, DataType } from "../../specification";
export let defaultAxisStyle: Specification.Types.AxisRenderingStyle = {
tickColor: { r: 0, g: 0, b: 0 },
lineColor: { r: 0, g: 0, b: 0 },
fontFamily: "Arial",
fontSize: 12,
tickSize: 5
};
function fillDefaultAxisStyle(
style?: Partial<Specification.Types.AxisRenderingStyle>
) {
return fillDefaults(style, defaultAxisStyle);
}
export interface TickDescription {
position: number;
label: string;
}
export class AxisRenderer {
public ticks: TickDescription[] = [];
public style: Specification.Types.AxisRenderingStyle = defaultAxisStyle;
public rangeMin: number = 0;
public rangeMax: number = 1;
public valueToPosition: (value: any) => number;
public oppositeSide: boolean = false;
private static textMeasurer = new TextMeasurer();
public setStyle(style?: Partial<Specification.Types.AxisRenderingStyle>) {
if (!style) {
this.style = defaultAxisStyle;
} else {
this.style = fillDefaultAxisStyle(deepClone(style));
}
return this;
}
public setAxisDataBinding(
data: Specification.Types.AxisDataBinding,
rangeMin: number,
rangeMax: number,
enablePrePostGap: boolean,
reverse: boolean,
getTickFormat?: (value: any) => string
) {
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
if (!data) {
return this;
}
this.setStyle(data.style);
this.oppositeSide = data.side == "opposite";
switch (data.type) {
case "numerical":
{
if (!data.numericalMode || data.numericalMode == "linear") {
this.setLinearScale(
data.domainMin,
data.domainMax,
rangeMin,
rangeMax,
data.tickFormat
);
}
if (data.numericalMode == "logarithmic") {
this.setLogarithmicScale(
data.domainMin,
data.domainMax,
rangeMin,
rangeMax,
data.tickFormat
);
}
if (data.numericalMode == "temporal") {
this.setTemporalScale(
data.domainMin,
data.domainMax,
rangeMin,
rangeMax,
data.tickFormat
);
}
}
break;
case "categorical":
{
this.setCategoricalScale(
data.categories,
getCategoricalAxis(data, enablePrePostGap, reverse).ranges,
rangeMin,
rangeMax,
getTickFormat
);
}
break;
case "default":
{
}
break;
}
return this;
}
public ticksData: Array<{ tick: any; value: any }>;
public setTicksByData(ticks: Array<{ tick: any; value: any }>) {
const position2Tick = new Map<number, string>();
for (const tick of ticks) {
const pos = this.valueToPosition(tick.value);
position2Tick.set(pos, tick.tick as string);
}
this.ticks = [];
for (const [pos, tick] of position2Tick.entries()) {
this.ticks.push({
position: pos,
label: tick
});
}
}
public getTickFormat(
tickFormat: string,
defaultFormat: (d: number) => string
) {
if (tickFormat == null || tickFormat == "") {
return defaultFormat;
} else {
// {.0%}
return (value: number) => {
return tickFormat.replace(/\{([^}]+)\}/g, (_, spec) => {
return format(spec)(value);
});
};
}
}
public setLinearScale(
domainMin: number,
domainMax: number,
rangeMin: number,
rangeMax: number,
tickFormat: string
) {
const scale = new Scale.LinearScale();
scale.domainMin = domainMin;
scale.domainMax = domainMax;
const rangeLength = Math.abs(rangeMax - rangeMin);
const ticks = scale.ticks(Math.round(Math.min(10, rangeLength / 40)));
const defaultFormat = scale.tickFormat(
Math.round(Math.min(10, rangeLength / 40))
);
const resolvedFormat = this.getTickFormat(tickFormat, defaultFormat);
const r: TickDescription[] = [];
for (let i = 0; i < ticks.length; i++) {
const tx =
((ticks[i] - domainMin) / (domainMax - domainMin)) *
(rangeMax - rangeMin) +
rangeMin;
r.push({
position: tx,
label: resolvedFormat(ticks[i])
});
}
this.valueToPosition = value =>
((value - domainMin) / (domainMax - domainMin)) * (rangeMax - rangeMin) +
rangeMin;
this.ticks = r;
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
return this;
}
public setLogarithmicScale(
domainMin: number,
domainMax: number,
rangeMin: number,
rangeMax: number,
tickFormat: string
) {
const scale = new Scale.LogarithmicScale();
scale.domainMin = domainMin;
scale.domainMax = domainMax;
const rangeLength = Math.abs(rangeMax - rangeMin);
const ticks = scale.ticks(Math.round(Math.min(10, rangeLength / 40)));
const defaultFormat = scale.tickFormat(
Math.round(Math.min(10, rangeLength / 40))
);
const resolvedFormat = this.getTickFormat(tickFormat, defaultFormat);
const r: TickDescription[] = [];
for (let i = 0; i < ticks.length; i++) {
const tx =
((Math.log(ticks[i]) - Math.log(domainMin)) /
(Math.log(domainMax) - Math.log(domainMin))) *
(rangeMax - rangeMin) +
rangeMin;
r.push({
position: tx,
label: resolvedFormat(ticks[i])
});
}
this.valueToPosition = value =>
((value - domainMin) / (domainMax - domainMin)) * (rangeMax - rangeMin) +
rangeMin;
this.ticks = r;
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
return this;
}
public setTemporalScale(
domainMin: number,
domainMax: number,
rangeMin: number,
rangeMax: number,
tickFormatString: string
) {
const scale = new Scale.DateScale();
scale.domainMin = domainMin;
scale.domainMax = domainMax;
const rangeLength = Math.abs(rangeMax - rangeMin);
const ticksCount = Math.round(Math.min(10, rangeLength / 40));
const ticks = scale.ticks(ticksCount);
const tickFormat = scale.tickFormat(ticksCount, tickFormatString);
const r: TickDescription[] = [];
for (let i = 0; i < ticks.length; i++) {
const tx =
((ticks[i] - domainMin) / (domainMax - domainMin)) *
(rangeMax - rangeMin) +
rangeMin;
r.push({
position: tx,
label: tickFormat(ticks[i])
});
}
this.valueToPosition = value =>
((value - domainMin) / (domainMax - domainMin)) * (rangeMax - rangeMin) +
rangeMin;
this.ticks = r;
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
return this;
}
public setCategoricalScale(
domain: string[],
range: Array<[number, number]>,
rangeMin: number,
rangeMax: number,
tickFormat?: ((value: any) => string)
) {
const r: TickDescription[] = [];
for (let i = 0; i < domain.length; i++) {
r.push({
position:
((range[i][0] + range[i][1]) / 2) * (rangeMax - rangeMin) + rangeMin,
label: tickFormat ? tickFormat(domain[i]) : domain[i]
});
}
this.valueToPosition = value => {
const i = domain.indexOf(value);
if (i >= 0) {
return (
((range[i][0] + range[i][1]) / 2) * (rangeMax - rangeMin) + rangeMin
);
} else {
return 0;
}
};
this.ticks = r;
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
return this;
}
public renderLine(x: number, y: number, angle: number, side: number): Group {
const g = makeGroup([]);
const style = this.style;
const rangeMin = this.rangeMin;
const rangeMax = this.rangeMax;
const tickSize = style.tickSize;
const lineStyle: Style = {
strokeLinecap: "square",
strokeColor: style.lineColor
};
AxisRenderer.textMeasurer.setFontFamily(style.fontFamily);
AxisRenderer.textMeasurer.setFontSize(style.fontSize);
if (this.oppositeSide) {
side = -side;
}
const cos = Math.cos((angle / 180) * Math.PI);
const sin = Math.sin((angle / 180) * Math.PI);
const x1 = x + rangeMin * cos;
const y1 = y + rangeMin * sin;
const x2 = x + rangeMax * cos;
const y2 = y + rangeMax * sin;
// Base line
g.elements.push(makeLine(x1, y1, x2, y2, lineStyle));
// Ticks
for (const tickPosition of this.ticks
.map(x => x.position)
.concat([rangeMin, rangeMax])) {
const tx = x + tickPosition * cos,
ty = y + tickPosition * sin;
const dx = side * tickSize * sin,
dy = -side * tickSize * cos;
g.elements.push(makeLine(tx, ty, tx + dx, ty + dy, lineStyle));
}
// Tick texts
const ticks = this.ticks.map(x => {
return {
position: x.position,
label: x.label,
measure: AxisRenderer.textMeasurer.measure(x.label)
};
});
let maxTextWidth = 0;
let maxTickDistance = 0;
for (let i = 0; i < ticks.length; i++) {
maxTextWidth = Math.max(maxTextWidth, ticks[i].measure.width);
if (i > 0) {
maxTickDistance = Math.max(
maxTickDistance,
Math.abs(ticks[i - 1].position - ticks[i].position)
);
}
}
for (const tick of ticks) {
const tx = x + tick.position * cos,
ty = y + tick.position * sin;
const offset = 3;
const dx = side * (tickSize + offset) * sin,
dy = -side * (tickSize + offset) * cos;
if (Math.abs(cos) < 0.5) {
// 60 ~ 120 degree
const [px, py] = TextMeasurer.ComputeTextPosition(
0,
0,
tick.measure,
side * sin < 0 ? "right" : "left",
"middle",
0
);
const gText = makeGroup([
makeText(px, py, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gText.transform = {
x: tx + dx,
y: ty + dy,
angle: 0
};
g.elements.push(gText);
} else if (Math.abs(cos) < Math.sqrt(3) / 2) {
const [px, py] = TextMeasurer.ComputeTextPosition(
0,
0,
tick.measure,
side * sin < 0 ? "right" : "left",
"middle",
0
);
const gText = makeGroup([
makeText(px, py, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gText.transform = {
x: tx + dx,
y: ty + dy,
angle: 0
};
g.elements.push(gText);
} else {
if (maxTextWidth > maxTickDistance) {
const [px, py] = TextMeasurer.ComputeTextPosition(
0,
0,
tick.measure,
side * cos > 0 ? "right" : "left",
side * cos > 0 ? "top" : "bottom",
0
);
const gText = makeGroup([
makeText(px, py, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gText.transform = {
x: tx + dx,
y: ty + dy,
angle: cos > 0 ? 36 + angle : 36 + angle - 180
};
g.elements.push(gText);
} else {
const [px, py] = TextMeasurer.ComputeTextPosition(
0,
0,
tick.measure,
"middle",
side * cos > 0 ? "top" : "bottom",
0
);
const gText = makeGroup([
makeText(px, py, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gText.transform = {
x: tx + dx,
y: ty + dy,
angle: 0
};
g.elements.push(gText);
}
}
}
return g;
}
public renderCartesian(x: number, y: number, axis: "x" | "y"): Group {
switch (axis) {
case "x": {
return this.renderLine(x, y, 0, 1);
}
case "y": {
return this.renderLine(x, y, 90, -1);
}
}
}
public renderPolar(
cx: number,
cy: number,
radius: number,
side: number
): Group {
const style = this.style;
const rangeMin = this.rangeMin;
const rangeMax = this.rangeMax;
const tickSize = style.tickSize;
const lineStyle: Style = {
strokeLinecap: "round",
strokeColor: style.lineColor
};
const g = makeGroup([]);
g.transform.x = cx;
g.transform.y = cy;
const hintStyle = {
strokeColor: { r: 0, g: 0, b: 0 },
strokeOpacity: 0.1
};
AxisRenderer.textMeasurer.setFontFamily(style.fontFamily);
AxisRenderer.textMeasurer.setFontSize(style.fontSize);
for (const tick of this.ticks) {
const angle = tick.position;
const radians = (angle / 180) * Math.PI;
const tx = Math.sin(radians) * radius;
const ty = Math.cos(radians) * radius;
const metrics = AxisRenderer.textMeasurer.measure(tick.label);
const [textX, textY] = TextMeasurer.ComputeTextPosition(
0,
style.tickSize * side,
metrics,
"middle",
side > 0 ? "bottom" : "top",
0,
2
);
const gt = makeGroup([
makeLine(0, 0, 0, style.tickSize * side, lineStyle),
makeText(textX, textY, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gt.transform.angle = -angle;
gt.transform.x = tx;
gt.transform.y = ty;
g.elements.push(gt);
}
return g;
}
public renderCurve(
coordinateSystem: CoordinateSystem,
y: number,
side: number
): Group {
const style = this.style;
const rangeMin = this.rangeMin;
const rangeMax = this.rangeMax;
const tickSize = style.tickSize;
const lineStyle: Style = {
strokeLinecap: "round",
strokeColor: style.lineColor
};
const g = makeGroup([]);
g.transform = coordinateSystem.getBaseTransform();
const hintStyle = {
strokeColor: { r: 0, g: 0, b: 0 },
strokeOpacity: 0.1
};
AxisRenderer.textMeasurer.setFontFamily(style.fontFamily);
AxisRenderer.textMeasurer.setFontSize(style.fontSize);
for (const tick of this.ticks) {
const tangent = tick.position;
const metrics = AxisRenderer.textMeasurer.measure(tick.label);
const [textX, textY] = TextMeasurer.ComputeTextPosition(
0,
-style.tickSize * side,
metrics,
"middle",
side < 0 ? "bottom" : "top",
0,
2
);
const gt = makeGroup([
makeLine(0, 0, 0, -style.tickSize * side, lineStyle),
makeText(textX, textY, tick.label, style.fontFamily, style.fontSize, {
fillColor: style.tickColor
})
]);
gt.transform = coordinateSystem.getLocalTransform(tangent, y);
g.elements.push(gt);
}
return g;
}
}
export function getCategoricalAxis(
data: Specification.Types.AxisDataBinding,
enablePrePostGap: boolean,
reverse: boolean
) {
if (data.enablePrePostGap) {
enablePrePostGap = true;
}
const chunkSize = (1 - data.gapRatio) / data.categories.length;
let preGap: number, postGap: number, gap: number, gapScale: number;
if (enablePrePostGap) {
gap = data.gapRatio / data.categories.length;
gapScale = 1 / data.categories.length;
preGap = gap / 2;
postGap = gap / 2;
} else {
if (data.categories.length == 1) {
gap = 0;
gapScale = 1;
} else {
gap = data.gapRatio / (data.categories.length - 1);
gapScale = 1 / (data.categories.length - 1);
}
preGap = 0;
postGap = 0;
}
const chunkRanges = data.categories.map((c, i) => {
return [
preGap + (gap + chunkSize) * i,
preGap + (gap + chunkSize) * i + chunkSize
] as [number, number];
});
if (reverse) {
chunkRanges.reverse();
}
return {
gap,
preGap,
postGap,
gapScale,
ranges: chunkRanges
};
}
export function getNumericalInterpolate(
data: Specification.Types.AxisDataBinding
) {
if (data.numericalMode == "logarithmic") {
const p1 = Math.log(data.domainMin);
const p2 = Math.log(data.domainMax);
const pdiff = p2 - p1;
return (x: number) => (Math.log(x) - p1) / pdiff;
} else {
const p1 = data.domainMin;
const p2 = data.domainMax;
const pdiff = p2 - p1;
return (x: number) => (x - p1) / pdiff;
}
}
export function buildAxisAppearanceWidgets(
isVisible: boolean,
axisProperty: string,
m: Controls.WidgetManager
) {
if (isVisible) {
return m.row(
"Visible",
m.horizontal(
[0, 0, 1, 0],
m.inputBoolean(
{ property: axisProperty, field: "visible" },
{ type: "checkbox" }
),
m.label("Position:"),
m.inputSelect(
{ property: axisProperty, field: "side" },
{
type: "dropdown",
showLabel: true,
options: ["default", "opposite"],
labels: ["Default", "Opposite"]
}
),
m.detailsButton(
m.sectionHeader("Axis Style"),
m.row(
"Line Color",
m.inputColor({
property: axisProperty,
field: ["style", "lineColor"]
})
),
m.row(
"Tick Color",
m.inputColor({
property: axisProperty,
field: ["style", "tickColor"]
})
),
m.row(
"Tick Size",
m.inputNumber({
property: axisProperty,
field: ["style", "tickSize"]
})
),
m.row(
"Font Family",
m.inputFontFamily({
property: axisProperty,
field: ["style", "fontFamily"]
})
),
m.row(
"Font Size",
m.inputNumber(
{ property: axisProperty, field: ["style", "fontSize"] },
{ showUpdown: true, updownStyle: "font", updownTick: 2 }
)
)
)
)
);
} else {
return m.row(
"Visible",
m.inputBoolean(
{ property: axisProperty, field: "visible" },
{ type: "checkbox" }
)
);
}
}
export function buildAxisWidgets(
data: Specification.Types.AxisDataBinding,
axisProperty: string,
m: Controls.WidgetManager,
axisName: string
): Controls.Widget[] {
const widgets = [];
const dropzoneOptions: Controls.RowOptions = {
dropzone: {
type: "axis-data-binding",
property: axisProperty,
prompt: axisName + ": drop here to assign data"
}
};
const makeAppearance = () => {
return buildAxisAppearanceWidgets(data.visible, axisProperty, m);
};
if (data != null) {
switch (data.type) {
case "numerical":
{
widgets.push(
m.sectionHeader(
axisName + ": Numerical",
m.clearButton({ property: axisProperty }),
dropzoneOptions
)
);
if (axisName != "Data Axis") {
widgets.push(
m.row(
"Data",
m.inputExpression({
property: axisProperty,
field: "expression"
})
)
);
}
if (data.valueType === "date") {
widgets.push(
m.row(
"Range",
m.vertical(
m.horizontal(
[0, 1],
m.label("start"),
m.inputDate({ property: axisProperty, field: "domainMin" })
),
m.horizontal(
[0, 1],
m.label("end"),
m.inputDate({ property: axisProperty, field: "domainMax" })
)
)
)
);
} else {
widgets.push(
m.row(
"Range",
m.horizontal(
[1, 0, 1],
m.inputNumber({ property: axisProperty, field: "domainMin" }),
m.label(" - "),
m.inputNumber({ property: axisProperty, field: "domainMax" })
)
)
);
}
if (data.numericalMode != "temporal") {
widgets.push(
m.row(
"Mode",
m.inputSelect(
{ property: axisProperty, field: "numericalMode" },
{
options: ["linear", "logarithmic"],
labels: ["Linear", "Logarithmic"],
showLabel: true,
type: "dropdown"
}
)
)
);
}
widgets.push(
m.row(
"Tick Data",
m.inputExpression({
property: axisProperty,
field: "tickDataExpression"
})
)
);
widgets.push(
m.row(
"Tick Format",
m.inputText(
{
property: axisProperty,
field: "tickFormat"
},
"(auto)"
)
)
);
widgets.push(makeAppearance());
}
break;
case "categorical":
{
widgets.push(
m.sectionHeader(
axisName + ": Categorical",
m.clearButton({ property: axisProperty }),
dropzoneOptions
)
);
widgets.push(
m.row(
"Data",
m.horizontal(
[1, 0],
m.inputExpression({
property: axisProperty,
field: "expression"
}),
m.reorderWidget({ property: axisProperty, field: "categories" })
)
)
);
widgets.push(
m.row(
"Gap",
m.inputNumber(
{ property: axisProperty, field: "gapRatio" },
{ minimum: 0, maximum: 1, percentage: true, showSlider: true }
)
)
);
widgets.push(makeAppearance());
}
break;
case "default":
{
widgets.push(
m.sectionHeader(
axisName + ": Stacking",
m.clearButton({ property: axisProperty }),
dropzoneOptions
)
);
widgets.push(
m.row(
"Gap",
m.inputNumber(
{ property: axisProperty, field: "gapRatio" },
{ minimum: 0, maximum: 1, percentage: true, showSlider: true }
)
)
);
}
break;
}
} else {
widgets.push(m.sectionHeader(axisName + ": (none)", null, dropzoneOptions));
}
return widgets;
}
export function buildAxisInference(
plotSegment: Specification.PlotSegment,
property: string
): Specification.Template.Inference {
const axis = plotSegment.properties[
property
] as Specification.Types.AxisDataBinding;
return {
objectID: plotSegment._id,
dataSource: {
table: plotSegment.table,
groupBy: plotSegment.groupBy
},
axis: {
expression: axis.expression,
type: axis.type,
style: axis.style,
property
}
};
}
export function | (
plotSegment: Specification.PlotSegment,
property: string
): Specification.Template.Property[] {
const axisObject = plotSegment.properties[property] as AttributeMap;
const style: any = axisObject.style;
if (!style) {
return [];
}
return [
{
objectID: plotSegment._id as string,
target: {
property: {
property,
field: "style",
subfield: "tickSize"
}
},
type: Specification.AttributeType.Number,
default: style.tickSize
},
{
objectID: plotSegment._id as string,
target: {
property: {
property,
field: "style",
subfield: "fontSize"
}
},
type: Specification.AttributeType.Number,
default: style.fontSize
},
{
objectID: plotSegment._id as string,
target: {
property: {
property,
field: "style",
subfield: "fontFamily"
}
},
type: Specification.AttributeType.FontFamily,
default: style.fontFamily
},
{
objectID: plotSegment._id as string,
target: {
property: {
property,
field: "style",
subfield: "lineColor"
}
},
type: Specification.AttributeType.Color,
default: rgbToHex(style.lineColor)
},
{
objectID: plotSegment._id as string,
target: {
property: {
property,
field: "style",
subfield: "tickColor"
}
},
type: Specification.AttributeType.Color,
default: rgbToHex(style.tickColor)
}
];
}
| buildAxisProperties |
tmpCleanup.js | /*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: MIT-0
*/
const fs = require('fs')
const path = require('path')
const directory = (process.env.LocalTest) ? './tmp' : '/tmp/'
// Deletes all files in a directory
const tmpCleanup = async () => { | if (err) reject(err)
console.log('Deleting: ', files)
for (const file of files) {
const fullPath = path.join(directory, file)
fs.unlink(fullPath, err => {
if (err) reject (err)
})
}
resolve()
})
})
}
module.exports = { tmpCleanup } | console.log('Starting tmpCleanup')
fs.readdir(directory, (err, files) => {
return new Promise((resolve, reject) => { |
hx711.rs | use core::time;
use std::thread;
use gpio::{GpioIn, GpioOut, GpioValue};
use gpio::sysfs::{SysFsGpioInput, SysFsGpioOutput};
use crate::gpio::{Pin, State, Direction, GPIOPin};
use std::time::Duration;
pub(crate) struct Hx711 {
pd_sck: GPIOPin,
d_out: GPIOPin,
gain: i32,
reference: f32,
offset: f32,
digits_after: u8
}
impl Hx711 {
pub(crate) fn new(sck_pin: i32, dout_pin: i32, gain: i32) -> Self {
let pd_sck = GPIOPin::new(sck_pin as u8, Direction::Out).unwrap();
let d_out = GPIOPin::new(dout_pin as u8, Direction::In).unwrap();
Hx711 {
pd_sck,
d_out,
gain: match gain {
128 => 1,
64 => 3,
32 => 2,
_ => 1
},
reference: 1.0,
offset: 0.0,
digits_after: 0
}
}
pub(crate) fn read(&mut self) -> i32 {
&self.wait_ready();
let mut value: i32 = 0;
let mut data: Vec<i32> = vec![0b0000_0000, 0b0000_0000, 0b0000_0000];
data[0] = self.read_next_byte();
data[1] = self.read_next_byte();
data[2] = self.read_next_byte();
// HX711 Channel and gain factor are set by number of bits read
// after 24 data bits.
for _ in 0..self.gain {
self.pd_sck.set_high();
self.pd_sck.set_low();
}
value = ((data[0]) << 16
| (data[1]) << 8
| (data[2]));
-(value & 0x800000) + (value & 0x7fffff)
}
fn wait_ready(&mut self) {
while *self.d_out.get_state() == State::High {
thread::sleep(time::Duration::from_millis(1));
};
}
fn read_next_byte(&mut self) -> i32 {
let mut value: i32 = 0;
for _ in 0..8 {
value <<= 1;
value |= self.read_next_bit() as i32;
}
value
}
fn read_next_bit(&mut self) -> u8 {
self.pd_sck.set_high();
self.pd_sck.set_low();
self.d_out.get_value()
}
pub(crate) fn get_units(&mut self, times: i32) -> f32 |
pub(crate) fn get_value(&mut self, times: i32) -> f32 {
self.read_average(times) - self.offset
}
fn read_average(&mut self, times: i32) -> f32 {
if times == 1 {
return self.read() as f32;
}
let times = times as usize;
if times < 5 {
return self.read_median(times);
}
let mut sum: Vec<i32> = vec![0; times];
for i in 0..times {
sum[i] += self.read();
};
sum.sort();
// just remove the worst outliers
sum[1..sum.len() - 1].iter().sum::<i32>() as f32 / (times as usize - 2) as f32
}
fn read_median(&mut self, times: usize) -> f32 {
let mut sum: Vec<i32> = Vec::with_capacity(times);
for i in 0..times {
sum[i] += self.read();
};
sum.sort();
sum[sum.len() / 2] as f32
}
pub(crate) fn set_reference(&mut self, reference: f32) {
if reference != 0 as f32 {
self.reference = reference;
}
}
pub(crate) fn set_offset(&mut self, offset: f32) {
self.offset = offset;
}
pub(crate) fn tare(&mut self, times: i32) {
let backup_reference: f32 = self.reference;
self.set_reference(1.0);
let value = self.read_average(times);
self.set_offset(value);
self.set_reference(backup_reference);
}
fn power_down(&mut self) {
self.pd_sck.set_low();
self.pd_sck.set_high();
thread::sleep(time::Duration::from_nanos(100))
}
fn power_up(&mut self) {
self.pd_sck.set_low();
thread::sleep(time::Duration::from_nanos(100))
}
pub(crate) fn reset(&mut self) {
&self.power_down();
&self.power_up();
}
}
| {
let factor = 10_i32.pow(self.digits_after as u32) as f32;
((self.get_value(times) as f32 / self.reference) * factor).round() / factor
} |
server.go | package comm
import (
"fmt"
"net"
"strings"
"sync"
"time"
bb "github.com/kenix/gomad/bytebuffer"
sp "github.com/kenix/gomad/supplier"
"github.com/kenix/gomad/util"
)
type Server struct {
service string
supplier sp.Supplier
clients map[*Client]DualChan
done chan util.Cue
monitorCh chan *Client
wgGroup sync.WaitGroup
}
func NewServer(service string, supplier sp.Supplier) *Server {
return &Server{service, supplier,
make(map[*Client]DualChan), make(chan util.Cue),
make(chan *Client, 1), sync.WaitGroup{}}
}
func (srv *Server) Start() error {
util.Li.Printf("to listen @%s\n", srv.service)
listener, err := net.Listen("tcp", srv.service)
if err != nil {
util.Le.Printf("failed listening @ %s: %s\n", srv.service, err)
return err
}
util.Li.Printf("service ready @%s\n", srv.service)
go srv.accept(listener)
go srv.monitor()
go srv.serve(listener)
return nil
}
func (srv *Server) accept(listener net.Listener) {
srv.wgGroup.Add(1)
defer srv.wgGroup.Done()
for {
conn, err := listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "closed network") {
util.Li.Println("stopped accepting connections")
return
}
util.Le.Println(err)
continue
}
util.Li.Printf("got connection from %s\n", conn.RemoteAddr())
dc := DualChan{make(chan []byte), make(chan []byte)}
client := NewClient(conn)
srv.clients[client] = dc
go client.Do(dc, srv.monitorCh)
}
}
func (srv *Server) monitor() {
srv.wgGroup.Add(1)
defer srv.wgGroup.Done()
util.Li.Println("started monitoring")
for c := range srv.monitorCh {
close(srv.clients[c].Out)
c.Close()
delete(srv.clients, c)
}
util.Li.Println("stopped monitoring")
}
func (srv *Server) serve(listener net.Listener) {
buf := bb.New(1024)
srv.wgGroup.Add(1)
defer srv.wgGroup.Done()
util.Li.Println("started serving")
for {
select {
case <-srv.done:
err := listener.Close()
if err != nil |
srv.closeClients()
close(srv.monitorCh)
util.Li.Println("stopped serving")
return
case <-time.After(time.Second):
srv.supplier.Get(buf)
if buf.Flip().HasRemaining() {
srv.commData(buf.GetN(buf.Remaining()))
}
buf.Clear()
}
}
}
func (srv *Server) closeClients() {
for c := range srv.clients {
srv.monitorCh <- c
}
}
func (srv *Server) commData(dat []byte) {
for _, dc := range srv.clients {
select {
case dc.Out <- dat:
}
}
}
func (srv *Server) Stop() error {
close(srv.done)
srv.wgGroup.Wait()
return nil
}
func (srv *Server) Status() string {
return fmt.Sprintf("%d client(s)", len(srv.clients))
}
| {
util.Le.Println(err)
} |
alexnet.py | # Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import mindspore.nn as nn
from mindspore.ops import operations as P
from mindspore.nn import Dense
class AlexNet(nn.Cell):
def | (self, num_classes=10):
super(AlexNet, self).__init__()
self.batch_size = 32
self.conv1 = nn.Conv2d(3, 96, 11, stride=4, pad_mode="valid")
self.conv2 = nn.Conv2d(96, 256, 5, stride=1, pad_mode="same")
self.conv3 = nn.Conv2d(256, 384, 3, stride=1, pad_mode="same")
self.conv4 = nn.Conv2d(384, 384, 3, stride=1, pad_mode="same")
self.conv5 = nn.Conv2d(384, 256, 3, stride=1, pad_mode="same")
self.relu = P.ReLU()
self.max_pool2d = nn.MaxPool2d(kernel_size=3, stride=2)
self.flatten = nn.Flatten()
self.fc1 = nn.Dense(66256, 4096)
self.fc2 = nn.Dense(4096, 4096)
self.fc3 = nn.Dense(4096, num_classes)
def construct(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.max_pool2d(x)
x = self.conv2(x)
x = self.relu(x)
x = self.max_pool2d(x)
x = self.conv3(x)
x = self.relu(x)
x = self.conv4(x)
x = self.relu(x)
x = self.conv5(x)
x = self.relu(x)
x = self.max_pool2d(x)
x = self.flatten(x)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
x = self.relu(x)
x = self.fc3(x)
return x
| __init__ |
privatter-dl.py | import requests, argparse, os, asyncio, concurrent.futures
from termcolor import colored
from bs4 import BeautifulSoup
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("-d", dest="directory", required=False, help="destination where all images will be saved")
p.add_argument("-u", dest="url", required=True, help="url for profile to be downloaded")
p.add_argument("-v", dest="verbose", required=False, default=True, help="specifies verbosity to true or false. Default true")
p.add_argument("-U", dest="username", required=True, help="Username for login to Privatter")
p.add_argument("-P", dest="password", required=True, help="Password for login to Privatter")
p.add_argument("-t", dest="threads", required=False, help="Amount of threads to spawn while downloading. Default is 1")
return p.parse_args()
def create_directory(url, dir):
p = os.getcwd() if dir is None else dir
if not p.endswith('/'):
p = p + '/'
# Get username from supplied url. Create destination directory with it
p = p + url.split('/')[-1].split('#')[0]
if not os.path.exists(p):
os.makedirs(p)
return p
def save_image(link, path, v):
name = link.rsplit('/', 1)[-1]
path = path + '/' + name
if os.path.exists(path):
if v is True:
print(colored(path, 'green'))
return
# Privatter, unlike poipiku, does not host images themselves. No auth needed once URLs have been found
r = requests.get(link, stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
for c in r:
f.write(c)
if v is True:
print(colored(path, 'white'))
def create_session(username, password):
|
def get_image_sites(s, url):
r = s.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
pages = soup.findAll(class_="pull-left")
links = ['https://privatter.net' + str(page).split('href="')[1].split('">')[0] for page in pages]
return links[::-1]
def get_image_direct_link(s, url, path, v):
r = s.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
direct_links = soup.findAll(class_="image")
for link in direct_links:
link = str(link).split('href="')[1].split('"')[0]
save_image(link, path, v)
async def main():
a = parse_args()
with create_session(a.username, a.password) as s:
path = create_directory(a.url, a.directory)
links = get_image_sites(s, a.url)
threads = 1 if a.threads is None else int(a.threads)
with concurrent.futures.ThreadPoolExecutor(threads) as executor:
loop = asyncio.get_event_loop()
tasks = [
loop.run_in_executor(
executor,
get_image_direct_link,
*(s, link, path, a.verbose)
)
for link in links
]
for response in await asyncio.gather(*tasks):
pass
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())
loop.close() | s = requests.Session()
s.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Host': 'privatter.net'
}
# Probably a really bad way to handle passwords... But we need to generate a unique login per session.
# Cookies CAN be used, but it's much easier to just use plain username and password
payload = {
'mode': 'login',
'login_id': username,
'password': password
}
s.post('https://privatter.net/login_pass', data=payload)
return s |
types.go | // Copyright 2019 Hewlett Packard Enterprise Development LP
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package validator
import (
"k8s.io/api/admission/v1beta1"
)
// admitFunc is used as the type for all the callback validators
type admitFunc func(*v1beta1.AdmissionReview) *v1beta1.AdmissionResponse
type checkFunc func() error
const (
validatorServiceName = "kubedirector-validator"
validatorWebhook = "kubedirector-webhook"
validatorSecret = "kubedirector-validator-secret"
webhookHandlerName = "validate-cr.kubedirector.hpe.com"
validationPort = 8443
validationPath = "/validate"
healthPath = "/healthz"
defaultNativeSystemd = false
appCrt = "app.crt"
appKey = "app.pem"
rootCrt = "ca.crt"
multipleSpecChange = "Change to spec not allowed before previous spec change has been processed."
pendingNotifies = "Change to spec not allowed because some members have not processed notifications of previous change."
appInUse = "KubeDirectorApp resource cannot be deleted or modified while referenced by the following KubeDirectorCluster resources: %s"
invalidAppMessage = "Invalid app(%s). This app resource ID has not been registered."
invalidCardinality = "Invalid member count for role(%s). Specified member count:%d Role cardinality:%s"
invalidRole = "Invalid role(%s) in app(%s) specified. Valid roles: \"%s\""
unconfiguredRole = "Active role(%s) in app(%s) must have its configuration included in the roles array."
modifiedProperty = "The %s property is read-only."
modifiedRole = "Role(%s) properties other than the members count cannot be modified while role members exist."
| invalidSelectedRoleID = "Invalid element(%s) in selectedRoles array in config section. Valid roles: \"%s\""
invalidServiceID = "Invalid service_id(%s) in roleServices array in config section. Valid services: \"%s\""
nonUniqueRoleID = "Each id in the roles array must be unique."
nonUniqueServiceID = "Each id in the services array must be unique."
nonUniqueSelectedRole = "Each element of selectedRoles array in config section must be unique."
nonUniqueServiceRole = "Each roleID in roleServices array in config section must be unique."
invalidDefaultSecretPrefix = "defaultSecret(%s) does not have the required name prefix(%s)."
invalidDefaultSecret = "Unable to find defaultSecret(%s) in namespace(%s)."
invalidSecretPrefix = "Secret(%s) for role(%s) does not have the required name prefix(%s)."
invalidSecret = "Unable to find secret(%s) for role(%s) in namespace(%s)."
noDefaultImage = "Role(%s) has no specified image, and no top-level default image is specified."
noURLScheme = "The endpoint for service(%s) must include a urlScheme value because isDashboard is true."
failedToPatch = "Internal error: failed to populate default values for unspecified properties."
invalidStorageDef = "Storage size for role (%s) is incorrectly defined."
invalidStorageSize = "Storage size for role (%s) should be greater than zero."
invalidStorageClass = "Unable to fetch storageClass object with the provided name(%s)."
invalidRoleStorageClass = "Unable to fetch storageClassName(%s) for role(%s)."
noDefaultStorageClass = "storageClassName is not specified for one or more roles, and no default storage class is available."
badDefaultStorageClass = "storageClassName is not specified for one or more roles, and default storage class (%s) is not available on the system."
invalidResource = "Specified resource(\"%s\") value(\"%s\") for role(\"%s\") is invalid. Minimum value must be \"%s\"."
invalidSrcURL = "Unable to access the specified URL(\"%s\") in file injection spec for the role (%s). error: %s."
maxMemberLimit = "Maximum number of total members per KD cluster supported is %d."
) | invalidNodeRoleID = "Invalid roleID(%s) in roleServices array in config section. Valid roles: \"%s\"" |
app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent { | } | title = 'BatalhaNaval'; |
test_envconfig.py | import pytest
from content.ext.envconfig import EnvConfig
@pytest.mark.parametrize('use_init_app', [True, False])
def test_ext_init(app, mocker, use_init_app):
mock_init_app = mocker.patch.object(EnvConfig, 'init_app')
if use_init_app:
ext = EnvConfig()
ext.init_app(app)
else:
EnvConfig(app)
assert mock_init_app.called_with(app)
@pytest.mark.parametrize('value, expected', [
(1, 1),
('x', 'x'),
('[1, "x"]', [1, 'x']),
('123abc', '123abc')
])
def test_envconfig(app, monkeypatch, value, expected):
monkeypatch.setenv('APP_TEST_VALUE', value)
env = EnvConfig()
env.init_app(app) | assert app.config['TEST_VALUE'] == expected |
|
RustCodeLensProvider.ts | "use strict";
import {
CancellationToken,
CodeLens,
CodeLensProvider,
Event,
EventEmitter,
Range,
TextDocument,
DebugConfiguration
} from "vscode";
import { RustTests } from "./RustTests";
import { basename, dirname } from "path";
export class | implements CodeLensProvider {
constructor(
private _onDidChange: EventEmitter<void>,
private rustTests: RustTests,
private main_args: string[],
private test_args: string[]
) {}
get onDidChangeCodeLenses(): Event<void> {
return this._onDidChange.event;
}
public async provideCodeLenses(
doc: TextDocument,
token: CancellationToken
): Promise<CodeLens[]> {
if (token.isCancellationRequested) {
return [];
}
let lenses: CodeLens[] = this.testMethodLenses(doc);
lenses.push(...this.mainMethodLenses(doc));
return lenses;
}
public update_args(main_args: string[], test_args: string[]) {
this.main_args = main_args;
this.test_args = test_args;
}
private mainMethodLenses(doc: TextDocument): any {
const text = doc.getText();
const reFnMain = /fn\s+(main)\s*\(\s*\)/g;
const match = reFnMain.exec(text);
let lenses: CodeLens[] = [];
if (match !== null) {
const codelens = this.makeLens(reFnMain.lastIndex, match[1], doc);
if (codelens !== undefined) {
lenses.push(codelens);
}
}
return lenses;
}
private testMethodLenses(doc: TextDocument) {
const text = doc.getText();
const reTest = /#\[(?:tokio::|async::)?test(?:\(.+?\))?\]/g;
const reFnTest = /fn\s+(.+?)\s*\(\s*\)/g;
let lenses: CodeLens[] = [];
while (reTest.exec(text) !== null) {
reFnTest.lastIndex = reTest.lastIndex;
const match = reFnTest.exec(text);
const fn = match === null ? null : match[1];
if (fn) {
const codelens = this.makeLens(reFnTest.lastIndex, fn, doc);
if (codelens !== undefined) {
lenses.push(codelens);
}
}
}
return lenses;
}
private makeLens(index: number, fn: string, doc: TextDocument) {
const startIdx = index - fn.length;
const start = doc.positionAt(startIdx);
const end = doc.positionAt(index);
const range = new Range(start, end);
const debugConfig = this.createDebugConfig(fn, doc);
if (debugConfig) {
return new CodeLens(range, {
title: "Debug",
command: "extension.debugTest",
tooltip: "Debug",
arguments: [debugConfig]
});
}
}
createDebugConfig(
fn: string,
doc: TextDocument
): DebugConfiguration | undefined {
const pkg = this.rustTests.getPackage(fn, doc.uri);
if (pkg) {
const is_main = fn === "main";
const args = is_main
? ["build", `--package=${pkg.name}`]
: ["test", "--no-run", `--package=${pkg.name}`];
const bin = this.rustTests.getBin(doc.fileName, pkg);
const filter = this.rustTests.getFilter(doc.fileName, pkg, bin);
if (bin !== undefined && filter.kind === "bin") {
args.push(`--bin=${bin}`);
}
if (filter.kind === "example") {
args.push(`--example=${bin}`);
}
args.push(`--manifest-path=${pkg.manifest_path}`);
const extra_args = is_main ? this.main_args : [fn, ...this.test_args];
return {
type: "lldb",
request: "launch",
name: `Debug ${fn} in ${basename(doc.fileName)}`,
cargo: {
args: args,
filter: filter
},
args: extra_args,
cwd: `${dirname(pkg.manifest_path)}`
};
}
}
}
| RustCodeLensProvider |
9_morphological.py | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([30, 150, 50])
upper_red = np.array([255, 255, 180])
mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(frame, frame, mask= mask)
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(mask, kernel, iterations = 1)
dilation = cv2.dilate(mask, kernel, iterations = 1)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
#cv2.imshow('erosion',erosion)
#cv2.imshow('dilation',dilation)
cv2.imshow('opening', opening)
cv2.imshow('closing', closing)
if cv2.waitKey(5) & 0xFF == 27:
|
cv2.destroyAllWindows()
cap.release()
| break |
permissions.py | from rest_framework.permissions import BasePermission
| class IsDeviceOwnerOnly(BasePermission):
def has_permission(self, request, view):
return request.user.is_superuser
def has_object_permission(self, request, view, obj):
return request.user.is_superuser | |
messagebox.rs | use crate::formatted_text::WrapMode;
use crate::{
button::ButtonBuilder,
core::{algebra::Vector2, pool::Handle},
draw::DrawingContext,
grid::{Column, GridBuilder, Row},
message::{
ButtonMessage, MessageBoxMessage, MessageData, MessageDirection, OsEvent, TextMessage,
UiMessage, UiMessageData, WindowMessage,
},
node::UINode,
stack_panel::StackPanelBuilder,
text::TextBuilder,
widget::{Widget, WidgetBuilder},
window::{Window, WindowBuilder, WindowTitle},
BuildContext, Control, HorizontalAlignment, NodeHandleMapping, Orientation, RestrictionEntry,
Thickness, UserInterface,
};
use std::ops::{Deref, DerefMut};
#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Hash, Debug)]
pub enum MessageBoxResult {
Ok,
No,
Yes,
Cancel,
}
#[derive(Copy, Clone, PartialOrd, PartialEq, Ord, Eq, Hash, Debug)]
pub enum MessageBoxButtons {
Ok,
YesNo,
YesNoCancel,
}
#[derive(Clone)]
pub struct MessageBox<M: MessageData, C: Control<M, C>> {
window: Window<M, C>,
buttons: MessageBoxButtons,
ok_yes: Handle<UINode<M, C>>,
no: Handle<UINode<M, C>>,
cancel: Handle<UINode<M, C>>,
text: Handle<UINode<M, C>>,
}
impl<M: MessageData, C: Control<M, C>> Deref for MessageBox<M, C> {
type Target = Widget<M, C>;
fn deref(&self) -> &Self::Target {
&self.window
}
}
impl<M: MessageData, C: Control<M, C>> DerefMut for MessageBox<M, C> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.window
}
}
// Message box extends Window widget so it delegates most of calls
// to inner window.
impl<M: MessageData, C: Control<M, C>> Control<M, C> for MessageBox<M, C> {
fn resolve(&mut self, node_map: &NodeHandleMapping<M, C>) {
self.window.resolve(node_map);
node_map.resolve(&mut self.ok_yes);
node_map.resolve(&mut self.no);
node_map.resolve(&mut self.cancel);
node_map.resolve(&mut self.text);
}
fn | (
&self,
ui: &UserInterface<M, C>,
available_size: Vector2<f32>,
) -> Vector2<f32> {
self.window.measure_override(ui, available_size)
}
fn arrange_override(&self, ui: &UserInterface<M, C>, final_size: Vector2<f32>) -> Vector2<f32> {
self.window.arrange_override(ui, final_size)
}
fn draw(&self, drawing_context: &mut DrawingContext) {
self.window.draw(drawing_context)
}
fn update(&mut self, dt: f32) {
self.window.update(dt);
}
fn handle_routed_message(
&mut self,
ui: &mut UserInterface<M, C>,
message: &mut UiMessage<M, C>,
) {
self.window.handle_routed_message(ui, message);
match &message.data() {
UiMessageData::Button(ButtonMessage::Click) => {
if message.destination() == self.ok_yes {
let result = match self.buttons {
MessageBoxButtons::Ok => MessageBoxResult::Ok,
MessageBoxButtons::YesNo => MessageBoxResult::Yes,
MessageBoxButtons::YesNoCancel => MessageBoxResult::Yes,
};
ui.send_message(MessageBoxMessage::close(
self.handle,
MessageDirection::ToWidget,
result,
));
} else if message.destination() == self.cancel {
ui.send_message(MessageBoxMessage::close(
self.handle(),
MessageDirection::ToWidget,
MessageBoxResult::Cancel,
));
} else if message.destination() == self.no {
ui.send_message(MessageBoxMessage::close(
self.handle(),
MessageDirection::ToWidget,
MessageBoxResult::No,
));
}
}
UiMessageData::MessageBox(msg) => {
match msg {
MessageBoxMessage::Open { title, text } => {
if let Some(title) = title {
ui.send_message(WindowMessage::title(
self.handle(),
MessageDirection::ToWidget,
WindowTitle::Text(title.clone()),
));
}
if let Some(text) = text {
ui.send_message(TextMessage::text(
self.text,
MessageDirection::ToWidget,
text.clone(),
));
}
ui.send_message(WindowMessage::open_modal(
self.handle(),
MessageDirection::ToWidget,
true,
));
}
MessageBoxMessage::Close(_) => {
// Translate message box message into window message.
ui.send_message(WindowMessage::close(
self.handle(),
MessageDirection::ToWidget,
));
}
}
}
_ => {}
}
}
fn preview_message(&self, ui: &UserInterface<M, C>, message: &mut UiMessage<M, C>) {
self.window.preview_message(ui, message);
}
fn handle_os_event(
&mut self,
self_handle: Handle<UINode<M, C>>,
ui: &mut UserInterface<M, C>,
event: &OsEvent,
) {
self.window.handle_os_event(self_handle, ui, event);
}
fn remove_ref(&mut self, handle: Handle<UINode<M, C>>) {
self.window.remove_ref(handle)
}
}
pub struct MessageBoxBuilder<'b, M: MessageData, C: Control<M, C>> {
window_builder: WindowBuilder<M, C>,
buttons: MessageBoxButtons,
text: &'b str,
}
impl<'a, 'b, M: MessageData, C: Control<M, C>> MessageBoxBuilder<'b, M, C> {
pub fn new(window_builder: WindowBuilder<M, C>) -> Self {
Self {
window_builder,
buttons: MessageBoxButtons::Ok,
text: "",
}
}
pub fn with_text(mut self, text: &'b str) -> Self {
self.text = text;
self
}
pub fn with_buttons(mut self, buttons: MessageBoxButtons) -> Self {
self.buttons = buttons;
self
}
pub fn build(mut self, ctx: &mut BuildContext<M, C>) -> Handle<UINode<M, C>> {
let ok_yes;
let mut no = Default::default();
let mut cancel = Default::default();
let text;
let content = match self.buttons {
MessageBoxButtons::Ok => GridBuilder::new(
WidgetBuilder::new()
.with_child({
text = TextBuilder::new(
WidgetBuilder::new().with_margin(Thickness::uniform(4.0)),
)
.with_text(self.text)
.with_wrap(WrapMode::Word)
.build(ctx);
text
})
.with_child({
ok_yes = ButtonBuilder::new(
WidgetBuilder::new()
.with_margin(Thickness::uniform(1.0))
.with_width(80.0)
.on_row(1)
.with_horizontal_alignment(HorizontalAlignment::Center),
)
.with_text("OK")
.build(ctx);
ok_yes
}),
)
.add_row(Row::stretch())
.add_row(Row::strict(25.0))
.add_column(Column::stretch())
.build(ctx),
MessageBoxButtons::YesNo => GridBuilder::new(
WidgetBuilder::new()
.with_child({
text = TextBuilder::new(WidgetBuilder::new())
.with_text(self.text)
.with_wrap(WrapMode::Word)
.build(ctx);
text
})
.with_child(
StackPanelBuilder::new(
WidgetBuilder::new()
.with_horizontal_alignment(HorizontalAlignment::Right)
.on_row(1)
.with_child({
ok_yes = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("Yes")
.build(ctx);
ok_yes
})
.with_child({
no = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("No")
.build(ctx);
no
}),
)
.with_orientation(Orientation::Horizontal)
.build(ctx),
),
)
.add_row(Row::stretch())
.add_row(Row::strict(25.0))
.add_column(Column::stretch())
.build(ctx),
MessageBoxButtons::YesNoCancel => GridBuilder::new(
WidgetBuilder::new()
.with_child({
text = TextBuilder::new(WidgetBuilder::new())
.with_text(self.text)
.with_wrap(WrapMode::Word)
.build(ctx);
text
})
.with_child(
StackPanelBuilder::new(
WidgetBuilder::new()
.with_horizontal_alignment(HorizontalAlignment::Right)
.on_row(1)
.with_child({
ok_yes = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("Yes")
.build(ctx);
ok_yes
})
.with_child({
no = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("No")
.build(ctx);
no
})
.with_child({
cancel = ButtonBuilder::new(
WidgetBuilder::new()
.with_width(80.0)
.with_margin(Thickness::uniform(1.0)),
)
.with_text("Cancel")
.build(ctx);
cancel
}),
)
.with_orientation(Orientation::Horizontal)
.build(ctx),
),
)
.add_row(Row::stretch())
.add_row(Row::strict(25.0))
.add_column(Column::stretch())
.build(ctx),
};
if self.window_builder.widget_builder.min_size.is_none() {
self.window_builder.widget_builder.min_size = Some(Vector2::new(200.0, 100.0));
}
self.window_builder.widget_builder.handle_os_events = true;
let is_open = self.window_builder.open;
let message_box = MessageBox {
buttons: self.buttons,
window: self.window_builder.with_content(content).build_window(ctx),
ok_yes,
no,
cancel,
text,
};
let handle = ctx.add_node(UINode::MessageBox(message_box));
if is_open {
// We must restrict picking because message box is modal.
ctx.ui
.push_picking_restriction(RestrictionEntry { handle, stop: true });
}
handle
}
}
| measure_override |
test_commands.py | from unittest import TestCase
from model_mommy import mommy
from physical.commands import HostCommandOL6, HostCommandOL7
class CommandsBaseTestCase(object):
OS_VERSION = ''
HOST_COMMAND_CLASS = None
EXPECTED_CMD_TMPL = ''
def setUp(self):
self.host = mommy.make(
'Host',
os_description='OL {}'.format(self.OS_VERSION)
)
self.instance = mommy.make('Instance', hostname=self.host)
def test_is_instance(self):
self.assertTrue(
isinstance(self.host.commands, self.HOST_COMMAND_CLASS) | def test_start(self):
cmd = self.host.commands.exec_service_command(
service_name='fake_service_name',
action='fake_start'
)
self.assertEqual(
cmd,
self.EXPECTED_CMD_TMPL.format(
service_name='fake_service_name',
action='fake_start'
)
)
def test_stop(self):
cmd = self.host.commands.exec_service_command(
service_name='fake_service_name',
action='fake_stop'
)
self.assertEqual(
cmd,
self.EXPECTED_CMD_TMPL.format(
service_name='fake_service_name',
action='fake_stop'
)
)
def test_start_no_output(self):
cmd = self.host.commands.exec_service_command(
service_name='fake_service_name',
action='fake_start',
no_output=True
)
expected_cmd = '{} > /dev/null'.format(
self.EXPECTED_CMD_TMPL.format(
service_name='fake_service_name',
action='fake_start'
)
)
self.assertEqual(
cmd,
expected_cmd
)
def test_stop_no_output(self):
cmd = self.host.commands.exec_service_command(
service_name='fake_service_name',
action='fake_stop',
no_output=True
)
expected_cmd = '{} > /dev/null'.format(
self.EXPECTED_CMD_TMPL.format(
service_name='fake_service_name',
action='fake_stop'
)
)
self.assertEqual(
cmd,
expected_cmd
)
class CustomCommandOL6TestCase(CommandsBaseTestCase, TestCase):
OS_VERSION = '6.10'
HOST_COMMAND_CLASS = HostCommandOL6
EXPECTED_CMD_TMPL = '/etc/init.d/{service_name} {action}'
class CustomCommandOL7TestCase(CommandsBaseTestCase, TestCase):
OS_VERSION = '7.10'
HOST_COMMAND_CLASS = HostCommandOL7
EXPECTED_CMD_TMPL = 'sudo systemctl {action} {service_name}.service' | )
|
lunr.js | /**
* lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.6
* Copyright (C) 2019 Oliver Nightingale
* @license MIT
*/
!function(){var e,t,r,i,n,s,o,a,u,l,c,h,d,f,p,y,m,g,x,v,w,Q,k,S,E,L,b,P,lunr=function(e){var t=new lunr.Builder;return t.pipeline.add(lunr.trimmer,lunr.stopWordFilter,lunr.stemmer),t.searchPipeline.add(lunr.stemmer),e.call(t,t),t.build()};lunr.version="2.3.6",
/*!
* lunr.utils
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.utils={},lunr.utils.warn=(e=this,function(t){e.console&&console.warn&&console.warn(t)}),lunr.utils.asString=function(e){return null==e?"":e.toString()},lunr.utils.clone=function(e){if(null==e)return e;for(var t=Object.create(null),r=Object.keys(e),i=0;i<r.length;i++){var n=r[i],s=e[n];if(Array.isArray(s))t[n]=s.slice();else{if("string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s)throw new TypeError("clone is not deep and does not support nested objects");t[n]=s}}return t},lunr.FieldRef=function(e,t,r){this.docRef=e,this.fieldName=t,this._stringValue=r},lunr.FieldRef.joiner="/",lunr.FieldRef.fromString=function(e){var t=e.indexOf(lunr.FieldRef.joiner);if(-1===t)throw"malformed field ref string";var r=e.slice(0,t),i=e.slice(t+1);return new lunr.FieldRef(i,r,e)},lunr.FieldRef.prototype.toString=function(){return null==this._stringValue&&(this._stringValue=this.fieldName+lunr.FieldRef.joiner+this.docRef),this._stringValue},
/*!
* lunr.Set
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.Set=function(e){if(this.elements=Object.create(null),e){this.length=e.length;for(var t=0;t<this.length;t++)this.elements[e[t]]=!0}else this.length=0},lunr.Set.complete={intersect:function(e){return e},union:function(e){return e},contains:function(){return!0}},lunr.Set.empty={intersect:function(){return this},union:function(e){return e},contains:function(){return!1}},lunr.Set.prototype.contains=function(e){return!!this.elements[e]},lunr.Set.prototype.intersect=function(e){var t,r,i,n=[];if(e===lunr.Set.complete)return this;if(e===lunr.Set.empty)return e;this.length<e.length?(t=this,r=e):(t=e,r=this),i=Object.keys(t.elements);for(var s=0;s<i.length;s++){var o=i[s];o in r.elements&&n.push(o)}return new lunr.Set(n)},lunr.Set.prototype.union=function(e){return e===lunr.Set.complete?lunr.Set.complete:e===lunr.Set.empty?this:new lunr.Set(Object.keys(this.elements).concat(Object.keys(e.elements)))},lunr.idf=function(e,t){var r=0;for(var i in e)"_index"!=i&&(r+=Object.keys(e[i]).length);var n=(t-r+.5)/(r+.5);return Math.log(1+Math.abs(n))},lunr.Token=function(e,t){this.str=e||"",this.metadata=t||{}},lunr.Token.prototype.toString=function(){return this.str},lunr.Token.prototype.update=function(e){return this.str=e(this.str,this.metadata),this},lunr.Token.prototype.clone=function(e){return e=e||function(e){return e},new lunr.Token(e(this.str,this.metadata),this.metadata)},
/*!
* lunr.tokenizer
* Copyright (C) 2019 Oliver Nightingale
*/ | /*!
* lunr.Pipeline
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.Pipeline=function(){this._stack=[]},lunr.Pipeline.registeredFunctions=Object.create(null),lunr.Pipeline.registerFunction=function(e,t){t in this.registeredFunctions&&lunr.utils.warn("Overwriting existing registered function: "+t),e.label=t,lunr.Pipeline.registeredFunctions[e.label]=e},lunr.Pipeline.warnIfFunctionNotRegistered=function(e){e.label&&e.label in this.registeredFunctions||lunr.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",e)},lunr.Pipeline.load=function(e){var t=new lunr.Pipeline;return e.forEach((function(e){var r=lunr.Pipeline.registeredFunctions[e];if(!r)throw new Error("Cannot load unregistered function: "+e);t.add(r)})),t},lunr.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach((function(e){lunr.Pipeline.warnIfFunctionNotRegistered(e),this._stack.push(e)}),this)},lunr.Pipeline.prototype.after=function(e,t){lunr.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");r+=1,this._stack.splice(r,0,t)},lunr.Pipeline.prototype.before=function(e,t){lunr.Pipeline.warnIfFunctionNotRegistered(t);var r=this._stack.indexOf(e);if(-1==r)throw new Error("Cannot find existingFn");this._stack.splice(r,0,t)},lunr.Pipeline.prototype.remove=function(e){var t=this._stack.indexOf(e);-1!=t&&this._stack.splice(t,1)},lunr.Pipeline.prototype.run=function(e){for(var t=this._stack.length,r=0;r<t;r++){for(var i=this._stack[r],n=[],s=0;s<e.length;s++){var o=i(e[s],s,e);if(void 0!==o&&""!==o)if(Array.isArray(o))for(var a=0;a<o.length;a++)n.push(o[a]);else n.push(o)}e=n}return e},lunr.Pipeline.prototype.runString=function(e,t){var r=new lunr.Token(e,t);return this.run([r]).map((function(e){return e.toString()}))},lunr.Pipeline.prototype.reset=function(){this._stack=[]},lunr.Pipeline.prototype.toJSON=function(){return this._stack.map((function(e){return lunr.Pipeline.warnIfFunctionNotRegistered(e),e.label}))},
/*!
* lunr.Vector
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.Vector=function(e){this._magnitude=0,this.elements=e||[]},lunr.Vector.prototype.positionForIndex=function(e){if(0==this.elements.length)return 0;for(var t=0,r=this.elements.length/2,i=r-t,n=Math.floor(i/2),s=this.elements[2*n];i>1&&(s<e&&(t=n),s>e&&(r=n),s!=e);)i=r-t,n=t+Math.floor(i/2),s=this.elements[2*n];return s==e?2*n:s>e?2*n:s<e?2*(n+1):void 0},lunr.Vector.prototype.insert=function(e,t){this.upsert(e,t,(function(){throw"duplicate index"}))},lunr.Vector.prototype.upsert=function(e,t,r){this._magnitude=0;var i=this.positionForIndex(e);this.elements[i]==e?this.elements[i+1]=r(this.elements[i+1],t):this.elements.splice(i,0,e,t)},lunr.Vector.prototype.magnitude=function(){if(this._magnitude)return this._magnitude;for(var e=0,t=this.elements.length,r=1;r<t;r+=2){var i=this.elements[r];e+=i*i}return this._magnitude=Math.sqrt(e)},lunr.Vector.prototype.dot=function(e){for(var t=0,r=this.elements,i=e.elements,n=r.length,s=i.length,o=0,a=0,u=0,l=0;u<n&&l<s;)(o=r[u])<(a=i[l])?u+=2:o>a?l+=2:o==a&&(t+=r[u+1]*i[l+1],u+=2,l+=2);return t},lunr.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},lunr.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),t=1,r=0;t<this.elements.length;t+=2,r++)e[r]=this.elements[t];return e},lunr.Vector.prototype.toJSON=function(){return this.elements},
/*!
* lunr.stemmer
* Copyright (C) 2019 Oliver Nightingale
* Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt
*/
lunr.stemmer=(t={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},r={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},i="[aeiouy]",n="[^aeiou][^aeiouy]*",s=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*"),o=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*"),a=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$"),u=new RegExp("^([^aeiou][^aeiouy]*)?[aeiouy]"),l=/^(.+?)(ss|i)es$/,c=/^(.+?)([^s])s$/,h=/^(.+?)eed$/,d=/^(.+?)(ed|ing)$/,f=/.$/,p=/(at|bl|iz)$/,y=new RegExp("([^aeiouylsz])\\1$"),m=new RegExp("^"+n+i+"[^aeiouwxy]$"),g=/^(.+?[^aeiou])y$/,x=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,v=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,w=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,Q=/^(.+?)(s|t)(ion)$/,k=/^(.+?)e$/,S=/ll$/,E=new RegExp("^"+n+i+"[^aeiouwxy]$"),L=function porterStemmer(e){var i,n,L,b,P,T,O;if(e.length<3)return e;if("y"==(L=e.substr(0,1))&&(e=L.toUpperCase()+e.substr(1)),P=c,(b=l).test(e)?e=e.replace(b,"$1$2"):P.test(e)&&(e=e.replace(P,"$1$2")),P=d,(b=h).test(e)){var I=b.exec(e);(b=s).test(I[1])&&(b=f,e=e.replace(b,""))}else P.test(e)&&(i=(I=P.exec(e))[1],(P=u).test(i)&&(T=y,O=m,(P=p).test(e=i)?e+="e":T.test(e)?(b=f,e=e.replace(b,"")):O.test(e)&&(e+="e")));return(b=g).test(e)&&(e=(i=(I=b.exec(e))[1])+"i"),(b=x).test(e)&&(i=(I=b.exec(e))[1],n=I[2],(b=s).test(i)&&(e=i+t[n])),(b=v).test(e)&&(i=(I=b.exec(e))[1],n=I[2],(b=s).test(i)&&(e=i+r[n])),P=Q,(b=w).test(e)?(i=(I=b.exec(e))[1],(b=o).test(i)&&(e=i)):P.test(e)&&(i=(I=P.exec(e))[1]+I[2],(P=o).test(i)&&(e=i)),(b=k).test(e)&&(i=(I=b.exec(e))[1],P=a,T=E,((b=o).test(i)||P.test(i)&&!T.test(i))&&(e=i)),P=o,(b=S).test(e)&&P.test(e)&&(b=f,e=e.replace(b,"")),"y"==L&&(e=L.toLowerCase()+e.substr(1)),e},function(e){return e.update(L)}),lunr.Pipeline.registerFunction(lunr.stemmer,"stemmer"),
/*!
* lunr.stopWordFilter
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.generateStopWordFilter=function(e){var t=e.reduce((function(e,t){return e[t]=t,e}),{});return function(e){if(e&&t[e.toString()]!==e.toString())return e}},lunr.stopWordFilter=lunr.generateStopWordFilter(["a","able","about","across","after","all","almost","also","am","among","an","and","any","are","as","at","be","because","been","but","by","can","cannot","could","dear","did","do","does","either","else","ever","every","for","from","get","got","had","has","have","he","her","hers","him","his","how","however","i","if","in","into","is","it","its","just","least","let","like","likely","may","me","might","most","must","my","neither","no","nor","not","of","off","often","on","only","or","other","our","own","rather","said","say","says","she","should","since","so","some","than","that","the","their","them","then","there","these","they","this","tis","to","too","twas","us","wants","was","we","were","what","when","where","which","while","who","whom","why","will","with","would","yet","you","your"]),lunr.Pipeline.registerFunction(lunr.stopWordFilter,"stopWordFilter"),
/*!
* lunr.trimmer
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.trimmer=function(e){return e.update((function(e){return e.replace(/^\W+/,"").replace(/\W+$/,"")}))},lunr.Pipeline.registerFunction(lunr.trimmer,"trimmer"),
/*!
* lunr.TokenSet
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.TokenSet=function(){this.final=!1,this.edges={},this.id=lunr.TokenSet._nextId,lunr.TokenSet._nextId+=1},lunr.TokenSet._nextId=1,lunr.TokenSet.fromArray=function(e){for(var t=new lunr.TokenSet.Builder,r=0,i=e.length;r<i;r++)t.insert(e[r]);return t.finish(),t.root},lunr.TokenSet.fromClause=function(e){return"editDistance"in e?lunr.TokenSet.fromFuzzyString(e.term,e.editDistance):lunr.TokenSet.fromString(e.term)},lunr.TokenSet.fromFuzzyString=function(e,t){for(var r=new lunr.TokenSet,i=[{node:r,editsRemaining:t,str:e}];i.length;){var n=i.pop();if(n.str.length>0){var s,o=n.str.charAt(0);o in n.node.edges?s=n.node.edges[o]:(s=new lunr.TokenSet,n.node.edges[o]=s),1==n.str.length&&(s.final=!0),i.push({node:s,editsRemaining:n.editsRemaining,str:n.str.slice(1)})}if(0!=n.editsRemaining){if("*"in n.node.edges)var a=n.node.edges["*"];else{a=new lunr.TokenSet;n.node.edges["*"]=a}if(0==n.str.length&&(a.final=!0),i.push({node:a,editsRemaining:n.editsRemaining-1,str:n.str}),n.str.length>1&&i.push({node:n.node,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)}),1==n.str.length&&(n.node.final=!0),n.str.length>=1){if("*"in n.node.edges)var u=n.node.edges["*"];else{u=new lunr.TokenSet;n.node.edges["*"]=u}1==n.str.length&&(u.final=!0),i.push({node:u,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)})}if(n.str.length>1){var l,c=n.str.charAt(0),h=n.str.charAt(1);h in n.node.edges?l=n.node.edges[h]:(l=new lunr.TokenSet,n.node.edges[h]=l),1==n.str.length&&(l.final=!0),i.push({node:l,editsRemaining:n.editsRemaining-1,str:c+n.str.slice(2)})}}}return r},lunr.TokenSet.fromString=function(e){for(var t=new lunr.TokenSet,r=t,i=0,n=e.length;i<n;i++){var s=e[i],o=i==n-1;if("*"==s)t.edges[s]=t,t.final=o;else{var a=new lunr.TokenSet;a.final=o,t.edges[s]=a,t=a}}return r},lunr.TokenSet.prototype.toArray=function(){for(var e=[],t=[{prefix:"",node:this}];t.length;){var r=t.pop(),i=Object.keys(r.node.edges),n=i.length;r.node.final&&(r.prefix.charAt(0),e.push(r.prefix));for(var s=0;s<n;s++){var o=i[s];t.push({prefix:r.prefix.concat(o),node:r.node.edges[o]})}}return e},lunr.TokenSet.prototype.toString=function(){if(this._str)return this._str;for(var e=this.final?"1":"0",t=Object.keys(this.edges).sort(),r=t.length,i=0;i<r;i++){var n=t[i];e=e+n+this.edges[n].id}return e},lunr.TokenSet.prototype.intersect=function(e){for(var t=new lunr.TokenSet,r=void 0,i=[{qNode:e,output:t,node:this}];i.length;){r=i.pop();for(var n=Object.keys(r.qNode.edges),s=n.length,o=Object.keys(r.node.edges),a=o.length,u=0;u<s;u++)for(var l=n[u],c=0;c<a;c++){var h=o[c];if(h==l||"*"==l){var d=r.node.edges[h],f=r.qNode.edges[l],p=d.final&&f.final,y=void 0;h in r.output.edges?(y=r.output.edges[h]).final=y.final||p:((y=new lunr.TokenSet).final=p,r.output.edges[h]=y),i.push({qNode:f,output:y,node:d})}}}return t},lunr.TokenSet.Builder=function(){this.previousWord="",this.root=new lunr.TokenSet,this.uncheckedNodes=[],this.minimizedNodes={}},lunr.TokenSet.Builder.prototype.insert=function(e){var t,r=0;if(e<this.previousWord)throw new Error("Out of order word insertion");for(var i=0;i<e.length&&i<this.previousWord.length&&e[i]==this.previousWord[i];i++)r++;this.minimize(r),t=0==this.uncheckedNodes.length?this.root:this.uncheckedNodes[this.uncheckedNodes.length-1].child;for(i=r;i<e.length;i++){var n=new lunr.TokenSet,s=e[i];t.edges[s]=n,this.uncheckedNodes.push({parent:t,char:s,child:n}),t=n}t.final=!0,this.previousWord=e},lunr.TokenSet.Builder.prototype.finish=function(){this.minimize(0)},lunr.TokenSet.Builder.prototype.minimize=function(e){for(var t=this.uncheckedNodes.length-1;t>=e;t--){var r=this.uncheckedNodes[t],i=r.child.toString();i in this.minimizedNodes?r.parent.edges[r.char]=this.minimizedNodes[i]:(r.child._str=i,this.minimizedNodes[i]=r.child),this.uncheckedNodes.pop()}},
/*!
* lunr.Index
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},lunr.Index.prototype.search=function(e){return this.query((function(t){new lunr.QueryParser(e,t).parse()}))},lunr.Index.prototype.query=function(e){for(var t=new lunr.Query(this.fields),r=Object.create(null),i=Object.create(null),n=Object.create(null),s=Object.create(null),o=Object.create(null),a=0;a<this.fields.length;a++)i[this.fields[a]]=new lunr.Vector;e.call(t,t);for(a=0;a<t.clauses.length;a++){var u=t.clauses[a],l=null,c=lunr.Set.complete;l=u.usePipeline?this.pipeline.runString(u.term,{fields:u.fields}):[u.term];for(var h=0;h<l.length;h++){var d=l[h];u.term=d;var f=lunr.TokenSet.fromClause(u),p=this.tokenSet.intersect(f).toArray();if(0===p.length&&u.presence===lunr.Query.presence.REQUIRED){for(var y=0;y<u.fields.length;y++){s[R=u.fields[y]]=lunr.Set.empty}break}for(var m=0;m<p.length;m++){var g=p[m],x=this.invertedIndex[g],v=x._index;for(y=0;y<u.fields.length;y++){var w=x[R=u.fields[y]],Q=Object.keys(w),k=g+"/"+R,S=new lunr.Set(Q);if(u.presence==lunr.Query.presence.REQUIRED&&(c=c.union(S),void 0===s[R]&&(s[R]=lunr.Set.complete)),u.presence!=lunr.Query.presence.PROHIBITED){if(i[R].upsert(v,u.boost,(function(e,t){return e+t})),!n[k]){for(var E=0;E<Q.length;E++){var L,b=Q[E],P=new lunr.FieldRef(b,R),T=w[b];void 0===(L=r[P])?r[P]=new lunr.MatchData(g,R,T):L.add(g,R,T)}n[k]=!0}}else void 0===o[R]&&(o[R]=lunr.Set.empty),o[R]=o[R].union(S)}}}if(u.presence===lunr.Query.presence.REQUIRED)for(y=0;y<u.fields.length;y++){s[R=u.fields[y]]=s[R].intersect(c)}}var O=lunr.Set.complete,I=lunr.Set.empty;for(a=0;a<this.fields.length;a++){var R;s[R=this.fields[a]]&&(O=O.intersect(s[R])),o[R]&&(I=I.union(o[R]))}var F=Object.keys(r),C=[],N=Object.create(null);if(t.isNegated()){F=Object.keys(this.fieldVectors);for(a=0;a<F.length;a++){P=F[a];var j=lunr.FieldRef.fromString(P);r[P]=new lunr.MatchData}}for(a=0;a<F.length;a++){var _=(j=lunr.FieldRef.fromString(F[a])).docRef;if(O.contains(_)&&!I.contains(_)){var D,A=this.fieldVectors[j],B=i[j.fieldName].similarity(A);if(void 0!==(D=N[_]))D.score+=B,D.matchData.combine(r[j]);else{var V={ref:_,score:B,matchData:r[j]};N[_]=V,C.push(V)}}}return C.sort((function(e,t){return t.score-e.score}))},lunr.Index.prototype.toJSON=function(){var e=Object.keys(this.invertedIndex).sort().map((function(e){return[e,this.invertedIndex[e]]}),this),t=Object.keys(this.fieldVectors).map((function(e){return[e,this.fieldVectors[e].toJSON()]}),this);return{version:lunr.version,fields:this.fields,fieldVectors:t,invertedIndex:e,pipeline:this.pipeline.toJSON()}},lunr.Index.load=function(e){var t={},r={},i=e.fieldVectors,n=Object.create(null),s=e.invertedIndex,o=new lunr.TokenSet.Builder,a=lunr.Pipeline.load(e.pipeline);e.version!=lunr.version&&lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '"+lunr.version+"' does not match serialized index '"+e.version+"'");for(var u=0;u<i.length;u++){var l=(h=i[u])[0],c=h[1];r[l]=new lunr.Vector(c)}for(u=0;u<s.length;u++){var h,d=(h=s[u])[0],f=h[1];o.insert(d),n[d]=f}return o.finish(),t.fields=e.fields,t.fieldVectors=r,t.invertedIndex=n,t.tokenSet=o.root,t.pipeline=a,new lunr.Index(t)},
/*!
* lunr.Builder
* Copyright (C) 2019 Oliver Nightingale
*/
lunr.Builder=function(){this._ref="id",this._fields=Object.create(null),this._documents=Object.create(null),this.invertedIndex=Object.create(null),this.fieldTermFrequencies={},this.fieldLengths={},this.tokenizer=lunr.tokenizer,this.pipeline=new lunr.Pipeline,this.searchPipeline=new lunr.Pipeline,this.documentCount=0,this._b=.75,this._k1=1.2,this.termIndex=0,this.metadataWhitelist=[]},lunr.Builder.prototype.ref=function(e){this._ref=e},lunr.Builder.prototype.field=function(e,t){if(/\//.test(e))throw new RangeError("Field '"+e+"' contains illegal character '/'");this._fields[e]=t||{}},lunr.Builder.prototype.b=function(e){this._b=e<0?0:e>1?1:e},lunr.Builder.prototype.k1=function(e){this._k1=e},lunr.Builder.prototype.add=function(e,t){var r=e[this._ref],i=Object.keys(this._fields);this._documents[r]=t||{},this.documentCount+=1;for(var n=0;n<i.length;n++){var s=i[n],o=this._fields[s].extractor,a=o?o(e):e[s],u=this.tokenizer(a,{fields:[s]}),l=this.pipeline.run(u),c=new lunr.FieldRef(r,s),h=Object.create(null);this.fieldTermFrequencies[c]=h,this.fieldLengths[c]=0,this.fieldLengths[c]+=l.length;for(var d=0;d<l.length;d++){var f=l[d];if(null==h[f]&&(h[f]=0),h[f]+=1,null==this.invertedIndex[f]){var p=Object.create(null);p._index=this.termIndex,this.termIndex+=1;for(var y=0;y<i.length;y++)p[i[y]]=Object.create(null);this.invertedIndex[f]=p}null==this.invertedIndex[f][s][r]&&(this.invertedIndex[f][s][r]=Object.create(null));for(var m=0;m<this.metadataWhitelist.length;m++){var g=this.metadataWhitelist[m],x=f.metadata[g];null==this.invertedIndex[f][s][r][g]&&(this.invertedIndex[f][s][r][g]=[]),this.invertedIndex[f][s][r][g].push(x)}}}},lunr.Builder.prototype.calculateAverageFieldLengths=function(){for(var e=Object.keys(this.fieldLengths),t=e.length,r={},i={},n=0;n<t;n++){var s=lunr.FieldRef.fromString(e[n]),o=s.fieldName;i[o]||(i[o]=0),i[o]+=1,r[o]||(r[o]=0),r[o]+=this.fieldLengths[s]}var a=Object.keys(this._fields);for(n=0;n<a.length;n++){var u=a[n];r[u]=r[u]/i[u]}this.averageFieldLength=r},lunr.Builder.prototype.createFieldVectors=function(){for(var e={},t=Object.keys(this.fieldTermFrequencies),r=t.length,i=Object.create(null),n=0;n<r;n++){for(var s=lunr.FieldRef.fromString(t[n]),o=s.fieldName,a=this.fieldLengths[s],u=new lunr.Vector,l=this.fieldTermFrequencies[s],c=Object.keys(l),h=c.length,d=this._fields[o].boost||1,f=this._documents[s.docRef].boost||1,p=0;p<h;p++){var y,m,g,x=c[p],v=l[x],w=this.invertedIndex[x]._index;void 0===i[x]?(y=lunr.idf(this.invertedIndex[x],this.documentCount),i[x]=y):y=i[x],m=y*((this._k1+1)*v)/(this._k1*(1-this._b+this._b*(a/this.averageFieldLength[o]))+v),m*=d,m*=f,g=Math.round(1e3*m)/1e3,u.insert(w,g)}e[s]=u}this.fieldVectors=e},lunr.Builder.prototype.createTokenSet=function(){this.tokenSet=lunr.TokenSet.fromArray(Object.keys(this.invertedIndex).sort())},lunr.Builder.prototype.build=function(){return this.calculateAverageFieldLengths(),this.createFieldVectors(),this.createTokenSet(),new lunr.Index({invertedIndex:this.invertedIndex,fieldVectors:this.fieldVectors,tokenSet:this.tokenSet,fields:Object.keys(this._fields),pipeline:this.searchPipeline})},lunr.Builder.prototype.use=function(e){var t=Array.prototype.slice.call(arguments,1);t.unshift(this),e.apply(this,t)},lunr.MatchData=function(e,t,r){for(var i=Object.create(null),n=Object.keys(r||{}),s=0;s<n.length;s++){var o=n[s];i[o]=r[o].slice()}this.metadata=Object.create(null),void 0!==e&&(this.metadata[e]=Object.create(null),this.metadata[e][t]=i)},lunr.MatchData.prototype.combine=function(e){for(var t=Object.keys(e.metadata),r=0;r<t.length;r++){var i=t[r],n=Object.keys(e.metadata[i]);null==this.metadata[i]&&(this.metadata[i]=Object.create(null));for(var s=0;s<n.length;s++){var o=n[s],a=Object.keys(e.metadata[i][o]);null==this.metadata[i][o]&&(this.metadata[i][o]=Object.create(null));for(var u=0;u<a.length;u++){var l=a[u];null==this.metadata[i][o][l]?this.metadata[i][o][l]=e.metadata[i][o][l]:this.metadata[i][o][l]=this.metadata[i][o][l].concat(e.metadata[i][o][l])}}}},lunr.MatchData.prototype.add=function(e,t,r){if(!(e in this.metadata))return this.metadata[e]=Object.create(null),void(this.metadata[e][t]=r);if(t in this.metadata[e])for(var i=Object.keys(r),n=0;n<i.length;n++){var s=i[n];s in this.metadata[e][t]?this.metadata[e][t][s]=this.metadata[e][t][s].concat(r[s]):this.metadata[e][t][s]=r[s]}else this.metadata[e][t]=r},lunr.Query=function(e){this.clauses=[],this.allFields=e},lunr.Query.wildcard=new String("*"),lunr.Query.wildcard.NONE=0,lunr.Query.wildcard.LEADING=1,lunr.Query.wildcard.TRAILING=2,lunr.Query.presence={OPTIONAL:1,REQUIRED:2,PROHIBITED:3},lunr.Query.prototype.clause=function(e){return"fields"in e||(e.fields=this.allFields),"boost"in e||(e.boost=1),"usePipeline"in e||(e.usePipeline=!0),"wildcard"in e||(e.wildcard=lunr.Query.wildcard.NONE),e.wildcard&lunr.Query.wildcard.LEADING&&e.term.charAt(0)!=lunr.Query.wildcard&&(e.term="*"+e.term),e.wildcard&lunr.Query.wildcard.TRAILING&&e.term.slice(-1)!=lunr.Query.wildcard&&(e.term=e.term+"*"),"presence"in e||(e.presence=lunr.Query.presence.OPTIONAL),this.clauses.push(e),this},lunr.Query.prototype.isNegated=function(){for(var e=0;e<this.clauses.length;e++)if(this.clauses[e].presence!=lunr.Query.presence.PROHIBITED)return!1;return!0},lunr.Query.prototype.term=function(e,t){if(Array.isArray(e))return e.forEach((function(e){this.term(e,lunr.utils.clone(t))}),this),this;var r=t||{};return r.term=e.toString(),this.clause(r),this},lunr.QueryParseError=function(e,t,r){this.name="QueryParseError",this.message=e,this.start=t,this.end=r},lunr.QueryParseError.prototype=new Error,lunr.QueryLexer=function(e){this.lexemes=[],this.str=e,this.length=e.length,this.pos=0,this.start=0,this.escapeCharPositions=[]},lunr.QueryLexer.prototype.run=function(){for(var e=lunr.QueryLexer.lexText;e;)e=e(this)},lunr.QueryLexer.prototype.sliceString=function(){for(var e=[],t=this.start,r=this.pos,i=0;i<this.escapeCharPositions.length;i++)r=this.escapeCharPositions[i],e.push(this.str.slice(t,r)),t=r+1;return e.push(this.str.slice(t,this.pos)),this.escapeCharPositions.length=0,e.join("")},lunr.QueryLexer.prototype.emit=function(e){this.lexemes.push({type:e,str:this.sliceString(),start:this.start,end:this.pos}),this.start=this.pos},lunr.QueryLexer.prototype.escapeCharacter=function(){this.escapeCharPositions.push(this.pos-1),this.pos+=1},lunr.QueryLexer.prototype.next=function(){if(this.pos>=this.length)return lunr.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},lunr.QueryLexer.prototype.width=function(){return this.pos-this.start},lunr.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},lunr.QueryLexer.prototype.backup=function(){this.pos-=1},lunr.QueryLexer.prototype.acceptDigitRun=function(){var e,t;do{t=(e=this.next()).charCodeAt(0)}while(t>47&&t<58);e!=lunr.QueryLexer.EOS&&this.backup()},lunr.QueryLexer.prototype.more=function(){return this.pos<this.length},lunr.QueryLexer.EOS="EOS",lunr.QueryLexer.FIELD="FIELD",lunr.QueryLexer.TERM="TERM",lunr.QueryLexer.EDIT_DISTANCE="EDIT_DISTANCE",lunr.QueryLexer.BOOST="BOOST",lunr.QueryLexer.PRESENCE="PRESENCE",lunr.QueryLexer.lexField=function(e){return e.backup(),e.emit(lunr.QueryLexer.FIELD),e.ignore(),lunr.QueryLexer.lexText},lunr.QueryLexer.lexTerm=function(e){if(e.width()>1&&(e.backup(),e.emit(lunr.QueryLexer.TERM)),e.ignore(),e.more())return lunr.QueryLexer.lexText},lunr.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(lunr.QueryLexer.EDIT_DISTANCE),lunr.QueryLexer.lexText},lunr.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(lunr.QueryLexer.BOOST),lunr.QueryLexer.lexText},lunr.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(lunr.QueryLexer.TERM)},lunr.QueryLexer.termSeparator=lunr.tokenizer.separator,lunr.QueryLexer.lexText=function(e){for(;;){var t=e.next();if(t==lunr.QueryLexer.EOS)return lunr.QueryLexer.lexEOS;if(92!=t.charCodeAt(0)){if(":"==t)return lunr.QueryLexer.lexField;if("~"==t)return e.backup(),e.width()>0&&e.emit(lunr.QueryLexer.TERM),lunr.QueryLexer.lexEditDistance;if("^"==t)return e.backup(),e.width()>0&&e.emit(lunr.QueryLexer.TERM),lunr.QueryLexer.lexBoost;if("+"==t&&1===e.width())return e.emit(lunr.QueryLexer.PRESENCE),lunr.QueryLexer.lexText;if("-"==t&&1===e.width())return e.emit(lunr.QueryLexer.PRESENCE),lunr.QueryLexer.lexText;if(t.match(lunr.QueryLexer.termSeparator))return lunr.QueryLexer.lexTerm}else e.escapeCharacter()}},lunr.QueryParser=function(e,t){this.lexer=new lunr.QueryLexer(e),this.query=t,this.currentClause={},this.lexemeIdx=0},lunr.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=lunr.QueryParser.parseClause;e;)e=e(this);return this.query},lunr.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},lunr.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},lunr.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},lunr.QueryParser.parseClause=function(e){var t=e.peekLexeme();if(null!=t)switch(t.type){case lunr.QueryLexer.PRESENCE:return lunr.QueryParser.parsePresence;case lunr.QueryLexer.FIELD:return lunr.QueryParser.parseField;case lunr.QueryLexer.TERM:return lunr.QueryParser.parseTerm;default:var r="expected either a field or a term, found "+t.type;throw t.str.length>=1&&(r+=" with value '"+t.str+"'"),new lunr.QueryParseError(r,t.start,t.end)}},lunr.QueryParser.parsePresence=function(e){var t=e.consumeLexeme();if(null!=t){switch(t.str){case"-":e.currentClause.presence=lunr.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=lunr.Query.presence.REQUIRED;break;default:var r="unrecognised presence operator'"+t.str+"'";throw new lunr.QueryParseError(r,t.start,t.end)}var i=e.peekLexeme();if(null==i){r="expecting term or field, found nothing";throw new lunr.QueryParseError(r,t.start,t.end)}switch(i.type){case lunr.QueryLexer.FIELD:return lunr.QueryParser.parseField;case lunr.QueryLexer.TERM:return lunr.QueryParser.parseTerm;default:r="expecting term or field, found '"+i.type+"'";throw new lunr.QueryParseError(r,i.start,i.end)}}},lunr.QueryParser.parseField=function(e){var t=e.consumeLexeme();if(null!=t){if(-1==e.query.allFields.indexOf(t.str)){var r=e.query.allFields.map((function(e){return"'"+e+"'"})).join(", "),i="unrecognised field '"+t.str+"', possible fields: "+r;throw new lunr.QueryParseError(i,t.start,t.end)}e.currentClause.fields=[t.str];var n=e.peekLexeme();if(null==n){i="expecting term, found nothing";throw new lunr.QueryParseError(i,t.start,t.end)}switch(n.type){case lunr.QueryLexer.TERM:return lunr.QueryParser.parseTerm;default:i="expecting term, found '"+n.type+"'";throw new lunr.QueryParseError(i,n.start,n.end)}}},lunr.QueryParser.parseTerm=function(e){var t=e.consumeLexeme();if(null!=t){e.currentClause.term=t.str.toLowerCase(),-1!=t.str.indexOf("*")&&(e.currentClause.usePipeline=!1);var r=e.peekLexeme();if(null!=r)switch(r.type){case lunr.QueryLexer.TERM:return e.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return e.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return e.nextClause(),lunr.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+r.type+"'";throw new lunr.QueryParseError(i,r.start,r.end)}else e.nextClause()}},lunr.QueryParser.parseEditDistance=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="edit distance must be numeric";throw new lunr.QueryParseError(i,t.start,t.end)}e.currentClause.editDistance=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case lunr.QueryLexer.TERM:return e.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return e.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return e.nextClause(),lunr.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new lunr.QueryParseError(i,n.start,n.end)}else e.nextClause()}},lunr.QueryParser.parseBoost=function(e){var t=e.consumeLexeme();if(null!=t){var r=parseInt(t.str,10);if(isNaN(r)){var i="boost must be numeric";throw new lunr.QueryParseError(i,t.start,t.end)}e.currentClause.boost=r;var n=e.peekLexeme();if(null!=n)switch(n.type){case lunr.QueryLexer.TERM:return e.nextClause(),lunr.QueryParser.parseTerm;case lunr.QueryLexer.FIELD:return e.nextClause(),lunr.QueryParser.parseField;case lunr.QueryLexer.EDIT_DISTANCE:return lunr.QueryParser.parseEditDistance;case lunr.QueryLexer.BOOST:return lunr.QueryParser.parseBoost;case lunr.QueryLexer.PRESENCE:return e.nextClause(),lunr.QueryParser.parsePresence;default:i="Unexpected lexeme type '"+n.type+"'";throw new lunr.QueryParseError(i,n.start,n.end)}else e.nextClause()}},b=this,P=function(){return lunr},"function"==typeof define&&define.amd?define(P):"object"==typeof exports?module.exports=P():b.lunr=P()}(); | lunr.tokenizer=function(e,t){if(null==e||null==e)return[];if(Array.isArray(e))return e.map((function(e){return new lunr.Token(lunr.utils.asString(e).toLowerCase(),lunr.utils.clone(t))}));for(var r=e.toString().trim().toLowerCase(),i=r.length,n=[],s=0,o=0;s<=i;s++){var a=s-o;if(r.charAt(s).match(lunr.tokenizer.separator)||s==i){if(a>0){var u=lunr.utils.clone(t)||{};u.position=[o,a],u.index=n.length,n.push(new lunr.Token(r.slice(o,s),u))}o=s+1}}return n},lunr.tokenizer.separator=/[\s\-]+/, |
framework.92982bd08c20a57f256c.js | (window.webpackJsonp_N_E=window.webpackJsonp_N_E||[]).push([[1],{"+wdc":function(e,t,n){"use strict";var r,l,a,o;if("object"===typeof performance&&"function"===typeof performance.now){var i=performance;t.unstable_now=function(){return i.now()}}else{var u=Date,s=u.now();t.unstable_now=function(){return u.now()-s}}if("undefined"===typeof window||"function"!==typeof MessageChannel){var c=null,f=null,d=function(){if(null!==c)try{var e=t.unstable_now();c(!0,e),c=null}catch(n){throw setTimeout(d,0),n}};r=function(e){null!==c?setTimeout(r,0,e):(c=e,setTimeout(d,0))},l=function(e,t){f=setTimeout(e,t)},a=function(){clearTimeout(f)},t.unstable_shouldYield=function(){return!1},o=t.unstable_forceFrameRate=function(){}}else{var p=window.setTimeout,h=window.clearTimeout;if("undefined"!==typeof console){var m=window.cancelAnimationFrame;"function"!==typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"),"function"!==typeof m&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills")}var v=!1,y=null,g=-1,b=5,w=0;t.unstable_shouldYield=function(){return t.unstable_now()>=w},o=function(){},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):b=0<e?Math.floor(1e3/e):5};var k=new MessageChannel,S=k.port2;k.port1.onmessage=function(){if(null!==y){var e=t.unstable_now();w=e+b;try{y(!0,e)?S.postMessage(null):(v=!1,y=null)}catch(n){throw S.postMessage(null),n}}else v=!1},r=function(e){y=e,v||(v=!0,S.postMessage(null))},l=function(e,n){g=p((function(){e(t.unstable_now())}),n)},a=function(){h(g),g=-1}}function E(e,t){var n=e.length;e.push(t);e:for(;;){var r=n-1>>>1,l=e[r];if(!(void 0!==l&&0<C(l,t)))break e;e[r]=t,e[n]=l,n=r}}function x(e){return void 0===(e=e[0])?null:e}function _(e){var t=e[0];if(void 0!==t){var n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,l=e.length;r<l;){var a=2*(r+1)-1,o=e[a],i=a+1,u=e[i];if(void 0!==o&&0>C(o,n))void 0!==u&&0>C(u,o)?(e[r]=u,e[i]=n,r=i):(e[r]=o,e[a]=n,r=a);else{if(!(void 0!==u&&0>C(u,n)))break e;e[r]=u,e[i]=n,r=i}}}return t}return null}function C(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}var P=[],N=[],T=1,L=null,z=3,O=!1,F=!1,I=!1;function R(e){for(var t=x(N);null!==t;){if(null===t.callback)_(N);else{if(!(t.startTime<=e))break;_(N),t.sortIndex=t.expirationTime,E(P,t)}t=x(N)}}function D(e){if(I=!1,R(e),!F)if(null!==x(P))F=!0,r(M);else{var t=x(N);null!==t&&l(D,t.startTime-e)}}function M(e,n){F=!1,I&&(I=!1,a()),O=!0;var r=z;try{for(R(n),L=x(P);null!==L&&(!(L.expirationTime>n)||e&&!t.unstable_shouldYield());){var o=L.callback;if("function"===typeof o){L.callback=null,z=L.priorityLevel;var i=o(L.expirationTime<=n);n=t.unstable_now(),"function"===typeof i?L.callback=i:L===x(P)&&_(P),R(n)}else _(P);L=x(P)}if(null!==L)var u=!0;else{var s=x(N);null!==s&&l(D,s.startTime-n),u=!1}return u}finally{L=null,z=r,O=!1}}var U=o;t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){F||O||(F=!0,r(M))},t.unstable_getCurrentPriorityLevel=function(){return z},t.unstable_getFirstCallbackNode=function(){return x(P)},t.unstable_next=function(e){switch(z){case 1:case 2:case 3:var t=3;break;default:t=z}var n=z;z=t;try{return e()}finally{z=n}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=U,t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=z;z=e;try{return t()}finally{z=n}},t.unstable_scheduleCallback=function(e,n,o){var i=t.unstable_now();switch("object"===typeof o&&null!==o?o="number"===typeof(o=o.delay)&&0<o?i+o:i:o=i,e){case 1:var u=-1;break;case 2:u=250;break;case 5:u=1073741823;break;case 4:u=1e4;break;default:u=5e3}return e={id:T++,callback:n,priorityLevel:e,startTime:o,expirationTime:u=o+u,sortIndex:-1},o>i?(e.sortIndex=o,E(N,e),null===x(P)&&e===x(N)&&(I?a():I=!0,l(D,o-i))):(e.sortIndex=u,E(P,e),F||O||(F=!0,r(M))),e},t.unstable_wrapCallback=function(e){var t=z;return function(){var n=z;z=t;try{return e.apply(this,arguments)}finally{z=n}}}},"0x2o":function(e,t,n){"use strict";n("Qetd");var r=n("q1tI"),l=60103;if(t.Fragment=60107,"function"===typeof Symbol&&Symbol.for){var a=Symbol.for;l=a("react.element"),t.Fragment=a("react.fragment")}var o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i=Object.prototype.hasOwnProperty,u={key:!0,ref:!0,__self:!0,__source:!0};function s(e,t,n){var r,a={},s=null,c=null;for(r in void 0!==n&&(s=""+n),void 0!==t.key&&(s=""+t.key),void 0!==t.ref&&(c=t.ref),t)i.call(t,r)&&!u.hasOwnProperty(r)&&(a[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===a[r]&&(a[r]=t[r]);return{$$typeof:l,type:e,key:s,ref:c,props:a,_owner:o.current}}t.jsx=s,t.jsxs=s},"16Al":function(e,t,n){"use strict";var r=n("WbBG");function l(){}function a(){}a.resetWarningCache=l,e.exports=function(){function e(e,t,n,l,a,o){if(o!==r){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:a,resetWarningCache:l};return n.PropTypes=n,n}},"17x9":function(e,t,n){e.exports=n("16Al")()},IDhZ:function(e,t,n){"use strict";var r=n("Qetd"),l=n("q1tI");function a(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var o=60106,i=60107,u=60108,s=60114,c=60109,f=60110,d=60112,p=60113,h=60120,m=60115,v=60116,y=60121,g=60117,b=60119,w=60129,k=60131;if("function"===typeof Symbol&&Symbol.for){var S=Symbol.for;o=S("react.portal"),i=S("react.fragment"),u=S("react.strict_mode"),s=S("react.profiler"),c=S("react.provider"),f=S("react.context"),d=S("react.forward_ref"),p=S("react.suspense"),h=S("react.suspense_list"),m=S("react.memo"),v=S("react.lazy"),y=S("react.block"),g=S("react.fundamental"),b=S("react.scope"),w=S("react.debug_trace_mode"),k=S("react.legacy_hidden")}function E(e){if(null==e)return null;if("function"===typeof e)return e.displayName||e.name||null;if("string"===typeof e)return e;switch(e){case i:return"Fragment";case o:return"Portal";case s:return"Profiler";case u:return"StrictMode";case p:return"Suspense";case h:return"SuspenseList"}if("object"===typeof e)switch(e.$$typeof){case f:return(e.displayName||"Context")+".Consumer";case c:return(e._context.displayName||"Context")+".Provider";case d:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef");case m:return E(e.type);case y:return E(e._render);case v:t=e._payload,e=e._init;try{return E(e(t))}catch(n){}}return null}var x=l.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,_={};function C(e,t){for(var n=0|e._threadCount;n<=t;n++)e[n]=e._currentValue2,e._threadCount=n+1}for(var P=new Uint16Array(16),N=0;15>N;N++)P[N]=N+1;P[15]=0;var T=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,L=Object.prototype.hasOwnProperty,z={},O={};function F(e){return!!L.call(O,e)||!L.call(z,e)&&(T.test(e)?O[e]=!0:(z[e]=!0,!1))}function I(e,t,n,r,l,a,o){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var R={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){R[e]=new I(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];R[t]=new I(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){R[e]=new I(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){R[e]=new I(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){R[e]=new I(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){R[e]=new I(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){R[e]=new I(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){R[e]=new I(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){R[e]=new I(e,5,!1,e.toLowerCase(),null,!1,!1)}));var D=/[\-:]([a-z])/g;function M(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(D,M);R[t]=new I(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(D,M);R[t]=new I(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(D,M);R[t]=new I(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){R[e]=new I(e,1,!1,e.toLowerCase(),null,!1,!1)})),R.xlinkHref=new I("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){R[e]=new I(e,1,!1,e.toLowerCase(),null,!0,!0)}));var U=/["'&<>]/;function A(e){if("boolean"===typeof e||"number"===typeof e)return""+e;e=""+e;var t=U.exec(e);if(t){var n,r="",l=0;for(n=t.index;n<e.length;n++){switch(e.charCodeAt(n)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}l!==n&&(r+=e.substring(l,n)),l=n+1,r+=t}e=l!==n?r+e.substring(l,n):r}return e}function V(e,t){var n,r=R.hasOwnProperty(e)?R[e]:null;return(n="style"!==e)&&(n=null!==r?0===r.type:2<e.length&&("o"===e[0]||"O"===e[0])&&("n"===e[1]||"N"===e[1])),n||function(e,t,n,r){if(null===t||"undefined"===typeof t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(e,t,r,!1)?"":null!==r?(e=r.attributeName,3===(n=r.type)||4===n&&!0===t?e+'=""':(r.sanitizeURL&&(t=""+t),e+'="'+A(t)+'"')):F(e)?e+'="'+A(t)+'"':""}var W="function"===typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e===1/t)||e!==e&&t!==t},j=null,$=null,B=null,H=!1,Q=!1,q=null,K=0;function Y(){if(null===j)throw Error(a(321));return j}function X(){if(0<K)throw Error(a(312));return{memoizedState:null,queue:null,next:null}}function G(){return null===B?null===$?(H=!1,$=B=X()):(H=!0,B=$):null===B.next?(H=!1,B=B.next=X()):(H=!0,B=B.next),B}function Z(e,t,n,r){for(;Q;)Q=!1,K+=1,B=null,n=e(t,r);return J(),n}function J(){j=null,Q=!1,$=null,K=0,B=q=null}function ee(e,t){return"function"===typeof t?t(e):t}function te(e,t,n){if(j=Y(),B=G(),H){var r=B.queue;if(t=r.dispatch,null!==q&&void 0!==(n=q.get(r))){q.delete(r),r=B.memoizedState;do{r=e(r,n.action),n=n.next}while(null!==n);return B.memoizedState=r,[r,t]}return[B.memoizedState,t]}return e=e===ee?"function"===typeof t?t():t:void 0!==n?n(t):t,B.memoizedState=e,e=(e=B.queue={last:null,dispatch:null}).dispatch=re.bind(null,j,e),[B.memoizedState,e]}function ne(e,t){if(j=Y(),t=void 0===t?null:t,null!==(B=G())){var n=B.memoizedState;if(null!==n&&null!==t){var r=n[1];e:if(null===r)r=!1;else{for(var l=0;l<r.length&&l<t.length;l++)if(!W(t[l],r[l])){r=!1;break e}r=!0}if(r)return n[0]}}return e=e(),B.memoizedState=[e,t],e}function re(e,t,n){if(!(25>K))throw Error(a(301));if(e===j)if(Q=!0,e={action:n,next:null},null===q&&(q=new Map),void 0===(n=q.get(t)))q.set(t,e);else{for(t=n;null!==t.next;)t=t.next;t.next=e}}function le(){}var ae=null,oe={readContext:function(e){var t=ae.threadID;return C(e,t),e[t]},useContext:function(e){Y();var t=ae.threadID;return C(e,t),e[t]},useMemo:ne,useReducer:te,useRef:function(e){j=Y();var t=(B=G()).memoizedState;return null===t?(e={current:e},B.memoizedState=e):t},useState:function(e){return te(ee,e)},useLayoutEffect:function(){},useCallback:function(e,t){return ne((function(){return e}),t)},useImperativeHandle:le,useEffect:le,useDebugValue:le,useDeferredValue:function(e){return Y(),e},useTransition:function(){return Y(),[function(e){e()},!1]},useOpaqueIdentifier:function(){return(ae.identifierPrefix||"")+"R:"+(ae.uniqueID++).toString(36)},useMutableSource:function(e,t){return Y(),t(e._source)}},ie="http://www.w3.org/1999/xhtml";function ue(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}var se={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},ce=r({menuitem:!0},se),fe={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},de=["Webkit","ms","Moz","O"];Object.keys(fe).forEach((function(e){de.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),fe[t]=fe[e]}))}));var pe=/([A-Z])/g,he=/^ms-/,me=l.Children.toArray,ve=x.ReactCurrentDispatcher,ye={listing:!0,pre:!0,textarea:!0},ge=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,be={},we={};var ke=Object.prototype.hasOwnProperty,Se={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null,suppressHydrationWarning:null};function Ee(e,t){if(void 0===e)throw Error(a(152,E(t)||"Component"))}function xe(e,t,n){function o(l,o){var i=o.prototype&&o.prototype.isReactComponent,u=function(e,t,n,r){if(r&&"object"===typeof(r=e.contextType)&&null!==r)return C(r,n),r[n];if(e=e.contextTypes){for(var l in n={},e)n[l]=t[l];t=n}else t=_;return t}(o,t,n,i),s=[],c=!1,f={isMounted:function(){return!1},enqueueForceUpdate:function(){if(null===s)return null},enqueueReplaceState:function(e,t){c=!0,s=[t]},enqueueSetState:function(e,t){if(null===s)return null;s.push(t)}};if(i){if(i=new o(l.props,u,f),"function"===typeof o.getDerivedStateFromProps){var d=o.getDerivedStateFromProps.call(null,l.props,i.state);null!=d&&(i.state=r({},i.state,d))}}else if(j={},i=o(l.props,u,f),null==(i=Z(o,l.props,i,u))||null==i.render)return void Ee(e=i,o);if(i.props=l.props,i.context=u,i.updater=f,void 0===(f=i.state)&&(i.state=f=null),"function"===typeof i.UNSAFE_componentWillMount||"function"===typeof i.componentWillMount)if("function"===typeof i.componentWillMount&&"function"!==typeof o.getDerivedStateFromProps&&i.componentWillMount(),"function"===typeof i.UNSAFE_componentWillMount&&"function"!==typeof o.getDerivedStateFromProps&&i.UNSAFE_componentWillMount(),s.length){f=s;var p=c;if(s=null,c=!1,p&&1===f.length)i.state=f[0];else{d=p?f[0]:i.state;var h=!0;for(p=p?1:0;p<f.length;p++){var m=f[p];null!=(m="function"===typeof m?m.call(i,d,l.props,u):m)&&(h?(h=!1,d=r({},d,m)):r(d,m))}i.state=d}}else s=null;if(Ee(e=i.render(),o),"function"===typeof i.getChildContext&&"object"===typeof(l=o.childContextTypes)){var v=i.getChildContext();for(var y in v)if(!(y in l))throw Error(a(108,E(o)||"Unknown",y))}v&&(t=r({},t,v))}for(;l.isValidElement(e);){var i=e,u=i.type;if("function"!==typeof u)break;o(i,u)}return{child:e,context:t}}var _e=function(){function e(e,t,n){l.isValidElement(e)?e.type!==i?e=[e]:(e=e.props.children,e=l.isValidElement(e)?[e]:me(e)):e=me(e),e={type:null,domNamespace:ie,children:e,childIndex:0,context:_,footer:""};var r=P[0];if(0===r){var o=P,u=2*(r=o.length);if(!(65536>=u))throw Error(a(304));var s=new Uint16Array(u);for(s.set(o),(P=s)[0]=r+1,o=r;o<u-1;o++)P[o]=o+1;P[u-1]=0}else P[0]=P[r];this.threadID=r,this.stack=[e],this.exhausted=!1,this.currentSelectValue=null,this.previousWasTextNode=!1,this.makeStaticMarkup=t,this.suspenseDepth=0,this.contextIndex=-1,this.contextStack=[],this.contextValueStack=[],this.uniqueID=0,this.identifierPrefix=n&&n.identifierPrefix||""}var t=e.prototype;return t.destroy=function(){if(!this.exhausted){this.exhausted=!0,this.clearProviders();var e=this.threadID;P[e]=P[0],P[0]=e}},t.pushProvider=function(e){var t=++this.contextIndex,n=e.type._context,r=this.threadID;C(n,r);var l=n[r];this.contextStack[t]=n,this.contextValueStack[t]=l,n[r]=e.props.value},t.popProvider=function(){var e=this.contextIndex,t=this.contextStack[e],n=this.contextValueStack[e];this.contextStack[e]=null,this.contextValueStack[e]=null,this.contextIndex--,t[this.threadID]=n},t.clearProviders=function(){for(var e=this.contextIndex;0<=e;e--)this.contextStack[e][this.threadID]=this.contextValueStack[e]},t.read=function(e){if(this.exhausted)return null;var t=ae;ae=this;var n=ve.current;ve.current=oe;try{for(var r=[""],l=!1;r[0].length<e;){if(0===this.stack.length){this.exhausted=!0;var o=this.threadID;P[o]=P[0],P[0]=o;break}var i=this.stack[this.stack.length-1];if(l||i.childIndex>=i.children.length){var u=i.footer;if(""!==u&&(this.previousWasTextNode=!1),this.stack.pop(),"select"===i.type)this.currentSelectValue=null;else if(null!=i.type&&null!=i.type.type&&i.type.type.$$typeof===c)this.popProvider(i.type);else if(i.type===p){this.suspenseDepth--;var s=r.pop();if(l){l=!1;var f=i.fallbackFrame;if(!f)throw Error(a(303));this.stack.push(f),r[this.suspenseDepth]+="\x3c!--$!--\x3e";continue}r[this.suspenseDepth]+=s}r[this.suspenseDepth]+=u}else{var d=i.children[i.childIndex++],h="";try{h+=this.render(d,i.context,i.domNamespace)}catch(m){if(null!=m&&"function"===typeof m.then)throw Error(a(294));throw m}r.length<=this.suspenseDepth&&r.push(""),r[this.suspenseDepth]+=h}}return r[0]}finally{ve.current=n,ae=t,J()}},t.render=function(e,t,n){if("string"===typeof e||"number"===typeof e)return""===(n=""+e)?"":this.makeStaticMarkup?A(n):this.previousWasTextNode?"\x3c!-- --\x3e"+A(n):(this.previousWasTextNode=!0,A(n));if(e=(t=xe(e,t,this.threadID)).child,t=t.context,null===e||!1===e)return"";if(!l.isValidElement(e)){if(null!=e&&null!=e.$$typeof){if((n=e.$$typeof)===o)throw Error(a(257));throw Error(a(258,n.toString()))}return e=me(e),this.stack.push({type:null,domNamespace:n,children:e,childIndex:0,context:t,footer:""}),""}var y=e.type;if("string"===typeof y)return this.renderDOM(e,t,n);switch(y){case k:case w:case u:case s:case h:case i:return e=me(e.props.children),this.stack.push({type:null,domNamespace:n,children:e,childIndex:0,context:t,footer:""}),"";case p:throw Error(a(294));case b:throw Error(a(343))}if("object"===typeof y&&null!==y)switch(y.$$typeof){case d:j={};var S=y.render(e.props,e.ref);return S=Z(y.render,e.props,S,e.ref),S=me(S),this.stack.push({type:null,domNamespace:n,children:S,childIndex:0,context:t,footer:""}),"";case m:return e=[l.createElement(y.type,r({ref:e.ref},e.props))],this.stack.push({type:null,domNamespace:n,children:e,childIndex:0,context:t,footer:""}),"";case c:return n={type:e,domNamespace:n,children:y=me(e.props.children),childIndex:0,context:t,footer:""},this.pushProvider(e),this.stack.push(n),"";case f:y=e.type,S=e.props;var E=this.threadID;return C(y,E),y=me(S.children(y[E])),this.stack.push({type:e,domNamespace:n,children:y,childIndex:0,context:t,footer:""}),"";case g:throw Error(a(338));case v:return y=(S=(y=e.type)._init)(y._payload),e=[l.createElement(y,r({ref:e.ref},e.props))],this.stack.push({type:null,domNamespace:n,children:e,childIndex:0,context:t,footer:""}),""}throw Error(a(130,null==y?y:typeof y,""))},t.renderDOM=function(e,t,n){var o=e.type.toLowerCase();if(n===ie&&ue(o),!be.hasOwnProperty(o)){if(!ge.test(o))throw Error(a(65,o));be[o]=!0}var i=e.props;if("input"===o)i=r({type:void 0},i,{defaultChecked:void 0,defaultValue:void 0,value:null!=i.value?i.value:i.defaultValue,checked:null!=i.checked?i.checked:i.defaultChecked});else if("textarea"===o){var u=i.value;if(null==u){u=i.defaultValue;var s=i.children;if(null!=s){if(null!=u)throw Error(a(92));if(Array.isArray(s)){if(!(1>=s.length))throw Error(a(93));s=s[0]}u=""+s}null==u&&(u="")}i=r({},i,{value:void 0,children:""+u})}else if("select"===o)this.currentSelectValue=null!=i.value?i.value:i.defaultValue,i=r({},i,{value:void 0});else if("option"===o){s=this.currentSelectValue;var c=function(e){if(void 0===e||null===e)return e;var t="";return l.Children.forEach(e,(function(e){null!=e&&(t+=e)})),t}(i.children);if(null!=s){var f=null!=i.value?i.value+"":c;if(u=!1,Array.isArray(s)){for(var d=0;d<s.length;d++)if(""+s[d]===f){u=!0;break}}else u=""+s===f;i=r({selected:void 0,children:void 0},i,{selected:u,children:c})}}if(u=i){if(ce[o]&&(null!=u.children||null!=u.dangerouslySetInnerHTML))throw Error(a(137,o));if(null!=u.dangerouslySetInnerHTML){if(null!=u.children)throw Error(a(60));if("object"!==typeof u.dangerouslySetInnerHTML||!("__html"in u.dangerouslySetInnerHTML))throw Error(a(61))}if(null!=u.style&&"object"!==typeof u.style)throw Error(a(62))}u=i,s=this.makeStaticMarkup,c=1===this.stack.length,f="<"+e.type;e:if(-1===o.indexOf("-"))d="string"===typeof u.is;else switch(o){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":d=!1;break e;default:d=!0}for(k in u)if(ke.call(u,k)){var p=u[k];if(null!=p){if("style"===k){var h=void 0,m="",v="";for(h in p)if(p.hasOwnProperty(h)){var y=0===h.indexOf("--"),g=p[h];if(null!=g){if(y)var b=h;else if(b=h,we.hasOwnProperty(b))b=we[b];else{var w=b.replace(pe,"-$1").toLowerCase().replace(he,"-ms-");b=we[b]=w}m+=v+b+":",v=h,m+=y=null==g||"boolean"===typeof g||""===g?"":y||"number"!==typeof g||0===g||fe.hasOwnProperty(v)&&fe[v]?(""+g).trim():g+"px",v=";"}}p=m||null}h=null,d?Se.hasOwnProperty(k)||(h=F(h=k)&&null!=p?h+'="'+A(p)+'"':""):h=V(k,p),h&&(f+=" "+h)}}s||c&&(f+=' data-reactroot=""');var k=f;u="",se.hasOwnProperty(o)?k+="/>":(k+=">",u="</"+e.type+">");e:{if(null!=(s=i.dangerouslySetInnerHTML)){if(null!=s.__html){s=s.__html;break e}}else if("string"===typeof(s=i.children)||"number"===typeof s){s=A(s);break e}s=null}return null!=s?(i=[],ye.hasOwnProperty(o)&&"\n"===s.charAt(0)&&(k+="\n"),k+=s):i=me(i.children),e=e.type,n=null==n||"http://www.w3.org/1999/xhtml"===n?ue(e):"http://www.w3.org/2000/svg"===n&&"foreignObject"===e?"http://www.w3.org/1999/xhtml":n,this.stack.push({domNamespace:n,type:o,children:i,childIndex:0,context:t,footer:u}),this.previousWasTextNode=!1,k},e}();t.renderToNodeStream=function(){throw Error(a(207))},t.renderToStaticMarkup=function(e,t){e=new _e(e,!0,t);try{return e.read(1/0)}finally{e.destroy()}},t.renderToStaticNodeStream=function(){throw Error(a(208))},t.renderToString=function(e,t){e=new _e(e,!1,t);try{return e.read(1/0)}finally{e.destroy()}},t.version="17.0.1"},KAy6:function(e,t,n){"use strict";e.exports=n("IDhZ")},QCnb:function(e,t,n){"use strict";e.exports=n("+wdc")},WbBG:function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},i8i4:function(e,t,n){"use strict";!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),e.exports=n("yl30")},nKUr:function(e,t,n){"use strict";e.exports=n("0x2o")},q1tI:function(e,t,n){"use strict";e.exports=n("viRO")},viRO:function(e,t,n){"use strict";var r=n("Qetd"),l=60103,a=60106;t.Fragment=60107,t.StrictMode=60108,t.Profiler=60114;var o=60109,i=60110,u=60112;t.Suspense=60113;var s=60115,c=60116;if("function"===typeof Symbol&&Symbol.for){var f=Symbol.for;l=f("react.element"),a=f("react.portal"),t.Fragment=f("react.fragment"),t.StrictMode=f("react.strict_mode"),t.Profiler=f("react.profiler"),o=f("react.provider"),i=f("react.context"),u=f("react.forward_ref"),t.Suspense=f("react.suspense"),s=f("react.memo"),c=f("react.lazy")}var d="function"===typeof Symbol&&Symbol.iterator;function p(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m={};function v(e,t,n){this.props=e,this.context=t,this.refs=m,this.updater=n||h}function y(){}function g(e,t,n){this.props=e,this.context=t,this.refs=m,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if("object"!==typeof e&&"function"!==typeof e&&null!=e)throw Error(p(85));this.updater.enqueueSetState(this,e,t,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},y.prototype=v.prototype;var b=g.prototype=new y;b.constructor=g,r(b,v.prototype),b.isPureReactComponent=!0;var w={current:null},k=Object.prototype.hasOwnProperty,S={key:!0,ref:!0,__self:!0,__source:!0};function E(e,t,n){var r,a={},o=null,i=null;if(null!=t)for(r in void 0!==t.ref&&(i=t.ref),void 0!==t.key&&(o=""+t.key),t)k.call(t,r)&&!S.hasOwnProperty(r)&&(a[r]=t[r]);var u=arguments.length-2;if(1===u)a.children=n;else if(1<u){for(var s=Array(u),c=0;c<u;c++)s[c]=arguments[c+2];a.children=s}if(e&&e.defaultProps)for(r in u=e.defaultProps)void 0===a[r]&&(a[r]=u[r]);return{$$typeof:l,type:e,key:o,ref:i,props:a,_owner:w.current}}function x(e){return"object"===typeof e&&null!==e&&e.$$typeof===l}var _=/\/+/g;function C(e,t){return"object"===typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function P(e,t,n,r,o){var i=typeof e;"undefined"!==i&&"boolean"!==i||(e=null);var u=!1;if(null===e)u=!0;else switch(i){case"string":case"number":u=!0;break;case"object":switch(e.$$typeof){case l:case a:u=!0}}if(u)return o=o(u=e),e=""===r?"."+C(u,0):r,Array.isArray(o)?(n="",null!=e&&(n=e.replace(_,"$&/")+"/"),P(o,t,n,"",(function(e){return e}))):null!=o&&(x(o)&&(o=function(e,t){return{$$typeof:l,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(o,n+(!o.key||u&&u.key===o.key?"":(""+o.key).replace(_,"$&/")+"/")+e)),t.push(o)),1;if(u=0,r=""===r?".":r+":",Array.isArray(e))for(var s=0;s<e.length;s++){var c=r+C(i=e[s],s);u+=P(i,t,n,c,o)}else if("function"===typeof(c=function(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=d&&e[d]||e["@@iterator"])?e:null}(e)))for(e=c.call(e),s=0;!(i=e.next()).done;)u+=P(i=i.value,t,n,c=r+C(i,s++),o);else if("object"===i)throw t=""+e,Error(p(31,"[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t));return u}function N(e,t,n){if(null==e)return e;var r=[],l=0;return P(e,r,"","",(function(e){return t.call(n,e,l++)})),r}function T(e){if(-1===e._status){var t=e._result;t=t(),e._status=0,e._result=t,t.then((function(t){0===e._status&&(t=t.default,e._status=1,e._result=t)}),(function(t){0===e._status&&(e._status=2,e._result=t)}))}if(1===e._status)return e._result;throw e._result}var L={current:null};function z(){var e=L.current;if(null===e)throw Error(p(321));return e}var O={ReactCurrentDispatcher:L,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:w,IsSomeRendererActing:{current:!1},assign:r};t.Children={map:N,forEach:function(e,t,n){N(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return N(e,(function(){t++})),t},toArray:function(e){return N(e,(function(e){return e}))||[]},only:function(e){if(!x(e))throw Error(p(143));return e}},t.Component=v,t.PureComponent=g,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=O,t.cloneElement=function(e,t,n){if(null===e||void 0===e)throw Error(p(267,e));var a=r({},e.props),o=e.key,i=e.ref,u=e._owner;if(null!=t){if(void 0!==t.ref&&(i=t.ref,u=w.current),void 0!==t.key&&(o=""+t.key),e.type&&e.type.defaultProps)var s=e.type.defaultProps;for(c in t)k.call(t,c)&&!S.hasOwnProperty(c)&&(a[c]=void 0===t[c]&&void 0!==s?s[c]:t[c])}var c=arguments.length-2;if(1===c)a.children=n;else if(1<c){s=Array(c);for(var f=0;f<c;f++)s[f]=arguments[f+2];a.children=s}return{$$typeof:l,type:e.type,key:o,ref:i,props:a,_owner:u}},t.createContext=function(e,t){return void 0===t&&(t=null),(e={$$typeof:i,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},t.createElement=E,t.createFactory=function(e){var t=E.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:u,render:e}},t.isValidElement=x,t.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:T}},t.memo=function(e,t){return{$$typeof:s,type:e,compare:void 0===t?null:t}},t.useCallback=function(e,t){return z().useCallback(e,t)},t.useContext=function(e,t){return z().useContext(e,t)},t.useDebugValue=function(){},t.useEffect=function(e,t){return z().useEffect(e,t)},t.useImperativeHandle=function(e,t,n){return z().useImperativeHandle(e,t,n)},t.useLayoutEffect=function(e,t){return z().useLayoutEffect(e,t)},t.useMemo=function(e,t){return z().useMemo(e,t)},t.useReducer=function(e,t,n){return z().useReducer(e,t,n)},t.useRef=function(e){return z().useRef(e)},t.useState=function(e){return z().useState(e)},t.version="17.0.1"},yl30:function(e,t,n){"use strict";var r=n("q1tI"),l=n("Qetd"),a=n("QCnb");function o(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!r)throw Error(o(227));var i=new Set,u={};function s(e,t){c(e,t),c(e+"Capture",t)}function c(e,t){for(u[e]=t,e=0;e<t.length;e++)i.add(t[e])}var f=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),d=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p=Object.prototype.hasOwnProperty,h={},m={};function v(e,t,n,r,l,a,o){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var y={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){y[e]=new v(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];y[t]=new v(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){y[e]=new v(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){y[e]=new v(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){y[e]=new v(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){y[e]=new v(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){y[e]=new v(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){y[e]=new v(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){y[e]=new v(e,5,!1,e.toLowerCase(),null,!1,!1)}));var g=/[\-:]([a-z])/g;function b(e){return e[1].toUpperCase()}function w(e,t,n,r){var l=y.hasOwnProperty(t)?y[t]:null;(null!==l?0===l.type:!r&&(2<t.length&&("o"===t[0]||"O"===t[0])&&("n"===t[1]||"N"===t[1])))||(function(e,t,n,r){if(null===t||"undefined"===typeof t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,l,r)&&(n=null),r||null===l?function(e){return!!p.call(m,e)||!p.call(h,e)&&(d.test(e)?m[e]=!0:(h[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):l.mustUseProperty?e[l.propertyName]=null===n?3!==l.type&&"":n:(t=l.attributeName,r=l.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(l=l.type)||4===l&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(g,b);y[t]=new v(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(g,b);y[t]=new v(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(g,b);y[t]=new v(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!1,!1)})),y.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!0,!0)}));var k=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,S=60103,E=60106,x=60107,_=60108,C=60114,P=60109,N=60110,T=60112,L=60113,z=60120,O=60115,F=60116,I=60121,R=60128,D=60129,M=60130,U=60131;if("function"===typeof Symbol&&Symbol.for){var A=Symbol.for;S=A("react.element"),E=A("react.portal"),x=A("react.fragment"),_=A("react.strict_mode"),C=A("react.profiler"),P=A("react.provider"),N=A("react.context"),T=A("react.forward_ref"),L=A("react.suspense"),z=A("react.suspense_list"),O=A("react.memo"),F=A("react.lazy"),I=A("react.block"),A("react.scope"),R=A("react.opaque.id"),D=A("react.debug_trace_mode"),M=A("react.offscreen"),U=A("react.legacy_hidden")}var V,W="function"===typeof Symbol&&Symbol.iterator;function j(e){return null===e||"object"!==typeof e?null:"function"===typeof(e=W&&e[W]||e["@@iterator"])?e:null}function $(e){if(void 0===V)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);V=t&&t[1]||""}return"\n"+V+e}var B=!1;function H(e,t){if(!e||B)return"";B=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(u){var r=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){r=u}e.call(t.prototype)}else{try{throw Error()}catch(u){r=u}e()}}catch(u){if(u&&r&&"string"===typeof u.stack){for(var l=u.stack.split("\n"),a=r.stack.split("\n"),o=l.length-1,i=a.length-1;1<=o&&0<=i&&l[o]!==a[i];)i--;for(;1<=o&&0<=i;o--,i--)if(l[o]!==a[i]){if(1!==o||1!==i)do{if(o--,0>--i||l[o]!==a[i])return"\n"+l[o].replace(" at new "," at ")}while(1<=o&&0<=i);break}}}finally{B=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?$(e):""}function Q(e){switch(e.tag){case 5:return $(e.type);case 16:return $("Lazy");case 13:return $("Suspense");case 19:return $("SuspenseList");case 0:case 2:case 15:return e=H(e.type,!1);case 11:return e=H(e.type.render,!1);case 22:return e=H(e.type._render,!1);case 1:return e=H(e.type,!0);default:return""}}function q(e){if(null==e)return null;if("function"===typeof e)return e.displayName||e.name||null;if("string"===typeof e)return e;switch(e){case x:return"Fragment";case E:return"Portal";case C:return"Profiler";case _:return"StrictMode";case L:return"Suspense";case z:return"SuspenseList"}if("object"===typeof e)switch(e.$$typeof){case N:return(e.displayName||"Context")+".Consumer";case P:return(e._context.displayName||"Context")+".Provider";case T:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef");case O:return q(e.type);case I:return q(e._render);case F:t=e._payload,e=e._init;try{return q(e(t))}catch(n){}}return null}function K(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function Y(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function X(e){e._valueTracker||(e._valueTracker=function(e){var t=Y(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&"undefined"!==typeof n&&"function"===typeof n.get&&"function"===typeof n.set){var l=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function G(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Y(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}function Z(e){if("undefined"===typeof(e=e||("undefined"!==typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function J(e,t){var n=t.checked;return l({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function ee(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=K(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function te(e,t){null!=(t=t.checked)&&w(e,"checked",t,!1)}function ne(e,t){te(e,t);var n=K(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?le(e,t.type,n):t.hasOwnProperty("defaultValue")&&le(e,t.type,K(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function re(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function le(e,t,n){"number"===t&&Z(e.ownerDocument)===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}function ae(e,t){return e=l({children:void 0},t),(t=function(e){var t="";return r.Children.forEach(e,(function(e){null!=e&&(t+=e)})),t}(t.children))&&(e.children=t),e}function oe(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(n=""+K(n),t=null,l=0;l<e.length;l++){if(e[l].value===n)return e[l].selected=!0,void(r&&(e[l].defaultSelected=!0));null!==t||e[l].disabled||(t=e[l])}null!==t&&(t.selected=!0)}}function ie(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(o(91));return l({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function ue(e,t){var n=t.value;if(null==n){if(n=t.children,t=t.defaultValue,null!=n){if(null!=t)throw Error(o(92));if(Array.isArray(n)){if(!(1>=n.length))throw Error(o(93));n=n[0]}t=n}null==t&&(t=""),n=t}e._wrapperState={initialValue:K(n)}}function se(e,t){var n=K(t.value),r=K(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function ce(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}var fe="http://www.w3.org/1999/xhtml",de="http://www.w3.org/2000/svg";function pe(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function he(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?pe(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var me,ve,ye=(ve=function(e,t){if(e.namespaceURI!==de||"innerHTML"in e)e.innerHTML=t;else{for((me=me||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=me.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction((function(){return ve(e,t)}))}:ve);function ge(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var be={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},we=["Webkit","ms","Moz","O"];function ke(e,t,n){return null==t||"boolean"===typeof t||""===t?"":n||"number"!==typeof t||0===t||be.hasOwnProperty(e)&&be[e]?(""+t).trim():t+"px"}function Se(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),l=ke(n,t[n],r);"float"===n&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}Object.keys(be).forEach((function(e){we.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),be[t]=be[e]}))}));var Ee=l({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function xe(e,t){if(t){if(Ee[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(o(137,e));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(o(60));if("object"!==typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(o(61))}if(null!=t.style&&"object"!==typeof t.style)throw Error(o(62))}}function _e(e,t){if(-1===e.indexOf("-"))return"string"===typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function Ce(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var Pe=null,Ne=null,Te=null;function Le(e){if(e=Jr(e)){if("function"!==typeof Pe)throw Error(o(280));var t=e.stateNode;t&&(t=tl(t),Pe(e.stateNode,e.type,t))}}function | (e){Ne?Te?Te.push(e):Te=[e]:Ne=e}function Oe(){if(Ne){var e=Ne,t=Te;if(Te=Ne=null,Le(e),t)for(e=0;e<t.length;e++)Le(t[e])}}function Fe(e,t){return e(t)}function Ie(e,t,n,r,l){return e(t,n,r,l)}function Re(){}var De=Fe,Me=!1,Ue=!1;function Ae(){null===Ne&&null===Te||(Re(),Oe())}function Ve(e,t){var n=e.stateNode;if(null===n)return null;var r=tl(n);if(null===r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}if(e)return null;if(n&&"function"!==typeof n)throw Error(o(231,t,typeof n));return n}var We=!1;if(f)try{var je={};Object.defineProperty(je,"passive",{get:function(){We=!0}}),window.addEventListener("test",je,je),window.removeEventListener("test",je,je)}catch(ve){We=!1}function $e(e,t,n,r,l,a,o,i,u){var s=Array.prototype.slice.call(arguments,3);try{t.apply(n,s)}catch(c){this.onError(c)}}var Be=!1,He=null,Qe=!1,qe=null,Ke={onError:function(e){Be=!0,He=e}};function Ye(e,t,n,r,l,a,o,i,u){Be=!1,He=null,$e.apply(Ke,arguments)}function Xe(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{0!==(1026&(t=e).flags)&&(n=t.return),e=t.return}while(e)}return 3===t.tag?n:null}function Ge(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&(null!==(e=e.alternate)&&(t=e.memoizedState)),null!==t)return t.dehydrated}return null}function Ze(e){if(Xe(e)!==e)throw Error(o(188))}function Je(e){if(!(e=function(e){var t=e.alternate;if(!t){if(null===(t=Xe(e)))throw Error(o(188));return t!==e?null:e}for(var n=e,r=t;;){var l=n.return;if(null===l)break;var a=l.alternate;if(null===a){if(null!==(r=l.return)){n=r;continue}break}if(l.child===a.child){for(a=l.child;a;){if(a===n)return Ze(l),e;if(a===r)return Ze(l),t;a=a.sibling}throw Error(o(188))}if(n.return!==r.return)n=l,r=a;else{for(var i=!1,u=l.child;u;){if(u===n){i=!0,n=l,r=a;break}if(u===r){i=!0,r=l,n=a;break}u=u.sibling}if(!i){for(u=a.child;u;){if(u===n){i=!0,n=a,r=l;break}if(u===r){i=!0,r=a,n=l;break}u=u.sibling}if(!i)throw Error(o(189))}}if(n.alternate!==r)throw Error(o(190))}if(3!==n.tag)throw Error(o(188));return n.stateNode.current===n?e:t}(e)))return null;for(var t=e;;){if(5===t.tag||6===t.tag)return t;if(t.child)t.child.return=t,t=t.child;else{if(t===e)break;for(;!t.sibling;){if(!t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}}return null}function et(e,t){for(var n=e.alternate;null!==t;){if(t===e||t===n)return!0;t=t.return}return!1}var tt,nt,rt,lt,at=!1,ot=[],it=null,ut=null,st=null,ct=new Map,ft=new Map,dt=[],pt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function ht(e,t,n,r,l){return{blockedOn:e,domEventName:t,eventSystemFlags:16|n,nativeEvent:l,targetContainers:[r]}}function mt(e,t){switch(e){case"focusin":case"focusout":it=null;break;case"dragenter":case"dragleave":ut=null;break;case"mouseover":case"mouseout":st=null;break;case"pointerover":case"pointerout":ct.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":ft.delete(t.pointerId)}}function vt(e,t,n,r,l,a){return null===e||e.nativeEvent!==a?(e=ht(t,n,r,l,a),null!==t&&(null!==(t=Jr(t))&&nt(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,null!==l&&-1===t.indexOf(l)&&t.push(l),e)}function yt(e){var t=Zr(e.target);if(null!==t){var n=Xe(t);if(null!==n)if(13===(t=n.tag)){if(null!==(t=Ge(n)))return e.blockedOn=t,void lt(e.lanePriority,(function(){a.unstable_runWithPriority(e.priority,(function(){rt(n)}))}))}else if(3===t&&n.stateNode.hydrate)return void(e.blockedOn=3===n.tag?n.stateNode.containerInfo:null)}e.blockedOn=null}function gt(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var n=Jt(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==n)return null!==(t=Jr(n))&&nt(t),e.blockedOn=n,!1;t.shift()}return!0}function bt(e,t,n){gt(e)&&n.delete(t)}function wt(){for(at=!1;0<ot.length;){var e=ot[0];if(null!==e.blockedOn){null!==(e=Jr(e.blockedOn))&&tt(e);break}for(var t=e.targetContainers;0<t.length;){var n=Jt(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==n){e.blockedOn=n;break}t.shift()}null===e.blockedOn&&ot.shift()}null!==it&>(it)&&(it=null),null!==ut&>(ut)&&(ut=null),null!==st&>(st)&&(st=null),ct.forEach(bt),ft.forEach(bt)}function kt(e,t){e.blockedOn===t&&(e.blockedOn=null,at||(at=!0,a.unstable_scheduleCallback(a.unstable_NormalPriority,wt)))}function St(e){function t(t){return kt(t,e)}if(0<ot.length){kt(ot[0],e);for(var n=1;n<ot.length;n++){var r=ot[n];r.blockedOn===e&&(r.blockedOn=null)}}for(null!==it&&kt(it,e),null!==ut&&kt(ut,e),null!==st&&kt(st,e),ct.forEach(t),ft.forEach(t),n=0;n<dt.length;n++)(r=dt[n]).blockedOn===e&&(r.blockedOn=null);for(;0<dt.length&&null===(n=dt[0]).blockedOn;)yt(n),null===n.blockedOn&&dt.shift()}function Et(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var xt={animationend:Et("Animation","AnimationEnd"),animationiteration:Et("Animation","AnimationIteration"),animationstart:Et("Animation","AnimationStart"),transitionend:Et("Transition","TransitionEnd")},_t={},Ct={};function Pt(e){if(_t[e])return _t[e];if(!xt[e])return e;var t,n=xt[e];for(t in n)if(n.hasOwnProperty(t)&&t in Ct)return _t[e]=n[t];return e}f&&(Ct=document.createElement("div").style,"AnimationEvent"in window||(delete xt.animationend.animation,delete xt.animationiteration.animation,delete xt.animationstart.animation),"TransitionEvent"in window||delete xt.transitionend.transition);var Nt=Pt("animationend"),Tt=Pt("animationiteration"),Lt=Pt("animationstart"),zt=Pt("transitionend"),Ot=new Map,Ft=new Map,It=["abort","abort",Nt,"animationEnd",Tt,"animationIteration",Lt,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata","loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking","seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",zt,"transitionEnd","waiting","waiting"];function Rt(e,t){for(var n=0;n<e.length;n+=2){var r=e[n],l=e[n+1];l="on"+(l[0].toUpperCase()+l.slice(1)),Ft.set(r,t),Ot.set(r,l),s(l,[r])}}(0,a.unstable_now)();var Dt=8;function Mt(e){if(0!==(1&e))return Dt=15,1;if(0!==(2&e))return Dt=14,2;if(0!==(4&e))return Dt=13,4;var t=24&e;return 0!==t?(Dt=12,t):0!==(32&e)?(Dt=11,32):0!==(t=192&e)?(Dt=10,t):0!==(256&e)?(Dt=9,256):0!==(t=3584&e)?(Dt=8,t):0!==(4096&e)?(Dt=7,4096):0!==(t=4186112&e)?(Dt=6,t):0!==(t=62914560&e)?(Dt=5,t):67108864&e?(Dt=4,67108864):0!==(134217728&e)?(Dt=3,134217728):0!==(t=805306368&e)?(Dt=2,t):0!==(1073741824&e)?(Dt=1,1073741824):(Dt=8,e)}function Ut(e,t){var n=e.pendingLanes;if(0===n)return Dt=0;var r=0,l=0,a=e.expiredLanes,o=e.suspendedLanes,i=e.pingedLanes;if(0!==a)r=a,l=Dt=15;else if(0!==(a=134217727&n)){var u=a&~o;0!==u?(r=Mt(u),l=Dt):0!==(i&=a)&&(r=Mt(i),l=Dt)}else 0!==(a=n&~o)?(r=Mt(a),l=Dt):0!==i&&(r=Mt(i),l=Dt);if(0===r)return 0;if(r=n&((0>(r=31-Bt(r))?0:1<<r)<<1)-1,0!==t&&t!==r&&0===(t&o)){if(Mt(t),l<=Dt)return t;Dt=l}if(0!==(t=e.entangledLanes))for(e=e.entanglements,t&=r;0<t;)l=1<<(n=31-Bt(t)),r|=e[n],t&=~l;return r}function At(e){return 0!==(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function Vt(e,t){switch(e){case 15:return 1;case 14:return 2;case 12:return 0===(e=Wt(24&~t))?Vt(10,t):e;case 10:return 0===(e=Wt(192&~t))?Vt(8,t):e;case 8:return 0===(e=Wt(3584&~t))&&(0===(e=Wt(4186112&~t))&&(e=512)),e;case 2:return 0===(t=Wt(805306368&~t))&&(t=268435456),t}throw Error(o(358,e))}function Wt(e){return e&-e}function jt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function $t(e,t,n){e.pendingLanes|=t;var r=t-1;e.suspendedLanes&=r,e.pingedLanes&=r,(e=e.eventTimes)[t=31-Bt(t)]=n}var Bt=Math.clz32?Math.clz32:function(e){return 0===e?32:31-(Ht(e)/Qt|0)|0},Ht=Math.log,Qt=Math.LN2;var qt=a.unstable_UserBlockingPriority,Kt=a.unstable_runWithPriority,Yt=!0;function Xt(e,t,n,r){Me||Re();var l=Zt,a=Me;Me=!0;try{Ie(l,e,t,n,r)}finally{(Me=a)||Ae()}}function Gt(e,t,n,r){Kt(qt,Zt.bind(null,e,t,n,r))}function Zt(e,t,n,r){var l;if(Yt)if((l=0===(4&t))&&0<ot.length&&-1<pt.indexOf(e))e=ht(null,e,t,n,r),ot.push(e);else{var a=Jt(e,t,n,r);if(null===a)l&&mt(e,r);else{if(l){if(-1<pt.indexOf(e))return e=ht(a,e,t,n,r),void ot.push(e);if(function(e,t,n,r,l){switch(t){case"focusin":return it=vt(it,e,t,n,r,l),!0;case"dragenter":return ut=vt(ut,e,t,n,r,l),!0;case"mouseover":return st=vt(st,e,t,n,r,l),!0;case"pointerover":var a=l.pointerId;return ct.set(a,vt(ct.get(a)||null,e,t,n,r,l)),!0;case"gotpointercapture":return a=l.pointerId,ft.set(a,vt(ft.get(a)||null,e,t,n,r,l)),!0}return!1}(a,e,t,n,r))return;mt(e,r)}zr(e,t,r,null,n)}}}function Jt(e,t,n,r){var l=Ce(r);if(null!==(l=Zr(l))){var a=Xe(l);if(null===a)l=null;else{var o=a.tag;if(13===o){if(null!==(l=Ge(a)))return l;l=null}else if(3===o){if(a.stateNode.hydrate)return 3===a.tag?a.stateNode.containerInfo:null;l=null}else a!==l&&(l=null)}}return zr(e,t,r,l,n),null}var en=null,tn=null,nn=null;function rn(){if(nn)return nn;var e,t,n=tn,r=n.length,l="value"in en?en.value:en.textContent,a=l.length;for(e=0;e<r&&n[e]===l[e];e++);var o=r-e;for(t=1;t<=o&&n[r-t]===l[a-t];t++);return nn=l.slice(e,1<t?1-t:void 0)}function ln(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function an(){return!0}function on(){return!1}function un(e){function t(t,n,r,l,a){for(var o in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=l,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(o)&&(t=e[o],this[o]=t?t(l):l[o]);return this.isDefaultPrevented=(null!=l.defaultPrevented?l.defaultPrevented:!1===l.returnValue)?an:on,this.isPropagationStopped=on,this}return l(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!==typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=an)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!==typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=an)},persist:function(){},isPersistent:an}),t}var sn,cn,fn,dn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},pn=un(dn),hn=l({},dn,{view:0,detail:0}),mn=un(hn),vn=l({},hn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Pn,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==fn&&(fn&&"mousemove"===e.type?(sn=e.screenX-fn.screenX,cn=e.screenY-fn.screenY):cn=sn=0,fn=e),sn)},movementY:function(e){return"movementY"in e?e.movementY:cn}}),yn=un(vn),gn=un(l({},vn,{dataTransfer:0})),bn=un(l({},hn,{relatedTarget:0})),wn=un(l({},dn,{animationName:0,elapsedTime:0,pseudoElement:0})),kn=un(l({},dn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}})),Sn=un(l({},dn,{data:0})),En={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},xn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},_n={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Cn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=_n[e])&&!!t[e]}function Pn(){return Cn}var Nn=un(l({},hn,{key:function(e){if(e.key){var t=En[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=ln(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?xn[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Pn,charCode:function(e){return"keypress"===e.type?ln(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ln(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}})),Tn=un(l({},vn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Ln=un(l({},hn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Pn})),zn=un(l({},dn,{propertyName:0,elapsedTime:0,pseudoElement:0})),On=un(l({},vn,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0})),Fn=[9,13,27,32],In=f&&"CompositionEvent"in window,Rn=null;f&&"documentMode"in document&&(Rn=document.documentMode);var Dn=f&&"TextEvent"in window&&!Rn,Mn=f&&(!In||Rn&&8<Rn&&11>=Rn),Un=String.fromCharCode(32),An=!1;function Vn(e,t){switch(e){case"keyup":return-1!==Fn.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Wn(e){return"object"===typeof(e=e.detail)&&"data"in e?e.data:null}var jn=!1;var $n={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Bn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!$n[e.type]:"textarea"===t}function Hn(e,t,n,r){ze(r),0<(t=Fr(t,"onChange")).length&&(n=new pn("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Qn=null,qn=null;function Kn(e){_r(e,0)}function Yn(e){if(G(el(e)))return e}function Xn(e,t){if("change"===e)return t}var Gn=!1;if(f){var Zn;if(f){var Jn="oninput"in document;if(!Jn){var er=document.createElement("div");er.setAttribute("oninput","return;"),Jn="function"===typeof er.oninput}Zn=Jn}else Zn=!1;Gn=Zn&&(!document.documentMode||9<document.documentMode)}function tr(){Qn&&(Qn.detachEvent("onpropertychange",nr),qn=Qn=null)}function nr(e){if("value"===e.propertyName&&Yn(qn)){var t=[];if(Hn(t,qn,e,Ce(e)),e=Kn,Me)e(t);else{Me=!0;try{Fe(e,t)}finally{Me=!1,Ae()}}}}function rr(e,t,n){"focusin"===e?(tr(),qn=n,(Qn=t).attachEvent("onpropertychange",nr)):"focusout"===e&&tr()}function lr(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Yn(qn)}function ar(e,t){if("click"===e)return Yn(t)}function or(e,t){if("input"===e||"change"===e)return Yn(t)}var ir="function"===typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e===1/t)||e!==e&&t!==t},ur=Object.prototype.hasOwnProperty;function sr(e,t){if(ir(e,t))return!0;if("object"!==typeof e||null===e||"object"!==typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++)if(!ur.call(t,n[r])||!ir(e[n[r]],t[n[r]]))return!1;return!0}function cr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function fr(e,t){var n,r=cr(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=cr(r)}}function dr(){for(var e=window,t=Z();t instanceof e.HTMLIFrameElement;){try{var n="string"===typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=Z((e=t.contentWindow).document)}return t}function pr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var hr=f&&"documentMode"in document&&11>=document.documentMode,mr=null,vr=null,yr=null,gr=!1;function br(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;gr||null==mr||mr!==Z(r)||("selectionStart"in(r=mr)&&pr(r)?r={start:r.selectionStart,end:r.selectionEnd}:r={anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},yr&&sr(yr,r)||(yr=r,0<(r=Fr(vr,"onSelect")).length&&(t=new pn("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=mr)))}Rt("cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focusin focus focusout blur input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),0),Rt("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1),Rt(It,2);for(var wr="change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),kr=0;kr<wr.length;kr++)Ft.set(wr[kr],0);c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),s("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),s("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),s("onBeforeInput",["compositionend","keypress","textInput","paste"]),s("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),s("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),s("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Sr="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Er=new Set("cancel close invalid load scroll toggle".split(" ").concat(Sr));function xr(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,function(e,t,n,r,l,a,i,u,s){if(Ye.apply(this,arguments),Be){if(!Be)throw Error(o(198));var c=He;Be=!1,He=null,Qe||(Qe=!0,qe=c)}}(r,t,void 0,e),e.currentTarget=null}function _r(e,t){t=0!==(4&t);for(var n=0;n<e.length;n++){var r=e[n],l=r.event;r=r.listeners;e:{var a=void 0;if(t)for(var o=r.length-1;0<=o;o--){var i=r[o],u=i.instance,s=i.currentTarget;if(i=i.listener,u!==a&&l.isPropagationStopped())break e;xr(l,i,s),a=u}else for(o=0;o<r.length;o++){if(u=(i=r[o]).instance,s=i.currentTarget,i=i.listener,u!==a&&l.isPropagationStopped())break e;xr(l,i,s),a=u}}}if(Qe)throw e=qe,Qe=!1,qe=null,e}function Cr(e,t){var n=nl(t),r=e+"__bubble";n.has(r)||(Lr(t,e,2,!1),n.add(r))}var Pr="_reactListening"+Math.random().toString(36).slice(2);function Nr(e){e[Pr]||(e[Pr]=!0,i.forEach((function(t){Er.has(t)||Tr(t,!1,e,null),Tr(t,!0,e,null)})))}function Tr(e,t,n,r){var l=4<arguments.length&&void 0!==arguments[4]?arguments[4]:0,a=n;if("selectionchange"===e&&9!==n.nodeType&&(a=n.ownerDocument),null!==r&&!t&&Er.has(e)){if("scroll"!==e)return;l|=2,a=r}var o=nl(a),i=e+"__"+(t?"capture":"bubble");o.has(i)||(t&&(l|=4),Lr(a,e,l,t),o.add(i))}function Lr(e,t,n,r){var l=Ft.get(t);switch(void 0===l?2:l){case 0:l=Xt;break;case 1:l=Gt;break;default:l=Zt}n=l.bind(null,t,n,e),l=void 0,!We||"touchstart"!==t&&"touchmove"!==t&&"wheel"!==t||(l=!0),r?void 0!==l?e.addEventListener(t,n,{capture:!0,passive:l}):e.addEventListener(t,n,!0):void 0!==l?e.addEventListener(t,n,{passive:l}):e.addEventListener(t,n,!1)}function zr(e,t,n,r,l){var a=r;if(0===(1&t)&&0===(2&t)&&null!==r)e:for(;;){if(null===r)return;var o=r.tag;if(3===o||4===o){var i=r.stateNode.containerInfo;if(i===l||8===i.nodeType&&i.parentNode===l)break;if(4===o)for(o=r.return;null!==o;){var u=o.tag;if((3===u||4===u)&&((u=o.stateNode.containerInfo)===l||8===u.nodeType&&u.parentNode===l))return;o=o.return}for(;null!==i;){if(null===(o=Zr(i)))return;if(5===(u=o.tag)||6===u){r=a=o;continue e}i=i.parentNode}}r=r.return}!function(e,t,n){if(Ue)return e(t,n);Ue=!0;try{De(e,t,n)}finally{Ue=!1,Ae()}}((function(){var r=a,l=Ce(n),o=[];e:{var i=Ot.get(e);if(void 0!==i){var u=pn,s=e;switch(e){case"keypress":if(0===ln(n))break e;case"keydown":case"keyup":u=Nn;break;case"focusin":s="focus",u=bn;break;case"focusout":s="blur",u=bn;break;case"beforeblur":case"afterblur":u=bn;break;case"click":if(2===n.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":u=yn;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":u=gn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":u=Ln;break;case Nt:case Tt:case Lt:u=wn;break;case zt:u=zn;break;case"scroll":u=mn;break;case"wheel":u=On;break;case"copy":case"cut":case"paste":u=kn;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":u=Tn}var c=0!==(4&t),f=!c&&"scroll"===e,d=c?null!==i?i+"Capture":null:i;c=[];for(var p,h=r;null!==h;){var m=(p=h).stateNode;if(5===p.tag&&null!==m&&(p=m,null!==d&&(null!=(m=Ve(h,d))&&c.push(Or(h,m,p)))),f)break;h=h.return}0<c.length&&(i=new u(i,s,null,n,l),o.push({event:i,listeners:c}))}}if(0===(7&t)){if(u="mouseout"===e||"pointerout"===e,(!(i="mouseover"===e||"pointerover"===e)||0!==(16&t)||!(s=n.relatedTarget||n.fromElement)||!Zr(s)&&!s[Xr])&&(u||i)&&(i=l.window===l?l:(i=l.ownerDocument)?i.defaultView||i.parentWindow:window,u?(u=r,null!==(s=(s=n.relatedTarget||n.toElement)?Zr(s):null)&&(s!==(f=Xe(s))||5!==s.tag&&6!==s.tag)&&(s=null)):(u=null,s=r),u!==s)){if(c=yn,m="onMouseLeave",d="onMouseEnter",h="mouse","pointerout"!==e&&"pointerover"!==e||(c=Tn,m="onPointerLeave",d="onPointerEnter",h="pointer"),f=null==u?i:el(u),p=null==s?i:el(s),(i=new c(m,h+"leave",u,n,l)).target=f,i.relatedTarget=p,m=null,Zr(l)===r&&((c=new c(d,h+"enter",s,n,l)).target=p,c.relatedTarget=f,m=c),f=m,u&&s)e:{for(d=s,h=0,p=c=u;p;p=Ir(p))h++;for(p=0,m=d;m;m=Ir(m))p++;for(;0<h-p;)c=Ir(c),h--;for(;0<p-h;)d=Ir(d),p--;for(;h--;){if(c===d||null!==d&&c===d.alternate)break e;c=Ir(c),d=Ir(d)}c=null}else c=null;null!==u&&Rr(o,i,u,c,!1),null!==s&&null!==f&&Rr(o,f,s,c,!0)}if("select"===(u=(i=r?el(r):window).nodeName&&i.nodeName.toLowerCase())||"input"===u&&"file"===i.type)var v=Xn;else if(Bn(i))if(Gn)v=or;else{v=lr;var y=rr}else(u=i.nodeName)&&"input"===u.toLowerCase()&&("checkbox"===i.type||"radio"===i.type)&&(v=ar);switch(v&&(v=v(e,r))?Hn(o,v,n,l):(y&&y(e,i,r),"focusout"===e&&(y=i._wrapperState)&&y.controlled&&"number"===i.type&&le(i,"number",i.value)),y=r?el(r):window,e){case"focusin":(Bn(y)||"true"===y.contentEditable)&&(mr=y,vr=r,yr=null);break;case"focusout":yr=vr=mr=null;break;case"mousedown":gr=!0;break;case"contextmenu":case"mouseup":case"dragend":gr=!1,br(o,n,l);break;case"selectionchange":if(hr)break;case"keydown":case"keyup":br(o,n,l)}var g;if(In)e:{switch(e){case"compositionstart":var b="onCompositionStart";break e;case"compositionend":b="onCompositionEnd";break e;case"compositionupdate":b="onCompositionUpdate";break e}b=void 0}else jn?Vn(e,n)&&(b="onCompositionEnd"):"keydown"===e&&229===n.keyCode&&(b="onCompositionStart");b&&(Mn&&"ko"!==n.locale&&(jn||"onCompositionStart"!==b?"onCompositionEnd"===b&&jn&&(g=rn()):(tn="value"in(en=l)?en.value:en.textContent,jn=!0)),0<(y=Fr(r,b)).length&&(b=new Sn(b,e,null,n,l),o.push({event:b,listeners:y}),g?b.data=g:null!==(g=Wn(n))&&(b.data=g))),(g=Dn?function(e,t){switch(e){case"compositionend":return Wn(t);case"keypress":return 32!==t.which?null:(An=!0,Un);case"textInput":return(e=t.data)===Un&&An?null:e;default:return null}}(e,n):function(e,t){if(jn)return"compositionend"===e||!In&&Vn(e,t)?(e=rn(),nn=tn=en=null,jn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return Mn&&"ko"!==t.locale?null:t.data;default:return null}}(e,n))&&(0<(r=Fr(r,"onBeforeInput")).length&&(l=new Sn("onBeforeInput","beforeinput",null,n,l),o.push({event:l,listeners:r}),l.data=g))}_r(o,t)}))}function Or(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Fr(e,t){for(var n=t+"Capture",r=[];null!==e;){var l=e,a=l.stateNode;5===l.tag&&null!==a&&(l=a,null!=(a=Ve(e,n))&&r.unshift(Or(e,a,l)),null!=(a=Ve(e,t))&&r.push(Or(e,a,l))),e=e.return}return r}function Ir(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function Rr(e,t,n,r,l){for(var a=t._reactName,o=[];null!==n&&n!==r;){var i=n,u=i.alternate,s=i.stateNode;if(null!==u&&u===r)break;5===i.tag&&null!==s&&(i=s,l?null!=(u=Ve(n,a))&&o.unshift(Or(n,u,i)):l||null!=(u=Ve(n,a))&&o.push(Or(n,u,i))),n=n.return}0!==o.length&&e.push({event:t,listeners:o})}function Dr(){}var Mr=null,Ur=null;function Ar(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function Vr(e,t){return"textarea"===e||"option"===e||"noscript"===e||"string"===typeof t.children||"number"===typeof t.children||"object"===typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var Wr="function"===typeof setTimeout?setTimeout:void 0,jr="function"===typeof clearTimeout?clearTimeout:void 0;function $r(e){1===e.nodeType?e.textContent="":9===e.nodeType&&(null!=(e=e.body)&&(e.textContent=""))}function Br(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break}return e}function Hr(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var n=e.data;if("$"===n||"$!"===n||"$?"===n){if(0===t)return e;t--}else"/$"===n&&t++}e=e.previousSibling}return null}var Qr=0;var qr=Math.random().toString(36).slice(2),Kr="__reactFiber$"+qr,Yr="__reactProps$"+qr,Xr="__reactContainer$"+qr,Gr="__reactEvents$"+qr;function Zr(e){var t=e[Kr];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Xr]||n[Kr]){if(n=t.alternate,null!==t.child||null!==n&&null!==n.child)for(e=Hr(e);null!==e;){if(n=e[Kr])return n;e=Hr(e)}return t}n=(e=n).parentNode}return null}function Jr(e){return!(e=e[Kr]||e[Xr])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function el(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(o(33))}function tl(e){return e[Yr]||null}function nl(e){var t=e[Gr];return void 0===t&&(t=e[Gr]=new Set),t}var rl=[],ll=-1;function al(e){return{current:e}}function ol(e){0>ll||(e.current=rl[ll],rl[ll]=null,ll--)}function il(e,t){ll++,rl[ll]=e.current,e.current=t}var ul={},sl=al(ul),cl=al(!1),fl=ul;function dl(e,t){var n=e.type.contextTypes;if(!n)return ul;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l,a={};for(l in n)a[l]=t[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function pl(e){return null!==(e=e.childContextTypes)&&void 0!==e}function hl(){ol(cl),ol(sl)}function ml(e,t,n){if(sl.current!==ul)throw Error(o(168));il(sl,t),il(cl,n)}function vl(e,t,n){var r=e.stateNode;if(e=t.childContextTypes,"function"!==typeof r.getChildContext)return n;for(var a in r=r.getChildContext())if(!(a in e))throw Error(o(108,q(t)||"Unknown",a));return l({},n,r)}function yl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ul,fl=sl.current,il(sl,e),il(cl,cl.current),!0}function gl(e,t,n){var r=e.stateNode;if(!r)throw Error(o(169));n?(e=vl(e,t,fl),r.__reactInternalMemoizedMergedChildContext=e,ol(cl),ol(sl),il(sl,e)):ol(cl),il(cl,n)}var bl=null,wl=null,kl=a.unstable_runWithPriority,Sl=a.unstable_scheduleCallback,El=a.unstable_cancelCallback,xl=a.unstable_shouldYield,_l=a.unstable_requestPaint,Cl=a.unstable_now,Pl=a.unstable_getCurrentPriorityLevel,Nl=a.unstable_ImmediatePriority,Tl=a.unstable_UserBlockingPriority,Ll=a.unstable_NormalPriority,zl=a.unstable_LowPriority,Ol=a.unstable_IdlePriority,Fl={},Il=void 0!==_l?_l:function(){},Rl=null,Dl=null,Ml=!1,Ul=Cl(),Al=1e4>Ul?Cl:function(){return Cl()-Ul};function Vl(){switch(Pl()){case Nl:return 99;case Tl:return 98;case Ll:return 97;case zl:return 96;case Ol:return 95;default:throw Error(o(332))}}function Wl(e){switch(e){case 99:return Nl;case 98:return Tl;case 97:return Ll;case 96:return zl;case 95:return Ol;default:throw Error(o(332))}}function jl(e,t){return e=Wl(e),kl(e,t)}function $l(e,t,n){return e=Wl(e),Sl(e,t,n)}function Bl(){if(null!==Dl){var e=Dl;Dl=null,El(e)}Hl()}function Hl(){if(!Ml&&null!==Rl){Ml=!0;var e=0;try{var t=Rl;jl(99,(function(){for(;e<t.length;e++){var n=t[e];do{n=n(!0)}while(null!==n)}})),Rl=null}catch(n){throw null!==Rl&&(Rl=Rl.slice(e+1)),Sl(Nl,Bl),n}finally{Ml=!1}}}var Ql=k.ReactCurrentBatchConfig;function ql(e,t){if(e&&e.defaultProps){for(var n in t=l({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}return t}var Kl=al(null),Yl=null,Xl=null,Gl=null;function Zl(){Gl=Xl=Yl=null}function Jl(e){var t=Kl.current;ol(Kl),e.type._context._currentValue=t}function ea(e,t){for(;null!==e;){var n=e.alternate;if((e.childLanes&t)===t){if(null===n||(n.childLanes&t)===t)break;n.childLanes|=t}else e.childLanes|=t,null!==n&&(n.childLanes|=t);e=e.return}}function ta(e,t){Yl=e,Gl=Xl=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!==(e.lanes&t)&&(Fo=!0),e.firstContext=null)}function na(e,t){if(Gl!==e&&!1!==t&&0!==t)if("number"===typeof t&&1073741823!==t||(Gl=e,t=1073741823),t={context:e,observedBits:t,next:null},null===Xl){if(null===Yl)throw Error(o(308));Xl=t,Yl.dependencies={lanes:0,firstContext:t,responders:null}}else Xl=Xl.next=t;return e._currentValue}var ra=!1;function la(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null},effects:null}}function aa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function oa(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ia(e,t){if(null!==(e=e.updateQueue)){var n=(e=e.shared).pending;null===n?t.next=t:(t.next=n.next,n.next=t),e.pending=t}}function ua(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var l=null,a=null;if(null!==(n=n.firstBaseUpdate)){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};null===a?l=a=o:a=a.next=o,n=n.next}while(null!==n);null===a?l=a=t:a=a.next=t}else l=a=t;return n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function sa(e,t,n,r){var a=e.updateQueue;ra=!1;var o=a.firstBaseUpdate,i=a.lastBaseUpdate,u=a.shared.pending;if(null!==u){a.shared.pending=null;var s=u,c=s.next;s.next=null,null===i?o=c:i.next=c,i=s;var f=e.alternate;if(null!==f){var d=(f=f.updateQueue).lastBaseUpdate;d!==i&&(null===d?f.firstBaseUpdate=c:d.next=c,f.lastBaseUpdate=s)}}if(null!==o){for(d=a.baseState,i=0,f=c=s=null;;){u=o.lane;var p=o.eventTime;if((r&u)===u){null!==f&&(f=f.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var h=e,m=o;switch(u=t,p=n,m.tag){case 1:if("function"===typeof(h=m.payload)){d=h.call(p,d,u);break e}d=h;break e;case 3:h.flags=-4097&h.flags|64;case 0:if(null===(u="function"===typeof(h=m.payload)?h.call(p,d,u):h)||void 0===u)break e;d=l({},d,u);break e;case 2:ra=!0}}null!==o.callback&&(e.flags|=32,null===(u=a.effects)?a.effects=[o]:u.push(o))}else p={eventTime:p,lane:u,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===f?(c=f=p,s=d):f=f.next=p,i|=u;if(null===(o=o.next)){if(null===(u=a.shared.pending))break;o=u.next,u.next=null,a.lastBaseUpdate=u,a.shared.pending=null}}null===f&&(s=d),a.baseState=s,a.firstBaseUpdate=c,a.lastBaseUpdate=f,Ri|=i,e.lanes=i,e.memoizedState=d}}function ca(e,t,n){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var r=e[t],l=r.callback;if(null!==l){if(r.callback=null,r=n,"function"!==typeof l)throw Error(o(191,l));l.call(r)}}}var fa=(new r.Component).refs;function da(e,t,n,r){n=null===(n=n(r,t=e.memoizedState))||void 0===n?t:l({},t,n),e.memoizedState=n,0===e.lanes&&(e.updateQueue.baseState=n)}var pa={isMounted:function(e){return!!(e=e._reactInternals)&&Xe(e)===e},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=ou(),l=iu(e),a=oa(r,l);a.payload=t,void 0!==n&&null!==n&&(a.callback=n),ia(e,a),uu(e,l,r)},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=ou(),l=iu(e),a=oa(r,l);a.tag=1,a.payload=t,void 0!==n&&null!==n&&(a.callback=n),ia(e,a),uu(e,l,r)},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=ou(),r=iu(e),l=oa(n,r);l.tag=2,void 0!==t&&null!==t&&(l.callback=t),ia(e,l),uu(e,r,n)}};function ha(e,t,n,r,l,a,o){return"function"===typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,o):!t.prototype||!t.prototype.isPureReactComponent||(!sr(n,r)||!sr(l,a))}function ma(e,t,n){var r=!1,l=ul,a=t.contextType;return"object"===typeof a&&null!==a?a=na(a):(l=pl(t)?fl:sl.current,a=(r=null!==(r=t.contextTypes)&&void 0!==r)?dl(e,l):ul),t=new t(n,a),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=pa,e.stateNode=t,t._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),t}function va(e,t,n,r){e=t.state,"function"===typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"===typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&pa.enqueueReplaceState(t,t.state,null)}function ya(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs=fa,la(e);var a=t.contextType;"object"===typeof a&&null!==a?l.context=na(a):(a=pl(t)?fl:sl.current,l.context=dl(e,a)),sa(e,n,l,r),l.state=e.memoizedState,"function"===typeof(a=t.getDerivedStateFromProps)&&(da(e,t,a,n),l.state=e.memoizedState),"function"===typeof t.getDerivedStateFromProps||"function"===typeof l.getSnapshotBeforeUpdate||"function"!==typeof l.UNSAFE_componentWillMount&&"function"!==typeof l.componentWillMount||(t=l.state,"function"===typeof l.componentWillMount&&l.componentWillMount(),"function"===typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),t!==l.state&&pa.enqueueReplaceState(l,l.state,null),sa(e,n,l,r),l.state=e.memoizedState),"function"===typeof l.componentDidMount&&(e.flags|=4)}var ga=Array.isArray;function ba(e,t,n){if(null!==(e=n.ref)&&"function"!==typeof e&&"object"!==typeof e){if(n._owner){if(n=n._owner){if(1!==n.tag)throw Error(o(309));var r=n.stateNode}if(!r)throw Error(o(147,e));var l=""+e;return null!==t&&null!==t.ref&&"function"===typeof t.ref&&t.ref._stringRef===l?t.ref:((t=function(e){var t=r.refs;t===fa&&(t=r.refs={}),null===e?delete t[l]:t[l]=e})._stringRef=l,t)}if("string"!==typeof e)throw Error(o(284));if(!n._owner)throw Error(o(290,e))}return e}function wa(e,t){if("textarea"!==e.type)throw Error(o(31,"[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t))}function ka(e){function t(t,n){if(e){var r=t.lastEffect;null!==r?(r.nextEffect=n,t.lastEffect=n):t.firstEffect=t.lastEffect=n,n.nextEffect=null,n.flags=8}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function l(e,t){return(e=Vu(e,t)).index=0,e.sibling=null,e}function a(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.flags=2,n):r:(t.flags=2,n):n}function i(t){return e&&null===t.alternate&&(t.flags=2),t}function u(e,t,n,r){return null===t||6!==t.tag?((t=Bu(n,e.mode,r)).return=e,t):((t=l(t,n)).return=e,t)}function s(e,t,n,r){return null!==t&&t.elementType===n.type?((r=l(t,n.props)).ref=ba(e,t,n),r.return=e,r):((r=Wu(n.type,n.key,n.props,null,e.mode,r)).ref=ba(e,t,n),r.return=e,r)}function c(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Hu(n,e.mode,r)).return=e,t):((t=l(t,n.children||[])).return=e,t)}function f(e,t,n,r,a){return null===t||7!==t.tag?((t=ju(n,e.mode,r,a)).return=e,t):((t=l(t,n)).return=e,t)}function d(e,t,n){if("string"===typeof t||"number"===typeof t)return(t=Bu(""+t,e.mode,n)).return=e,t;if("object"===typeof t&&null!==t){switch(t.$$typeof){case S:return(n=Wu(t.type,t.key,t.props,null,e.mode,n)).ref=ba(e,null,t),n.return=e,n;case E:return(t=Hu(t,e.mode,n)).return=e,t}if(ga(t)||j(t))return(t=ju(t,e.mode,n,null)).return=e,t;wa(e,t)}return null}function p(e,t,n,r){var l=null!==t?t.key:null;if("string"===typeof n||"number"===typeof n)return null!==l?null:u(e,t,""+n,r);if("object"===typeof n&&null!==n){switch(n.$$typeof){case S:return n.key===l?n.type===x?f(e,t,n.props.children,r,l):s(e,t,n,r):null;case E:return n.key===l?c(e,t,n,r):null}if(ga(n)||j(n))return null!==l?null:f(e,t,n,r,null);wa(e,n)}return null}function h(e,t,n,r,l){if("string"===typeof r||"number"===typeof r)return u(t,e=e.get(n)||null,""+r,l);if("object"===typeof r&&null!==r){switch(r.$$typeof){case S:return e=e.get(null===r.key?n:r.key)||null,r.type===x?f(t,e,r.props.children,l,r.key):s(t,e,r,l);case E:return c(t,e=e.get(null===r.key?n:r.key)||null,r,l)}if(ga(r)||j(r))return f(t,e=e.get(n)||null,r,l,null);wa(t,r)}return null}function m(l,o,i,u){for(var s=null,c=null,f=o,m=o=0,v=null;null!==f&&m<i.length;m++){f.index>m?(v=f,f=null):v=f.sibling;var y=p(l,f,i[m],u);if(null===y){null===f&&(f=v);break}e&&f&&null===y.alternate&&t(l,f),o=a(y,o,m),null===c?s=y:c.sibling=y,c=y,f=v}if(m===i.length)return n(l,f),s;if(null===f){for(;m<i.length;m++)null!==(f=d(l,i[m],u))&&(o=a(f,o,m),null===c?s=f:c.sibling=f,c=f);return s}for(f=r(l,f);m<i.length;m++)null!==(v=h(f,l,m,i[m],u))&&(e&&null!==v.alternate&&f.delete(null===v.key?m:v.key),o=a(v,o,m),null===c?s=v:c.sibling=v,c=v);return e&&f.forEach((function(e){return t(l,e)})),s}function v(l,i,u,s){var c=j(u);if("function"!==typeof c)throw Error(o(150));if(null==(u=c.call(u)))throw Error(o(151));for(var f=c=null,m=i,v=i=0,y=null,g=u.next();null!==m&&!g.done;v++,g=u.next()){m.index>v?(y=m,m=null):y=m.sibling;var b=p(l,m,g.value,s);if(null===b){null===m&&(m=y);break}e&&m&&null===b.alternate&&t(l,m),i=a(b,i,v),null===f?c=b:f.sibling=b,f=b,m=y}if(g.done)return n(l,m),c;if(null===m){for(;!g.done;v++,g=u.next())null!==(g=d(l,g.value,s))&&(i=a(g,i,v),null===f?c=g:f.sibling=g,f=g);return c}for(m=r(l,m);!g.done;v++,g=u.next())null!==(g=h(m,l,v,g.value,s))&&(e&&null!==g.alternate&&m.delete(null===g.key?v:g.key),i=a(g,i,v),null===f?c=g:f.sibling=g,f=g);return e&&m.forEach((function(e){return t(l,e)})),c}return function(e,r,a,u){var s="object"===typeof a&&null!==a&&a.type===x&&null===a.key;s&&(a=a.props.children);var c="object"===typeof a&&null!==a;if(c)switch(a.$$typeof){case S:e:{for(c=a.key,s=r;null!==s;){if(s.key===c){switch(s.tag){case 7:if(a.type===x){n(e,s.sibling),(r=l(s,a.props.children)).return=e,e=r;break e}break;default:if(s.elementType===a.type){n(e,s.sibling),(r=l(s,a.props)).ref=ba(e,s,a),r.return=e,e=r;break e}}n(e,s);break}t(e,s),s=s.sibling}a.type===x?((r=ju(a.props.children,e.mode,u,a.key)).return=e,e=r):((u=Wu(a.type,a.key,a.props,null,e.mode,u)).ref=ba(e,r,a),u.return=e,e=u)}return i(e);case E:e:{for(s=a.key;null!==r;){if(r.key===s){if(4===r.tag&&r.stateNode.containerInfo===a.containerInfo&&r.stateNode.implementation===a.implementation){n(e,r.sibling),(r=l(r,a.children||[])).return=e,e=r;break e}n(e,r);break}t(e,r),r=r.sibling}(r=Hu(a,e.mode,u)).return=e,e=r}return i(e)}if("string"===typeof a||"number"===typeof a)return a=""+a,null!==r&&6===r.tag?(n(e,r.sibling),(r=l(r,a)).return=e,e=r):(n(e,r),(r=Bu(a,e.mode,u)).return=e,e=r),i(e);if(ga(a))return m(e,r,a,u);if(j(a))return v(e,r,a,u);if(c&&wa(e,a),"undefined"===typeof a&&!s)switch(e.tag){case 1:case 22:case 0:case 11:case 15:throw Error(o(152,q(e.type)||"Component"))}return n(e,r)}}var Sa=ka(!0),Ea=ka(!1),xa={},_a=al(xa),Ca=al(xa),Pa=al(xa);function Na(e){if(e===xa)throw Error(o(174));return e}function Ta(e,t){switch(il(Pa,t),il(Ca,e),il(_a,xa),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:he(null,"");break;default:t=he(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}ol(_a),il(_a,t)}function La(){ol(_a),ol(Ca),ol(Pa)}function za(e){Na(Pa.current);var t=Na(_a.current),n=he(t,e.type);t!==n&&(il(Ca,e),il(_a,n))}function Oa(e){Ca.current===e&&(ol(_a),ol(Ca))}var Fa=al(0);function Ia(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!==(64&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Ra=null,Da=null,Ma=!1;function Ua(e,t){var n=Uu(5,null,null,0);n.elementType="DELETED",n.type="DELETED",n.stateNode=t,n.return=e,n.flags=8,null!==e.lastEffect?(e.lastEffect.nextEffect=n,e.lastEffect=n):e.firstEffect=e.lastEffect=n}function Aa(e,t){switch(e.tag){case 5:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,!0);case 13:default:return!1}}function Va(e){if(Ma){var t=Da;if(t){var n=t;if(!Aa(e,t)){if(!(t=Br(n.nextSibling))||!Aa(e,t))return e.flags=-1025&e.flags|2,Ma=!1,void(Ra=e);Ua(Ra,n)}Ra=e,Da=Br(t.firstChild)}else e.flags=-1025&e.flags|2,Ma=!1,Ra=e}}function Wa(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;Ra=e}function ja(e){if(e!==Ra)return!1;if(!Ma)return Wa(e),Ma=!0,!1;var t=e.type;if(5!==e.tag||"head"!==t&&"body"!==t&&!Vr(t,e.memoizedProps))for(t=Da;t;)Ua(e,t),t=Br(t.nextSibling);if(Wa(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(o(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var n=e.data;if("/$"===n){if(0===t){Da=Br(e.nextSibling);break e}t--}else"$"!==n&&"$!"!==n&&"$?"!==n||t++}e=e.nextSibling}Da=null}}else Da=Ra?Br(e.stateNode.nextSibling):null;return!0}function $a(){Da=Ra=null,Ma=!1}var Ba=[];function Ha(){for(var e=0;e<Ba.length;e++)Ba[e]._workInProgressVersionPrimary=null;Ba.length=0}var Qa=k.ReactCurrentDispatcher,qa=k.ReactCurrentBatchConfig,Ka=0,Ya=null,Xa=null,Ga=null,Za=!1,Ja=!1;function eo(){throw Error(o(321))}function to(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!ir(e[n],t[n]))return!1;return!0}function no(e,t,n,r,l,a){if(Ka=a,Ya=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,Qa.current=null===e||null===e.memoizedState?To:Lo,e=n(r,l),Ja){a=0;do{if(Ja=!1,!(25>a))throw Error(o(301));a+=1,Ga=Xa=null,t.updateQueue=null,Qa.current=zo,e=n(r,l)}while(Ja)}if(Qa.current=No,t=null!==Xa&&null!==Xa.next,Ka=0,Ga=Xa=Ya=null,Za=!1,t)throw Error(o(300));return e}function ro(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===Ga?Ya.memoizedState=Ga=e:Ga=Ga.next=e,Ga}function lo(){if(null===Xa){var e=Ya.alternate;e=null!==e?e.memoizedState:null}else e=Xa.next;var t=null===Ga?Ya.memoizedState:Ga.next;if(null!==t)Ga=t,Xa=e;else{if(null===e)throw Error(o(310));e={memoizedState:(Xa=e).memoizedState,baseState:Xa.baseState,baseQueue:Xa.baseQueue,queue:Xa.queue,next:null},null===Ga?Ya.memoizedState=Ga=e:Ga=Ga.next=e}return Ga}function ao(e,t){return"function"===typeof t?t(e):t}function oo(e){var t=lo(),n=t.queue;if(null===n)throw Error(o(311));n.lastRenderedReducer=e;var r=Xa,l=r.baseQueue,a=n.pending;if(null!==a){if(null!==l){var i=l.next;l.next=a.next,a.next=i}r.baseQueue=l=a,n.pending=null}if(null!==l){l=l.next,r=r.baseState;var u=i=a=null,s=l;do{var c=s.lane;if((Ka&c)===c)null!==u&&(u=u.next={lane:0,action:s.action,eagerReducer:s.eagerReducer,eagerState:s.eagerState,next:null}),r=s.eagerReducer===e?s.eagerState:e(r,s.action);else{var f={lane:c,action:s.action,eagerReducer:s.eagerReducer,eagerState:s.eagerState,next:null};null===u?(i=u=f,a=r):u=u.next=f,Ya.lanes|=c,Ri|=c}s=s.next}while(null!==s&&s!==l);null===u?a=r:u.next=i,ir(r,t.memoizedState)||(Fo=!0),t.memoizedState=r,t.baseState=a,t.baseQueue=u,n.lastRenderedState=r}return[t.memoizedState,n.dispatch]}function io(e){var t=lo(),n=t.queue;if(null===n)throw Error(o(311));n.lastRenderedReducer=e;var r=n.dispatch,l=n.pending,a=t.memoizedState;if(null!==l){n.pending=null;var i=l=l.next;do{a=e(a,i.action),i=i.next}while(i!==l);ir(a,t.memoizedState)||(Fo=!0),t.memoizedState=a,null===t.baseQueue&&(t.baseState=a),n.lastRenderedState=a}return[a,r]}function uo(e,t,n){var r=t._getVersion;r=r(t._source);var l=t._workInProgressVersionPrimary;if(null!==l?e=l===r:(e=e.mutableReadLanes,(e=(Ka&e)===e)&&(t._workInProgressVersionPrimary=r,Ba.push(t))),e)return n(t._source);throw Ba.push(t),Error(o(350))}function so(e,t,n,r){var l=Pi;if(null===l)throw Error(o(349));var a=t._getVersion,i=a(t._source),u=Qa.current,s=u.useState((function(){return uo(l,t,n)})),c=s[1],f=s[0];s=Ga;var d=e.memoizedState,p=d.refs,h=p.getSnapshot,m=d.source;d=d.subscribe;var v=Ya;return e.memoizedState={refs:p,source:t,subscribe:r},u.useEffect((function(){p.getSnapshot=n,p.setSnapshot=c;var e=a(t._source);if(!ir(i,e)){e=n(t._source),ir(f,e)||(c(e),e=iu(v),l.mutableReadLanes|=e&l.pendingLanes),e=l.mutableReadLanes,l.entangledLanes|=e;for(var r=l.entanglements,o=e;0<o;){var u=31-Bt(o),s=1<<u;r[u]|=e,o&=~s}}}),[n,t,r]),u.useEffect((function(){return r(t._source,(function(){var e=p.getSnapshot,n=p.setSnapshot;try{n(e(t._source));var r=iu(v);l.mutableReadLanes|=r&l.pendingLanes}catch(a){n((function(){throw a}))}}))}),[t,r]),ir(h,n)&&ir(m,t)&&ir(d,r)||((e={pending:null,dispatch:null,lastRenderedReducer:ao,lastRenderedState:f}).dispatch=c=Po.bind(null,Ya,e),s.queue=e,s.baseQueue=null,f=uo(l,t,n),s.memoizedState=s.baseState=f),f}function co(e,t,n){return so(lo(),e,t,n)}function fo(e){var t=ro();return"function"===typeof e&&(e=e()),t.memoizedState=t.baseState=e,e=(e=t.queue={pending:null,dispatch:null,lastRenderedReducer:ao,lastRenderedState:e}).dispatch=Po.bind(null,Ya,e),[t.memoizedState,e]}function po(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},null===(t=Ya.updateQueue)?(t={lastEffect:null},Ya.updateQueue=t,t.lastEffect=e.next=e):null===(n=t.lastEffect)?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e),e}function ho(e){return e={current:e},ro().memoizedState=e}function mo(){return lo().memoizedState}function vo(e,t,n,r){var l=ro();Ya.flags|=e,l.memoizedState=po(1|t,n,void 0,void 0===r?null:r)}function yo(e,t,n,r){var l=lo();r=void 0===r?null:r;var a=void 0;if(null!==Xa){var o=Xa.memoizedState;if(a=o.destroy,null!==r&&to(r,o.deps))return void po(t,n,a,r)}Ya.flags|=e,l.memoizedState=po(1|t,n,a,r)}function go(e,t){return vo(516,4,e,t)}function bo(e,t){return yo(516,4,e,t)}function wo(e,t){return yo(4,2,e,t)}function ko(e,t){return"function"===typeof t?(e=e(),t(e),function(){t(null)}):null!==t&&void 0!==t?(e=e(),t.current=e,function(){t.current=null}):void 0}function So(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,yo(4,2,ko.bind(null,t,e),n)}function Eo(){}function xo(e,t){var n=lo();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&to(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function _o(e,t){var n=lo();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&to(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function Co(e,t){var n=Vl();jl(98>n?98:n,(function(){e(!0)})),jl(97<n?97:n,(function(){var n=qa.transition;qa.transition=1;try{e(!1),t()}finally{qa.transition=n}}))}function Po(e,t,n){var r=ou(),l=iu(e),a={lane:l,action:n,eagerReducer:null,eagerState:null,next:null},o=t.pending;if(null===o?a.next=a:(a.next=o.next,o.next=a),t.pending=a,o=e.alternate,e===Ya||null!==o&&o===Ya)Ja=Za=!0;else{if(0===e.lanes&&(null===o||0===o.lanes)&&null!==(o=t.lastRenderedReducer))try{var i=t.lastRenderedState,u=o(i,n);if(a.eagerReducer=o,a.eagerState=u,ir(u,i))return}catch(s){}uu(e,l,r)}}var No={readContext:na,useCallback:eo,useContext:eo,useEffect:eo,useImperativeHandle:eo,useLayoutEffect:eo,useMemo:eo,useReducer:eo,useRef:eo,useState:eo,useDebugValue:eo,useDeferredValue:eo,useTransition:eo,useMutableSource:eo,useOpaqueIdentifier:eo,unstable_isNewReconciler:!1},To={readContext:na,useCallback:function(e,t){return ro().memoizedState=[e,void 0===t?null:t],e},useContext:na,useEffect:go,useImperativeHandle:function(e,t,n){return n=null!==n&&void 0!==n?n.concat([e]):null,vo(4,2,ko.bind(null,t,e),n)},useLayoutEffect:function(e,t){return vo(4,2,e,t)},useMemo:function(e,t){var n=ro();return t=void 0===t?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ro();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e=(e=r.queue={pending:null,dispatch:null,lastRenderedReducer:e,lastRenderedState:t}).dispatch=Po.bind(null,Ya,e),[r.memoizedState,e]},useRef:ho,useState:fo,useDebugValue:Eo,useDeferredValue:function(e){var t=fo(e),n=t[0],r=t[1];return go((function(){var t=qa.transition;qa.transition=1;try{r(e)}finally{qa.transition=t}}),[e]),n},useTransition:function(){var e=fo(!1),t=e[0];return ho(e=Co.bind(null,e[1])),[e,t]},useMutableSource:function(e,t,n){var r=ro();return r.memoizedState={refs:{getSnapshot:t,setSnapshot:null},source:e,subscribe:n},so(r,e,t,n)},useOpaqueIdentifier:function(){if(Ma){var e=!1,t=function(e){return{$$typeof:R,toString:e,valueOf:e}}((function(){throw e||(e=!0,n("r:"+(Qr++).toString(36))),Error(o(355))})),n=fo(t)[1];return 0===(2&Ya.mode)&&(Ya.flags|=516,po(5,(function(){n("r:"+(Qr++).toString(36))}),void 0,null)),t}return fo(t="r:"+(Qr++).toString(36)),t},unstable_isNewReconciler:!1},Lo={readContext:na,useCallback:xo,useContext:na,useEffect:bo,useImperativeHandle:So,useLayoutEffect:wo,useMemo:_o,useReducer:oo,useRef:mo,useState:function(){return oo(ao)},useDebugValue:Eo,useDeferredValue:function(e){var t=oo(ao),n=t[0],r=t[1];return bo((function(){var t=qa.transition;qa.transition=1;try{r(e)}finally{qa.transition=t}}),[e]),n},useTransition:function(){var e=oo(ao)[0];return[mo().current,e]},useMutableSource:co,useOpaqueIdentifier:function(){return oo(ao)[0]},unstable_isNewReconciler:!1},zo={readContext:na,useCallback:xo,useContext:na,useEffect:bo,useImperativeHandle:So,useLayoutEffect:wo,useMemo:_o,useReducer:io,useRef:mo,useState:function(){return io(ao)},useDebugValue:Eo,useDeferredValue:function(e){var t=io(ao),n=t[0],r=t[1];return bo((function(){var t=qa.transition;qa.transition=1;try{r(e)}finally{qa.transition=t}}),[e]),n},useTransition:function(){var e=io(ao)[0];return[mo().current,e]},useMutableSource:co,useOpaqueIdentifier:function(){return io(ao)[0]},unstable_isNewReconciler:!1},Oo=k.ReactCurrentOwner,Fo=!1;function Io(e,t,n,r){t.child=null===e?Ea(t,null,n,r):Sa(t,e.child,n,r)}function Ro(e,t,n,r,l){n=n.render;var a=t.ref;return ta(t,l),r=no(e,t,n,r,a,l),null===e||Fo?(t.flags|=1,Io(e,t,r,l),t.child):(t.updateQueue=e.updateQueue,t.flags&=-517,e.lanes&=~l,ti(e,t,l))}function Do(e,t,n,r,l,a){if(null===e){var o=n.type;return"function"!==typeof o||Au(o)||void 0!==o.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=Wu(n.type,null,r,t,t.mode,a)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=o,Mo(e,t,o,r,l,a))}return o=e.child,0===(l&a)&&(l=o.memoizedProps,(n=null!==(n=n.compare)?n:sr)(l,r)&&e.ref===t.ref)?ti(e,t,a):(t.flags|=1,(e=Vu(o,r)).ref=t.ref,e.return=t,t.child=e)}function Mo(e,t,n,r,l,a){if(null!==e&&sr(e.memoizedProps,r)&&e.ref===t.ref){if(Fo=!1,0===(a&l))return t.lanes=e.lanes,ti(e,t,a);0!==(16384&e.flags)&&(Fo=!0)}return Vo(e,t,n,r,a)}function Uo(e,t,n){var r=t.pendingProps,l=r.children,a=null!==e?e.memoizedState:null;if("hidden"===r.mode||"unstable-defer-without-hiding"===r.mode)if(0===(4&t.mode))t.memoizedState={baseLanes:0},vu(t,n);else{if(0===(1073741824&n))return e=null!==a?a.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e},vu(t,e),null;t.memoizedState={baseLanes:0},vu(t,null!==a?a.baseLanes:n)}else null!==a?(r=a.baseLanes|n,t.memoizedState=null):r=n,vu(t,r);return Io(e,t,l,n),t.child}function Ao(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.flags|=128)}function Vo(e,t,n,r,l){var a=pl(n)?fl:sl.current;return a=dl(t,a),ta(t,l),n=no(e,t,n,r,a,l),null===e||Fo?(t.flags|=1,Io(e,t,n,l),t.child):(t.updateQueue=e.updateQueue,t.flags&=-517,e.lanes&=~l,ti(e,t,l))}function Wo(e,t,n,r,l){if(pl(n)){var a=!0;yl(t)}else a=!1;if(ta(t,l),null===t.stateNode)null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2),ma(t,n,r),ya(t,n,r,l),r=!0;else if(null===e){var o=t.stateNode,i=t.memoizedProps;o.props=i;var u=o.context,s=n.contextType;"object"===typeof s&&null!==s?s=na(s):s=dl(t,s=pl(n)?fl:sl.current);var c=n.getDerivedStateFromProps,f="function"===typeof c||"function"===typeof o.getSnapshotBeforeUpdate;f||"function"!==typeof o.UNSAFE_componentWillReceiveProps&&"function"!==typeof o.componentWillReceiveProps||(i!==r||u!==s)&&va(t,o,r,s),ra=!1;var d=t.memoizedState;o.state=d,sa(t,r,o,l),u=t.memoizedState,i!==r||d!==u||cl.current||ra?("function"===typeof c&&(da(t,n,c,r),u=t.memoizedState),(i=ra||ha(t,n,i,r,d,u,s))?(f||"function"!==typeof o.UNSAFE_componentWillMount&&"function"!==typeof o.componentWillMount||("function"===typeof o.componentWillMount&&o.componentWillMount(),"function"===typeof o.UNSAFE_componentWillMount&&o.UNSAFE_componentWillMount()),"function"===typeof o.componentDidMount&&(t.flags|=4)):("function"===typeof o.componentDidMount&&(t.flags|=4),t.memoizedProps=r,t.memoizedState=u),o.props=r,o.state=u,o.context=s,r=i):("function"===typeof o.componentDidMount&&(t.flags|=4),r=!1)}else{o=t.stateNode,aa(e,t),i=t.memoizedProps,s=t.type===t.elementType?i:ql(t.type,i),o.props=s,f=t.pendingProps,d=o.context,"object"===typeof(u=n.contextType)&&null!==u?u=na(u):u=dl(t,u=pl(n)?fl:sl.current);var p=n.getDerivedStateFromProps;(c="function"===typeof p||"function"===typeof o.getSnapshotBeforeUpdate)||"function"!==typeof o.UNSAFE_componentWillReceiveProps&&"function"!==typeof o.componentWillReceiveProps||(i!==f||d!==u)&&va(t,o,r,u),ra=!1,d=t.memoizedState,o.state=d,sa(t,r,o,l);var h=t.memoizedState;i!==f||d!==h||cl.current||ra?("function"===typeof p&&(da(t,n,p,r),h=t.memoizedState),(s=ra||ha(t,n,s,r,d,h,u))?(c||"function"!==typeof o.UNSAFE_componentWillUpdate&&"function"!==typeof o.componentWillUpdate||("function"===typeof o.componentWillUpdate&&o.componentWillUpdate(r,h,u),"function"===typeof o.UNSAFE_componentWillUpdate&&o.UNSAFE_componentWillUpdate(r,h,u)),"function"===typeof o.componentDidUpdate&&(t.flags|=4),"function"===typeof o.getSnapshotBeforeUpdate&&(t.flags|=256)):("function"!==typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=256),t.memoizedProps=r,t.memoizedState=h),o.props=r,o.state=h,o.context=u,r=s):("function"!==typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!==typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=256),r=!1)}return jo(e,t,n,r,a,l)}function jo(e,t,n,r,l,a){Ao(e,t);var o=0!==(64&t.flags);if(!r&&!o)return l&&gl(t,n,!1),ti(e,t,a);r=t.stateNode,Oo.current=t;var i=o&&"function"!==typeof n.getDerivedStateFromError?null:r.render();return t.flags|=1,null!==e&&o?(t.child=Sa(t,e.child,null,a),t.child=Sa(t,null,i,a)):Io(e,t,i,a),t.memoizedState=r.state,l&&gl(t,n,!0),t.child}function $o(e){var t=e.stateNode;t.pendingContext?ml(0,t.pendingContext,t.pendingContext!==t.context):t.context&&ml(0,t.context,!1),Ta(e,t.containerInfo)}var Bo,Ho,Qo,qo={dehydrated:null,retryLane:0};function Ko(e,t,n){var r,l=t.pendingProps,a=Fa.current,o=!1;return(r=0!==(64&t.flags))||(r=(null===e||null!==e.memoizedState)&&0!==(2&a)),r?(o=!0,t.flags&=-65):null!==e&&null===e.memoizedState||void 0===l.fallback||!0===l.unstable_avoidThisFallback||(a|=1),il(Fa,1&a),null===e?(void 0!==l.fallback&&Va(t),e=l.children,a=l.fallback,o?(e=Yo(t,e,a,n),t.child.memoizedState={baseLanes:n},t.memoizedState=qo,e):"number"===typeof l.unstable_expectedLoadTime?(e=Yo(t,e,a,n),t.child.memoizedState={baseLanes:n},t.memoizedState=qo,t.lanes=33554432,e):((n=$u({mode:"visible",children:e},t.mode,n,null)).return=t,t.child=n)):(e.memoizedState,o?(l=Go(e,t,l.children,l.fallback,n),o=t.child,a=e.child.memoizedState,o.memoizedState=null===a?{baseLanes:n}:{baseLanes:a.baseLanes|n},o.childLanes=e.childLanes&~n,t.memoizedState=qo,l):(n=Xo(e,t,l.children,n),t.memoizedState=null,n))}function Yo(e,t,n,r){var l=e.mode,a=e.child;return t={mode:"hidden",children:t},0===(2&l)&&null!==a?(a.childLanes=0,a.pendingProps=t):a=$u(t,l,0,null),n=ju(n,l,r,null),a.return=e,n.return=e,a.sibling=n,e.child=a,n}function Xo(e,t,n,r){var l=e.child;return e=l.sibling,n=Vu(l,{mode:"visible",children:n}),0===(2&t.mode)&&(n.lanes=r),n.return=t,n.sibling=null,null!==e&&(e.nextEffect=null,e.flags=8,t.firstEffect=t.lastEffect=e),t.child=n}function Go(e,t,n,r,l){var a=t.mode,o=e.child;e=o.sibling;var i={mode:"hidden",children:n};return 0===(2&a)&&t.child!==o?((n=t.child).childLanes=0,n.pendingProps=i,null!==(o=n.lastEffect)?(t.firstEffect=n.firstEffect,t.lastEffect=o,o.nextEffect=null):t.firstEffect=t.lastEffect=null):n=Vu(o,i),null!==e?r=Vu(e,r):(r=ju(r,a,l,null)).flags|=2,r.return=t,n.return=t,n.sibling=r,t.child=n,r}function Zo(e,t){e.lanes|=t;var n=e.alternate;null!==n&&(n.lanes|=t),ea(e.return,t)}function Jo(e,t,n,r,l,a){var o=e.memoizedState;null===o?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l,lastEffect:a}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=l,o.lastEffect=a)}function ei(e,t,n){var r=t.pendingProps,l=r.revealOrder,a=r.tail;if(Io(e,t,r.children,n),0!==(2&(r=Fa.current)))r=1&r|2,t.flags|=64;else{if(null!==e&&0!==(64&e.flags))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Zo(e,n);else if(19===e.tag)Zo(e,n);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(il(Fa,r),0===(2&t.mode))t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;null!==n;)null!==(e=n.alternate)&&null===Ia(e)&&(l=n),n=n.sibling;null===(n=l)?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),Jo(t,!1,l,n,a,t.lastEffect);break;case"backwards":for(n=null,l=t.child,t.child=null;null!==l;){if(null!==(e=l.alternate)&&null===Ia(e)){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}Jo(t,!0,n,null,a,t.lastEffect);break;case"together":Jo(t,!1,null,null,void 0,t.lastEffect);break;default:t.memoizedState=null}return t.child}function ti(e,t,n){if(null!==e&&(t.dependencies=e.dependencies),Ri|=t.lanes,0!==(n&t.childLanes)){if(null!==e&&t.child!==e.child)throw Error(o(153));if(null!==t.child){for(n=Vu(e=t.child,e.pendingProps),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Vu(e,e.pendingProps)).return=t;n.sibling=null}return t.child}return null}function ni(e,t){if(!Ma)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;null!==t;)null!==t.alternate&&(n=t),t=t.sibling;null===n?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;null!==n;)null!==n.alternate&&(r=n),n=n.sibling;null===r?t||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function ri(e,t,n){var r=t.pendingProps;switch(t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return pl(t.type)&&hl(),null;case 3:return La(),ol(cl),ol(sl),Ha(),(r=t.stateNode).pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),null!==e&&null!==e.child||(ja(t)?t.flags|=4:r.hydrate||(t.flags|=256)),null;case 5:Oa(t);var a=Na(Pa.current);if(n=t.type,null!==e&&null!=t.stateNode)Ho(e,t,n,r),e.ref!==t.ref&&(t.flags|=128);else{if(!r){if(null===t.stateNode)throw Error(o(166));return null}if(e=Na(_a.current),ja(t)){r=t.stateNode,n=t.type;var i=t.memoizedProps;switch(r[Kr]=t,r[Yr]=i,n){case"dialog":Cr("cancel",r),Cr("close",r);break;case"iframe":case"object":case"embed":Cr("load",r);break;case"video":case"audio":for(e=0;e<Sr.length;e++)Cr(Sr[e],r);break;case"source":Cr("error",r);break;case"img":case"image":case"link":Cr("error",r),Cr("load",r);break;case"details":Cr("toggle",r);break;case"input":ee(r,i),Cr("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!i.multiple},Cr("invalid",r);break;case"textarea":ue(r,i),Cr("invalid",r)}for(var s in xe(n,i),e=null,i)i.hasOwnProperty(s)&&(a=i[s],"children"===s?"string"===typeof a?r.textContent!==a&&(e=["children",a]):"number"===typeof a&&r.textContent!==""+a&&(e=["children",""+a]):u.hasOwnProperty(s)&&null!=a&&"onScroll"===s&&Cr("scroll",r));switch(n){case"input":X(r),re(r,i,!0);break;case"textarea":X(r),ce(r);break;case"select":case"option":break;default:"function"===typeof i.onClick&&(r.onclick=Dr)}r=e,t.updateQueue=r,null!==r&&(t.flags|=4)}else{switch(s=9===a.nodeType?a:a.ownerDocument,e===fe&&(e=pe(n)),e===fe?"script"===n?((e=s.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"===typeof r.is?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),"select"===n&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Kr]=t,e[Yr]=r,Bo(e,t),t.stateNode=e,s=_e(n,r),n){case"dialog":Cr("cancel",e),Cr("close",e),a=r;break;case"iframe":case"object":case"embed":Cr("load",e),a=r;break;case"video":case"audio":for(a=0;a<Sr.length;a++)Cr(Sr[a],e);a=r;break;case"source":Cr("error",e),a=r;break;case"img":case"image":case"link":Cr("error",e),Cr("load",e),a=r;break;case"details":Cr("toggle",e),a=r;break;case"input":ee(e,r),a=J(e,r),Cr("invalid",e);break;case"option":a=ae(e,r);break;case"select":e._wrapperState={wasMultiple:!!r.multiple},a=l({},r,{value:void 0}),Cr("invalid",e);break;case"textarea":ue(e,r),a=ie(e,r),Cr("invalid",e);break;default:a=r}xe(n,a);var c=a;for(i in c)if(c.hasOwnProperty(i)){var f=c[i];"style"===i?Se(e,f):"dangerouslySetInnerHTML"===i?null!=(f=f?f.__html:void 0)&&ye(e,f):"children"===i?"string"===typeof f?("textarea"!==n||""!==f)&&ge(e,f):"number"===typeof f&&ge(e,""+f):"suppressContentEditableWarning"!==i&&"suppressHydrationWarning"!==i&&"autoFocus"!==i&&(u.hasOwnProperty(i)?null!=f&&"onScroll"===i&&Cr("scroll",e):null!=f&&w(e,i,f,s))}switch(n){case"input":X(e),re(e,r,!1);break;case"textarea":X(e),ce(e);break;case"option":null!=r.value&&e.setAttribute("value",""+K(r.value));break;case"select":e.multiple=!!r.multiple,null!=(i=r.value)?oe(e,!!r.multiple,i,!1):null!=r.defaultValue&&oe(e,!!r.multiple,r.defaultValue,!0);break;default:"function"===typeof a.onClick&&(e.onclick=Dr)}Ar(n,r)&&(t.flags|=4)}null!==t.ref&&(t.flags|=128)}return null;case 6:if(e&&null!=t.stateNode)Qo(0,t,e.memoizedProps,r);else{if("string"!==typeof r&&null===t.stateNode)throw Error(o(166));n=Na(Pa.current),Na(_a.current),ja(t)?(r=t.stateNode,n=t.memoizedProps,r[Kr]=t,r.nodeValue!==n&&(t.flags|=4)):((r=(9===n.nodeType?n:n.ownerDocument).createTextNode(r))[Kr]=t,t.stateNode=r)}return null;case 13:return ol(Fa),r=t.memoizedState,0!==(64&t.flags)?(t.lanes=n,t):(r=null!==r,n=!1,null===e?void 0!==t.memoizedProps.fallback&&ja(t):n=null!==e.memoizedState,r&&!n&&0!==(2&t.mode)&&(null===e&&!0!==t.memoizedProps.unstable_avoidThisFallback||0!==(1&Fa.current)?0===Oi&&(Oi=3):(0!==Oi&&3!==Oi||(Oi=4),null===Pi||0===(134217727&Ri)&&0===(134217727&Di)||du(Pi,Ti))),(r||n)&&(t.flags|=4),null);case 4:return La(),null===e&&Nr(t.stateNode.containerInfo),null;case 10:return Jl(t),null;case 17:return pl(t.type)&&hl(),null;case 19:if(ol(Fa),null===(r=t.memoizedState))return null;if(i=0!==(64&t.flags),null===(s=r.rendering))if(i)ni(r,!1);else{if(0!==Oi||null!==e&&0!==(64&e.flags))for(e=t.child;null!==e;){if(null!==(s=Ia(e))){for(t.flags|=64,ni(r,!1),null!==(i=s.updateQueue)&&(t.updateQueue=i,t.flags|=4),null===r.lastEffect&&(t.firstEffect=null),t.lastEffect=r.lastEffect,r=n,n=t.child;null!==n;)e=r,(i=n).flags&=2,i.nextEffect=null,i.firstEffect=null,i.lastEffect=null,null===(s=i.alternate)?(i.childLanes=0,i.lanes=e,i.child=null,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=s.childLanes,i.lanes=s.lanes,i.child=s.child,i.memoizedProps=s.memoizedProps,i.memoizedState=s.memoizedState,i.updateQueue=s.updateQueue,i.type=s.type,e=s.dependencies,i.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return il(Fa,1&Fa.current|2),t.child}e=e.sibling}null!==r.tail&&Al()>Vi&&(t.flags|=64,i=!0,ni(r,!1),t.lanes=33554432)}else{if(!i)if(null!==(e=Ia(s))){if(t.flags|=64,i=!0,null!==(n=e.updateQueue)&&(t.updateQueue=n,t.flags|=4),ni(r,!0),null===r.tail&&"hidden"===r.tailMode&&!s.alternate&&!Ma)return null!==(t=t.lastEffect=r.lastEffect)&&(t.nextEffect=null),null}else 2*Al()-r.renderingStartTime>Vi&&1073741824!==n&&(t.flags|=64,i=!0,ni(r,!1),t.lanes=33554432);r.isBackwards?(s.sibling=t.child,t.child=s):(null!==(n=r.last)?n.sibling=s:t.child=s,r.last=s)}return null!==r.tail?(n=r.tail,r.rendering=n,r.tail=n.sibling,r.lastEffect=t.lastEffect,r.renderingStartTime=Al(),n.sibling=null,t=Fa.current,il(Fa,i?1&t|2:1&t),n):null;case 23:case 24:return yu(),null!==e&&null!==e.memoizedState!==(null!==t.memoizedState)&&"unstable-defer-without-hiding"!==r.mode&&(t.flags|=4),null}throw Error(o(156,t.tag))}function li(e){switch(e.tag){case 1:pl(e.type)&&hl();var t=e.flags;return 4096&t?(e.flags=-4097&t|64,e):null;case 3:if(La(),ol(cl),ol(sl),Ha(),0!==(64&(t=e.flags)))throw Error(o(285));return e.flags=-4097&t|64,e;case 5:return Oa(e),null;case 13:return ol(Fa),4096&(t=e.flags)?(e.flags=-4097&t|64,e):null;case 19:return ol(Fa),null;case 4:return La(),null;case 10:return Jl(e),null;case 23:case 24:return yu(),null;default:return null}}function ai(e,t){try{var n="",r=t;do{n+=Q(r),r=r.return}while(r);var l=n}catch(a){l="\nError generating stack: "+a.message+"\n"+a.stack}return{value:e,source:t,stack:l}}function oi(e,t){try{console.error(t.value)}catch(n){setTimeout((function(){throw n}))}}Bo=function(e,t){for(var n=t.child;null!==n;){if(5===n.tag||6===n.tag)e.appendChild(n.stateNode);else if(4!==n.tag&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)break;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},Ho=function(e,t,n,r){var a=e.memoizedProps;if(a!==r){e=t.stateNode,Na(_a.current);var o,i=null;switch(n){case"input":a=J(e,a),r=J(e,r),i=[];break;case"option":a=ae(e,a),r=ae(e,r),i=[];break;case"select":a=l({},a,{value:void 0}),r=l({},r,{value:void 0}),i=[];break;case"textarea":a=ie(e,a),r=ie(e,r),i=[];break;default:"function"!==typeof a.onClick&&"function"===typeof r.onClick&&(e.onclick=Dr)}for(f in xe(n,r),n=null,a)if(!r.hasOwnProperty(f)&&a.hasOwnProperty(f)&&null!=a[f])if("style"===f){var s=a[f];for(o in s)s.hasOwnProperty(o)&&(n||(n={}),n[o]="")}else"dangerouslySetInnerHTML"!==f&&"children"!==f&&"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(u.hasOwnProperty(f)?i||(i=[]):(i=i||[]).push(f,null));for(f in r){var c=r[f];if(s=null!=a?a[f]:void 0,r.hasOwnProperty(f)&&c!==s&&(null!=c||null!=s))if("style"===f)if(s){for(o in s)!s.hasOwnProperty(o)||c&&c.hasOwnProperty(o)||(n||(n={}),n[o]="");for(o in c)c.hasOwnProperty(o)&&s[o]!==c[o]&&(n||(n={}),n[o]=c[o])}else n||(i||(i=[]),i.push(f,n)),n=c;else"dangerouslySetInnerHTML"===f?(c=c?c.__html:void 0,s=s?s.__html:void 0,null!=c&&s!==c&&(i=i||[]).push(f,c)):"children"===f?"string"!==typeof c&&"number"!==typeof c||(i=i||[]).push(f,""+c):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&(u.hasOwnProperty(f)?(null!=c&&"onScroll"===f&&Cr("scroll",e),i||s===c||(i=[])):"object"===typeof c&&null!==c&&c.$$typeof===R?c.toString():(i=i||[]).push(f,c))}n&&(i=i||[]).push("style",n);var f=i;(t.updateQueue=f)&&(t.flags|=4)}},Qo=function(e,t,n,r){n!==r&&(t.flags|=4)};var ii="function"===typeof WeakMap?WeakMap:Map;function ui(e,t,n){(n=oa(-1,n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Bi||(Bi=!0,Hi=r),oi(0,t)},n}function si(e,t,n){(n=oa(-1,n)).tag=3;var r=e.type.getDerivedStateFromError;if("function"===typeof r){var l=t.value;n.payload=function(){return oi(0,t),r(l)}}var a=e.stateNode;return null!==a&&"function"===typeof a.componentDidCatch&&(n.callback=function(){"function"!==typeof r&&(null===Qi?Qi=new Set([this]):Qi.add(this),oi(0,t));var e=t.stack;this.componentDidCatch(t.value,{componentStack:null!==e?e:""})}),n}var ci="function"===typeof WeakSet?WeakSet:Set;function fi(e){var t=e.ref;if(null!==t)if("function"===typeof t)try{t(null)}catch(n){Iu(e,n)}else t.current=null}function di(e,t){switch(t.tag){case 0:case 11:case 15:case 22:return;case 1:if(256&t.flags&&null!==e){var n=e.memoizedProps,r=e.memoizedState;t=(e=t.stateNode).getSnapshotBeforeUpdate(t.elementType===t.type?n:ql(t.type,n),r),e.__reactInternalSnapshotBeforeUpdate=t}return;case 3:return void(256&t.flags&&$r(t.stateNode.containerInfo));case 5:case 6:case 4:case 17:return}throw Error(o(163))}function pi(e,t,n){switch(n.tag){case 0:case 11:case 15:case 22:if(null!==(t=null!==(t=n.updateQueue)?t.lastEffect:null)){e=t=t.next;do{if(3===(3&e.tag)){var r=e.create;e.destroy=r()}e=e.next}while(e!==t)}if(null!==(t=null!==(t=n.updateQueue)?t.lastEffect:null)){e=t=t.next;do{var l=e;r=l.next,0!==(4&(l=l.tag))&&0!==(1&l)&&(zu(n,e),Lu(n,e)),e=r}while(e!==t)}return;case 1:return e=n.stateNode,4&n.flags&&(null===t?e.componentDidMount():(r=n.elementType===n.type?t.memoizedProps:ql(n.type,t.memoizedProps),e.componentDidUpdate(r,t.memoizedState,e.__reactInternalSnapshotBeforeUpdate))),void(null!==(t=n.updateQueue)&&ca(n,t,e));case 3:if(null!==(t=n.updateQueue)){if(e=null,null!==n.child)switch(n.child.tag){case 5:e=n.child.stateNode;break;case 1:e=n.child.stateNode}ca(n,t,e)}return;case 5:return e=n.stateNode,void(null===t&&4&n.flags&&Ar(n.type,n.memoizedProps)&&e.focus());case 6:case 4:case 12:return;case 13:return void(null===n.memoizedState&&(n=n.alternate,null!==n&&(n=n.memoizedState,null!==n&&(n=n.dehydrated,null!==n&&St(n)))));case 19:case 17:case 20:case 21:case 23:case 24:return}throw Error(o(163))}function hi(e,t){for(var n=e;;){if(5===n.tag){var r=n.stateNode;if(t)"function"===typeof(r=r.style).setProperty?r.setProperty("display","none","important"):r.display="none";else{r=n.stateNode;var l=n.memoizedProps.style;l=void 0!==l&&null!==l&&l.hasOwnProperty("display")?l.display:null,r.style.display=ke("display",l)}}else if(6===n.tag)n.stateNode.nodeValue=t?"":n.memoizedProps;else if((23!==n.tag&&24!==n.tag||null===n.memoizedState||n===e)&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}function mi(e,t){if(wl&&"function"===typeof wl.onCommitFiberUnmount)try{wl.onCommitFiberUnmount(bl,t)}catch(a){}switch(t.tag){case 0:case 11:case 14:case 15:case 22:if(null!==(e=t.updateQueue)&&null!==(e=e.lastEffect)){var n=e=e.next;do{var r=n,l=r.destroy;if(r=r.tag,void 0!==l)if(0!==(4&r))zu(t,n);else{r=t;try{l()}catch(a){Iu(r,a)}}n=n.next}while(n!==e)}break;case 1:if(fi(t),"function"===typeof(e=t.stateNode).componentWillUnmount)try{e.props=t.memoizedProps,e.state=t.memoizedState,e.componentWillUnmount()}catch(a){Iu(t,a)}break;case 5:fi(t);break;case 4:bi(e,t)}}function vi(e){e.alternate=null,e.child=null,e.dependencies=null,e.firstEffect=null,e.lastEffect=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.return=null,e.updateQueue=null}function yi(e){return 5===e.tag||3===e.tag||4===e.tag}function gi(e){e:{for(var t=e.return;null!==t;){if(yi(t))break e;t=t.return}throw Error(o(160))}var n=t;switch(t=n.stateNode,n.tag){case 5:var r=!1;break;case 3:case 4:t=t.containerInfo,r=!0;break;default:throw Error(o(161))}16&n.flags&&(ge(t,""),n.flags&=-17);e:t:for(n=e;;){for(;null===n.sibling;){if(null===n.return||yi(n.return)){n=null;break e}n=n.return}for(n.sibling.return=n.return,n=n.sibling;5!==n.tag&&6!==n.tag&&18!==n.tag;){if(2&n.flags)continue t;if(null===n.child||4===n.tag)continue t;n.child.return=n,n=n.child}if(!(2&n.flags)){n=n.stateNode;break e}}r?function e(t,n,r){var l=t.tag,a=5===l||6===l;if(a)t=a?t.stateNode:t.stateNode.instance,n?8===r.nodeType?r.parentNode.insertBefore(t,n):r.insertBefore(t,n):(8===r.nodeType?(n=r.parentNode).insertBefore(t,r):(n=r).appendChild(t),null!==(r=r._reactRootContainer)&&void 0!==r||null!==n.onclick||(n.onclick=Dr));else if(4!==l&&null!==(t=t.child))for(e(t,n,r),t=t.sibling;null!==t;)e(t,n,r),t=t.sibling}(e,n,t):function e(t,n,r){var l=t.tag,a=5===l||6===l;if(a)t=a?t.stateNode:t.stateNode.instance,n?r.insertBefore(t,n):r.appendChild(t);else if(4!==l&&null!==(t=t.child))for(e(t,n,r),t=t.sibling;null!==t;)e(t,n,r),t=t.sibling}(e,n,t)}function bi(e,t){for(var n,r,l=t,a=!1;;){if(!a){a=l.return;e:for(;;){if(null===a)throw Error(o(160));switch(n=a.stateNode,a.tag){case 5:r=!1;break e;case 3:case 4:n=n.containerInfo,r=!0;break e}a=a.return}a=!0}if(5===l.tag||6===l.tag){e:for(var i=e,u=l,s=u;;)if(mi(i,s),null!==s.child&&4!==s.tag)s.child.return=s,s=s.child;else{if(s===u)break e;for(;null===s.sibling;){if(null===s.return||s.return===u)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}r?(i=n,u=l.stateNode,8===i.nodeType?i.parentNode.removeChild(u):i.removeChild(u)):n.removeChild(l.stateNode)}else if(4===l.tag){if(null!==l.child){n=l.stateNode.containerInfo,r=!0,l.child.return=l,l=l.child;continue}}else if(mi(e,l),null!==l.child){l.child.return=l,l=l.child;continue}if(l===t)break;for(;null===l.sibling;){if(null===l.return||l.return===t)return;4===(l=l.return).tag&&(a=!1)}l.sibling.return=l.return,l=l.sibling}}function wi(e,t){switch(t.tag){case 0:case 11:case 14:case 15:case 22:var n=t.updateQueue;if(null!==(n=null!==n?n.lastEffect:null)){var r=n=n.next;do{3===(3&r.tag)&&(e=r.destroy,r.destroy=void 0,void 0!==e&&e()),r=r.next}while(r!==n)}return;case 1:return;case 5:if(null!=(n=t.stateNode)){r=t.memoizedProps;var l=null!==e?e.memoizedProps:r;e=t.type;var a=t.updateQueue;if(t.updateQueue=null,null!==a){for(n[Yr]=r,"input"===e&&"radio"===r.type&&null!=r.name&&te(n,r),_e(e,l),t=_e(e,r),l=0;l<a.length;l+=2){var i=a[l],u=a[l+1];"style"===i?Se(n,u):"dangerouslySetInnerHTML"===i?ye(n,u):"children"===i?ge(n,u):w(n,i,u,t)}switch(e){case"input":ne(n,r);break;case"textarea":se(n,r);break;case"select":e=n._wrapperState.wasMultiple,n._wrapperState.wasMultiple=!!r.multiple,null!=(a=r.value)?oe(n,!!r.multiple,a,!1):e!==!!r.multiple&&(null!=r.defaultValue?oe(n,!!r.multiple,r.defaultValue,!0):oe(n,!!r.multiple,r.multiple?[]:"",!1))}}}return;case 6:if(null===t.stateNode)throw Error(o(162));return void(t.stateNode.nodeValue=t.memoizedProps);case 3:return void((n=t.stateNode).hydrate&&(n.hydrate=!1,St(n.containerInfo)));case 12:return;case 13:return null!==t.memoizedState&&(Ai=Al(),hi(t.child,!0)),void ki(t);case 19:return void ki(t);case 17:return;case 23:case 24:return void hi(t,null!==t.memoizedState)}throw Error(o(163))}function ki(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var n=e.stateNode;null===n&&(n=e.stateNode=new ci),t.forEach((function(t){var r=Du.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))}))}}function Si(e,t){return null!==e&&(null===(e=e.memoizedState)||null!==e.dehydrated)&&(null!==(t=t.memoizedState)&&null===t.dehydrated)}var Ei=Math.ceil,xi=k.ReactCurrentDispatcher,_i=k.ReactCurrentOwner,Ci=0,Pi=null,Ni=null,Ti=0,Li=0,zi=al(0),Oi=0,Fi=null,Ii=0,Ri=0,Di=0,Mi=0,Ui=null,Ai=0,Vi=1/0;function Wi(){Vi=Al()+500}var ji,$i=null,Bi=!1,Hi=null,Qi=null,qi=!1,Ki=null,Yi=90,Xi=[],Gi=[],Zi=null,Ji=0,eu=null,tu=-1,nu=0,ru=0,lu=null,au=!1;function ou(){return 0!==(48&Ci)?Al():-1!==tu?tu:tu=Al()}function iu(e){if(0===(2&(e=e.mode)))return 1;if(0===(4&e))return 99===Vl()?1:2;if(0===nu&&(nu=Ii),0!==Ql.transition){0!==ru&&(ru=null!==Ui?Ui.pendingLanes:0),e=nu;var t=4186112&~ru;return 0===(t&=-t)&&(0===(t=(e=4186112&~e)&-e)&&(t=8192)),t}return e=Vl(),0!==(4&Ci)&&98===e?e=Vt(12,nu):e=Vt(e=function(e){switch(e){case 99:return 15;case 98:return 10;case 97:case 96:return 8;case 95:return 2;default:return 0}}(e),nu),e}function uu(e,t,n){if(50<Ji)throw Ji=0,eu=null,Error(o(185));if(null===(e=su(e,t)))return null;$t(e,t,n),e===Pi&&(Di|=t,4===Oi&&du(e,Ti));var r=Vl();1===t?0!==(8&Ci)&&0===(48&Ci)?pu(e):(cu(e,n),0===Ci&&(Wi(),Bl())):(0===(4&Ci)||98!==r&&99!==r||(null===Zi?Zi=new Set([e]):Zi.add(e)),cu(e,n)),Ui=e}function su(e,t){e.lanes|=t;var n=e.alternate;for(null!==n&&(n.lanes|=t),n=e,e=e.return;null!==e;)e.childLanes|=t,null!==(n=e.alternate)&&(n.childLanes|=t),n=e,e=e.return;return 3===n.tag?n.stateNode:null}function cu(e,t){for(var n=e.callbackNode,r=e.suspendedLanes,l=e.pingedLanes,a=e.expirationTimes,i=e.pendingLanes;0<i;){var u=31-Bt(i),s=1<<u,c=a[u];if(-1===c){if(0===(s&r)||0!==(s&l)){c=t,Mt(s);var f=Dt;a[u]=10<=f?c+250:6<=f?c+5e3:-1}}else c<=t&&(e.expiredLanes|=s);i&=~s}if(r=Ut(e,e===Pi?Ti:0),t=Dt,0===r)null!==n&&(n!==Fl&&El(n),e.callbackNode=null,e.callbackPriority=0);else{if(null!==n){if(e.callbackPriority===t)return;n!==Fl&&El(n)}15===t?(n=pu.bind(null,e),null===Rl?(Rl=[n],Dl=Sl(Nl,Hl)):Rl.push(n),n=Fl):14===t?n=$l(99,pu.bind(null,e)):n=$l(n=function(e){switch(e){case 15:case 14:return 99;case 13:case 12:case 11:case 10:return 98;case 9:case 8:case 7:case 6:case 4:case 5:return 97;case 3:case 2:case 1:return 95;case 0:return 90;default:throw Error(o(358,e))}}(t),fu.bind(null,e)),e.callbackPriority=t,e.callbackNode=n}}function fu(e){if(tu=-1,ru=nu=0,0!==(48&Ci))throw Error(o(327));var t=e.callbackNode;if(Tu()&&e.callbackNode!==t)return null;var n=Ut(e,e===Pi?Ti:0);if(0===n)return null;var r=n,l=Ci;Ci|=16;var a=wu();for(Pi===e&&Ti===r||(Wi(),gu(e,r));;)try{Eu();break}catch(u){bu(e,u)}if(Zl(),xi.current=a,Ci=l,null!==Ni?r=0:(Pi=null,Ti=0,r=Oi),0!==(Ii&Di))gu(e,0);else if(0!==r){if(2===r&&(Ci|=64,e.hydrate&&(e.hydrate=!1,$r(e.containerInfo)),0!==(n=At(e))&&(r=ku(e,n))),1===r)throw t=Fi,gu(e,0),du(e,n),cu(e,Al()),t;switch(e.finishedWork=e.current.alternate,e.finishedLanes=n,r){case 0:case 1:throw Error(o(345));case 2:Cu(e);break;case 3:if(du(e,n),(62914560&n)===n&&10<(r=Ai+500-Al())){if(0!==Ut(e,0))break;if(((l=e.suspendedLanes)&n)!==n){ou(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=Wr(Cu.bind(null,e),r);break}Cu(e);break;case 4:if(du(e,n),(4186112&n)===n)break;for(r=e.eventTimes,l=-1;0<n;){var i=31-Bt(n);a=1<<i,(i=r[i])>l&&(l=i),n&=~a}if(n=l,10<(n=(120>(n=Al()-n)?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Ei(n/1960))-n)){e.timeoutHandle=Wr(Cu.bind(null,e),n);break}Cu(e);break;case 5:Cu(e);break;default:throw Error(o(329))}}return cu(e,Al()),e.callbackNode===t?fu.bind(null,e):null}function du(e,t){for(t&=~Mi,t&=~Di,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-Bt(t),r=1<<n;e[n]=-1,t&=~r}}function pu(e){if(0!==(48&Ci))throw Error(o(327));if(Tu(),e===Pi&&0!==(e.expiredLanes&Ti)){var t=Ti,n=ku(e,t);0!==(Ii&Di)&&(n=ku(e,t=Ut(e,t)))}else n=ku(e,t=Ut(e,0));if(0!==e.tag&&2===n&&(Ci|=64,e.hydrate&&(e.hydrate=!1,$r(e.containerInfo)),0!==(t=At(e))&&(n=ku(e,t))),1===n)throw n=Fi,gu(e,0),du(e,t),cu(e,Al()),n;return e.finishedWork=e.current.alternate,e.finishedLanes=t,Cu(e),cu(e,Al()),null}function hu(e,t){var n=Ci;Ci|=1;try{return e(t)}finally{0===(Ci=n)&&(Wi(),Bl())}}function mu(e,t){var n=Ci;Ci&=-2,Ci|=8;try{return e(t)}finally{0===(Ci=n)&&(Wi(),Bl())}}function vu(e,t){il(zi,Li),Li|=t,Ii|=t}function yu(){Li=zi.current,ol(zi)}function gu(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(-1!==n&&(e.timeoutHandle=-1,jr(n)),null!==Ni)for(n=Ni.return;null!==n;){var r=n;switch(r.tag){case 1:null!==(r=r.type.childContextTypes)&&void 0!==r&&hl();break;case 3:La(),ol(cl),ol(sl),Ha();break;case 5:Oa(r);break;case 4:La();break;case 13:case 19:ol(Fa);break;case 10:Jl(r);break;case 23:case 24:yu()}n=n.return}Pi=e,Ni=Vu(e.current,null),Ti=Li=Ii=t,Oi=0,Fi=null,Mi=Di=Ri=0}function bu(e,t){for(;;){var n=Ni;try{if(Zl(),Qa.current=No,Za){for(var r=Ya.memoizedState;null!==r;){var l=r.queue;null!==l&&(l.pending=null),r=r.next}Za=!1}if(Ka=0,Ga=Xa=Ya=null,Ja=!1,_i.current=null,null===n||null===n.return){Oi=1,Fi=t,Ni=null;break}e:{var a=e,o=n.return,i=n,u=t;if(t=Ti,i.flags|=2048,i.firstEffect=i.lastEffect=null,null!==u&&"object"===typeof u&&"function"===typeof u.then){var s=u;if(0===(2&i.mode)){var c=i.alternate;c?(i.updateQueue=c.updateQueue,i.memoizedState=c.memoizedState,i.lanes=c.lanes):(i.updateQueue=null,i.memoizedState=null)}var f=0!==(1&Fa.current),d=o;do{var p;if(p=13===d.tag){var h=d.memoizedState;if(null!==h)p=null!==h.dehydrated;else{var m=d.memoizedProps;p=void 0!==m.fallback&&(!0!==m.unstable_avoidThisFallback||!f)}}if(p){var v=d.updateQueue;if(null===v){var y=new Set;y.add(s),d.updateQueue=y}else v.add(s);if(0===(2&d.mode)){if(d.flags|=64,i.flags|=16384,i.flags&=-2981,1===i.tag)if(null===i.alternate)i.tag=17;else{var g=oa(-1,1);g.tag=2,ia(i,g)}i.lanes|=1;break e}u=void 0,i=t;var b=a.pingCache;if(null===b?(b=a.pingCache=new ii,u=new Set,b.set(s,u)):void 0===(u=b.get(s))&&(u=new Set,b.set(s,u)),!u.has(i)){u.add(i);var w=Ru.bind(null,a,s,i);s.then(w,w)}d.flags|=4096,d.lanes=t;break e}d=d.return}while(null!==d);u=Error((q(i.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.")}5!==Oi&&(Oi=2),u=ai(u,i),d=o;do{switch(d.tag){case 3:a=u,d.flags|=4096,t&=-t,d.lanes|=t,ua(d,ui(0,a,t));break e;case 1:a=u;var k=d.type,S=d.stateNode;if(0===(64&d.flags)&&("function"===typeof k.getDerivedStateFromError||null!==S&&"function"===typeof S.componentDidCatch&&(null===Qi||!Qi.has(S)))){d.flags|=4096,t&=-t,d.lanes|=t,ua(d,si(d,a,t));break e}}d=d.return}while(null!==d)}_u(n)}catch(E){t=E,Ni===n&&null!==n&&(Ni=n=n.return);continue}break}}function wu(){var e=xi.current;return xi.current=No,null===e?No:e}function ku(e,t){var n=Ci;Ci|=16;var r=wu();for(Pi===e&&Ti===t||gu(e,t);;)try{Su();break}catch(l){bu(e,l)}if(Zl(),Ci=n,xi.current=r,null!==Ni)throw Error(o(261));return Pi=null,Ti=0,Oi}function Su(){for(;null!==Ni;)xu(Ni)}function Eu(){for(;null!==Ni&&!xl();)xu(Ni)}function xu(e){var t=ji(e.alternate,e,Li);e.memoizedProps=e.pendingProps,null===t?_u(e):Ni=t,_i.current=null}function _u(e){var t=e;do{var n=t.alternate;if(e=t.return,0===(2048&t.flags)){if(null!==(n=ri(n,t,Li)))return void(Ni=n);if(24!==(n=t).tag&&23!==n.tag||null===n.memoizedState||0!==(1073741824&Li)||0===(4&n.mode)){for(var r=0,l=n.child;null!==l;)r|=l.lanes|l.childLanes,l=l.sibling;n.childLanes=r}null!==e&&0===(2048&e.flags)&&(null===e.firstEffect&&(e.firstEffect=t.firstEffect),null!==t.lastEffect&&(null!==e.lastEffect&&(e.lastEffect.nextEffect=t.firstEffect),e.lastEffect=t.lastEffect),1<t.flags&&(null!==e.lastEffect?e.lastEffect.nextEffect=t:e.firstEffect=t,e.lastEffect=t))}else{if(null!==(n=li(t)))return n.flags&=2047,void(Ni=n);null!==e&&(e.firstEffect=e.lastEffect=null,e.flags|=2048)}if(null!==(t=t.sibling))return void(Ni=t);Ni=t=e}while(null!==t);0===Oi&&(Oi=5)}function Cu(e){var t=Vl();return jl(99,Pu.bind(null,e,t)),null}function Pu(e,t){do{Tu()}while(null!==Ki);if(0!==(48&Ci))throw Error(o(327));var n=e.finishedWork;if(null===n)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(o(177));e.callbackNode=null;var r=n.lanes|n.childLanes,l=r,a=e.pendingLanes&~l;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=l,e.mutableReadLanes&=l,e.entangledLanes&=l,l=e.entanglements;for(var i=e.eventTimes,u=e.expirationTimes;0<a;){var s=31-Bt(a),c=1<<s;l[s]=0,i[s]=-1,u[s]=-1,a&=~c}if(null!==Zi&&0===(24&r)&&Zi.has(e)&&Zi.delete(e),e===Pi&&(Ni=Pi=null,Ti=0),1<n.flags?null!==n.lastEffect?(n.lastEffect.nextEffect=n,r=n.firstEffect):r=n:r=n.firstEffect,null!==r){if(l=Ci,Ci|=32,_i.current=null,Mr=Yt,pr(i=dr())){if("selectionStart"in i)u={start:i.selectionStart,end:i.selectionEnd};else e:if(u=(u=i.ownerDocument)&&u.defaultView||window,(c=u.getSelection&&u.getSelection())&&0!==c.rangeCount){u=c.anchorNode,a=c.anchorOffset,s=c.focusNode,c=c.focusOffset;try{u.nodeType,s.nodeType}catch(C){u=null;break e}var f=0,d=-1,p=-1,h=0,m=0,v=i,y=null;t:for(;;){for(var g;v!==u||0!==a&&3!==v.nodeType||(d=f+a),v!==s||0!==c&&3!==v.nodeType||(p=f+c),3===v.nodeType&&(f+=v.nodeValue.length),null!==(g=v.firstChild);)y=v,v=g;for(;;){if(v===i)break t;if(y===u&&++h===a&&(d=f),y===s&&++m===c&&(p=f),null!==(g=v.nextSibling))break;y=(v=y).parentNode}v=g}u=-1===d||-1===p?null:{start:d,end:p}}else u=null;u=u||{start:0,end:0}}else u=null;Ur={focusedElem:i,selectionRange:u},Yt=!1,lu=null,au=!1,$i=r;do{try{Nu()}catch(C){if(null===$i)throw Error(o(330));Iu($i,C),$i=$i.nextEffect}}while(null!==$i);lu=null,$i=r;do{try{for(i=e;null!==$i;){var b=$i.flags;if(16&b&&ge($i.stateNode,""),128&b){var w=$i.alternate;if(null!==w){var k=w.ref;null!==k&&("function"===typeof k?k(null):k.current=null)}}switch(1038&b){case 2:gi($i),$i.flags&=-3;break;case 6:gi($i),$i.flags&=-3,wi($i.alternate,$i);break;case 1024:$i.flags&=-1025;break;case 1028:$i.flags&=-1025,wi($i.alternate,$i);break;case 4:wi($i.alternate,$i);break;case 8:bi(i,u=$i);var S=u.alternate;vi(u),null!==S&&vi(S)}$i=$i.nextEffect}}catch(C){if(null===$i)throw Error(o(330));Iu($i,C),$i=$i.nextEffect}}while(null!==$i);if(k=Ur,w=dr(),b=k.focusedElem,i=k.selectionRange,w!==b&&b&&b.ownerDocument&&function e(t,n){return!(!t||!n)&&(t===n||(!t||3!==t.nodeType)&&(n&&3===n.nodeType?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}(b.ownerDocument.documentElement,b)){null!==i&&pr(b)&&(w=i.start,void 0===(k=i.end)&&(k=w),"selectionStart"in b?(b.selectionStart=w,b.selectionEnd=Math.min(k,b.value.length)):(k=(w=b.ownerDocument||document)&&w.defaultView||window).getSelection&&(k=k.getSelection(),u=b.textContent.length,S=Math.min(i.start,u),i=void 0===i.end?S:Math.min(i.end,u),!k.extend&&S>i&&(u=i,i=S,S=u),u=fr(b,S),a=fr(b,i),u&&a&&(1!==k.rangeCount||k.anchorNode!==u.node||k.anchorOffset!==u.offset||k.focusNode!==a.node||k.focusOffset!==a.offset)&&((w=w.createRange()).setStart(u.node,u.offset),k.removeAllRanges(),S>i?(k.addRange(w),k.extend(a.node,a.offset)):(w.setEnd(a.node,a.offset),k.addRange(w))))),w=[];for(k=b;k=k.parentNode;)1===k.nodeType&&w.push({element:k,left:k.scrollLeft,top:k.scrollTop});for("function"===typeof b.focus&&b.focus(),b=0;b<w.length;b++)(k=w[b]).element.scrollLeft=k.left,k.element.scrollTop=k.top}Yt=!!Mr,Ur=Mr=null,e.current=n,$i=r;do{try{for(b=e;null!==$i;){var E=$i.flags;if(36&E&&pi(b,$i.alternate,$i),128&E){w=void 0;var x=$i.ref;if(null!==x){var _=$i.stateNode;switch($i.tag){case 5:w=_;break;default:w=_}"function"===typeof x?x(w):x.current=w}}$i=$i.nextEffect}}catch(C){if(null===$i)throw Error(o(330));Iu($i,C),$i=$i.nextEffect}}while(null!==$i);$i=null,Il(),Ci=l}else e.current=n;if(qi)qi=!1,Ki=e,Yi=t;else for($i=r;null!==$i;)t=$i.nextEffect,$i.nextEffect=null,8&$i.flags&&((E=$i).sibling=null,E.stateNode=null),$i=t;if(0===(r=e.pendingLanes)&&(Qi=null),1===r?e===eu?Ji++:(Ji=0,eu=e):Ji=0,n=n.stateNode,wl&&"function"===typeof wl.onCommitFiberRoot)try{wl.onCommitFiberRoot(bl,n,void 0,64===(64&n.current.flags))}catch(C){}if(cu(e,Al()),Bi)throw Bi=!1,e=Hi,Hi=null,e;return 0!==(8&Ci)||Bl(),null}function Nu(){for(;null!==$i;){var e=$i.alternate;au||null===lu||(0!==(8&$i.flags)?et($i,lu)&&(au=!0):13===$i.tag&&Si(e,$i)&&et($i,lu)&&(au=!0));var t=$i.flags;0!==(256&t)&&di(e,$i),0===(512&t)||qi||(qi=!0,$l(97,(function(){return Tu(),null}))),$i=$i.nextEffect}}function Tu(){if(90!==Yi){var e=97<Yi?97:Yi;return Yi=90,jl(e,Ou)}return!1}function Lu(e,t){Xi.push(t,e),qi||(qi=!0,$l(97,(function(){return Tu(),null})))}function zu(e,t){Gi.push(t,e),qi||(qi=!0,$l(97,(function(){return Tu(),null})))}function Ou(){if(null===Ki)return!1;var e=Ki;if(Ki=null,0!==(48&Ci))throw Error(o(331));var t=Ci;Ci|=32;var n=Gi;Gi=[];for(var r=0;r<n.length;r+=2){var l=n[r],a=n[r+1],i=l.destroy;if(l.destroy=void 0,"function"===typeof i)try{i()}catch(s){if(null===a)throw Error(o(330));Iu(a,s)}}for(n=Xi,Xi=[],r=0;r<n.length;r+=2){l=n[r],a=n[r+1];try{var u=l.create;l.destroy=u()}catch(s){if(null===a)throw Error(o(330));Iu(a,s)}}for(u=e.current.firstEffect;null!==u;)e=u.nextEffect,u.nextEffect=null,8&u.flags&&(u.sibling=null,u.stateNode=null),u=e;return Ci=t,Bl(),!0}function Fu(e,t,n){ia(e,t=ui(0,t=ai(n,t),1)),t=ou(),null!==(e=su(e,1))&&($t(e,1,t),cu(e,t))}function Iu(e,t){if(3===e.tag)Fu(e,e,t);else for(var n=e.return;null!==n;){if(3===n.tag){Fu(n,e,t);break}if(1===n.tag){var r=n.stateNode;if("function"===typeof n.type.getDerivedStateFromError||"function"===typeof r.componentDidCatch&&(null===Qi||!Qi.has(r))){var l=si(n,e=ai(t,e),1);if(ia(n,l),l=ou(),null!==(n=su(n,1)))$t(n,1,l),cu(n,l);else if("function"===typeof r.componentDidCatch&&(null===Qi||!Qi.has(r)))try{r.componentDidCatch(t,e)}catch(a){}break}}n=n.return}}function Ru(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),t=ou(),e.pingedLanes|=e.suspendedLanes&n,Pi===e&&(Ti&n)===n&&(4===Oi||3===Oi&&(62914560&Ti)===Ti&&500>Al()-Ai?gu(e,0):Mi|=n),cu(e,t)}function Du(e,t){var n=e.stateNode;null!==n&&n.delete(t),0===(t=0)&&(0===(2&(t=e.mode))?t=1:0===(4&t)?t=99===Vl()?1:2:(0===nu&&(nu=Ii),0===(t=Wt(62914560&~nu))&&(t=4194304))),n=ou(),null!==(e=su(e,t))&&($t(e,t,n),cu(e,n))}function Mu(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.flags=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childLanes=this.lanes=0,this.alternate=null}function Uu(e,t,n,r){return new Mu(e,t,n,r)}function Au(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Vu(e,t){var n=e.alternate;return null===n?((n=Uu(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.nextEffect=null,n.firstEffect=null,n.lastEffect=null),n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Wu(e,t,n,r,l,a){var i=2;if(r=e,"function"===typeof e)Au(e)&&(i=1);else if("string"===typeof e)i=5;else e:switch(e){case x:return ju(n.children,l,a,t);case D:i=8,l|=16;break;case _:i=8,l|=1;break;case C:return(e=Uu(12,n,t,8|l)).elementType=C,e.type=C,e.lanes=a,e;case L:return(e=Uu(13,n,t,l)).type=L,e.elementType=L,e.lanes=a,e;case z:return(e=Uu(19,n,t,l)).elementType=z,e.lanes=a,e;case M:return $u(n,l,a,t);case U:return(e=Uu(24,n,t,l)).elementType=U,e.lanes=a,e;default:if("object"===typeof e&&null!==e)switch(e.$$typeof){case P:i=10;break e;case N:i=9;break e;case T:i=11;break e;case O:i=14;break e;case F:i=16,r=null;break e;case I:i=22;break e}throw Error(o(130,null==e?e:typeof e,""))}return(t=Uu(i,n,t,l)).elementType=e,t.type=r,t.lanes=a,t}function ju(e,t,n,r){return(e=Uu(7,e,r,t)).lanes=n,e}function $u(e,t,n,r){return(e=Uu(23,e,r,t)).elementType=M,e.lanes=n,e}function Bu(e,t,n){return(e=Uu(6,e,null,t)).lanes=n,e}function Hu(e,t,n){return(t=Uu(4,null!==e.children?e.children:[],e.key,t)).lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Qu(e,t,n){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.pendingContext=this.context=null,this.hydrate=n,this.callbackNode=null,this.callbackPriority=0,this.eventTimes=jt(0),this.expirationTimes=jt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=jt(0),this.mutableSourceEagerHydrationData=null}function qu(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:E,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}function Ku(e,t,n,r){var l=t.current,a=ou(),i=iu(l);e:if(n){t:{if(Xe(n=n._reactInternals)!==n||1!==n.tag)throw Error(o(170));var u=n;do{switch(u.tag){case 3:u=u.stateNode.context;break t;case 1:if(pl(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break t}}u=u.return}while(null!==u);throw Error(o(171))}if(1===n.tag){var s=n.type;if(pl(s)){n=vl(n,s,u);break e}}n=u}else n=ul;return null===t.context?t.context=n:t.pendingContext=n,(t=oa(a,i)).payload={element:e},null!==(r=void 0===r?null:r)&&(t.callback=r),ia(l,t),uu(l,i,a),i}function Yu(e){if(!(e=e.current).child)return null;switch(e.child.tag){case 5:default:return e.child.stateNode}}function Xu(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var n=e.retryLane;e.retryLane=0!==n&&n<t?n:t}}function Gu(e,t){Xu(e,t),(e=e.alternate)&&Xu(e,t)}function Zu(e,t,n){var r=null!=n&&null!=n.hydrationOptions&&n.hydrationOptions.mutableSources||null;if(n=new Qu(e,t,null!=n&&!0===n.hydrate),t=Uu(3,null,null,2===t?7:1===t?3:0),n.current=t,t.stateNode=n,la(t),e[Xr]=n.current,Nr(8===e.nodeType?e.parentNode:e),r)for(e=0;e<r.length;e++){var l=(t=r[e])._getVersion;l=l(t._source),null==n.mutableSourceEagerHydrationData?n.mutableSourceEagerHydrationData=[t,l]:n.mutableSourceEagerHydrationData.push(t,l)}this._internalRoot=n}function Ju(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function es(e,t,n,r,l){var a=n._reactRootContainer;if(a){var o=a._internalRoot;if("function"===typeof l){var i=l;l=function(){var e=Yu(o);i.call(e)}}Ku(t,o,e,l)}else{if(a=n._reactRootContainer=function(e,t){if(t||(t=!(!(t=e?9===e.nodeType?e.documentElement:e.firstChild:null)||1!==t.nodeType||!t.hasAttribute("data-reactroot"))),!t)for(var n;n=e.lastChild;)e.removeChild(n);return new Zu(e,0,t?{hydrate:!0}:void 0)}(n,r),o=a._internalRoot,"function"===typeof l){var u=l;l=function(){var e=Yu(o);u.call(e)}}mu((function(){Ku(t,o,e,l)}))}return Yu(o)}function ts(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Ju(t))throw Error(o(200));return qu(e,t,null,n)}ji=function(e,t,n){var r=t.lanes;if(null!==e)if(e.memoizedProps!==t.pendingProps||cl.current)Fo=!0;else{if(0===(n&r)){switch(Fo=!1,t.tag){case 3:$o(t),$a();break;case 5:za(t);break;case 1:pl(t.type)&&yl(t);break;case 4:Ta(t,t.stateNode.containerInfo);break;case 10:r=t.memoizedProps.value;var l=t.type._context;il(Kl,l._currentValue),l._currentValue=r;break;case 13:if(null!==t.memoizedState)return 0!==(n&t.child.childLanes)?Ko(e,t,n):(il(Fa,1&Fa.current),null!==(t=ti(e,t,n))?t.sibling:null);il(Fa,1&Fa.current);break;case 19:if(r=0!==(n&t.childLanes),0!==(64&e.flags)){if(r)return ei(e,t,n);t.flags|=64}if(null!==(l=t.memoizedState)&&(l.rendering=null,l.tail=null,l.lastEffect=null),il(Fa,Fa.current),r)break;return null;case 23:case 24:return t.lanes=0,Uo(e,t,n)}return ti(e,t,n)}Fo=0!==(16384&e.flags)}else Fo=!1;switch(t.lanes=0,t.tag){case 2:if(r=t.type,null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2),e=t.pendingProps,l=dl(t,sl.current),ta(t,n),l=no(null,t,r,e,l,n),t.flags|=1,"object"===typeof l&&null!==l&&"function"===typeof l.render&&void 0===l.$$typeof){if(t.tag=1,t.memoizedState=null,t.updateQueue=null,pl(r)){var a=!0;yl(t)}else a=!1;t.memoizedState=null!==l.state&&void 0!==l.state?l.state:null,la(t);var i=r.getDerivedStateFromProps;"function"===typeof i&&da(t,r,i,e),l.updater=pa,t.stateNode=l,l._reactInternals=t,ya(t,r,e,n),t=jo(null,t,r,!0,a,n)}else t.tag=0,Io(null,t,l,n),t=t.child;return t;case 16:l=t.elementType;e:{switch(null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2),e=t.pendingProps,l=(a=l._init)(l._payload),t.type=l,a=t.tag=function(e){if("function"===typeof e)return Au(e)?1:0;if(void 0!==e&&null!==e){if((e=e.$$typeof)===T)return 11;if(e===O)return 14}return 2}(l),e=ql(l,e),a){case 0:t=Vo(null,t,l,e,n);break e;case 1:t=Wo(null,t,l,e,n);break e;case 11:t=Ro(null,t,l,e,n);break e;case 14:t=Do(null,t,l,ql(l.type,e),r,n);break e}throw Error(o(306,l,""))}return t;case 0:return r=t.type,l=t.pendingProps,Vo(e,t,r,l=t.elementType===r?l:ql(r,l),n);case 1:return r=t.type,l=t.pendingProps,Wo(e,t,r,l=t.elementType===r?l:ql(r,l),n);case 3:if($o(t),r=t.updateQueue,null===e||null===r)throw Error(o(282));if(r=t.pendingProps,l=null!==(l=t.memoizedState)?l.element:null,aa(e,t),sa(t,r,null,n),(r=t.memoizedState.element)===l)$a(),t=ti(e,t,n);else{if((a=(l=t.stateNode).hydrate)&&(Da=Br(t.stateNode.containerInfo.firstChild),Ra=t,a=Ma=!0),a){if(null!=(e=l.mutableSourceEagerHydrationData))for(l=0;l<e.length;l+=2)(a=e[l])._workInProgressVersionPrimary=e[l+1],Ba.push(a);for(n=Ea(t,null,r,n),t.child=n;n;)n.flags=-3&n.flags|1024,n=n.sibling}else Io(e,t,r,n),$a();t=t.child}return t;case 5:return za(t),null===e&&Va(t),r=t.type,l=t.pendingProps,a=null!==e?e.memoizedProps:null,i=l.children,Vr(r,l)?i=null:null!==a&&Vr(r,a)&&(t.flags|=16),Ao(e,t),Io(e,t,i,n),t.child;case 6:return null===e&&Va(t),null;case 13:return Ko(e,t,n);case 4:return Ta(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=Sa(t,null,r,n):Io(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,Ro(e,t,r,l=t.elementType===r?l:ql(r,l),n);case 7:return Io(e,t,t.pendingProps,n),t.child;case 8:case 12:return Io(e,t,t.pendingProps.children,n),t.child;case 10:e:{r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value;var u=t.type._context;if(il(Kl,u._currentValue),u._currentValue=a,null!==i)if(u=i.value,0===(a=ir(u,a)?0:0|("function"===typeof r._calculateChangedBits?r._calculateChangedBits(u,a):1073741823))){if(i.children===l.children&&!cl.current){t=ti(e,t,n);break e}}else for(null!==(u=t.child)&&(u.return=t);null!==u;){var s=u.dependencies;if(null!==s){i=u.child;for(var c=s.firstContext;null!==c;){if(c.context===r&&0!==(c.observedBits&a)){1===u.tag&&((c=oa(-1,n&-n)).tag=2,ia(u,c)),u.lanes|=n,null!==(c=u.alternate)&&(c.lanes|=n),ea(u.return,n),s.lanes|=n;break}c=c.next}}else i=10===u.tag&&u.type===t.type?null:u.child;if(null!==i)i.return=u;else for(i=u;null!==i;){if(i===t){i=null;break}if(null!==(u=i.sibling)){u.return=i.return,i=u;break}i=i.return}u=i}Io(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=(a=t.pendingProps).children,ta(t,n),r=r(l=na(l,a.unstable_observedBits)),t.flags|=1,Io(e,t,r,n),t.child;case 14:return a=ql(l=t.type,t.pendingProps),Do(e,t,l,a=ql(l.type,a),r,n);case 15:return Mo(e,t,t.type,t.pendingProps,r,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ql(r,l),null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2),t.tag=1,pl(r)?(e=!0,yl(t)):e=!1,ta(t,n),ma(t,r,l),ya(t,r,l,n),jo(null,t,r,!0,e,n);case 19:return ei(e,t,n);case 23:case 24:return Uo(e,t,n)}throw Error(o(156,t.tag))},Zu.prototype.render=function(e){Ku(e,this._internalRoot,null,null)},Zu.prototype.unmount=function(){var e=this._internalRoot,t=e.containerInfo;Ku(null,e,null,(function(){t[Xr]=null}))},tt=function(e){13===e.tag&&(uu(e,4,ou()),Gu(e,4))},nt=function(e){13===e.tag&&(uu(e,67108864,ou()),Gu(e,67108864))},rt=function(e){if(13===e.tag){var t=ou(),n=iu(e);uu(e,n,t),Gu(e,n)}},lt=function(e,t){return t()},Pe=function(e,t,n){switch(t){case"input":if(ne(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=tl(r);if(!l)throw Error(o(90));G(r),ne(r,l)}}}break;case"textarea":se(e,n);break;case"select":null!=(t=n.value)&&oe(e,!!n.multiple,t,!1)}},Fe=hu,Ie=function(e,t,n,r,l){var a=Ci;Ci|=4;try{return jl(98,e.bind(null,t,n,r,l))}finally{0===(Ci=a)&&(Wi(),Bl())}},Re=function(){0===(49&Ci)&&(function(){if(null!==Zi){var e=Zi;Zi=null,e.forEach((function(e){e.expiredLanes|=24&e.pendingLanes,cu(e,Al())}))}Bl()}(),Tu())},De=function(e,t){var n=Ci;Ci|=2;try{return e(t)}finally{0===(Ci=n)&&(Wi(),Bl())}};var ns={Events:[Jr,el,tl,ze,Oe,Tu,{current:!1}]},rs={findFiberByHostInstance:Zr,bundleType:0,version:"17.0.1",rendererPackageName:"react-dom"},ls={bundleType:rs.bundleType,version:rs.version,rendererPackageName:rs.rendererPackageName,rendererConfig:rs.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:k.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=Je(e))?null:e.stateNode},findFiberByHostInstance:rs.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var as=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!as.isDisabled&&as.supportsFiber)try{bl=as.inject(ls),wl=as}catch(ve){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ns,t.createPortal=ts,t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"===typeof e.render)throw Error(o(188));throw Error(o(268,Object.keys(e)))}return e=null===(e=Je(t))?null:e.stateNode},t.flushSync=function(e,t){var n=Ci;if(0!==(48&n))return e(t);Ci|=1;try{if(e)return jl(99,e.bind(null,t))}finally{Ci=n,Bl()}},t.hydrate=function(e,t,n){if(!Ju(t))throw Error(o(200));return es(null,e,t,!0,n)},t.render=function(e,t,n){if(!Ju(t))throw Error(o(200));return es(null,e,t,!1,n)},t.unmountComponentAtNode=function(e){if(!Ju(e))throw Error(o(40));return!!e._reactRootContainer&&(mu((function(){es(null,null,e,!1,(function(){e._reactRootContainer=null,e[Xr]=null}))})),!0)},t.unstable_batchedUpdates=hu,t.unstable_createPortal=function(e,t){return ts(e,t,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)},t.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!Ju(n))throw Error(o(200));if(null==e||void 0===e._reactInternals)throw Error(o(38));return es(e,t,n,!1,r)},t.version="17.0.1"}}]); | ze |
http.go | package http
import (
"context"
"errors"
"fmt"
"math/rand"
"net/url"
"strings"
"time"
"github.com/klyed/tendermint/light/provider"
rpcclient "github.com/klyed/tendermint/rpc/client"
rpchttp "github.com/klyed/tendermint/rpc/client/http"
ctypes "github.com/klyed/tendermint/rpc/core/types"
rpctypes "github.com/klyed/tendermint/rpc/jsonrpc/types"
"github.com/klyed/tendermint/types"
)
var defaultOptions = Options{
MaxRetryAttempts: 5,
Timeout: 3 * time.Second,
NoBlockThreshold: 5,
NoResponseThreshold: 5,
}
// http provider uses an RPC client to obtain the necessary information.
type http struct {
chainID string
client rpcclient.RemoteClient
// httt provider heuristics
// The provider tracks the amount of times that the
// client doesn't respond. If this exceeds the threshold
// then the provider will return an unreliable provider error
noResponseThreshold uint16
noResponseCount uint16
// The provider tracks the amount of time the client
// doesn't have a block. If this exceeds the threshold
// then the provider will return an unreliable provider error
noBlockThreshold uint16
noBlockCount uint16
// In a single request, the provider attempts multiple times
// with exponential backoff to reach the client. If this
// exceeds the maxRetry attempts, this result in a ErrNoResponse
maxRetryAttempts uint16
}
type Options struct {
// 0 means no retries
MaxRetryAttempts uint16
// 0 means no timeout.
Timeout time.Duration
// The amount of requests that a client doesn't have the block
// for before the provider deems the client unreliable
NoBlockThreshold uint16
// The amount of requests that a client doesn't respond to
// before the provider deems the client unreliable
NoResponseThreshold uint16
}
// New creates a HTTP provider, which is using the rpchttp.HTTP client under
// the hood. If no scheme is provided in the remote URL, http will be used by
// default. The 5s timeout is used for all requests.
func New(chainID, remote string) (provider.Provider, error) {
return NewWithOptions(chainID, remote, defaultOptions)
}
// NewWithOptions is an extension to creating a new http provider that allows the addition
// of a specified timeout and maxRetryAttempts
func NewWithOptions(chainID, remote string, options Options) (provider.Provider, error) {
// Ensure URL scheme is set (default HTTP) when not provided.
if !strings.Contains(remote, "://") {
remote = "http://" + remote
}
httpClient, err := rpchttp.NewWithTimeout(remote, options.Timeout)
if err != nil {
return nil, err
}
return NewWithClientAndOptions(chainID, httpClient, options), nil
}
func NewWithClient(chainID string, client rpcclient.RemoteClient) provider.Provider {
return NewWithClientAndOptions(chainID, client, defaultOptions)
}
// NewWithClient allows you to provide a custom client.
func | (chainID string, client rpcclient.RemoteClient, options Options) provider.Provider {
return &http{
client: client,
chainID: chainID,
maxRetryAttempts: options.MaxRetryAttempts,
noResponseThreshold: options.NoResponseThreshold,
noBlockThreshold: options.NoBlockThreshold,
}
}
func (p *http) String() string {
return fmt.Sprintf("http{%s}", p.client.Remote())
}
// LightBlock fetches a LightBlock at the given height and checks the
// chainID matches.
func (p *http) LightBlock(ctx context.Context, height int64) (*types.LightBlock, error) {
h, err := validateHeight(height)
if err != nil {
return nil, provider.ErrBadLightBlock{Reason: err}
}
sh, err := p.signedHeader(ctx, h)
if err != nil {
return nil, err
}
vs, err := p.validatorSet(ctx, &sh.Height)
if err != nil {
return nil, err
}
lb := &types.LightBlock{
SignedHeader: sh,
ValidatorSet: vs,
}
err = lb.ValidateBasic(p.chainID)
if err != nil {
return nil, provider.ErrBadLightBlock{Reason: err}
}
return lb, nil
}
// ReportEvidence calls `/broadcast_evidence` endpoint.
func (p *http) ReportEvidence(ctx context.Context, ev types.Evidence) error {
_, err := p.client.BroadcastEvidence(ctx, ev)
return err
}
func (p *http) validatorSet(ctx context.Context, height *int64) (*types.ValidatorSet, error) {
// Since the malicious node could report a massive number of pages, making us
// spend a considerable time iterating, we restrict the number of pages here.
// => 10000 validators max
const maxPages = 100
var (
perPage = 100
vals = []*types.Validator{}
page = 1
total = -1
)
for len(vals) != total && page <= maxPages {
// create another for loop to control retries. If p.maxRetryAttempts
// is negative we will keep repeating.
attempt := uint16(0)
for {
res, err := p.client.Validators(ctx, height, &page, &perPage)
switch e := err.(type) {
case nil: // success!! Now we validate the response
if len(res.Validators) == 0 {
return nil, provider.ErrBadLightBlock{
Reason: fmt.Errorf("validator set is empty (height: %d, page: %d, per_page: %d)",
height, page, perPage),
}
}
if res.Total <= 0 {
return nil, provider.ErrBadLightBlock{
Reason: fmt.Errorf("total number of vals is <= 0: %d (height: %d, page: %d, per_page: %d)",
res.Total, height, page, perPage),
}
}
case *url.Error:
if e.Timeout() {
// if we have exceeded retry attempts then return a no response error
if attempt == p.maxRetryAttempts {
return nil, p.noResponse()
}
attempt++
// request timed out: we wait and try again with exponential backoff
time.Sleep(backoffTimeout(attempt))
continue
}
return nil, provider.ErrBadLightBlock{Reason: e}
case *rpctypes.RPCError:
// check if the error indicates that the peer doesn't have the block
if strings.Contains(e.Data, ctypes.ErrHeightNotAvailable.Error()) ||
strings.Contains(e.Data, ctypes.ErrHeightExceedsChainHead.Error()) {
return nil, provider.ErrLightBlockNotFound
}
return nil, provider.ErrBadLightBlock{Reason: e}
default:
// If we don't know the error then by default we return a bad light block error and
// terminate the connection with the peer.
return nil, provider.ErrBadLightBlock{Reason: e}
}
// update the total and increment the page index so we can fetch the
// next page of validators if need be
total = res.Total
vals = append(vals, res.Validators...)
page++
break
}
}
valSet, err := types.ValidatorSetFromExistingValidators(vals)
if err != nil {
return nil, provider.ErrBadLightBlock{Reason: err}
}
return valSet, nil
}
func (p *http) signedHeader(ctx context.Context, height *int64) (*types.SignedHeader, error) {
// create a for loop to control retries. If p.maxRetryAttempts
// is negative we will keep repeating.
for attempt := uint16(0); attempt != p.maxRetryAttempts+1; attempt++ {
commit, err := p.client.Commit(ctx, height)
switch e := err.(type) {
case nil: // success!!
return &commit.SignedHeader, nil
case *url.Error:
if e.Timeout() {
// we wait and try again with exponential backoff
time.Sleep(backoffTimeout(attempt))
continue
}
return nil, provider.ErrBadLightBlock{Reason: e}
case *rpctypes.RPCError:
// check if the error indicates that the peer doesn't have the block
if strings.Contains(e.Data, ctypes.ErrHeightNotAvailable.Error()) ||
strings.Contains(e.Data, ctypes.ErrHeightExceedsChainHead.Error()) {
return nil, p.noBlock()
}
// for every other error, the provider returns a bad block
return nil, provider.ErrBadLightBlock{Reason: errors.New(e.Data)}
default:
// If we don't know the error then by default we return a bad light block error and
// terminate the connection with the peer.
return nil, provider.ErrBadLightBlock{Reason: e}
}
}
return nil, p.noResponse()
}
func (p *http) noResponse() error {
p.noResponseCount++
if p.noResponseCount > p.noResponseThreshold {
return provider.ErrUnreliableProvider{
Reason: fmt.Sprintf("failed to respond after %d attempts", p.noResponseCount),
}
}
return provider.ErrNoResponse
}
func (p *http) noBlock() error {
p.noBlockCount++
if p.noBlockCount > p.noBlockThreshold {
return provider.ErrUnreliableProvider{
Reason: fmt.Sprintf("failed to provide a block after %d attempts", p.noBlockCount),
}
}
return provider.ErrLightBlockNotFound
}
func validateHeight(height int64) (*int64, error) {
if height < 0 {
return nil, fmt.Errorf("expected height >= 0, got height %d", height)
}
h := &height
if height == 0 {
h = nil
}
return h, nil
}
// exponential backoff (with jitter)
// 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation
func backoffTimeout(attempt uint16) time.Duration {
// nolint:gosec // G404: Use of weak random number generator
return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond
}
| NewWithClientAndOptions |
urls.py | """plantara URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views | 1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from plantara.contrib.users.views import UserViewSet, ObtainAuthToken
from plantara.contrib.plants.views import PlantViewSet
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="user")
router.register(r"plants", PlantViewSet, basename="plant")
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include(router.urls)),
path("api/auth/", include("rest_framework.urls")),
path("api/token/", ObtainAuthToken.as_view()),
]
if settings.DEBUG:
import debug_toolbar # NOQA
urlpatterns += [path("__debug__/", include(debug_toolbar.urls))] | |
validation.py | """
Validator for a regular language.
"""
from typing import Dict
from prompt_toolkit.document import Document
from prompt_toolkit.validation import ValidationError, Validator
from .compiler import _CompiledGrammar
__all__ = [
"GrammarValidator",
]
class GrammarValidator(Validator):
"""
Validator which can be used for validation according to variables in
the grammar. Each variable can have its own validator.
:param compiled_grammar: `GrammarCompleter` instance.
:param validators: `dict` mapping variable names of the grammar to the
`Validator` instances to be used for each variable.
"""
def __init__(
self, compiled_grammar: _CompiledGrammar, validators: Dict[str, Validator]
) -> None:
self.compiled_grammar = compiled_grammar
self.validators = validators
def validate(self, document: Document) -> None:
# Parse input document.
# We use `match`, not `match_prefix`, because for validation, we want
# the actual, unambiguous interpretation of the input.
m = self.compiled_grammar.match(document.text)
if m:
for v in m.variables():
validator = self.validators.get(v.varname)
if validator:
# Unescape text.
unwrapped_text = self.compiled_grammar.unescape(v.varname, v.value)
# Create a document, for the completions API (text/cursor_position)
inner_document = Document(unwrapped_text, len(unwrapped_text))
try:
validator.validate(inner_document)
except ValidationError as e:
raise ValidationError(
cursor_position=v.start + e.cursor_position,
message=e.message,
)
else:
| raise ValidationError(
cursor_position=len(document.text), message="Invalid command"
) |
|
script.js | function palindrome(str) {
//lowercase the string and use a regular expression to remove unwanted characters
var re = /[^A-Za-z0–9]/g;
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
| palindrome("tacocat"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.