hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
647f1fe4774e538273d34a059131d141fdfba169 | 4,320 | sql | SQL | backend/src/main/resources/db/migration/V0001__init.sql | Ninja-Squad/rare-basket | a20a76b80fcbf88ca7050228668ebad4b87d20e7 | [
"BSD-3-Clause"
] | null | null | null | backend/src/main/resources/db/migration/V0001__init.sql | Ninja-Squad/rare-basket | a20a76b80fcbf88ca7050228668ebad4b87d20e7 | [
"BSD-3-Clause"
] | 5 | 2022-03-04T18:56:37.000Z | 2022-03-25T08:38:46.000Z | backend/src/main/resources/db/migration/V0001__init.sql | Ninja-Squad/rare-basket | a20a76b80fcbf88ca7050228668ebad4b87d20e7 | [
"BSD-3-Clause"
] | null | null | null | CREATE TABLE grc (
id BIGINT PRIMARY KEY,
name VARCHAR NOT NULL UNIQUE,
institution VARCHAR NOT NULL,
address VARCHAR NOT NULL
);
CREATE SEQUENCE grc_seq START WITH 1001 INCREMENT 50;
CREATE TABLE accession_holder (
id BIGINT PRIMARY KEY,
name VARCHAR NOT NULL UNIQUE,
email VARCHAR NOT NULL UNIQUE,
phone VARCHAR NOT NULL,
grc_id BIGINT NOT NULL
CONSTRAINT accession_holder_fk1 REFERENCES grc(id)
);
CREATE SEQUENCE accession_holder_seq START WITH 1001 INCREMENT 50;
CREATE TABLE basket (
id BIGINT PRIMARY KEY,
reference VARCHAR NOT NULL UNIQUE,
customer_name VARCHAR,
customer_organization VARCHAR,
customer_email VARCHAR,
customer_delivery_address VARCHAR,
customer_billing_address VARCHAR,
customer_type VARCHAR,
customer_language VARCHAR,
status VARCHAR NOT NULL,
creation_instant TIMESTAMPTZ NOT NULL,
rationale VARCHAR,
confirmation_code VARCHAR,
confirmation_instant TIMESTAMPTZ
);
CREATE SEQUENCE basket_seq START WITH 1001 INCREMENT 50;
CREATE TABLE basket_item (
id BIGINT PRIMARY KEY,
accession_name VARCHAR NOT NULL,
accession_identifier VARCHAR NOT NULL,
quantity INT,
unit VARCHAR,
basket_id BIGINT NOT NULL
CONSTRAINT basket_item_fk1 REFERENCES basket(id),
accession_holder_id BIGINT NOT NULL
CONSTRAINT basket_item_fk2 REFERENCES accession_holder(id)
);
CREATE INDEX basket_item_idx1 ON basket_item(basket_id);
CREATE SEQUENCE basket_item_seq START WITH 1001 INCREMENT 50;
CREATE TABLE accession_order (
id BIGINT PRIMARY KEY,
basket_id BIGINT NOT NULL
CONSTRAINT accession_order_fk1 REFERENCES basket(id),
accession_holder_id BIGINT NOT NULL
CONSTRAINT accession_order_fk2 REFERENCES accession_holder(id),
status VARCHAR NOT NULL,
closing_instant TIMESTAMPTZ
);
CREATE INDEX accession_order_idx1 ON accession_order(accession_holder_id);
CREATE TABLE accession_order_item (
id BIGINT PRIMARY KEY,
accession_name VARCHAR NOT NULL,
accession_identifier VARCHAR NOT NULL,
quantity INT,
unit VARCHAR,
order_id BIGINT NOT NULL
CONSTRAINT accession_order_item_fk1 REFERENCES accession_order(id)
);
CREATE INDEX accession_order_item_idx1 ON accession_order_item(order_id);
CREATE SEQUENCE accession_order_item_seq START WITH 1001 INCREMENT 50;
CREATE SEQUENCE accession_order_seq START WITH 1001 INCREMENT 50;
CREATE TABLE document (
id BIGINT PRIMARY KEY,
type VARCHAR NOT NULL,
description VARCHAR,
creation_instant TIMESTAMPTZ,
content_type VARCHAR NOT NULL,
original_file_name VARCHAR NOT NULL,
on_delivery_form BOOLEAN NOT NULL
);
CREATE SEQUENCE document_seq START WITH 1001 INCREMENT 50;
CREATE TABLE accession_order_document (
order_id BIGINT NOT NULL
CONSTRAINT accession_order_document_fk1 REFERENCES accession_order(id),
document_id BIGINT NOT NULL
CONSTRAINT accession_order_document_fk2 REFERENCES document(id),
PRIMARY KEY (order_id, document_id)
);
CREATE TABLE app_user (
id BIGINT PRIMARY KEY,
name VARCHAR NOT NULL UNIQUE,
global_visualization BOOLEAN NOT NULL,
accession_holder_id BIGINT
CONSTRAINT app_user_fk1 REFERENCES accession_holder(id)
);
CREATE SEQUENCE app_user_seq START WITH 1001 INCREMENT 50;
CREATE TABLE user_permission (
id BIGINT PRIMARY KEY,
permission VARCHAR NOT NULL,
user_id BIGINT NOT NULL
CONSTRAINT user_permission_fk1 REFERENCES app_user(id)
);
CREATE SEQUENCE user_permission_seq START WITH 1001 INCREMENT 50;
CREATE TABLE user_visualization_grc (
user_id BIGINT NOT NULL
CONSTRAINT user_visualization_grc_fk1 REFERENCES app_user(id),
grc_id BIGINT NOT NULL
CONSTRAINT user_visualization_grc_fk2 REFERENCES grc(id),
PRIMARY KEY (user_id, grc_id)
)
| 34.015748 | 79 | 0.687963 |
5649d4af01b9f35a81315940f14a92ede04b4d44 | 42,745 | go | Go | pkg/logproto/metrics.pb.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | pkg/logproto/metrics.pb.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | pkg/logproto/metrics.pb.go | RickyC0626/loki | 3d941ccccbcc6109224dce1845f7aaead30d5ddf | [
"Apache-2.0"
] | null | null | null | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: pkg/logproto/metrics.proto
package logproto
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
reflect "reflect"
strconv "strconv"
strings "strings"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type WriteRequest_SourceEnum int32
const (
API WriteRequest_SourceEnum = 0
RULE WriteRequest_SourceEnum = 1
)
var WriteRequest_SourceEnum_name = map[int32]string{
0: "API",
1: "RULE",
}
var WriteRequest_SourceEnum_value = map[string]int32{
"API": 0,
"RULE": 1,
}
func (WriteRequest_SourceEnum) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{0, 0}
}
type MetricMetadata_MetricType int32
const (
UNKNOWN MetricMetadata_MetricType = 0
COUNTER MetricMetadata_MetricType = 1
GAUGE MetricMetadata_MetricType = 2
HISTOGRAM MetricMetadata_MetricType = 3
GAUGEHISTOGRAM MetricMetadata_MetricType = 4
SUMMARY MetricMetadata_MetricType = 5
INFO MetricMetadata_MetricType = 6
STATESET MetricMetadata_MetricType = 7
)
var MetricMetadata_MetricType_name = map[int32]string{
0: "UNKNOWN",
1: "COUNTER",
2: "GAUGE",
3: "HISTOGRAM",
4: "GAUGEHISTOGRAM",
5: "SUMMARY",
6: "INFO",
7: "STATESET",
}
var MetricMetadata_MetricType_value = map[string]int32{
"UNKNOWN": 0,
"COUNTER": 1,
"GAUGE": 2,
"HISTOGRAM": 3,
"GAUGEHISTOGRAM": 4,
"SUMMARY": 5,
"INFO": 6,
"STATESET": 7,
}
func (MetricMetadata_MetricType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{3, 0}
}
type WriteRequest struct {
Timeseries []PreallocTimeseries `protobuf:"bytes,1,rep,name=timeseries,proto3,customtype=PreallocTimeseries" json:"timeseries"`
Source WriteRequest_SourceEnum `protobuf:"varint,2,opt,name=Source,proto3,enum=logproto.WriteRequest_SourceEnum" json:"Source,omitempty"`
Metadata []*MetricMetadata `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty"`
SkipLabelNameValidation bool `protobuf:"varint,1000,opt,name=skip_label_name_validation,json=skipLabelNameValidation,proto3" json:"skip_label_name_validation,omitempty"`
}
func (m *WriteRequest) Reset() { *m = WriteRequest{} }
func (*WriteRequest) ProtoMessage() {}
func (*WriteRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{0}
}
func (m *WriteRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *WriteRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_WriteRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *WriteRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_WriteRequest.Merge(m, src)
}
func (m *WriteRequest) XXX_Size() int {
return m.Size()
}
func (m *WriteRequest) XXX_DiscardUnknown() {
xxx_messageInfo_WriteRequest.DiscardUnknown(m)
}
var xxx_messageInfo_WriteRequest proto.InternalMessageInfo
func (m *WriteRequest) GetSource() WriteRequest_SourceEnum {
if m != nil {
return m.Source
}
return API
}
func (m *WriteRequest) GetMetadata() []*MetricMetadata {
if m != nil {
return m.Metadata
}
return nil
}
func (m *WriteRequest) GetSkipLabelNameValidation() bool {
if m != nil {
return m.SkipLabelNameValidation
}
return false
}
type WriteResponse struct {
}
func (m *WriteResponse) Reset() { *m = WriteResponse{} }
func (*WriteResponse) ProtoMessage() {}
func (*WriteResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{1}
}
func (m *WriteResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *WriteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_WriteResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *WriteResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_WriteResponse.Merge(m, src)
}
func (m *WriteResponse) XXX_Size() int {
return m.Size()
}
func (m *WriteResponse) XXX_DiscardUnknown() {
xxx_messageInfo_WriteResponse.DiscardUnknown(m)
}
var xxx_messageInfo_WriteResponse proto.InternalMessageInfo
type TimeSeries struct {
Labels []LabelAdapter `protobuf:"bytes,1,rep,name=labels,proto3,customtype=LabelAdapter" json:"labels"`
// Sorted by time, oldest sample first.
Samples []LegacySample `protobuf:"bytes,2,rep,name=samples,proto3" json:"samples"`
}
func (m *TimeSeries) Reset() { *m = TimeSeries{} }
func (*TimeSeries) ProtoMessage() {}
func (*TimeSeries) Descriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{2}
}
func (m *TimeSeries) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *TimeSeries) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_TimeSeries.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *TimeSeries) XXX_Merge(src proto.Message) {
xxx_messageInfo_TimeSeries.Merge(m, src)
}
func (m *TimeSeries) XXX_Size() int {
return m.Size()
}
func (m *TimeSeries) XXX_DiscardUnknown() {
xxx_messageInfo_TimeSeries.DiscardUnknown(m)
}
var xxx_messageInfo_TimeSeries proto.InternalMessageInfo
func (m *TimeSeries) GetSamples() []LegacySample {
if m != nil {
return m.Samples
}
return nil
}
type MetricMetadata struct {
Type MetricMetadata_MetricType `protobuf:"varint,1,opt,name=type,proto3,enum=logproto.MetricMetadata_MetricType" json:"type,omitempty"`
MetricFamilyName string `protobuf:"bytes,2,opt,name=metric_family_name,json=metricFamilyName,proto3" json:"metric_family_name,omitempty"`
Help string `protobuf:"bytes,4,opt,name=help,proto3" json:"help,omitempty"`
Unit string `protobuf:"bytes,5,opt,name=unit,proto3" json:"unit,omitempty"`
}
func (m *MetricMetadata) Reset() { *m = MetricMetadata{} }
func (*MetricMetadata) ProtoMessage() {}
func (*MetricMetadata) Descriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{3}
}
func (m *MetricMetadata) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MetricMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MetricMetadata.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MetricMetadata) XXX_Merge(src proto.Message) {
xxx_messageInfo_MetricMetadata.Merge(m, src)
}
func (m *MetricMetadata) XXX_Size() int {
return m.Size()
}
func (m *MetricMetadata) XXX_DiscardUnknown() {
xxx_messageInfo_MetricMetadata.DiscardUnknown(m)
}
var xxx_messageInfo_MetricMetadata proto.InternalMessageInfo
func (m *MetricMetadata) GetType() MetricMetadata_MetricType {
if m != nil {
return m.Type
}
return UNKNOWN
}
func (m *MetricMetadata) GetMetricFamilyName() string {
if m != nil {
return m.MetricFamilyName
}
return ""
}
func (m *MetricMetadata) GetHelp() string {
if m != nil {
return m.Help
}
return ""
}
func (m *MetricMetadata) GetUnit() string {
if m != nil {
return m.Unit
}
return ""
}
type Metric struct {
Labels []LabelAdapter `protobuf:"bytes,1,rep,name=labels,proto3,customtype=LabelAdapter" json:"labels"`
}
func (m *Metric) Reset() { *m = Metric{} }
func (*Metric) ProtoMessage() {}
func (*Metric) Descriptor() ([]byte, []int) {
return fileDescriptor_d2388e514bd0aa0e, []int{4}
}
func (m *Metric) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Metric) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Metric.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Metric) XXX_Merge(src proto.Message) {
xxx_messageInfo_Metric.Merge(m, src)
}
func (m *Metric) XXX_Size() int {
return m.Size()
}
func (m *Metric) XXX_DiscardUnknown() {
xxx_messageInfo_Metric.DiscardUnknown(m)
}
var xxx_messageInfo_Metric proto.InternalMessageInfo
func init() {
proto.RegisterEnum("logproto.WriteRequest_SourceEnum", WriteRequest_SourceEnum_name, WriteRequest_SourceEnum_value)
proto.RegisterEnum("logproto.MetricMetadata_MetricType", MetricMetadata_MetricType_name, MetricMetadata_MetricType_value)
proto.RegisterType((*WriteRequest)(nil), "logproto.WriteRequest")
proto.RegisterType((*WriteResponse)(nil), "logproto.WriteResponse")
proto.RegisterType((*TimeSeries)(nil), "logproto.TimeSeries")
proto.RegisterType((*MetricMetadata)(nil), "logproto.MetricMetadata")
proto.RegisterType((*Metric)(nil), "logproto.Metric")
}
func init() { proto.RegisterFile("pkg/logproto/metrics.proto", fileDescriptor_d2388e514bd0aa0e) }
var fileDescriptor_d2388e514bd0aa0e = []byte{
// 631 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0xcd, 0x6e, 0xd3, 0x40,
0x10, 0xf6, 0x26, 0x69, 0x92, 0x4e, 0x7f, 0xb0, 0x56, 0x15, 0x98, 0x20, 0x6d, 0x8a, 0xe1, 0xd0,
0x03, 0x24, 0x52, 0x91, 0x40, 0x20, 0x2e, 0x09, 0x4a, 0x43, 0x45, 0xf3, 0xc3, 0xda, 0xa1, 0xa2,
0x97, 0x68, 0x93, 0x6e, 0xd3, 0x55, 0xed, 0xd8, 0xd8, 0x0e, 0x52, 0x6e, 0xbc, 0x00, 0x12, 0x67,
0x9e, 0x80, 0x27, 0xe0, 0x19, 0x7a, 0xec, 0xb1, 0xe2, 0x50, 0x51, 0xf7, 0xd2, 0x63, 0x1f, 0x01,
0x79, 0xed, 0xc4, 0x29, 0x12, 0x37, 0x4e, 0x9e, 0xf9, 0xbe, 0xf9, 0x66, 0x46, 0xdf, 0x78, 0xa1,
0xe4, 0x9e, 0x8c, 0xaa, 0x96, 0x33, 0x72, 0x3d, 0x27, 0x70, 0xaa, 0x36, 0x0f, 0x3c, 0x31, 0xf4,
0x2b, 0x32, 0xc3, 0xc5, 0x19, 0x5e, 0x7a, 0x3a, 0x12, 0xc1, 0xf1, 0x64, 0x50, 0x19, 0x3a, 0x76,
0x75, 0xe4, 0x8c, 0x9c, 0xaa, 0x84, 0x07, 0x93, 0x23, 0x99, 0xc5, 0xda, 0x28, 0x8a, 0x85, 0xa5,
0x07, 0xb7, 0x9a, 0xce, 0x82, 0x98, 0xd4, 0x7f, 0x66, 0x60, 0x75, 0xdf, 0x13, 0x01, 0xa7, 0xfc,
0xd3, 0x84, 0xfb, 0x01, 0xee, 0x02, 0x04, 0xc2, 0xe6, 0x3e, 0xf7, 0x04, 0xf7, 0x35, 0xb4, 0x99,
0xdd, 0x5a, 0xd9, 0xde, 0xa8, 0xcc, 0x55, 0xa6, 0xb0, 0xb9, 0x21, 0xb9, 0x7a, 0xe9, 0xf4, 0xa2,
0xac, 0xfc, 0xba, 0x28, 0xe3, 0xae, 0xc7, 0x99, 0x65, 0x39, 0x43, 0x73, 0xae, 0xa3, 0x0b, 0x3d,
0xf0, 0x4b, 0xc8, 0x1b, 0xce, 0xc4, 0x1b, 0x72, 0x2d, 0xb3, 0x89, 0xb6, 0xd6, 0xb7, 0x1f, 0xa6,
0xdd, 0x16, 0x27, 0x57, 0xe2, 0xa2, 0xc6, 0x78, 0x62, 0xd3, 0x44, 0x80, 0x5f, 0x41, 0xd1, 0xe6,
0x01, 0x3b, 0x64, 0x01, 0xd3, 0xb2, 0x72, 0x15, 0x2d, 0x15, 0xb7, 0xa4, 0x3d, 0xad, 0x84, 0xaf,
0xe7, 0x4e, 0x2f, 0xca, 0x88, 0xce, 0xeb, 0xf1, 0x6b, 0x28, 0xf9, 0x27, 0xc2, 0xed, 0x5b, 0x6c,
0xc0, 0xad, 0xfe, 0x98, 0xd9, 0xbc, 0xff, 0x99, 0x59, 0xe2, 0x90, 0x05, 0xc2, 0x19, 0x6b, 0xd7,
0x85, 0x4d, 0xb4, 0x55, 0xa4, 0xf7, 0xa2, 0x92, 0xbd, 0xa8, 0xa2, 0xcd, 0x6c, 0xfe, 0x61, 0xce,
0xeb, 0x65, 0x80, 0x74, 0x1f, 0x5c, 0x80, 0x6c, 0xad, 0xbb, 0xab, 0x2a, 0xb8, 0x08, 0x39, 0xda,
0xdb, 0x6b, 0xa8, 0x48, 0xbf, 0x03, 0x6b, 0xc9, 0xf6, 0xbe, 0xeb, 0x8c, 0x7d, 0xae, 0x7f, 0x45,
0x00, 0xa9, 0x3b, 0xb8, 0x09, 0x79, 0x39, 0x79, 0xe6, 0xe1, 0xfd, 0x74, 0xf1, 0x3d, 0x3e, 0x62,
0xc3, 0xa9, 0x9c, 0xda, 0x65, 0xc2, 0xab, 0x6f, 0x24, 0x46, 0xae, 0x4a, 0xa8, 0x76, 0xc8, 0xdc,
0x80, 0x7b, 0x34, 0x91, 0xe3, 0xe7, 0x50, 0xf0, 0x99, 0xed, 0x5a, 0xdc, 0xd7, 0x32, 0xb2, 0xd3,
0xdd, 0xbf, 0x3b, 0x19, 0x92, 0x96, 0x06, 0x28, 0x74, 0x56, 0xac, 0x7f, 0xcf, 0xc0, 0xfa, 0x6d,
0x8b, 0xf0, 0x0b, 0xc8, 0x05, 0x53, 0x97, 0x6b, 0x48, 0xde, 0xe1, 0xd1, 0xbf, 0xac, 0x4c, 0x52,
0x73, 0xea, 0x72, 0x2a, 0x05, 0xf8, 0x09, 0xe0, 0xf8, 0x67, 0xec, 0x1f, 0x31, 0x5b, 0x58, 0x53,
0x69, 0xa7, 0x3c, 0xe7, 0x32, 0x55, 0x63, 0x66, 0x47, 0x12, 0x91, 0x8b, 0x18, 0x43, 0xee, 0x98,
0x5b, 0xae, 0x96, 0x93, 0xbc, 0x8c, 0x23, 0x6c, 0x32, 0x16, 0x81, 0xb6, 0x14, 0x63, 0x51, 0xac,
0x4f, 0x01, 0xd2, 0x49, 0x78, 0x05, 0x0a, 0xbd, 0xf6, 0xbb, 0x76, 0x67, 0xbf, 0xad, 0x2a, 0x51,
0xf2, 0xa6, 0xd3, 0x6b, 0x9b, 0x0d, 0xaa, 0x22, 0xbc, 0x0c, 0x4b, 0xcd, 0x5a, 0xaf, 0xd9, 0x50,
0x33, 0x78, 0x0d, 0x96, 0xdf, 0xee, 0x1a, 0x66, 0xa7, 0x49, 0x6b, 0x2d, 0x35, 0x8b, 0x31, 0xac,
0x4b, 0x26, 0xc5, 0x72, 0x91, 0xd4, 0xe8, 0xb5, 0x5a, 0x35, 0xfa, 0x51, 0x5d, 0x8a, 0xee, 0xb5,
0xdb, 0xde, 0xe9, 0xa8, 0x79, 0xbc, 0x0a, 0x45, 0xc3, 0xac, 0x99, 0x0d, 0xa3, 0x61, 0xaa, 0x05,
0xfd, 0x3d, 0xe4, 0xe3, 0xd1, 0xff, 0xed, 0x4e, 0xf5, 0x83, 0xb3, 0x4b, 0xa2, 0x9c, 0x5f, 0x12,
0xe5, 0xe6, 0x92, 0xa0, 0x2f, 0x21, 0x41, 0x3f, 0x42, 0x82, 0x4e, 0x43, 0x82, 0xce, 0x42, 0x82,
0x7e, 0x87, 0x04, 0x5d, 0x87, 0x44, 0xb9, 0x09, 0x09, 0xfa, 0x76, 0x45, 0x94, 0xb3, 0x2b, 0xa2,
0x9c, 0x5f, 0x11, 0xe5, 0xe0, 0xf1, 0xe2, 0x5b, 0xf6, 0xd8, 0x11, 0x1b, 0xb3, 0xaa, 0xe5, 0x9c,
0x88, 0xea, 0xe2, 0xa3, 0x1d, 0xe4, 0xe5, 0xe7, 0xd9, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfb,
0x14, 0x52, 0xd7, 0x20, 0x04, 0x00, 0x00,
}
func (x WriteRequest_SourceEnum) String() string {
s, ok := WriteRequest_SourceEnum_name[int32(x)]
if ok {
return s
}
return strconv.Itoa(int(x))
}
func (x MetricMetadata_MetricType) String() string {
s, ok := MetricMetadata_MetricType_name[int32(x)]
if ok {
return s
}
return strconv.Itoa(int(x))
}
func (this *WriteRequest) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*WriteRequest)
if !ok {
that2, ok := that.(WriteRequest)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.Timeseries) != len(that1.Timeseries) {
return false
}
for i := range this.Timeseries {
if !this.Timeseries[i].Equal(that1.Timeseries[i]) {
return false
}
}
if this.Source != that1.Source {
return false
}
if len(this.Metadata) != len(that1.Metadata) {
return false
}
for i := range this.Metadata {
if !this.Metadata[i].Equal(that1.Metadata[i]) {
return false
}
}
if this.SkipLabelNameValidation != that1.SkipLabelNameValidation {
return false
}
return true
}
func (this *WriteResponse) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*WriteResponse)
if !ok {
that2, ok := that.(WriteResponse)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
return true
}
func (this *TimeSeries) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*TimeSeries)
if !ok {
that2, ok := that.(TimeSeries)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.Labels) != len(that1.Labels) {
return false
}
for i := range this.Labels {
if !this.Labels[i].Equal(that1.Labels[i]) {
return false
}
}
if len(this.Samples) != len(that1.Samples) {
return false
}
for i := range this.Samples {
if !this.Samples[i].Equal(&that1.Samples[i]) {
return false
}
}
return true
}
func (this *MetricMetadata) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*MetricMetadata)
if !ok {
that2, ok := that.(MetricMetadata)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Type != that1.Type {
return false
}
if this.MetricFamilyName != that1.MetricFamilyName {
return false
}
if this.Help != that1.Help {
return false
}
if this.Unit != that1.Unit {
return false
}
return true
}
func (this *Metric) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Metric)
if !ok {
that2, ok := that.(Metric)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.Labels) != len(that1.Labels) {
return false
}
for i := range this.Labels {
if !this.Labels[i].Equal(that1.Labels[i]) {
return false
}
}
return true
}
func (this *WriteRequest) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&logproto.WriteRequest{")
s = append(s, "Timeseries: "+fmt.Sprintf("%#v", this.Timeseries)+",\n")
s = append(s, "Source: "+fmt.Sprintf("%#v", this.Source)+",\n")
if this.Metadata != nil {
s = append(s, "Metadata: "+fmt.Sprintf("%#v", this.Metadata)+",\n")
}
s = append(s, "SkipLabelNameValidation: "+fmt.Sprintf("%#v", this.SkipLabelNameValidation)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *WriteResponse) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 4)
s = append(s, "&logproto.WriteResponse{")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *TimeSeries) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 6)
s = append(s, "&logproto.TimeSeries{")
s = append(s, "Labels: "+fmt.Sprintf("%#v", this.Labels)+",\n")
if this.Samples != nil {
vs := make([]*LegacySample, len(this.Samples))
for i := range vs {
vs[i] = &this.Samples[i]
}
s = append(s, "Samples: "+fmt.Sprintf("%#v", vs)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *MetricMetadata) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 8)
s = append(s, "&logproto.MetricMetadata{")
s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
s = append(s, "MetricFamilyName: "+fmt.Sprintf("%#v", this.MetricFamilyName)+",\n")
s = append(s, "Help: "+fmt.Sprintf("%#v", this.Help)+",\n")
s = append(s, "Unit: "+fmt.Sprintf("%#v", this.Unit)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *Metric) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&logproto.Metric{")
s = append(s, "Labels: "+fmt.Sprintf("%#v", this.Labels)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func valueToGoStringMetrics(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func (m *WriteRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *WriteRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *WriteRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.SkipLabelNameValidation {
i--
if m.SkipLabelNameValidation {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i--
dAtA[i] = 0x3e
i--
dAtA[i] = 0xc0
}
if len(m.Metadata) > 0 {
for iNdEx := len(m.Metadata) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Metadata[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintMetrics(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if m.Source != 0 {
i = encodeVarintMetrics(dAtA, i, uint64(m.Source))
i--
dAtA[i] = 0x10
}
if len(m.Timeseries) > 0 {
for iNdEx := len(m.Timeseries) - 1; iNdEx >= 0; iNdEx-- {
{
size := m.Timeseries[iNdEx].Size()
i -= size
if _, err := m.Timeseries[iNdEx].MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintMetrics(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *WriteResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *WriteResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *WriteResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *TimeSeries) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *TimeSeries) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *TimeSeries) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Samples) > 0 {
for iNdEx := len(m.Samples) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Samples[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintMetrics(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
}
}
if len(m.Labels) > 0 {
for iNdEx := len(m.Labels) - 1; iNdEx >= 0; iNdEx-- {
{
size := m.Labels[iNdEx].Size()
i -= size
if _, err := m.Labels[iNdEx].MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintMetrics(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func (m *MetricMetadata) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MetricMetadata) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MetricMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Unit) > 0 {
i -= len(m.Unit)
copy(dAtA[i:], m.Unit)
i = encodeVarintMetrics(dAtA, i, uint64(len(m.Unit)))
i--
dAtA[i] = 0x2a
}
if len(m.Help) > 0 {
i -= len(m.Help)
copy(dAtA[i:], m.Help)
i = encodeVarintMetrics(dAtA, i, uint64(len(m.Help)))
i--
dAtA[i] = 0x22
}
if len(m.MetricFamilyName) > 0 {
i -= len(m.MetricFamilyName)
copy(dAtA[i:], m.MetricFamilyName)
i = encodeVarintMetrics(dAtA, i, uint64(len(m.MetricFamilyName)))
i--
dAtA[i] = 0x12
}
if m.Type != 0 {
i = encodeVarintMetrics(dAtA, i, uint64(m.Type))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *Metric) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Metric) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *Metric) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Labels) > 0 {
for iNdEx := len(m.Labels) - 1; iNdEx >= 0; iNdEx-- {
{
size := m.Labels[iNdEx].Size()
i -= size
if _, err := m.Labels[iNdEx].MarshalTo(dAtA[i:]); err != nil {
return 0, err
}
i = encodeVarintMetrics(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func encodeVarintMetrics(dAtA []byte, offset int, v uint64) int {
offset -= sovMetrics(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *WriteRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Timeseries) > 0 {
for _, e := range m.Timeseries {
l = e.Size()
n += 1 + l + sovMetrics(uint64(l))
}
}
if m.Source != 0 {
n += 1 + sovMetrics(uint64(m.Source))
}
if len(m.Metadata) > 0 {
for _, e := range m.Metadata {
l = e.Size()
n += 1 + l + sovMetrics(uint64(l))
}
}
if m.SkipLabelNameValidation {
n += 3
}
return n
}
func (m *WriteResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *TimeSeries) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Labels) > 0 {
for _, e := range m.Labels {
l = e.Size()
n += 1 + l + sovMetrics(uint64(l))
}
}
if len(m.Samples) > 0 {
for _, e := range m.Samples {
l = e.Size()
n += 1 + l + sovMetrics(uint64(l))
}
}
return n
}
func (m *MetricMetadata) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovMetrics(uint64(m.Type))
}
l = len(m.MetricFamilyName)
if l > 0 {
n += 1 + l + sovMetrics(uint64(l))
}
l = len(m.Help)
if l > 0 {
n += 1 + l + sovMetrics(uint64(l))
}
l = len(m.Unit)
if l > 0 {
n += 1 + l + sovMetrics(uint64(l))
}
return n
}
func (m *Metric) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Labels) > 0 {
for _, e := range m.Labels {
l = e.Size()
n += 1 + l + sovMetrics(uint64(l))
}
}
return n
}
func sovMetrics(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozMetrics(x uint64) (n int) {
return sovMetrics(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *WriteRequest) String() string {
if this == nil {
return "nil"
}
repeatedStringForMetadata := "[]*MetricMetadata{"
for _, f := range this.Metadata {
repeatedStringForMetadata += strings.Replace(f.String(), "MetricMetadata", "MetricMetadata", 1) + ","
}
repeatedStringForMetadata += "}"
s := strings.Join([]string{`&WriteRequest{`,
`Timeseries:` + fmt.Sprintf("%v", this.Timeseries) + `,`,
`Source:` + fmt.Sprintf("%v", this.Source) + `,`,
`Metadata:` + repeatedStringForMetadata + `,`,
`SkipLabelNameValidation:` + fmt.Sprintf("%v", this.SkipLabelNameValidation) + `,`,
`}`,
}, "")
return s
}
func (this *WriteResponse) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&WriteResponse{`,
`}`,
}, "")
return s
}
func (this *TimeSeries) String() string {
if this == nil {
return "nil"
}
repeatedStringForSamples := "[]LegacySample{"
for _, f := range this.Samples {
repeatedStringForSamples += fmt.Sprintf("%v", f) + ","
}
repeatedStringForSamples += "}"
s := strings.Join([]string{`&TimeSeries{`,
`Labels:` + fmt.Sprintf("%v", this.Labels) + `,`,
`Samples:` + repeatedStringForSamples + `,`,
`}`,
}, "")
return s
}
func (this *MetricMetadata) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&MetricMetadata{`,
`Type:` + fmt.Sprintf("%v", this.Type) + `,`,
`MetricFamilyName:` + fmt.Sprintf("%v", this.MetricFamilyName) + `,`,
`Help:` + fmt.Sprintf("%v", this.Help) + `,`,
`Unit:` + fmt.Sprintf("%v", this.Unit) + `,`,
`}`,
}, "")
return s
}
func (this *Metric) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&Metric{`,
`Labels:` + fmt.Sprintf("%v", this.Labels) + `,`,
`}`,
}, "")
return s
}
func valueToStringMetrics(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *WriteRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: WriteRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: WriteRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timeseries", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Timeseries = append(m.Timeseries, PreallocTimeseries{})
if err := m.Timeseries[len(m.Timeseries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType)
}
m.Source = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Source |= WriteRequest_SourceEnum(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Metadata = append(m.Metadata, &MetricMetadata{})
if err := m.Metadata[len(m.Metadata)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 1000:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field SkipLabelNameValidation", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.SkipLabelNameValidation = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipMetrics(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *WriteResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: WriteResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: WriteResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipMetrics(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *TimeSeries) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: TimeSeries: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: TimeSeries: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Labels = append(m.Labels, LabelAdapter{})
if err := m.Labels[len(m.Labels)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Samples", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Samples = append(m.Samples, LegacySample{})
if err := m.Samples[len(m.Samples)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipMetrics(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MetricMetadata) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MetricMetadata: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MetricMetadata: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= MetricMetadata_MetricType(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MetricFamilyName", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.MetricFamilyName = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Help", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Help = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Unit", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Unit = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipMetrics(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Metric) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Metric: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Metric: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMetrics
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthMetrics
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthMetrics
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Labels = append(m.Labels, LabelAdapter{})
if err := m.Labels[len(m.Labels)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipMetrics(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMetrics
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipMetrics(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthMetrics
}
iNdEx += length
if iNdEx < 0 {
return 0, ErrInvalidLengthMetrics
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipMetrics(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
if iNdEx < 0 {
return 0, ErrInvalidLengthMetrics
}
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthMetrics = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowMetrics = fmt.Errorf("proto: integer overflow")
)
| 24.411765 | 189 | 0.625664 |
40c903e5b6a40b582f2bef01e29c1aab33ccae19 | 9,767 | py | Python | app/libs/asset.py | anjali-92/tuesday | e85366ee4d88e3821d6a3177881dfbf050dd7c34 | [
"MIT"
] | 6 | 2019-04-04T06:10:56.000Z | 2020-06-09T22:30:08.000Z | app/libs/asset.py | anjali-92/tuesday | e85366ee4d88e3821d6a3177881dfbf050dd7c34 | [
"MIT"
] | 2 | 2019-04-05T04:38:45.000Z | 2019-08-16T11:17:43.000Z | app/libs/asset.py | anjali-92/tuesday | e85366ee4d88e3821d6a3177881dfbf050dd7c34 | [
"MIT"
] | 4 | 2019-08-26T06:27:03.000Z | 2020-10-07T11:55:39.000Z | import arrow
import datetime
from converge import settings
from apphelpers.rest.hug import user_id
from apphelpers.errors import NotFoundError
from app.models import Asset, PendingComment, Comment, Member, groups
from app.libs import comment as commentlib
from app.libs import member as memberlib
from app.libs import pending_comment as pendingcommentlib
commenter_fields = [Member.id, Member.username, Member.name, Member.badges]
def create_or_replace(id, url, title, publication, moderation_policy, open_till=None):
asset = get_by_url(url)
if asset:
return asset.id
if open_till is None:
open_till = arrow.utcnow().shift(days=settings.DEFAULT_ASSET_OPEN_DURATION).datetime
asset = Asset.create(
id=id,
url=url,
title=title,
publication=publication,
open_till=open_till,
moderation_policy=moderation_policy
)
return asset.id
def update(id, **mod_data):
updatables = ('title', 'open_till', 'moderation_policy')
update_dict = dict((k, v) for (k, v) in list(mod_data.items()) if k in updatables)
Asset.update(**update_dict).where(Asset.id == id).execute()
update.groups_required = [groups.moderator.value]
def exists(id):
return bool(Asset.get_or_none(Asset.id == id))
def get(id):
asset = Asset.get_or_none(Asset.id == id)
if asset:
return asset.to_dict()
def get_all(ids):
assets = Asset.select().where(Asset.id << ids)
return [asset.to_dict() for asset in assets]
def get_by_url(url):
return Asset.get_or_none(Asset.url == url)
def list_():
assets = Asset.select().order_by(Asset.created.desc())
return [
{
'comments_count': asset.comments_count,
'pending_comments_count': asset.pending_comments_count,
'rejected_comments_count': asset.rejected_comments_count,
**asset.to_dict()
}
for asset in assets
]
list_.groups_required = [groups.moderator.value]
def stop(id):
open_till = arrow.utcnow().datetime
update(id, open_till=open_till)
stop.groups_required = [groups.moderator.value]
def stop_all():
open_till = arrow.utcnow().datetime
Asset.update({'open_till': open_till}).where(Asset.open_till > open_till).execute()
stop_all.groups_required = [groups.moderator.value]
def restart(id, open_till=None):
if open_till is None:
open_till = arrow.utcnow().shift(days=settings.DEFAULT_ASSET_OPEN_DURATION).datetime
update(id, open_till=open_till)
restart.groups_required = [groups.moderator.value]
def get_pending_comments(id, parent=0, offset=None, limit=None):
where = [PendingComment.asset == id, PendingComment.parent == parent]
if offset is not None:
where.append(PendingComment.id < offset)
comments = PendingComment.select().where(*where).order_by(PendingComment.id.desc())
if limit:
comments = comments.limit(limit)
return [comment.to_dict() for comment in comments]
def get_approved_comments(id, parent=0, offset=None, limit=None):
where = [Comment.asset == id, Comment.parent == parent]
if offset is not None:
where.append(Comment.id < offset)
comments = Comment.select().where(*where).order_by(Comment.id.desc())
if limit:
comments = comments.limit(limit)
return [comment.to_dict() for comment in comments]
# Todo Add Caching
def get_unfiltered_replies(parent, limit=10, offset=None):
# Getting Approved Comments
approved_replies = commentlib.get_replies(parent=parent, limit=limit, offset=offset)
approved_replies = [
{
**comment,
'pending': False,
'replies': get_unfiltered_replies(parent=comment['id'], limit=limit)
}
for comment in approved_replies
]
# Getting Pending Comments
pending_replies = pendingcommentlib.get_replies(parent=parent, limit=limit, offset=offset)
pending_replies = [{**comment, 'pending': True} for comment in pending_replies]
# Combining Approved & Pending Comments
return sorted(approved_replies + pending_replies, key=lambda x: x['created'])
# Todo Add Caching
def get_unfiltered_comments(id, parent=0, offset=None, limit=None, replies_limit=None):
limit = limit if limit else settings.DEFAULT_COMMENTS_FETCH_LIMIT
replies_limit = replies_limit if replies_limit else settings.DEFAULT_REPLIES_FETCH_LIMIT
# Getting Approved Comments
approved_comments = get_approved_comments(id, parent=parent, offset=offset, limit=limit)
approved_comments = [
{
**comment,
'pending': False,
'replies': get_unfiltered_replies(parent=comment['id'], limit=replies_limit)
}
for comment in approved_comments
]
# Getting Pending Comments
pending_comments = get_pending_comments(id, parent=parent, offset=offset, limit=limit)
pending_comments = [{**comment, 'pending': True} for comment in pending_comments]
# Combining Approved & Pending Comments
return sorted(pending_comments + approved_comments, key=lambda x: x['created'], reverse=True)
get_unfiltered_replies.groups_required = [groups.moderator.value]
def filter_inaccessible_comments(user_id, comments, limit, replies_limit=None):
user_accessible_comments = []
for comment in comments:
if comment['pending'] is False or comment['commenter']['id'] == user_id:
comment['replies'] = filter_inaccessible_comments(
user_id, comment.get('replies', []), replies_limit, replies_limit
)
user_accessible_comments.append(comment)
if limit is not None:
limit -= 1
if limit == 0:
break
return user_accessible_comments
def get_comments(id, user_id: user_id=None, parent=0, offset=None, limit=None, replies_limit=None):
limit = limit if limit else settings.DEFAULT_COMMENTS_FETCH_LIMIT
replies_limit = replies_limit if replies_limit else settings.DEFAULT_REPLIES_FETCH_LIMIT
comments = get_unfiltered_comments(
id, parent=parent, offset=offset,
limit=limit, replies_limit=replies_limit
)
return filter_inaccessible_comments(user_id, comments, limit, replies_limit)
def get_replies(parent, user_id: user_id=None, limit=None, offset=None):
limit = limit if limit else settings.DEFAULT_COMMENTS_FETCH_LIMIT
replies = get_unfiltered_replies(parent=parent, limit=limit, offset=offset)
return filter_inaccessible_comments(user_id, replies, limit, limit)
# Todo Add Caching
def get_approved_comments_count(id):
return Comment.select().where(Comment.asset == id).count()
def get_pending_comments_count(id):
return PendingComment.select().where(PendingComment.asset == id).count()
def get_comments_count(id):
return get_approved_comments_count(id)
def get_comments_view(id, user_id: user_id=None, offset=None, limit: int=None):
view = {"comments": get_comments(id, user_id, offset=offset, limit=limit)}
if user_id: # to support anonymous view
user = memberlib.get_or_create(user_id, fields=['username', 'enabled', 'name'])
view["commenter"] = {
"username": user["username"],
"banned": not user["enabled"],
"name": user["name"]
}
asset = get(id)
view["meta"] = {"commenting_closed": asset["open_till"] <= arrow.utcnow().datetime}
return view
def get_unfiltered_comments_view(id, parent=0, offset=None, limit: int=None):
return {"comments": get_unfiltered_comments(id, parent=parent, offset=offset, limit=limit)}
def get_meta(id):
asset = get(id)
if asset is not None:
return {
'comments_count': get_comments_count(id),
'commenting_closed': asset["open_till"] <= arrow.utcnow().datetime
}
get_meta.not_found_on_none = True
def get_assets_meta(ids):
assets = get_all(ids)
metas = {
asset['id']: {
'comments_count': get_comments_count(asset['id']),
'commenting_closed': asset['open_till'] <= arrow.utcnow().datetime
}
for asset in assets
}
return metas
def get_comment_view(id, comment_id, user_id: user_id=None): #TODO: Remove this. Deprecated
view = {"comment": commentlib.get(comment_id)}
if user_id: # to support anonymous view
user = memberlib.get_or_create(user_id, fields=['username', 'enabled', 'name'])
view["commenter"] = {
"username": user["username"],
"banned": not user["enabled"],
"name": user["name"]
}
asset = get(id)
view["meta"] = {"commenting_closed": asset["open_till"] <= arrow.utcnow().datetime}
return view
def get_with_featured_comments(asset_ids, no_of_comments=1):
commented_assets = Comment.select(
Comment.asset_id
).where(
Comment.asset_id << asset_ids
).distinct()
assets = Asset.select(
).order_by(
Asset.created.desc()
).where(
(Asset.id << asset_ids) &
(
(Asset.open_till > arrow.utcnow().datetime) |
(Asset.id << commented_assets)
)
)
asset_ids = [asset.id for asset in assets]
featured_comments = commentlib.get_featured_comments_for_assets(asset_ids, no_of_comments)
return {
'assets': [
{
'comments_count': asset.comments_count,
'commenting_closed': asset.commenting_closed,
'featured_comments': featured_comments.get(asset.id, []),
**asset.to_dict()
}
for asset in assets
]
}
get_with_featured_comments.groups_required = [groups.moderator.value]
| 33.334471 | 99 | 0.673288 |
bd4b9cdeccd7b757b4270b5b409c081b0f8b227b | 1,616 | swift | Swift | Sources/Dictionary.swift | netguru/picguard-swift | dc0da8f760edba744b1ebd02ab46fd30df44ec85 | [
"MIT"
] | 15 | 2016-05-19T11:43:56.000Z | 2021-10-05T08:17:42.000Z | Sources/Dictionary.swift | netguru/picguard-swift | dc0da8f760edba744b1ebd02ab46fd30df44ec85 | [
"MIT"
] | 1 | 2016-05-20T11:56:38.000Z | 2016-05-20T13:01:57.000Z | Sources/Dictionary.swift | netguru/picguard-swift | dc0da8f760edba744b1ebd02ab46fd30df44ec85 | [
"MIT"
] | 4 | 2016-07-24T04:59:48.000Z | 2020-04-28T15:15:12.000Z | //
// Dictionary.swift
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
internal extension Dictionary {
/// Applies the mapping transform over `self`.
///
/// - Parameter transform: The transformation function.
///
/// - Throws: Rethrows whatever error was thrown by the transform function.
///
/// - Returns: A `Dictionary` containing the results of mapping `transform`
/// over the values of `self`.
func map<T>(@noescape transform: (Value) throws -> T) rethrows -> [Key: T] {
var memo = Dictionary<Key, T>(minimumCapacity: count)
try self.forEach { memo[$0] = try transform($1) }
return memo
}
/// Adds an element to the dictionary.
///
/// - Parameter element: An element to append. Will override value in `self`
/// in case key already exists.
///
/// - Returns: A `Dictionary` containing values of `self` with appended
/// `element`.
func appending(element element: Generator.Element) -> [Key: Value] {
var mutableSelf = self
mutableSelf[element.0] = element.1
return mutableSelf
}
}
/// Compacts `dictionary` by removing `nil` values. Note: This is a free
/// function because a Swift doesn't support `Value`-constrained `Dictionary`
/// extensions (yet).
///
/// - Parameter dictionary: The dictionary to be compacted.
///
/// - Returns: A `Dictionary` containing non-`nil` values of input `dictionary`.
internal func compact<K, V>(dictionary: [K: V?]) -> [K: V] {
return dictionary.reduce([:]) { memo, pair in
if let value = pair.1 {
return memo.appending(element: (pair.0, value))
}
return memo
}
}
| 29.925926 | 80 | 0.67203 |
c7c3e6cf1622b4615ac8a67c8aa6d802571777f5 | 382 | py | Python | ptrack/templatetags/ptrack.py | unformatt/django-ptrack | 9f87b6ed37ec72525de513376f31566bb14d2b9c | [
"Apache-2.0"
] | null | null | null | ptrack/templatetags/ptrack.py | unformatt/django-ptrack | 9f87b6ed37ec72525de513376f31566bb14d2b9c | [
"Apache-2.0"
] | null | null | null | ptrack/templatetags/ptrack.py | unformatt/django-ptrack | 9f87b6ed37ec72525de513376f31566bb14d2b9c | [
"Apache-2.0"
] | null | null | null | """Ptrack Template Tag"""
import logging
from django import template
from django.utils.html import mark_safe
logger = logging.getLogger(__name__)
register = template.Library()
@register.simple_tag
def ptrack(*args, **kwargs):
"""Generate a tracking pixel html img element."""
from ptrack import create_img
img = create_img(*args, **kwargs)
return mark_safe(img)
| 22.470588 | 53 | 0.735602 |
52d9498a7de55014decadcb471a0516cd7251004 | 1,160 | lua | Lua | src/IncludedCommands/BasicCommands/pchat.lua | TheNexusAvenger/Nexus-Admin | 38ae3f128b19af023b3fff137e5bfd695675b310 | [
"MIT"
] | 4 | 2021-04-08T02:10:44.000Z | 2022-03-23T21:34:19.000Z | src/IncludedCommands/BasicCommands/pchat.lua | TheNexusAvenger/Nexus-Admin | 38ae3f128b19af023b3fff137e5bfd695675b310 | [
"MIT"
] | 4 | 2020-07-22T20:08:43.000Z | 2021-01-06T02:32:01.000Z | src/IncludedCommands/BasicCommands/pchat.lua | TheNexusAvenger/Nexus-Admin | 38ae3f128b19af023b3fff137e5bfd695675b310 | [
"MIT"
] | 2 | 2020-07-23T10:05:14.000Z | 2021-07-24T21:57:58.000Z | --[[
TheNexusAvenger
Implementation of a command.
--]]
local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand"))
local Command = BaseCommand:Extend()
--[[
Creates the command.
--]]
function Command:__new()
self:InitializeSuper({"pchat","pc"},"BasicCommands","Starts a private chat between a set of players.")
self.Arguments = {
{
Type = "nexusAdminPlayers",
Name = "Players",
Description = "Players to run the vote for.",
},
{
Type = "string",
Name = "Question",
Description = "Message to send.",
},
}
--Set up the remote objects.
local SendPrivateMessageRemoteEvent = Instance.new("RemoteEvent")
SendPrivateMessageRemoteEvent.Name = "SendPrivateMessage"
SendPrivateMessageRemoteEvent.Parent = self.API.EventContainer
SendPrivateMessageRemoteEvent.OnServerEvent:Connect(function(Player,TargetPlayer,Message)
Message = self.API.Filter:FilterString(Message,Player,TargetPlayer)
SendPrivateMessageRemoteEvent:FireClient(TargetPlayer,Player,Message)
end)
end
return Command | 26.363636 | 106 | 0.668966 |
f43de810d17db031a7b05bdde6c4ee8f889771fb | 501 | go | Go | tests/resources/go/advanced/nullable-omitempty-map-slice/entities_test.go | swaggest/go-code-builder | b3e41b0859797899a13eaf1f43e3cd6070baf1b4 | [
"MIT"
] | 3 | 2019-07-11T19:18:38.000Z | 2020-10-08T07:20:25.000Z | tests/resources/go/advanced/nullable-omitempty-map-slice/entities_test.go | swaggest/go-code-builder | b3e41b0859797899a13eaf1f43e3cd6070baf1b4 | [
"MIT"
] | 34 | 2019-02-14T23:40:03.000Z | 2022-01-02T16:17:12.000Z | tests/resources/go/advanced/nullable-omitempty-map-slice/entities_test.go | swaggest/go-code-builder | b3e41b0859797899a13eaf1f43e3cd6070baf1b4 | [
"MIT"
] | 1 | 2019-10-23T21:19:33.000Z | 2019-10-23T21:19:33.000Z | package entities
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/swaggest/assertjson"
)
func TestRequiredNullable_MarshalJSON_roundtrip(t *testing.T) {
var (
jsonValue = []byte(`{"slice":["aeff"],"map":{"effefd":"dd"}}`)
v RequiredNullable
)
require.NoError(t, json.Unmarshal(jsonValue, &v))
marshaled, err := json.Marshal(v)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(marshaled, &v))
assertjson.Equal(t, jsonValue, marshaled)
}
| 20.875 | 64 | 0.714571 |
84143ee8516adb222832f3006bf3c8bc3542f761 | 737 | ps1 | PowerShell | Get-JenkinsCredential.ps1 | doomjaw87/p0w3rsh3ll | e8446540302668567ab6a43c7106f080446baf59 | [
"MIT"
] | 2 | 2016-10-12T19:34:49.000Z | 2020-01-21T22:21:57.000Z | Get-JenkinsCredential.ps1 | doomjaw87/p0w3rsh3ll | e8446540302668567ab6a43c7106f080446baf59 | [
"MIT"
] | null | null | null | Get-JenkinsCredential.ps1 | doomjaw87/p0w3rsh3ll | e8446540302668567ab6a43c7106f080446baf59 | [
"MIT"
] | 1 | 2016-12-10T15:35:24.000Z | 2016-12-10T15:35:24.000Z | $jenkinsUrl = 'http://10.101.222.4:8080/scriptText'
$apiToken = '11a65a6453b20fb37200d8d2bd20b091a7'
$authUsername = 'automationuser'
$headers = @{Authorization = $("Basic $([System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($authUsername):$($apiToken)")))")}
$script = @"
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
Jenkins.instance,
null,
null
);
for (c in creds) {
println "`${c.id} : `${c.description}"
}
"@
$params = @{Body = "script=$($script)"
Headers = $headers
Uri = $jenkinsUrl
Method = 'Post'}
$response = Invoke-WebRequest @params
$response.Content | 30.708333 | 149 | 0.700136 |
e92005bcb0760c240bb635e95e69b5dbc4b28d8b | 4,211 | go | Go | Godeps/_workspace/src/github.com/golang/geo/s2/s2_test.go | skidder/go-loco | 75216fcc55e1d1af6d75505ccdc04b78f237f812 | [
"Apache-2.0"
] | null | null | null | Godeps/_workspace/src/github.com/golang/geo/s2/s2_test.go | skidder/go-loco | 75216fcc55e1d1af6d75505ccdc04b78f237f812 | [
"Apache-2.0"
] | null | null | null | Godeps/_workspace/src/github.com/golang/geo/s2/s2_test.go | skidder/go-loco | 75216fcc55e1d1af6d75505ccdc04b78f237f812 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package s2
import (
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"github.com/golang/geo/s1"
)
func float64Eq(x, y float64) bool { return math.Abs(x-y) < 1e-14 }
// TODO(roberts): Add in flag to allow specifying the random seed for repeatable tests.
// kmToAngle converts a distance on the Earth's surface to an angle.
func kmToAngle(km float64) s1.Angle {
// The Earth's mean radius in kilometers (according to NASA).
const earthRadiusKm = 6371.01
return s1.Angle(km / earthRadiusKm)
}
// randomBits returns a 64-bit random unsigned integer whose lowest "num" are random, and
// whose other bits are zero.
func randomBits(num uint32) uint64 {
// Make sure the request is for not more than 63 bits.
if num > 63 {
num = 63
}
return uint64(rand.Int63()) & ((1 << num) - 1)
}
// Return a uniformly distributed 64-bit unsigned integer.
func randomUint64() uint64 {
return uint64(rand.Int63() | (rand.Int63() << 63))
}
// Return a uniformly distributed 64-bit unsigned integer.
func randomUint32() uint32 {
return uint32(randomBits(32))
}
// randomFloat64 returns a uniformly distributed value in the range [0,1).
// Note that the values returned are all multiples of 2**-53, which means that
// not all possible values in this range are returned.
func randomFloat64() float64 {
const randomFloatBits = 53
return math.Ldexp(float64(randomBits(randomFloatBits)), -randomFloatBits)
}
// randomUniformDouble returns a uniformly distributed value in the range [min, max).
func randomUniformDouble(min, max float64) float64 {
return min + randomFloat64()*(max-min)
}
// randomPoint returns a random unit-length vector.
func randomPoint() Point {
return Point{PointFromCoords(randomUniformDouble(-1, 1),
randomUniformDouble(-1, 1), randomUniformDouble(-1, 1)).Normalize()}
}
// parsePoint returns an Point from the latitude-longitude coordinate in degrees
// in the given string, or the origin if the string was invalid.
// e.g., "-20:150"
func parsePoint(s string) Point {
p := parsePoints(s)
if len(p) > 0 {
return p[0]
}
return PointFromCoords(0, 0, 0)
}
// parseRect returns the minimal bounding Rect that contains the one or more
// latitude-longitude coordinates in degrees in the given string.
// Examples of input:
// "-20:150" // one point
// "-20:150, -20:151, -19:150" // three points
func parseRect(s string) Rect {
var rect Rect
lls := parseLatLngs(s)
if len(lls) > 0 {
rect = RectFromLatLng(lls[0])
}
for _, ll := range lls[1:] {
rect = rect.AddPoint(ll)
}
return rect
}
// parseLatLngs splits up a string of lat:lng points and returns the list of parsed
// entries.
func parseLatLngs(s string) []LatLng {
pieces := strings.Split(s, ",")
var lls []LatLng
for _, piece := range pieces {
// Skip empty strings.
if len(strings.TrimSpace(piece)) == 0 {
continue
}
p := strings.Split(strings.TrimSpace(piece), ":")
if len(p) != 2 {
panic(fmt.Sprintf("invalid input string for parseLatLngs: %q", piece))
}
lat, err := strconv.ParseFloat(p[0], 64)
if err != nil {
panic(fmt.Sprintf("invalid float in parseLatLngs: %q, err: %v", p[0], err))
}
lng, err := strconv.ParseFloat(p[1], 64)
if err != nil {
panic(fmt.Sprintf("invalid float in parseLatLngs: %q, err: %v", p[1], err))
}
lls = append(lls, LatLngFromDegrees(lat, lng))
}
return lls
}
// parsePoints takes a string of lat:lng points and returns the set of Points it defines.
func parsePoints(s string) []Point {
lls := parseLatLngs(s)
points := make([]Point, len(lls))
for i, ll := range lls {
points[i] = PointFromLatLng(ll)
}
return points
}
| 28.073333 | 89 | 0.703396 |
21c9e121035b36313ae45f65d46876825a8b38c6 | 5,014 | rs | Rust | src/fft.rs | apuranik1/rust-algorithms | a3a20826cb433b35a240388de20cf24379f28c2e | [
"MIT"
] | 2 | 2019-08-30T19:46:16.000Z | 2019-09-03T22:27:16.000Z | src/fft.rs | apuranik1/rust-algorithms | a3a20826cb433b35a240388de20cf24379f28c2e | [
"MIT"
] | null | null | null | src/fft.rs | apuranik1/rust-algorithms | a3a20826cb433b35a240388de20cf24379f28c2e | [
"MIT"
] | null | null | null | use num::complex::Complex64;
use num::Zero;
/// Compute the fourier transform of data
/// The order of the transform is data.len() rounded up to a power of 2
pub fn fft(data: &[Complex64]) -> Vec<Complex64> {
let order = power_of_2_geq_n(data.len());
eval_polynomial(order, true, data, 0, 1)
}
/// Compute the inverse fourier transform of data
/// The order is data.len(), which must be a power of 2
/// If the order is not a power of 2, returns None
pub fn ifft(data: &[Complex64]) -> Option<Vec<Complex64>> {
let order = power_of_2_geq_n(data.len());
if order != data.len() {
None
} else {
let scale_factor = 1.0 / (order as f64);
Some(
eval_polynomial(order, false, data, 0, 1)
.iter()
.map(|v: &Complex64| v.scale(scale_factor))
.collect(),
)
}
}
fn power_of_2_geq_n(n: usize) -> usize {
match n {
0 => 1,
1 => 1,
_ => {
if n % 2 == 0 {
2 * power_of_2_geq_n(n / 2)
} else {
2 * power_of_2_geq_n(n / 2 + 1) // round up
}
}
}
}
/// Evaluate the polynomial given by a_j = coefs[offset + j * stride] at all the roots
/// of unity of order coefs.len() / stride
/// Assumes order is a power of 2 (WILL DO UNEXPECTED THINGS IF IT ISN'T)
fn eval_polynomial(
order: usize,
negative_angle: bool,
coefs: &[Complex64],
offset: usize,
stride: usize,
) -> Vec<Complex64> {
if order == 0 {
panic!("Illegal state: coefs.len() < stride")
} else if order == 1 {
// If it's off the end, then implicitly zero-pad
match coefs.get(offset) {
Some(c) => vec![*c],
None => vec![Complex64::zero()],
}
} else {
let even_result = eval_polynomial(order / 2, negative_angle, coefs, offset, stride * 2);
let odd_result = eval_polynomial(
order / 2,
negative_angle,
coefs,
offset + stride,
stride * 2,
);
let angle =
(if negative_angle { -1.0 } else { 1.0 }) * 2.0 * std::f64::consts::PI / (order as f64);
let half_order = order / 2;
let mut computed = vec![Complex64::new(0.0, 0.0); order];
for (k, (even_part, odd_part)) in
Iterator::zip(even_result.iter(), odd_result.iter()).enumerate()
{
let root = Complex64::from_polar(&(1.0), &(angle * k as f64));
let twiddled = root * odd_part;
computed[k] = even_part + twiddled;
computed[k + half_order] = even_part - twiddled;
}
computed
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_all_close<'a, T: Iterator<Item = &'a Complex64>>(first: T, second: T, tol: f64) {
for (a, b) in Iterator::zip(first, second) {
assert!((b - a).norm_sqr() < tol);
}
}
#[test]
fn test_nearest_power_of_2() {
assert_eq!(power_of_2_geq_n(16), 16);
assert_eq!(power_of_2_geq_n(17), 32);
assert_eq!(power_of_2_geq_n(24), 32);
}
#[test]
fn test_fourier_sin() {
let data = vec![
Complex64::new(0.0, 0.0),
Complex64::new(1.0, 0.0),
Complex64::new(0.0, 0.0),
Complex64::new(-1.0, 0.0),
];
let expected_ft = vec![
Complex64::new(0.0, 0.0),
Complex64::new(0.0, -2.0),
Complex64::new(0.0, 0.0),
Complex64::new(0.0, 2.0),
];
let fourier = fft(&data);
assert_all_close(expected_ft.iter(), fourier.iter(), 1e-12);
}
#[test]
fn test_fourier_cos() {
let data = vec![
Complex64::new(1.0, 0.0),
Complex64::new(0.0, 0.0),
Complex64::new(-1.0, 0.0),
];
let expected_ft = vec![
Complex64::new(0.0, 0.0),
Complex64::new(2.0, 0.0),
Complex64::new(0.0, 0.0),
Complex64::new(2.0, 0.0),
];
let fourier = fft(&data);
assert_all_close(expected_ft.iter(), fourier.iter(), 1e-12);
}
#[test]
fn test_inverse_fourier_sin() {
let data = vec![
Complex64::new(0.0, 0.0),
Complex64::new(0.0, -2.0),
Complex64::new(0.0, 0.0),
Complex64::new(0.0, 2.0),
];
let expected_ift = vec![
Complex64::new(0.0, 0.0),
Complex64::new(1.0, 0.0),
Complex64::new(0.0, 0.0),
Complex64::new(-1.0, 0.0),
];
let inv_fourier = ifft(&data).unwrap();
assert_all_close(expected_ift.iter(), inv_fourier.iter(), 1e-12);
}
#[test]
fn test_big_fourier_roundtrip() {
let data: Vec<Complex64> = (0..10000).map(|x| Complex64::new(x as f64, 0.0)).collect();
let reconstructed = ifft(&fft(&data)).unwrap();
assert_all_close(data.iter(), reconstructed.iter(), 1e-12);
}
}
| 30.760736 | 100 | 0.515955 |
291d411557920f0dd714b8cb09d8459149ffc80d | 3,350 | py | Python | kaggle_cat-in-the-dat.py | ak110/applications | d5266f72f912991b255c572ac268e4cee6c57145 | [
"MIT"
] | null | null | null | kaggle_cat-in-the-dat.py | ak110/applications | d5266f72f912991b255c572ac268e4cee6c57145 | [
"MIT"
] | null | null | null | kaggle_cat-in-the-dat.py | ak110/applications | d5266f72f912991b255c572ac268e4cee6c57145 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""Categorical Feature Encoding Challengeの実験用コード。"""
import pathlib
import numpy as np
import pandas as pd
import sklearn.metrics
import pytoolkit as tk
nfold = 5
params = {
"objective": "binary",
"metric": "auc",
"learning_rate": 0.01,
"nthread": -1,
# "verbosity": -1,
# "max_bin": 511,
# "num_leaves": 31,
# "min_data_in_leaf": 10,
"feature_fraction": "sqrt",
"bagging_freq": 0,
# "max_depth": 4,
}
seeds = np.arange(5) + 1
# split_seeds = np.arange(5) + 1
data_dir = pathlib.Path("data/kaggle_cat-in-the-dat")
models_dir = pathlib.Path(f"models/{pathlib.Path(__file__).stem}")
app = tk.cli.App(output_dir=models_dir)
logger = tk.log.get(__name__)
@app.command()
def train():
train_set = load_train_data()
folds = tk.validation.split(train_set, nfold, split_seed=1)
create_model().cv(train_set, folds)
validate()
@app.command()
def validate():
train_set = load_train_data()
folds = tk.validation.split(train_set, nfold, split_seed=1)
model = create_model().load()
oofp = model.predict_oof(train_set, folds)
tk.notifications.post_evals(
{"auc": sklearn.metrics.roc_auc_score(train_set.labels, oofp)}
)
predict()
@app.command()
def predict():
# TODO: ValueError: Unknown values in column 'nom_8': {'2be51c868', '1f0a80e1d', 'ec337ce4c', 'a9bf3dc47'}
test_set = load_test_data()
model = create_model().load()
pred = model.predict(test_set)
df = pd.DataFrame()
df["id"] = test_set.ids
df["target"] = pred
df.to_csv(models_dir / "submission.csv", index=False)
def load_train_data():
df = pd.read_csv(data_dir / "train.csv")
return _preprocess(df)
def load_test_data():
df = pd.read_csv(data_dir / "test.csv")
return _preprocess(df)
def _preprocess(df):
df["bin_0"] = tk.preprocessing.encode_binary(df["bin_0"], 1, 0)
df["bin_1"] = tk.preprocessing.encode_binary(df["bin_1"], 1, 0)
df["bin_2"] = tk.preprocessing.encode_binary(df["bin_2"], 1, 0)
df["bin_3"] = tk.preprocessing.encode_binary(df["bin_3"], "T", "F")
df["bin_4"] = tk.preprocessing.encode_binary(df["bin_4"], "Y", "N")
df["ord_1"] = tk.preprocessing.encode_ordinal(
df["ord_1"], ["Novice", "Contributor", "Expert", "Master", "Grandmaster"]
)
df["ord_2"] = tk.preprocessing.encode_ordinal(
df["ord_2"], ["Freezing", "Cold", "Warm", "Hot", "Boiling Hot", "Lava Hot"]
)
df["ord_3"] = df["ord_3"].map(ord).astype(np.int32)
df["ord_4"] = df["ord_4"].map(ord).astype(np.int32)
df["ord_5"] = (
df["ord_5"].apply(lambda s: ord(s[0]) * 255 + ord(s[1])).astype(np.int32)
)
df[["day_sin", "day_cos"]] = tk.preprocessing.encode_cyclic(df["day"], 1, 7 + 1)
df[["month_sin", "month_cos"]] = tk.preprocessing.encode_cyclic(
df["month"], 1, 12 + 1
)
if "target" in df.columns.values:
return tk.data.Dataset(
data=df.drop(columns=["target"]), labels=df["target"].values
)
else:
return tk.data.Dataset(data=df)
def create_model():
return tk.pipeline.LGBModel(
params=params,
nfold=nfold,
models_dir=models_dir,
seeds=seeds,
preprocessors=[tk.preprocessing.FeaturesEncoder()],
)
if __name__ == "__main__":
app.run(default="train")
| 28.87931 | 110 | 0.630746 |
727154cbff659f1f6ccdad720c9a42510f1e4220 | 774 | sql | SQL | truncate_all.sql | tim-hub/AdventureWorks | 8b51197180d9dbed1b2d0c9df2609c2bde1fc676 | [
"Apache-2.0"
] | 1 | 2021-12-11T06:06:32.000Z | 2021-12-11T06:06:32.000Z | truncate_all.sql | tim-hub/AdventureWorks | 8b51197180d9dbed1b2d0c9df2609c2bde1fc676 | [
"Apache-2.0"
] | null | null | null | truncate_all.sql | tim-hub/AdventureWorks | 8b51197180d9dbed1b2d0c9df2609c2bde1fc676 | [
"Apache-2.0"
] | 1 | 2021-04-26T16:37:38.000Z | 2021-04-26T16:37:38.000Z | TRUNCATE TABLE EmployeeJobTitleRejectLog11 ;
TRUNCATE TABLE EmployeeHireDateRejectLog12 ;
TRUNCATE TABLE EmployeeJobTitleAllow24 ;
TRUNCATE TABLE EmployeeHireDateAllow25 ;
TRUNCATE TABLE PersonStaging ;
TRUNCATE TABLE PersonAllNamesNullRejectLog9 ;
TRUNCATE TABLE PersonTypeReject10 ;
TRUNCATE TABLE PersonTypeEmptyRejectLog23 ;
TRUNCATE TABLE PersonNameFixLog22 ;
TRUNCATE TABLE SubCategoryNameFixLog18 ;
TRUNCATE TABLE SubCategoryStaging ;
TRUNCATE TABLE SalesPersonIDRejectLog8 ;
TRUNCATE TABLE OrderQtyLog_1 ;
TRUNCATE TABLE OrderQtyLog14 ;
TRUNCATE TABLE ProductIDRjectLog4 ;
TRUNCATE TABLE ProductIDRjectLog17 ;
TRUNCATE TABLE SubCategoryIdNullRejectLog5 ;
TRUNCATE TABLE factStaging ;
TRUNCATE TABLE PersonAnyNameNullFix54 ;
TRUNCATE TABLE SalesPersonIDNullReject59 ; | 38.7 | 45 | 0.872093 |
5c865d5f2f02d8058581fc244338a4a42bcaa531 | 2,452 | css | CSS | assets/js/plugins/loaders/pace-corner-indicator.css | Eze4Manuel/Emmet-Blue-Ui | 05374a377985301225c02187258c2ac96a84807e | [
"MIT"
] | 1 | 2016-07-05T21:30:56.000Z | 2016-07-05T21:30:56.000Z | assets/js/plugins/loaders/pace-corner-indicator.css | Eze4Manuel/Emmet-Blue-Ui | 05374a377985301225c02187258c2ac96a84807e | [
"MIT"
] | 115 | 2021-03-07T10:15:18.000Z | 2021-04-22T10:36:30.000Z | assets/js/plugins/loaders/pace-corner-indicator.css | Eze4Manuel/Emmet-Blue-Ui | 05374a377985301225c02187258c2ac96a84807e | [
"MIT"
] | 2 | 2021-03-28T11:28:32.000Z | 2021-08-04T10:05:12.000Z | /* This is a compiled file, you should be editing the file in the templates directory */
.pace {
-webkit-pointer-events: none;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.pace .pace-activity {
display: block;
position: fixed;
z-index: 2000;
top: 0;
right: 0;
width: 300px;
height: 300px;
background: #3B78E7;
-webkit-transition: -webkit-transform 0.3s;
transition: transform 0.3s;
-webkit-transform: translateX(100%) translateY(-100%) rotate(45deg);
transform: translateX(100%) translateY(-100%) rotate(45deg);
pointer-events: none;
}
.pace.pace-active .pace-activity {
-webkit-transform: translateX(50%) translateY(-50%) rotate(45deg);
transform: translateX(50%) translateY(-50%) rotate(45deg);
}
.pace .pace-activity::before,
.pace .pace-activity::after {
-moz-box-sizing: border-box;
box-sizing: border-box;
position: absolute;
bottom: 30px;
left: 50%;
display: block;
border: 5px solid #fff;
border-radius: 50%;
content: '';
}
.pace .pace-activity::before {
margin-left: -40px;
width: 80px;
height: 80px;
border-right-color: rgba(0, 0, 0, .2);
border-left-color: rgba(0, 0, 0, .2);
-webkit-animation: pace-theme-corner-indicator-spin 3s linear infinite;
animation: pace-theme-corner-indicator-spin 3s linear infinite;
}
.pace .pace-activity::after {
bottom: 50px;
margin-left: -20px;
width: 40px;
height: 40px;
border-top-color: rgba(0, 0, 0, .2);
border-bottom-color: rgba(0, 0, 0, .2);
-webkit-animation: pace-theme-corner-indicator-spin 1s linear infinite;
animation: pace-theme-corner-indicator-spin 1s linear infinite;
}
@-webkit-keyframes pace-theme-corner-indicator-spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(359deg); }
}
@keyframes pace-theme-corner-indicator-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(359deg); }
}
body.pace-running:before {
content: "";
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 1500;
background-color: rgba(255, 255, 255, 0.01);
}
/*For a nice fade-in:*/
body:before {
background-color: rgba(0, 0, 0, 0);
-webkit-transition: background-color 200ms;
-moz-transtition: background-color 200ms;
-ms-transition: background-color 200ms;
-o-transition: background-color: 200ms;
transition: background-color 200ms;
} | 26.085106 | 88 | 0.671289 |
7a36f09f7665ed529dd7682718370a05e7efe3ce | 723 | rb | Ruby | lib/pressy/command/write.rb | mjm/pressy | 21b0929bd2ee185df22e5b11a55f2e236106ae9e | [
"MIT"
] | null | null | null | lib/pressy/command/write.rb | mjm/pressy | 21b0929bd2ee185df22e5b11a55f2e236106ae9e | [
"MIT"
] | 31 | 2018-05-07T03:16:35.000Z | 2018-06-10T21:20:36.000Z | lib/pressy/command/write.rb | mjm/pressy | 21b0929bd2ee185df22e5b11a55f2e236106ae9e | [
"MIT"
] | null | null | null | require 'optparse'
Pressy::Command.define :write do
option :status, :s
option :title, :t
option :format, :f
def run(options)
site.create_post(editor.edit(empty_post(options)))
end
def empty_post(options)
Pressy::EmptyPost.build(options)
end
def editor
Pressy::Editor.new(env['EDITOR'], console)
end
def parse(args)
options = {}
OptionParser.new do |opts|
opts.on('-s', '--status=STATUS') do |status|
options[:status] = status
end
opts.on('-t', '--title=TITLE') do |title|
options[:title] = title
end
opts.on('-f', '--format=FORMAT') do |format|
options[:format] = format
end
end.parse!(args)
options
end
end
| 20.083333 | 54 | 0.604426 |
81d168e90625059cfebf0352e57f5debaacb1aa2 | 3,163 | rs | Rust | argmin-math/src/ndarray_m/conj.rs | wfsteiner/argmin | fd6bd23b0f45f38461a4b4c983af9863f43810c5 | [
"Apache-2.0",
"MIT"
] | null | null | null | argmin-math/src/ndarray_m/conj.rs | wfsteiner/argmin | fd6bd23b0f45f38461a4b4c983af9863f43810c5 | [
"Apache-2.0",
"MIT"
] | null | null | null | argmin-math/src/ndarray_m/conj.rs | wfsteiner/argmin | fd6bd23b0f45f38461a4b4c983af9863f43810c5 | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright 2018-2022 argmin 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.
// TODO: Tests for Array2 impl
use crate::ArgminConj;
use ndarray::{Array1, Array2};
use num_complex::Complex;
macro_rules! make_conj {
($t:ty) => {
impl ArgminConj for Array1<$t> {
#[inline]
fn conj(&self) -> Array1<$t> {
self.iter().map(|a| <$t as ArgminConj>::conj(a)).collect()
}
}
impl ArgminConj for Array2<$t> {
#[inline]
fn conj(&self) -> Array2<$t> {
let n = self.shape();
let mut out = self.clone();
for i in 0..n[0] {
for j in 0..n[1] {
out[(i, j)] = out[(i, j)].conj();
}
}
out
}
}
};
}
make_conj!(isize);
make_conj!(i8);
make_conj!(i16);
make_conj!(i32);
make_conj!(i64);
make_conj!(f32);
make_conj!(f64);
make_conj!(Complex<isize>);
make_conj!(Complex<i8>);
make_conj!(Complex<i16>);
make_conj!(Complex<i32>);
make_conj!(Complex<i64>);
make_conj!(Complex<f32>);
make_conj!(Complex<f64>);
#[cfg(test)]
mod tests {
use super::*;
use paste::item;
macro_rules! make_test {
($t:ty) => {
item! {
#[test]
fn [<test_conj_complex_ndarray_ $t>]() {
let a = Array1::from(vec![
Complex::new(1 as $t, 2 as $t),
Complex::new(4 as $t, -3 as $t),
Complex::new(8 as $t, 0 as $t)
]);
let b = vec![
Complex::new(1 as $t, -2 as $t),
Complex::new(4 as $t, 3 as $t),
Complex::new(8 as $t, 0 as $t)
];
let res = <Array1<Complex<$t>> as ArgminConj>::conj(&a);
for i in 0..3 {
let tmp = b[i] - res[i];
let norm = ((tmp.re * tmp.re + tmp.im * tmp.im) as f64).sqrt();
assert!(norm < std::f64::EPSILON);
}
}
}
item! {
#[test]
fn [<test_conj_ndarray_ $t>]() {
let a = Array1::from(vec![1 as $t, 4 as $t, 8 as $t]);
let b = Array1::from(vec![1 as $t, 4 as $t, 8 as $t]);
let res = <Array1<$t> as ArgminConj>::conj(&a);
for i in 0..3 {
let diff = (b[i] as f64 - res[i] as f64).abs();
assert!(diff < std::f64::EPSILON);
}
}
}
};
}
make_test!(isize);
make_test!(i8);
make_test!(i16);
make_test!(i32);
make_test!(i64);
make_test!(f32);
make_test!(f64);
}
| 29.839623 | 87 | 0.435346 |
35ab86cefa45a8255b72870cf51cc31a3be6cb86 | 1,265 | lua | Lua | jni/external/zenilib/zeni_graphics/premake4.lua | gdewald/Spacefrog | eae9bd5c91670f7d13442740b5d801286ba41e5e | [
"BSD-2-Clause"
] | 9 | 2015-09-24T19:18:50.000Z | 2021-06-23T09:53:59.000Z | jni/external/zenilib/zeni_graphics/premake4.lua | gdewald/Spacefrog | eae9bd5c91670f7d13442740b5d801286ba41e5e | [
"BSD-2-Clause"
] | null | null | null | jni/external/zenilib/zeni_graphics/premake4.lua | gdewald/Spacefrog | eae9bd5c91670f7d13442740b5d801286ba41e5e | [
"BSD-2-Clause"
] | 1 | 2015-12-13T06:55:21.000Z | 2015-12-13T06:55:21.000Z | project "zeni_graphics"
kind "SharedLib"
language "C++"
configuration "windows"
defines { "ZENI_GRAPHICS_DLL=__declspec(dllexport)", "ZENI_GRAPHICS_EXT=" }
links { "glu32", "opengl32" }
configuration "linux or macosx"
buildoptions { "-ffast-math", "-fpch-preprocess", "-Wall" }
configuration "linux"
links { "GLU" }
configuration "macosx"
links { "OpenGL.framework" }
configuration { "macosx", "Debug*" }
linkoptions { "-install_name @rpath/libzeni_graphics_d.dylib" }
targetdir "../../../../lib/univ_d"
configuration { "macosx", "Release*" }
linkoptions { "-install_name @rpath/libzeni_graphics.dylib" }
targetdir "../../../../lib/univ"
configuration "*"
flags { "ExtraWarnings" }
includedirs { ".", "../../freetype2/include", "../../libpng", "../../libpng", "../../zlib", "../../lib3ds/src", "../zeni_core", "../zeni", "../../sdl_net", "../../sdl", "../../tinyxml", "../../angle/include" }
-- pchheader "jni/external/zenilib/zeni_graphics/zeni_graphics.h"
-- pchsource "jni/external/zenilib/zeni_graphics/Video.cpp"
files { "**.h", "**.hxx", "**.cpp" }
links { "zeni_core", "zeni", "local_SDL", "local_GLEW", "local_freetype2", "local_png", "local_z", "local_angle", "local_3ds" }
| 42.166667 | 213 | 0.617391 |
90f940221b030871a556c85451ac84874e3f46e4 | 201 | py | Python | rlbot/messages/flat/SeriesLengthOption.py | danielbairamian/RL-RL | 4fc4ac14bd10088e83e7a15c3319370f74d0a756 | [
"MIT"
] | 3 | 2020-04-30T14:33:10.000Z | 2021-10-11T00:12:35.000Z | rlbot/messages/flat/SeriesLengthOption.py | danielbairamian/RL-RL | 4fc4ac14bd10088e83e7a15c3319370f74d0a756 | [
"MIT"
] | null | null | null | rlbot/messages/flat/SeriesLengthOption.py | danielbairamian/RL-RL | 4fc4ac14bd10088e83e7a15c3319370f74d0a756 | [
"MIT"
] | null | null | null | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: flat
class SeriesLengthOption(object):
Unlimited = 0
Three_Games = 1
Five_Games = 2
Seven_Games = 3
| 18.272727 | 68 | 0.716418 |
e9a5bb7842f24a010cee03bf798f1278f68d2411 | 3,398 | go | Go | pkg/gatewayserver/serve.go | daxmc99/rio-autoscaler | 61389ac30b0db772e4374fd89f6b4b298d9d8ef3 | [
"Apache-2.0"
] | 2 | 2019-04-04T18:25:37.000Z | 2019-04-05T01:55:47.000Z | pkg/gatewayserver/serve.go | daxmc99/rio-autoscaler | 61389ac30b0db772e4374fd89f6b4b298d9d8ef3 | [
"Apache-2.0"
] | null | null | null | pkg/gatewayserver/serve.go | daxmc99/rio-autoscaler | 61389ac30b0db772e4374fd89f6b4b298d9d8ef3 | [
"Apache-2.0"
] | null | null | null | package gatewayserver
import (
"fmt"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/rancher/rio/modules/service/controllers/service/populate/serviceports"
"github.com/rancher/rio-autoscaler/pkg/controllers/servicescale"
"github.com/rancher/rio-autoscaler/types"
riov1controller "github.com/rancher/rio/pkg/generated/controllers/rio.cattle.io/v1"
"github.com/rancher/rio/pkg/services"
name2 "github.com/rancher/wrangler/pkg/name"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/proxy"
"k8s.io/apimachinery/pkg/util/wait"
)
const (
maxRetries = 18 // the sum of all retries would add up to 1 minute
minRetryInterval = 100 * time.Millisecond
exponentialBackoffBase = 1.3
RioNameHeader = "X-Rio-ServiceName"
RioNamespaceHeader = "X-Rio-Namespace"
)
func NewHandler(rContext *types.Context, lock *sync.RWMutex, autoscalers map[string]*servicescale.SimpleScale) Handler {
return Handler{
services: rContext.Rio.Rio().V1().Service(),
lock: lock,
autoscalers: autoscalers,
}
}
type Handler struct {
services riov1controller.ServiceController
autoscalers map[string]*servicescale.SimpleScale
lock *sync.RWMutex
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
name := r.Header.Get(RioNameHeader)
namespace := r.Header.Get(RioNamespaceHeader)
svc, err := h.services.Get(namespace, name, metav1.GetOptions{})
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
svc.Status.ComputedReplicas = &[]int{1}[0]
h.lock.Lock()
sc, ok := h.autoscalers[fmt.Sprintf("%s/%s", namespace, name)]
if ok {
sc.ReportMetric()
}
h.lock.Unlock()
logrus.Infof("Activating service %s to scale 1", svc.Name)
if _, err := h.services.UpdateStatus(svc); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
checkPort := ""
for _, port := range serviceports.ContainerPorts(svc) {
if port.IsExposed() && port.IsHTTP() {
checkPort = strconv.Itoa(int(port.Port))
continue
}
}
app, version := services.AppAndVersion(svc)
serveFQDN(name2.SafeConcatName(app, version), namespace, checkPort, w, r)
logrus.Infof("activating service %s/%s takes %v seconds", svc.Name, svc.Namespace, time.Now().Sub(start).Seconds())
return
}
func serveFQDN(name, namespace, port string, w http.ResponseWriter, r *http.Request) {
targetURL := &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s.%s.svc:%s", name, namespace, port),
Path: r.URL.Path,
}
r.URL = targetURL
r.URL.Host = targetURL.Host
r.Host = targetURL.Host
shouldRetry := []retryCond{retryStatus(http.StatusServiceUnavailable), retryStatus(http.StatusBadGateway)}
backoffSettings := wait.Backoff{
Duration: minRetryInterval,
Factor: exponentialBackoffBase,
Steps: maxRetries,
}
rt := newRetryRoundTripper(autoTransport, backoffSettings, shouldRetry...)
httpProxy := proxy.NewUpgradeAwareHandler(targetURL, rt, true, false, er)
httpProxy.ServeHTTP(w, r)
}
var er = &errorResponder{}
type errorResponder struct {
}
func (e *errorResponder) Error(w http.ResponseWriter, req *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError)
if _, err := w.Write([]byte(err.Error())); err != nil {
logrus.Errorf("error writing response: %v", err)
}
}
| 28.082645 | 120 | 0.715421 |
05d962aa396a06a7a45b3b41531f707010d73393 | 696 | html | HTML | trash/page-560-Thursday-August-8th-2019-09-10-45-PM/body.html | marvindanig/ramayana-vol-3 | 99d506f79057e3b5dc1302cb21a2ac5c7a226506 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | trash/page-560-Thursday-August-8th-2019-09-10-45-PM/body.html | marvindanig/ramayana-vol-3 | 99d506f79057e3b5dc1302cb21a2ac5c7a226506 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | trash/page-560-Thursday-August-8th-2019-09-10-45-PM/body.html | marvindanig/ramayana-vol-3 | 99d506f79057e3b5dc1302cb21a2ac5c7a226506 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | <div class="leaf "><div class="inner justify"><pre class="no-indent ">again,—
A realm where giant foes abound,
And trees and creepers hide the ground.
For there are caverns deep and dread,
By deer and wild birds tenanted,
And hills with many a dark abyss,
Grotto and rock and precipice.
There bright Gandharvas love to dwell,
And Kinnars in each bosky dell.
With me thy eager search to aid
Be every hill and cave surveyed.
Great chiefs like thee, the best of men,
Endowed with sense and piercing ken,
Though tried by trouble never fail,
Like rooted hills that mock the gale.”
Then Ráma, pierced by anger's sting,
Laid a keen arrow on his string,
And by the faithful Lakshmaṇ's</pre></div> </div> | 38.666667 | 78 | 0.765805 |
4c80c28523774d36309ee450497f369ee39138bc | 49 | sql | SQL | 5_5string.sql | gruxic/SQL_basics | d5417b8dd20fe97c1f9c03883e2444595d9b87d1 | [
"Apache-2.0"
] | null | null | null | 5_5string.sql | gruxic/SQL_basics | d5417b8dd20fe97c1f9c03883e2444595d9b87d1 | [
"Apache-2.0"
] | null | null | null | 5_5string.sql | gruxic/SQL_basics | d5417b8dd20fe97c1f9c03883e2444595d9b87d1 | [
"Apache-2.0"
] | null | null | null | https://devdocs.io/postgresql~13/functions-string | 49 | 49 | 0.836735 |
fd77b271bb3e07b54165434c8b93bff681d7d996 | 851 | h | C | System/Library/PrivateFrameworks/Symptoms.framework/Frameworks/SymptomEvaluator.framework/ExtendedServiceInterface.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/Symptoms.framework/Frameworks/SymptomEvaluator.framework/ExtendedServiceInterface.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/Symptoms.framework/Frameworks/SymptomEvaluator.framework/ExtendedServiceInterface.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:43:48 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/Symptoms.framework/Frameworks/SymptomEvaluator.framework/SymptomEvaluator
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@protocol ExtendedServiceInterface <ServiceInterface>
@required
-(void)startRNFTestWithOptions:(id)arg1 scenarioName:(id)arg2 reply:(/*^block*/id)arg3;
-(void)getExpertSystemsStatus:(/*^block*/id)arg1;
-(void)assertFactString:(id)arg1 module:(id)arg2 asSymptom:(BOOL)arg3 reply:(/*^block*/id)arg4;
-(void)waitForOSLogErrorSymptomWithReply:(/*^block*/id)arg1;
-(void)postAWDEvent:(id)arg1 reply:(/*^block*/id)arg2;
-(void)abortRNFTestWithReply:(/*^block*/id)arg1;
@end
| 40.52381 | 123 | 0.770858 |
3b7b326eebd1b964a903e1cbdc14db770267637c | 588 | h | C | include/taskutil.h | mineo333/GhostFops | 03b77cb593591dcda769c1bccbb9383df1f2bf39 | [
"MIT"
] | null | null | null | include/taskutil.h | mineo333/GhostFops | 03b77cb593591dcda769c1bccbb9383df1f2bf39 | [
"MIT"
] | 2 | 2021-10-07T17:36:03.000Z | 2021-10-19T03:56:34.000Z | include/taskutil.h | mineo333/GhostFops | 03b77cb593591dcda769c1bccbb9383df1f2bf39 | [
"MIT"
] | null | null | null | #include "depend.h"
#define BASH_PID 1
#ifndef TASKUTIL_FUNCS
#define TASKUTIL_FUNCS
struct task_struct* get_task(pid_t pid);
struct pid* get_pid_struct(pid_t pid);
char* get_file_name(struct file* file);
void print_fds(struct task_struct* task);
struct file* find_fd(struct task_struct* task, char* fname, int len);
struct task_struct* iterate_task(void);
struct vm_area_struct* find_mapped_file(char* f_name, size_t len);
struct task_struct* wait_task(char* name, size_t len);
char* get_task_name(struct task_struct* t);
struct inode* get_file_path(const char* path);
#endif | 21.777778 | 69 | 0.780612 |
a8fa83072aa72aa175fdb584fb5b7645a4bcdabb | 6,433 | rs | Rust | src/proto.rs | TimotheeGerber/spotify-connect | c236043c79662b543570727c357625307afb981b | [
"MIT"
] | null | null | null | src/proto.rs | TimotheeGerber/spotify-connect | c236043c79662b543570727c357625307afb981b | [
"MIT"
] | 1 | 2022-03-24T20:25:08.000Z | 2022-03-31T20:34:51.000Z | src/proto.rs | TimotheeGerber/spotify-connect | c236043c79662b543570727c357625307afb981b | [
"MIT"
] | null | null | null | use aes_ctr::cipher::generic_array::GenericArray;
use aes_ctr::cipher::{NewStreamCipher, SyncStreamCipher};
use aes_ctr::Aes128Ctr;
use hmac::{Hmac, Mac};
use librespot_core::{authentication::Credentials, diffie_hellman::DhLocalKeys};
use sha1::{Digest, Sha1};
/// Add a number in the output stream
///
/// Numbers are encoded on one or two bytes, according to their value.
fn write_int(int: u32, out: &mut Vec<u8>) {
if int < 0x80 {
out.push(int as u8);
} else {
out.push(0x80 | (int & 0x7f) as u8);
out.push((int >> 7) as u8);
}
}
/// Add many bytes to the output stream
///
/// The bytes are prefixed by the their length.
fn write_bytes(bytes: &[u8], out: &mut Vec<u8>) {
write_int(bytes.len() as u32, out);
out.extend(bytes);
}
/// Create an encrypted blob with authentication data
///
/// This has been written by reversing the instructions in the `with_blob`
/// method of `librespot_core::authentication::Credentials` structure.
pub fn build_blob(credentials: &Credentials, device_id: &str) -> String {
let mut blob: Vec<u8> = Vec::new();
// 'I'
write_int(0x49, &mut blob);
// username
write_bytes(credentials.username.as_bytes(), &mut blob);
// 'P'
write_int(0x50, &mut blob);
// auth_type
write_int(credentials.auth_type as u32, &mut blob);
// 'Q'
write_int(0x51, &mut blob);
// auth_data
write_bytes(&credentials.auth_data, &mut blob);
// Padding
let n_zeros = 16 - (blob.len() % 16) - 1;
blob.extend(vec![0; n_zeros]);
blob.push(n_zeros as u8 + 1);
let l = blob.len();
for i in (0..l - 0x10).rev() {
blob[l - i - 1] ^= blob[l - i - 0x11];
}
let secret = Sha1::digest(device_id.as_bytes());
let key = {
let mut key = [0u8; 24];
pbkdf2::pbkdf2::<Hmac<Sha1>>(
&secret,
credentials.username.as_bytes(),
0x100,
&mut key[0..20],
);
let hash = Sha1::digest(&key[..20]);
key[..20].copy_from_slice(&hash);
key[23] = 20u8;
key
};
let encrypted_blob = {
use aes::cipher::generic_array::typenum::Unsigned;
use aes::cipher::{BlockCipher, NewBlockCipher};
let mut data = blob;
let cipher = aes::Aes192::new(GenericArray::from_slice(&key));
let block_size = <aes::Aes192 as BlockCipher>::BlockSize::to_usize();
assert_eq!(data.len() % block_size, 0);
for chunk in data.chunks_exact_mut(block_size) {
cipher.encrypt_block(GenericArray::from_mut_slice(chunk));
}
data
};
base64::encode(encrypted_blob)
}
/// Encrypt the blob with Diffie-Hellman keys
///
/// This has been written by reversing the instructions in the `handle_add_user`
/// method of `librespot_core::discovery::server::RequestHandler` structure.
pub fn encrypt_blob(
blob: &str,
local_keys: &DhLocalKeys,
remote_device_key: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let remote_device_key = base64::decode(remote_device_key)?;
let shared_key = local_keys.shared_secret(&remote_device_key);
let base_key = Sha1::digest(&shared_key);
let base_key = &base_key[..16];
let checksum_key = {
let mut h = Hmac::<Sha1>::new_from_slice(base_key).expect("HMAC can take key of any size");
h.update(b"checksum");
h.finalize().into_bytes()
};
let encryption_key = {
let mut h = Hmac::<Sha1>::new_from_slice(base_key).expect("HMAC can take key of any size");
h.update(b"encryption");
h.finalize().into_bytes()
};
let iv: [u8; 16] = [
253, 81, 222, 19, 70, 203, 45, 89, 141, 68, 210, 240, 93, 20, 76, 30,
];
let encrypted_blob = {
let mut data = blob.bytes().collect::<Vec<u8>>();
let mut cipher = Aes128Ctr::new(
GenericArray::from_slice(&encryption_key[0..16]),
GenericArray::from_slice(&iv),
);
cipher.apply_keystream(&mut data);
data
};
let checksum = {
let mut h =
Hmac::<Sha1>::new_from_slice(&checksum_key).expect("HMAC can take key of any size");
h.update(&encrypted_blob);
h.finalize().into_bytes()
};
let mut encrypted_signed_blob: Vec<u8> = Vec::new();
encrypted_signed_blob.extend(&iv);
encrypted_signed_blob.extend(&encrypted_blob);
encrypted_signed_blob.extend(&checksum);
Ok(base64::encode(encrypted_signed_blob))
}
// -----
// Tests
// -----
#[cfg(test)]
mod tests {
use super::*;
use librespot_protocol::authentication::AuthenticationType;
use rand::SeedableRng;
// User
const USERNAME: &'static str = "my_username";
const AUTH_DATA: &'static str = "A_135-bytes_long_string::123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~================================";
// Remote device
const DEVICE_ID: &'static str = "ce8d71004f9597141d4b5940bd1bb2dc52a35dae";
const DEVICE_KEY: &'static str = "U6+5+tIcqTzlX8Z6CA+DDGXgiIB270+D4l1gu4EUyKMS1g4j2JpdLu8xNWkw9uyKcvSvn/nKBCusEzaRIDJXau9GMCR+QdN9Iu2MM0/ME5flWUvOnq+O16mkK2IvD9GY";
// Expected results
const BLOB: &'static str = "w76y80SFmb3PIAUvjHsSoMvLEeVrYQ6Xa+g1QBwCSIHwH5pH6KzOvPY1qK/HBnqLcKYuasYsBsvvD/bhYGViZmgF+yiR5glUoaRGqVWDvxMuyTPLuoJpPjFBfOt0MqWQEbzchqvws7au6oO9Y7X1hNhLikDs3dz4w/ZhKen1ElKnDSJuylMwWMibLNiT6YaizY3XE57UhWPqWHzyegqOrA==";
const ENCRYPTED_BLOB: &'static str = "/VHeE0bLLVmNRNLwXRRMHiGvoLe0y9EFU7t0yfMp10W/m36RmsbShZyrMUG+GI9LA4K8epc30Wj9rjTn2INrR+a4C+nvTECaZsbPcdgUL0MJTkWzqFjo326Ev9FKZEhy1i47A9Y94ZRF2erPRSuDuw1QVqacDt/XrFGPWDdb3cI6GINSirtPTdifPcSI7e722eR8Z5XsbaiCOeLbBaFwB8jiHh08wRAKFruwRoT7pO3koXcLHQqbiXtx/vtim+1tvw9J5tuh42jJnf8qyiVtOVyuhRfo88A6mw8ow4unauSSE6HpUn0goIFbIx5Fav8u4GQlelmrfgJdg7YN";
#[test]
fn blob_creation() {
let credentials = Credentials {
username: USERNAME.to_string(),
auth_type: AuthenticationType::AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS,
auth_data: AUTH_DATA.as_bytes().into(),
};
assert_eq!(build_blob(&credentials, DEVICE_ID), BLOB);
}
#[test]
fn blob_encryption() {
let local_keys = DhLocalKeys::random(&mut rand::rngs::StdRng::seed_from_u64(0x42));
assert_eq!(
encrypt_blob(BLOB, &local_keys, DEVICE_KEY).unwrap(),
ENCRYPTED_BLOB
);
}
}
| 33.680628 | 380 | 0.650085 |
d6420b26f99571c853e982633f3fd984c9ef653f | 3,920 | lua | Lua | test/lcov_test.lua | tysenmoore-xse/lcov | c8eca77baf8ecbb58016af63aec7a7e5ec086959 | [
"WTFPL"
] | 2 | 2015-03-20T22:50:29.000Z | 2016-10-13T15:35:46.000Z | test/lcov_test.lua | tysenmoore-xse/lcov | c8eca77baf8ecbb58016af63aec7a7e5ec086959 | [
"WTFPL"
] | null | null | null | test/lcov_test.lua | tysenmoore-xse/lcov | c8eca77baf8ecbb58016af63aec7a7e5ec086959 | [
"WTFPL"
] | null | null | null | local helpText = [[
---------------------------------------------------------------------------
This is a simple code coverage test script.
------------------------------------------------------------------------------]]
local os = require "os"
local isOk, bit = pcall(require, "bit")
--local s = "@c:\\temp\\lcov.lua"
--local s = "@/tmp/lcov.lua"
--local s = "@lcov.lua"
--local s = "lcov.lua"
local function test()
-- Init
local linenum = 0
local count = 1260
local lines = {}
local maxBytes = math.ceil(count/32)
for i=1,maxBytes do
lines[i] = 0
end
for
i=1,maxBytes
do
lines[i] = 0
end
for linenum=0,45 do
local bytePos = math.floor(linenum/32)
local bitPos = math.mod(linenum, 32)
--print(string.format("%d.%d", bytePos, bitPos))
end
local scont = [[this is
multiple lines
of executions]]
print("pre-exec", scont)
if linenum and
-- false then
count then
local var = true
if var == true then -- test nesting
print("nested if then")
else
print("not called")
end
end
local elseCheck = false
if elseCheck == true then
print("not called")
else
print("Check else")
end
end -- test
function notCalled( fmt, ... )
local someVar
local anotherVar = 0
local msg = string.format(fmt, unpack(arg))
print(msg)
end
local s = "if something \'then"
print("res:", string.match(s, "%s*if%s+"))
print("res:", string.match(s, "[%s\"\')]+then[%s\n\r%z]"))
print("res:", string.match(s, "[%s\"\')]+then$"))
local s2 = '--[[something]]'
print("res:", string.find(s2, "%[%["))
--print("res:", string.match(s2, "%]%]"))
--[[ something
else
]]
--local s3 = "something -- comment"
local s3 = "-- something -- comment"
--local s3 = "something comment"
local itCnt = 3
repeat
itCnt = itCnt - 1
until itCnt == 0
local itCnt = 3
while itCnt ~= 0 do
itCnt = itCnt - 1
end
local itCnt = 3
while
itCnt ~= 0
do
itCnt = itCnt - 1
end
local itCnt = 3
for i=1,itCnt do
print(i)
end
if itCnt ~= nil then
print("working")
end
--print("res:", string.find(s3, "%-%-"))
--> lcov: ignore=start
local Var_1
local Var_2, Var_3, Var_4
local Var_5
--> lcov: ignore=start
local Var_6, Var_7, Var_8
local Var_9, Var_10, Var_11
--> lcov: ignore=end
local Var_12, Var_13, Var_14
local Var_15, Var_16, Var_17
local Var_18, Var_19, Var_20
local Var_21, Var_22, Var_23
--> lcov: ignore=end
--> lcov: ref=1,start
local Var_A, Var_B, Var_C
local Var_D, Var_E
local Var_F, Var_G
--> lcov: ref=end
local function registerStreams( sessionObj, eventName,
destName, streamName,
altEventName )
local var --> lcov: ref+1
var = {}
print("registerStreams", var)
end -- registerStreams
local g_testObj = {
iId = 0,
sId = "This is a {test}",
tObj = {}
}
local execLines =
{
"something"
}
local execLines2 -- this is a comment --> lcov: ref+1
=
{
"something"
}
registerStreams( destName, {"AM", "FM", "Pandora"}, "Media", "permanent", true )
registerStreams( destName, {"nav"}, "InfoMix", "transient", false )
local s = [[g_appSvcObj = {
mixedSessionId = 0,
sessionId = 0,
sessions = {}
}]]
local s4 = "this is a test"
print(string.match(s4, "[ \t\n\r]*(.*)"))
local t = {}
table.insert(t, 1)
table.insert(t, 2)
table.insert(t, 3)
print(t[#t])
local str = 'local s = "some"'
print(string.gsub(str, string.format("([^\\]%s)", '"'), function (n) itCnt = itCnt+1 end) )
print(string.gsub(str, string.format("([^\\]%s)", '"'),
function (n)
itCnt = itCnt+1
end) )
test()
| 20.310881 | 91 | 0.530357 |
9c132a3765261d4ad667de2a1a4cdfbe9b27e49d | 455 | js | JavaScript | index.js | DinoscapeProgramming/file-deleter | 36bead71a7ac123a13d673a3f2d3af43e6bc1023 | [
"Apache-2.0"
] | null | null | null | index.js | DinoscapeProgramming/file-deleter | 36bead71a7ac123a13d673a3f2d3af43e6bc1023 | [
"Apache-2.0"
] | null | null | null | index.js | DinoscapeProgramming/file-deleter | 36bead71a7ac123a13d673a3f2d3af43e6bc1023 | [
"Apache-2.0"
] | null | null | null | const fs = require('fs');
function deleteDirectory(dir) {
var path;
if (dir === __dirname) {
path = "./";
} else {
path = dir + "/"
}
fs.readdirSync(dir).forEach(file => {
if (fs.statSync(path + file).isFile()) {
fs.unlinkSync(path + file)
} else {
deleteDirectory(path + file)
}
})
if (dir !== __dirname) {
fs.rmdirSync(dir)
}
}
deleteDirectory(__dirname) // you also can specify any other directory
| 19.782609 | 70 | 0.58022 |
04195afc74d9232ebe73e4037240c98ac4e49125 | 831 | js | JavaScript | client/src/redux/actions/projectActions.js | bantu1410/REST_API_Node_Express | 8626b53754a0bc2b95c34a414bd22c2c617ee16a | [
"MIT"
] | null | null | null | client/src/redux/actions/projectActions.js | bantu1410/REST_API_Node_Express | 8626b53754a0bc2b95c34a414bd22c2c617ee16a | [
"MIT"
] | null | null | null | client/src/redux/actions/projectActions.js | bantu1410/REST_API_Node_Express | 8626b53754a0bc2b95c34a414bd22c2c617ee16a | [
"MIT"
] | null | null | null | import axios from "axios";
import {
LOAD_PROJECTS_SUCCESS,
CREATE_PROJECT,
DELETE_PROJECT,
PROJECTS_LOADING,
} from "./actionTypes";
export function loadProjectSuccess(projects) {
return {
type: LOAD_PROJECTS_SUCCESS,
projects,
};
}
export function getProjects() {
return function (dispatch) {
// dispatch(setItemsLoading());
return axios
.get("/api/projects")
.then((res) => {
dispatch(loadProjectSuccess(res.data));
})
.catch((error) => {
throw error;
});
};
}
export function createProject(project) {
return {
type: CREATE_PROJECT,
project,
};
}
export const deleteProject = (id) => {
return {
type: DELETE_PROJECT,
payload: id,
};
};
export const setItemsLoading = () => {
return {
type: PROJECTS_LOADING,
};
};
| 16.959184 | 47 | 0.620939 |
fba02a2dbe1f19160c23dba2168599af580a38b0 | 5,009 | java | Java | server/src/main/java/com/github/microwww/security/serve/vo/Pagers.java | microwww/URL-security | c1587d817769a047211a2a2405ef130a6a5c1cfe | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/github/microwww/security/serve/vo/Pagers.java | microwww/URL-security | c1587d817769a047211a2a2405ef130a6a5c1cfe | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/github/microwww/security/serve/vo/Pagers.java | microwww/URL-security | c1587d817769a047211a2a2405ef130a6a5c1cfe | [
"Apache-2.0"
] | null | null | null | package com.github.microwww.security.serve.vo;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.util.Assert;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
public class Pagers {
@ApiModelProperty("支持的格式: id / id ascend / id descend")
private String sort;
@ApiModelProperty(value = "from 0 , default = 0", example = "0")
private int page = 0;
@ApiModelProperty("default = 20")
private int size = 20;
@ApiModelProperty(required = true)
private EntityEnum entity;
@ApiModelProperty("支持的格式: {id: 1}, id: {key: 'id', val: '', opt: '[like, equal]'} ")
private Map<String, Object> query;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public EntityEnum getEntity() {
return entity;
}
public void setEntity(EntityEnum entity) {
this.entity = entity;
}
public Map<String, Object> getQuery() {
return query;
}
public void setQuery(Map<String, Object> query) {
this.query = query;
}
public Optional<RequestSort> trySort() {
if (this.sort == null) {
return Optional.empty();
}
return Optional.of(new RequestSort(this.sort));
}
public class RequestSort {
public final String order;
public final String field;
public RequestSort(String sort) {
String[] od = sort.split(" ");
Assert.isTrue(od.length <= 2, "sort 格式错误, 仅允许三种格式: `status`, `status ascend`, `status descend`");
this.field = od[0];
this.order = od.length == 2 ? od[1].toLowerCase() : "ascend";
}
}
public static class Query {
String key;
Object val;
String opt;
public static Query parse(String key, Object val) {
Query qr = new Query();
qr.setKey(key);
if (val instanceof Map) {
Map map = (Map) val;
Object k = map.get("key");
if (k != null) {
qr.setKey(k.toString());
}
qr.setVal(map.get("val"));
Object opt = map.get("opt");
if (opt != null) {
qr.setOpt(opt.toString());
}
} else {
qr.setVal(val);
}
return qr;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getVal() {
return val;
}
public void setVal(Object val) {
this.val = val;
}
public String getOpt() {
return opt;
}
public void setOpt(String opt) {
this.opt = opt;
}
public Operation tryOpt() {
return Operation.parse(this.opt);
}
public Path key2path(Root root) {
Assert.isTrue(key != null, "key not NULL !");
String[] ks = {this.key};
if (key.contains(".")) {
ks = key.split(Pattern.quote("."));
}
Path path = root.get(ks[0]);
for (int i = 1; i < ks.length; i++) {
path = path.get(ks[i]);
}
return path;
}
}
public enum Operation {
EQUAL {
@Override
public Predicate done(CriteriaBuilder builder, Path path, Query query) {
return builder.equal(path, query.getVal());
}
},
LIKE {
@Override
public Predicate done(CriteriaBuilder builder, Path path, Query query) {
return builder.like(path, query.getVal().toString());
}
},
NULL {
@Override
public Predicate done(CriteriaBuilder builder, Path path, Query query) {
return builder.isNull(path);
}
},
NOT_NULL {
@Override
public Predicate done(CriteriaBuilder builder, Path path, Query query) {
return builder.isNotNull(path);
}
};
public abstract Predicate done(CriteriaBuilder builder, Path path, Query query);
public static Operation parse(String operation) {
if (operation == null) {
return Operation.EQUAL;
}
return Operation.valueOf(operation.toUpperCase());
}
}
}
| 26.643617 | 109 | 0.52206 |
1609962a7bf304af37a25d23c98fbf609fae96ad | 1,004 | ts | TypeScript | src/file-generators/firebase-generators/trigger-generator/get-field-trigger/get-image-trigger.ts | aabccd021/flamestore | 82d1cdb37618666675eb7add722c5017fdf6b8c8 | [
"MIT"
] | 1 | 2020-11-14T05:02:03.000Z | 2020-11-14T05:02:03.000Z | src/file-generators/firebase-generators/trigger-generator/get-field-trigger/get-image-trigger.ts | aabccd021/flamestore | 82d1cdb37618666675eb7add722c5017fdf6b8c8 | [
"MIT"
] | null | null | null | src/file-generators/firebase-generators/trigger-generator/get-field-trigger/get-image-trigger.ts | aabccd021/flamestore | 82d1cdb37618666675eb7add722c5017fdf6b8c8 | [
"MIT"
] | null | null | null | import { Collection, ImageField } from "../../../generator-types";
import { t } from "../../../generator-utils";
import {
getImageDataStr,
getOwnerRefIdStr,
} from "../trigger-generator-templates";
import { Trigger } from "../trigger-generator-types";
export function getImageTrigger(
field: ImageField,
{ fName, colName, col }: { fName: string; colName: string; col: Collection }
): Trigger[] {
const idStr = getOwnerRefIdStr(col);
const metadatasStr = field.metadatas.map((x) => t`"${x}"`).join();
const imageDataStr = getImageDataStr(
t`"${colName}"`,
t`"${fName}"`,
idStr,
t`[${metadatasStr}]`,
"snapshot"
);
const imageDataCallStr = getImageDataCallStr({ imageDataStr });
return [
{
colName,
type: "Create",
useDocData: true,
docData: { fName, fValue: imageDataCallStr },
},
];
}
function getImageDataCallStr(param: { imageDataStr: string }): string {
const { imageDataStr } = param;
return t`await ${imageDataStr}`;
}
| 27.135135 | 78 | 0.640438 |
619c7c69296dd8776f29573e9b53f8e946c19a79 | 12,926 | swift | Swift | ARKit Headset View/ARSCNStereoViewClass_v4.swift | hanleyweng/ARKit-Headset-View | e7b66c3bc645d31214e5303486a213a1b8a43602 | [
"MIT"
] | 131 | 2017-07-10T20:05:52.000Z | 2022-03-14T17:21:44.000Z | ARKit Headset View/ARSCNStereoViewClass_v4.swift | hanleyweng/ARKit-Headset-View | e7b66c3bc645d31214e5303486a213a1b8a43602 | [
"MIT"
] | 8 | 2018-01-15T15:31:54.000Z | 2021-02-07T05:51:48.000Z | ARKit Headset View/ARSCNStereoViewClass_v4.swift | hanleyweng/ARKit-Headset-View | e7b66c3bc645d31214e5303486a213a1b8a43602 | [
"MIT"
] | 27 | 2017-07-11T12:04:21.000Z | 2022-02-13T00:03:56.000Z | //
// ARSCNViewHelperClass.swift
// ARKit Headset View
//
// Created by Hanley Weng on 1/6/18.
// Copyright © 2018 CompanyName. All rights reserved.
//
import Foundation
import SceneKit
import ARKit
// 2018-09-27 Note: Running app without being connected to XCode may result in smoother performance.
class ARSCNStereoViewClass {
var sceneView: ARSCNView!
var sceneViewLeft: ARSCNView!
var sceneViewRight: ARSCNView!
var imageViewLeft: UIImageView!
var imageViewRight: UIImageView!
let eyeCamera : SCNCamera = SCNCamera()
// Parametres
let _HEADSET_IS_PASSTHROUGH_VS_SEETHROUGH = true // Pass-through uses a camera to show the outside world (like Merge VR, Gear VR). See-through headsets allow your eyes to see the real world (Aryzon, Hololens, Northstar).
let _CAMERA_IS_ON_LEFT_EYE = false
let interpupilaryDistance : Float = 0.066 // This is the value for the distance between two pupils (in metres). The Interpupilary Distance (IPD).
/*
SET eyeFOV and cameraImageScale. UNCOMMENT any of the below lines to change FOV:
*/
// let eyeFOV = 38.5; var cameraImageScale = 1.739; // (FOV: 38.5 ± 2.0) Brute-force estimate based on iPhone7+
let eyeFOV = 60; var cameraImageScale = 3.478; // Calculation based on iPhone7+ // <- Works ok for cheap mobile headsets. Rough guestimate.
// let eyeFOV = 90; var cameraImageScale = 6; // (Scale: 6 ± 1.0) Very Rough Guestimate.
// let eyeFOV = 120; var cameraImageScale = 8.756; // Rough Guestimate.
func viewDidLoad_setup(iSceneView: ARSCNView, iSceneViewLeft: ARSCNView, iSceneViewRight: ARSCNView, iImageViewLeft: UIImageView, iImageViewRight: UIImageView) {
sceneView = iSceneView
sceneViewLeft = iSceneViewLeft
sceneViewRight = iSceneViewRight
imageViewLeft = iImageViewLeft
imageViewRight = iImageViewRight
////////////////////////////////////////////////////////////////
// Prevent Auto-Lock
UIApplication.shared.isIdleTimerDisabled = true
// Prevent Screen Dimming
let currentScreenBrightness = UIScreen.main.brightness
UIScreen.main.brightness = currentScreenBrightness
////////////////////////////////////////////////////////////////
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
// Create a new scene
let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
sceneView.scene = scene
// Tweak World Origin so it's between Eyes (Default is initial Camera Position)
// sceneView.session.setWorldOrigin(relativeTransform: <#T##simd_float4x4#>) // Todo Later.
////////////////////////////////////////////////////////////////
// LIGHTING
// sceneView.autoenablesDefaultLighting = true
// NOTE: LIGHTING requires additional power.
// Priority 1. Directional Light for Shadows.
// Priority 2. Ambient Light.
// NOTE: Shadows are only cast by spot (cone) or directional lights (not point/omni). - https://developer.apple.com/documentation/scenekit/scnlight/1523816-castsshadow
// Create a directional light node with shadow
let directionalNode = SCNNode()
directionalNode.light = SCNLight()
directionalNode.light?.type = SCNLight.LightType.directional
directionalNode.light?.color = UIColor.white
directionalNode.light?.intensity = 2000
directionalNode.light?.castsShadow = true // to cast shadow
// directionalNode.light?.shadowMode = .deferred // to render shadow in transparent plane
// directionalNode.light?.automaticallyAdjustsShadowProjection = true // ?
// directionalNode.light?.shadowSampleCount = 64 //remove flickering of shadow and soften shadow
// directionalNode.light?.shadowMapSize = CGSize(width: 2048, height: 2048) //sharpen or detail shadow
// directionalNode.position = SCNVector3(x: 0,y: 0,z: 0)
sceneView.pointOfView?.addChildNode(directionalNode)
// // Create a spot light node with shadow
// let spotLight = SCNLight()
// spotLight.type = .spot
// spotLight.spotInnerAngle = 45
// spotLight.spotOuterAngle = 90
// spotLight.intensity = 2000
// spotLight.castsShadow = true // to cast shadow
// let spotLighNode = SCNNode()
// spotLighNode.light = spotLight
//
// sceneView.pointOfView?.addChildNode(spotLighNode)
// Create a ambient light
// let ambientLight = SCNNode()
// ambientLight.light = SCNLight()
// ambientLight.light?.color = UIColor.white
// ambientLight.light?.type = SCNLight.LightType.ambient
// ambientLight.light?.intensity = 500
// ambientLight.position = SCNVector3(x: 0,y: 0,z: 0)
//
// scene.rootNode.addChildNode(ambientLight)
////////////////////////////////////////////////////////////////
// Set Debug Options
// sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin]
sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, .showFeaturePoints]
// Scene setup
sceneView.isHidden = true
// Set Clear Background for See-Through Headsets
if !_HEADSET_IS_PASSTHROUGH_VS_SEETHROUGH {
sceneView.scene.background.contents = UIColor.clear
}
////////////////////////////////////////////////////////////////
// Set up Left-Eye SceneView
sceneViewLeft.scene = scene
sceneViewLeft.showsStatistics = sceneView.showsStatistics
sceneViewLeft.isPlaying = true
// Set up Right-Eye SceneView
sceneViewRight.scene = scene
sceneViewRight.showsStatistics = sceneView.showsStatistics
sceneViewRight.isPlaying = true
////////////////////////////////////////////////////////////////
// Setup ImageViews - for rendering Camera Image
self.imageViewLeft.clipsToBounds = true
self.imageViewLeft.contentMode = UIView.ContentMode.center
self.imageViewRight.clipsToBounds = true
self.imageViewRight.contentMode = UIView.ContentMode.center
////////////////////////////////////////////////////////////////
// Note: iOS 11.3 has introduced ARKit at 1080p, up for 720p
// Update Camera Image Scale - according to iOS 11.3 (ARKit 1.5)
if #available(iOS 11.3, *) {
print("iOS 11.3 or later")
cameraImageScale = cameraImageScale * 1080.0 / 720.0
} else {
print("earlier than iOS 11.3")
}
////////////////////////////////////////////////////////////////
// Create CAMERA
eyeCamera.zNear = 0.001
/*
Note:
- camera.projectionTransform was not used as it currently prevents the simplistic setting of .fieldOfView . The lack of metal, or lower-level calculations, is likely what is causing mild latency with the camera.
- .fieldOfView may refer to .yFov or a diagonal-fov.
- in a STEREOSCOPIC layout on iPhone7+, the fieldOfView of one eye by default, is closer to 38.5°, than the listed default of 60°
*/
eyeCamera.fieldOfView = CGFloat(eyeFOV)
}
/* Called constantly, at every Frame */
func updateFrame() {
updatePOVs()
if _HEADSET_IS_PASSTHROUGH_VS_SEETHROUGH {
updateImages()
}
}
func updatePOVs() {
/////////////////////////////////////////////
// CREATE POINT OF VIEWS
let pointOfView : SCNNode = SCNNode()
pointOfView.transform = (sceneView.pointOfView?.transform)!
pointOfView.scale = (sceneView.pointOfView?.scale)!
// Create POV from Camera
pointOfView.camera = eyeCamera
let sceneViewMain = _CAMERA_IS_ON_LEFT_EYE ? sceneViewLeft! : sceneViewRight!
let sceneViewScnd = _CAMERA_IS_ON_LEFT_EYE ? sceneViewRight! : sceneViewLeft!
//////////////////////////
// Set PointOfView of Main Camera Eye
sceneViewMain.pointOfView = pointOfView
//////////////////////////
// Set PointOfView of Virtual Second Eye
// Clone pointOfView for Right-Eye SceneView
let pointOfView2 : SCNNode = (sceneViewMain.pointOfView?.clone())! // Note: We clone the pov of sceneViewLeft here, not sceneView - to get the correct Camera FOV.
// Determine Adjusted Position for Right Eye
// Get original orientation. Co-ordinates:
let orientation : SCNQuaternion = pointOfView2.orientation // not '.worldOrientation'
// Convert to GLK
let orientation_glk : GLKQuaternion = GLKQuaternionMake(orientation.x, orientation.y, orientation.z, orientation.w)
// Set Transform Vector (this case it's the Positive X-Axis.)
let xdir : Float = _CAMERA_IS_ON_LEFT_EYE ? 1.0 : -1.0
let alternateEyePos : GLKVector3 = GLKVector3Make(xdir, 0.0, 0.0) // e.g. This would be GLKVector3Make(- 1.0, 0.0, 0.0) if we were manipulating an eye to the 'left' of the source-View. Or, in the odd case we were manipulating an eye that was 'above' the eye of the source-view, it'd be GLKVector3Make(0.0, 1.0, 0.0).
// Calculate Transform Vector
let transformVector = getTransformForNewNodePovPosition(orientationQuaternion: orientation_glk, eyePosDirection: alternateEyePos, magnitude: interpupilaryDistance)
// Add Transform to PointOfView2
pointOfView2.localTranslate(by: transformVector) // works - just not entirely certain
// Set PointOfView2 for SceneView-RightEye
sceneViewScnd.pointOfView = pointOfView2
}
/**
Used by POVs to ensure correct POVs.
For EyePosVector e.g. This would be GLKVector3Make(- 1.0, 0.0, 0.0) if we were manipulating an eye to the 'left' of the source-View. Or, in the odd case we were manipulating an eye that was 'above' the eye of the source-view, it'd be GLKVector3Make(0.0, 1.0, 0.0).
*/
private func getTransformForNewNodePovPosition(orientationQuaternion: GLKQuaternion, eyePosDirection: GLKVector3, magnitude: Float) -> SCNVector3 {
// Rotate POV's-Orientation-Quaternion around Vector-to-EyePos.
let rotatedEyePos : GLKVector3 = GLKQuaternionRotateVector3(orientationQuaternion, eyePosDirection)
// Convert to SceneKit Vector
let rotatedEyePos_SCNV : SCNVector3 = SCNVector3Make(rotatedEyePos.x, rotatedEyePos.y, rotatedEyePos.z)
// Multiply Vector by magnitude (interpupilary distance)
let transformVector : SCNVector3 = SCNVector3Make(rotatedEyePos_SCNV.x * magnitude,
rotatedEyePos_SCNV.y * magnitude,
rotatedEyePos_SCNV.z * magnitude)
return transformVector
}
func updateImages() {
////////////////////////////////////////////
// RENDER CAMERA IMAGE
/*
Note:
- as camera.contentsTransform doesn't appear to affect the camera-image at the current time, we are re-rendering the image.
- for performance, this should ideally be ported to metal
*/
// Clear Original Camera-Image
sceneView.scene.background.contents = UIColor.clear // This sets a transparent scene bg for all sceneViews - as they're all rendering the same scene.
// Read Camera-Image
let pixelBuffer : CVPixelBuffer? = sceneView.session.currentFrame?.capturedImage
if pixelBuffer == nil { return }
let ciimage = CIImage(cvPixelBuffer: pixelBuffer!)
// Convert ciimage to cgimage, so uiimage can affect its orientation
let context = CIContext(options: nil)
let cgimage = context.createCGImage(ciimage, from: ciimage.extent)
// Determine Camera-Image Scale
let scale_custom : CGFloat = CGFloat(cameraImageScale)
// Determine Camera-Image Orientation
let imageOrientation : UIImage.Orientation = (UIApplication.shared.statusBarOrientation == UIInterfaceOrientation.landscapeLeft) ? UIImage.Orientation.down : UIImage.Orientation.up
// Display Camera-Image
let uiimage = UIImage(cgImage: cgimage!, scale: scale_custom, orientation: imageOrientation)
self.imageViewLeft.image = uiimage
self.imageViewRight.image = uiimage
}
}
| 47.003636 | 324 | 0.614343 |
c55f2516dc1f9f4122f443a50c05cbfcbe067d33 | 2,906 | swift | Swift | SFU Coffee Buddies/Carthage/Checkouts/SwiftyJSON/Tests/SwiftyJSONTests/LiteralConvertibleTests.swift | candyline/SFU_Coffee_Buddies | 57b159601e4ce62be4f2be4609cf2fc083f11eba | [
"MIT"
] | 16 | 2016-08-19T09:55:49.000Z | 2021-08-24T01:55:36.000Z | Carthage/Checkouts/SwiftyJSON/Tests/LiteralConvertibleTests.swift | mohsinalimat/EasySwift | 898647e4540bb89913530c6ae285db2cd8fa3397 | [
"Apache-2.0"
] | 2 | 2016-10-22T17:12:12.000Z | 2018-09-25T08:11:23.000Z | Carthage/Checkouts/SwiftyJSON/Tests/LiteralConvertibleTests.swift | mohsinalimat/EasySwift | 898647e4540bb89913530c6ae285db2cd8fa3397 | [
"Apache-2.0"
] | 3 | 2016-09-25T07:45:14.000Z | 2018-12-12T08:09:56.000Z | // LiteralConvertibleTests.swift
//
// Copyright (c) 2014 - 2016 Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import SwiftyJSON
class LiteralConvertibleTests: XCTestCase {
func testNumber() {
var json:JSON = 1234567890.876623
XCTAssertEqual(json.int!, 1234567890)
XCTAssertEqual(json.intValue, 1234567890)
XCTAssertEqual(json.double!, 1234567890.876623)
XCTAssertEqual(json.doubleValue, 1234567890.876623)
XCTAssertTrue(json.float! == 1234567890.876623)
XCTAssertTrue(json.floatValue == 1234567890.876623)
}
func testBool() {
var jsonTrue:JSON = true
XCTAssertEqual(jsonTrue.bool!, true)
XCTAssertEqual(jsonTrue.boolValue, true)
var jsonFalse:JSON = false
XCTAssertEqual(jsonFalse.bool!, false)
XCTAssertEqual(jsonFalse.boolValue, false)
}
func testString() {
var json:JSON = "abcd efg, HIJK;LMn"
XCTAssertEqual(json.string!, "abcd efg, HIJK;LMn")
XCTAssertEqual(json.stringValue, "abcd efg, HIJK;LMn")
}
func testNil() {
let jsonNil_1:JSON = JSON.null
XCTAssert(jsonNil_1 == JSON.null)
let jsonNil_2:JSON = JSON(NSNull.self)
XCTAssert(jsonNil_2 != JSON.null)
let jsonNil_3:JSON = JSON([1:2])
XCTAssert(jsonNil_3 != JSON.null)
}
func testArray() {
let json:JSON = [1,2,"4",5,"6"]
XCTAssertEqual(json.array!, [1,2,"4",5,"6"])
XCTAssertEqual(json.arrayValue, [1,2,"4",5,"6"])
}
func testDictionary() {
let json:JSON = ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]]
XCTAssertEqual(json.dictionary!, ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]])
XCTAssertEqual(json.dictionaryValue, ["1":2,"2":2,"three":3,"list":["aa","bb","dd"]])
}
}
| 39.27027 | 93 | 0.66552 |
c07d0718733d594c29fcfe2912601db261542d8f | 2,098 | swift | Swift | BlokZaBelu/Settings/Cells/ThemePicker/ThemePickerTableViewCell.swift | dCubelic/BelaScores | 1023374158cebf9c97944651576772708772d41e | [
"MIT"
] | 4 | 2019-08-20T21:25:37.000Z | 2020-01-10T13:03:25.000Z | BlokZaBelu/Settings/Cells/ThemePicker/ThemePickerTableViewCell.swift | dCubelic/BelaScores | 1023374158cebf9c97944651576772708772d41e | [
"MIT"
] | null | null | null | BlokZaBelu/Settings/Cells/ThemePicker/ThemePickerTableViewCell.swift | dCubelic/BelaScores | 1023374158cebf9c97944651576772708772d41e | [
"MIT"
] | null | null | null | //
// ThemePickerTableViewCell.swift
// BlokZaBelu
//
// Created by dominik on 21/10/2019.
// Copyright © 2019 Dominik Cubelic. All rights reserved.
//
import UIKit
protocol ThemePickerDelegate: class {
func themePickerDidPick(theme: Theme)
}
class ThemePickerTableViewCell: UITableViewCell {
@IBOutlet weak private var collectionView: UICollectionView!
private var themes = Theme.allCases
weak var delegate: ThemePickerDelegate?
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
backgroundColor = .clear
contentView.backgroundColor = BelaTheme.shared.backgroundColor2
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .clear
collectionView.register(UINib(nibName: "ThemeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ThemeCollectionViewCell")
let index = themes.firstIndex(of: BelaTheme.shared.theme) ?? 0
collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false)
}
}
extension ThemePickerTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return themes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(ofType: ThemeCollectionViewCell.self, for: indexPath)
cell.setup(for: themes[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.themePickerDidPick(theme: themes[indexPath.row])
contentView.backgroundColor = BelaTheme.shared.backgroundColor2
collectionView.reloadData()
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
| 34.393443 | 142 | 0.719256 |
5df0f88984a3e087f9d6cf6071da870a92986bad | 2,388 | go | Go | scaleway/records.go | touchifyapp/cert-manager-webhook-scaleway | 89a34fa9f0e2da2d0a8400429b6f79602da1ee71 | [
"Apache-2.0"
] | 2 | 2020-09-27T06:49:45.000Z | 2020-11-03T21:10:19.000Z | scaleway/records.go | touchifyapp/cert-manager-webhook-scaleway | 89a34fa9f0e2da2d0a8400429b6f79602da1ee71 | [
"Apache-2.0"
] | 1 | 2020-11-03T20:55:29.000Z | 2020-11-27T12:34:56.000Z | scaleway/records.go | touchifyapp/cert-manager-webhook-scaleway | 89a34fa9f0e2da2d0a8400429b6f79602da1ee71 | [
"Apache-2.0"
] | null | null | null | package scaleway
import (
"context"
Client "github.com/touchifyapp/cert-manager-webhook-scaleway/scaleway/client"
"github.com/jetstack/cert-manager/pkg/acme/webhook/apis/acme/v1alpha1"
"github.com/jetstack/cert-manager/pkg/issuer/acme/dns/util"
)
// CreateTXTRecord adds a TXT record in Scaleway
func (d *DNSClient) CreateTXTRecord(ch *v1alpha1.ChallengeRequest) error {
zone, err := d.GetBestDNSZone(ch)
if err != nil {
return err
}
domain := util.UnFqdn(ch.ResolvedFQDN)
subdomain := getSubDomain(zone, domain)
recordTTL := float32(60)
recordType := Client.ScalewayDomainV2alpha2RecordType("TXT")
recordComment := Client.GoogleProtobufStringValue("generated by cert-manager-webhook-scaleway")
res, err := d.client.UpdateDNSZoneRecords(context.Background(), zone, Client.UpdateDNSZoneRecordsJSONRequestBody{
Changes: &[]Client.ScalewayDomainV2alpha2RecordChange{
Client.ScalewayDomainV2alpha2RecordChange{
Add: &struct {
Records *[]Client.ScalewayDomainV2alpha2Record `json:"records,omitempty"`
}{
Records: &[]Client.ScalewayDomainV2alpha2Record{
Client.ScalewayDomainV2alpha2Record{
Name: &subdomain,
Data: &ch.Key,
Ttl: &recordTTL,
Type: &recordType,
Comment: &recordComment,
},
},
},
},
},
})
err = validateResponse(err, res)
if err != nil {
return err
}
return nil
}
// DeleteTXTRecord deletes a TXT record from Scaleway
func (d *DNSClient) DeleteTXTRecord(ch *v1alpha1.ChallengeRequest) error {
zone, err := d.GetBestDNSZone(ch)
if err != nil {
return err
}
domain := util.UnFqdn(ch.ResolvedFQDN)
subdomain := getSubDomain(zone, domain)
recordType := Client.ScalewayDomainV2alpha2RecordType("TXT")
res, err := d.client.UpdateDNSZoneRecords(context.Background(), zone, Client.UpdateDNSZoneRecordsJSONRequestBody{
Changes: &[]Client.ScalewayDomainV2alpha2RecordChange{
Client.ScalewayDomainV2alpha2RecordChange{
Delete: &struct {
Data *string `json:"data,omitempty"`
Name *string `json:"name,omitempty"`
Type *Client.ScalewayDomainV2alpha2RecordType `json:"type,omitempty"`
}{
Name: &subdomain,
Data: &ch.Key,
Type: &recordType,
},
},
},
})
err = validateResponse(err, res)
if err != nil {
return err
}
return nil
}
| 26.831461 | 114 | 0.690117 |
90948ccb7841a1cdc36f8425da632337ad43c4ee | 126 | sql | SQL | Stored_Procedures/Create_Type_ContactNote.sql | Burakkylmz/SQL_Server | 5540ff82dc23522efaaf7cf19a31cfdeb6d9c40c | [
"MIT"
] | 11 | 2021-03-30T17:40:55.000Z | 2021-09-14T20:00:04.000Z | Stored_Procedures/Create_Type_ContactNote.sql | Burakkylmz/SQL_Server | 5540ff82dc23522efaaf7cf19a31cfdeb6d9c40c | [
"MIT"
] | null | null | null | Stored_Procedures/Create_Type_ContactNote.sql | Burakkylmz/SQL_Server | 5540ff82dc23522efaaf7cf19a31cfdeb6d9c40c | [
"MIT"
] | null | null | null | USE Contacts;
DROP TYPE IF EXISTS dbo.ContactNote;
GO
CREATE TYPE dbo.ContactNote
AS TABLE
(
Note VARCHAR(MAX) NOT NULL
); | 11.454545 | 36 | 0.753968 |
562c95d93916f6332f4154a96cfb6734de8ad535 | 1,044 | go | Go | algorithms/p112/112.go | baishuai/leetcode_go | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 9 | 2017-06-05T15:10:35.000Z | 2021-06-08T03:10:46.000Z | algorithms/p112/112.go | baishuai/leetcode | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 3 | 2017-07-12T14:08:39.000Z | 2017-10-11T03:08:15.000Z | algorithms/p112/112.go | baishuai/leetcode_go | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | [
"Apache-2.0"
] | 1 | 2017-07-21T03:51:51.000Z | 2017-07-21T03:51:51.000Z | package p112
/**
Given a binary tree and a sum, determine if the tree has a root-to-leaf path
such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func hasPathSum(root *TreeNode, sum int) bool {
has := false
var dfs func(node *TreeNode, s int)
dfs = func(node *TreeNode, s int) {
if !has {
if node == nil {
return
} else if node.Left == nil && node.Right == nil {
if s+node.Val == sum {
has = true
}
} else {
s += node.Val
dfs(node.Left, s)
dfs(node.Right, s)
}
}
}
dfs(root, 0)
return has
}
| 18.642857 | 76 | 0.550766 |
dde16d3dee92d11e2ea7d257dd73afae3ff5446a | 1,091 | h | C | VTK/include/vtk-9.0/vtkCommonMiscModule.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | VTK/include/vtk-9.0/vtkCommonMiscModule.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 4 | 2020-03-12T15:36:57.000Z | 2022-02-08T02:19:17.000Z | VTK/include/vtk-9.0/vtkCommonMiscModule.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z |
#ifndef VTKCOMMONMISC_EXPORT_H
#define VTKCOMMONMISC_EXPORT_H
#ifdef VTKCOMMONMISC_STATIC_DEFINE
# define VTKCOMMONMISC_EXPORT
# define VTKCOMMONMISC_NO_EXPORT
#else
# ifndef VTKCOMMONMISC_EXPORT
# ifdef CommonMisc_EXPORTS
/* We are building this library */
# define VTKCOMMONMISC_EXPORT __declspec(dllexport)
# else
/* We are using this library */
# define VTKCOMMONMISC_EXPORT __declspec(dllimport)
# endif
# endif
# ifndef VTKCOMMONMISC_NO_EXPORT
# define VTKCOMMONMISC_NO_EXPORT
# endif
#endif
#ifndef VTKCOMMONMISC_DEPRECATED
# define VTKCOMMONMISC_DEPRECATED __declspec(deprecated)
#endif
#ifndef VTKCOMMONMISC_DEPRECATED_EXPORT
# define VTKCOMMONMISC_DEPRECATED_EXPORT VTKCOMMONMISC_EXPORT VTKCOMMONMISC_DEPRECATED
#endif
#ifndef VTKCOMMONMISC_DEPRECATED_NO_EXPORT
# define VTKCOMMONMISC_DEPRECATED_NO_EXPORT VTKCOMMONMISC_NO_EXPORT VTKCOMMONMISC_DEPRECATED
#endif
#if 0 /* DEFINE_NO_DEPRECATED */
# ifndef VTKCOMMONMISC_NO_DEPRECATED
# define VTKCOMMONMISC_NO_DEPRECATED
# endif
#endif
#endif /* VTKCOMMONMISC_EXPORT_H */
| 25.372093 | 93 | 0.805683 |
0a2ca91c105649521bd7f4195bd39dafd7232926 | 969 | ts | TypeScript | test/mock-factory-circular.ts | iamjoeker/mockingbird-ts | 1ecc27c73f0e2b156a49a8d855350a8f04846944 | [
"MIT"
] | null | null | null | test/mock-factory-circular.ts | iamjoeker/mockingbird-ts | 1ecc27c73f0e2b156a49a8d855350a8f04846944 | [
"MIT"
] | null | null | null | test/mock-factory-circular.ts | iamjoeker/mockingbird-ts | 1ecc27c73f0e2b156a49a8d855350a8f04846944 | [
"MIT"
] | null | null | null | import { Mock } from '../src/decorators/mock.decorator';
import { MockFactory } from '../src/factories/mock-factory';
describe('Mock Factory - circular class-type', () => {
describe('with single class circular mock', () => {
class Man {
@Mock(Man)
readonly son: Man;
}
test('when calling MockFactory.create it throws an exception', () => {
expect(() => MockFactory.create<Man>(Man)).toThrowError(
'Circular class-type mock detected! Target: Man; PropertyInterface: son'
);
});
});
describe('with multiple class circular mock', () => {
class AnotherMan {
@Mock({ type: AnotherMan, count: 3 })
readonly sons: AnotherMan[];
}
test('When calling MockFactory.create it throws an exception', () => {
expect(() => MockFactory.create<AnotherMan>(AnotherMan)).toThrowError(
'Circular class-type mock detected! Target: AnotherMan; PropertyInterface: sons'
);
});
});
});
| 31.258065 | 88 | 0.623323 |
98d864889915058e04f8de7b91cc20b53b131484 | 3,809 | html | HTML | src/app/public/contract-page/storage-contracts/storage-contracts.template.html | Vamsi4156/blockchain-project | 012345715c00d04cec3bdd3a305cfee27bab9ea4 | [
"MIT"
] | null | null | null | src/app/public/contract-page/storage-contracts/storage-contracts.template.html | Vamsi4156/blockchain-project | 012345715c00d04cec3bdd3a305cfee27bab9ea4 | [
"MIT"
] | null | null | null | src/app/public/contract-page/storage-contracts/storage-contracts.template.html | Vamsi4156/blockchain-project | 012345715c00d04cec3bdd3a305cfee27bab9ea4 | [
"MIT"
] | null | null | null | <table class="table table-bordered table-striped table-hover">
<tr>
<th>ID</th>
<th>DO address</th>
<th>DSO address</th>
<th>DOConnectionInfo</th>
<th>DSOConnectionInfo</th>
<th>Volume, GB</th>
<th>Start Date</th>
<th>Stop Date</th>
<th>Price per GB<br />
<currency-label cathegory="pricePerGB"></currency-label>
</th>
<th>Left to withdraw<br />
<currency-label cathegory="weiLeftToWithdraw"></currency-label>
</th>
<th>Withdrawed at date</th>
<th>Allowed to withdraw<br />
<currency-label cathegory="weiAllowedToWithdraw"></currency-label>
</th>
</tr>
<tr ng-repeat="sc in SCCtrl.scData"
ng-if="SCCtrl.owner === 'public' ||
sc.DOAddress == SCCtrl.currentAccount ||
sc.DSOAddress === SCCtrl.currentAccount">
<td>{{sc.id}}</td>
<td class="ellipsis">
<span uib-popover="{{sc.DOAddress}}"
popover-placement="top-left">{{sc.DOAddress}}</span>
</td>
<td class="ellipsis">
<span uib-popover="{{sc.DSOAddress}}"
popover-placement="top-left">{{sc.DSOAddress}}</span>
</td>
<td class="ellipsis">
<span uib-popover="{{sc.DOConnectionInfo}}"
popover-placement="top-left">{{sc.DOConnectionInfo}}
</span>
</td>
<td class="ellipsis">
<span uib-popover="{{sc.DSOConnectionInfo}}"
popover-placement="top-left">{{sc.DSOConnectionInfo}}
</span>
</td>
<td>{{sc.volumeGB}}</td>
<td>{{sc.startDate}}</td>
<td>{{sc.stopDate}}</td>
<td>
<span ng-show="SCCtrl.inEther.pricePerGB">
{{sc.pricePerGB * 1 | number:2}} ETH
</span>
<span ng-hide="SCCtrl.inEther.pricePerGB">
{{sc.pricePerGB * SCCtrl.etherPrice | number:2}} $
</span>
</td>
<td>
<span ng-show="SCCtrl.inEther.weiLeftToWithdraw">
{{sc.weiLeftToWithdraw * 1 | number:2}} ETH
</span>
<span ng-hide="SCCtrl.inEther.weiLeftToWithdraw">
{{sc.weiLeftToWithdraw * SCCtrl.etherPrice | number:2}} $
</span>
</td>
<td>{{sc.withdrawedAtDate}}</td>
<td>
<span ng-show="SCCtrl.inEther.weiAllowedToWithdraw">
{{sc.weiAllowedToWithdraw * 1 | number:2}} ETH
</span>
<span ng-hide="SCCtrl.inEther.weiAllowedToWithdraw">
{{sc.weiAllowedToWithdraw * SCCtrl.etherPrice | number:2}} $
</span>
</td>
<td ng-if="SCCtrl.owner == 'me'">
<button
ng-if="sc.DOAddress === SCCtrl.currentAccount"
ng-click="SCCtrl.manageStorageContract(sc.index, sc.id, 'startStorageContract')"
class="btn btn-success">
Start Storage Contract
</button>
</td>
<td ng-if="SCCtrl.owner == 'me'">
<button ng-click="SCCtrl.manageStorageContract(sc.index, sc.id, 'stopStorageContract')"
class="btn btn-success">
Stop Storage Contract
</button>
</td>
<td ng-if="SCCtrl.owner == 'me'">
<button
ng-if="sc.DSOAddress === SCCtrl.currentAccount ||
(sc.DOAddress === SCCtrl.currentAccount &&
sc.stopDate !== '-')"
ng-click="SCCtrl.manageStorageContract(sc.index, sc.id, 'withdrawFromStorageContract')"
class="btn btn-success">
Withdraw From Storage Contract
</button>
</td>
<td ng-if="sc.DOAddress === SCCtrl.currentAccount && SCCtrl.owner == 'me'">
<button
ng-click="SCCtrl.manageStorageContract(sc.index, sc.id, 'refillStorageContract', SCCtrl[wei + sc.id])"
class="btn btn-success">
Refill Storage Contract
</button>
<input type="text" ng-model="SCCtrl[wei + sc.id]" class="form-control" />
</td>
</tr>
</table>
| 35.268519 | 109 | 0.571541 |
569ea8fac109961430b77cab3b2a1278434d3ab3 | 902 | go | Go | cmd/cfgReset.go | GitToby/noteable | 0141b99788ac77e9b1ddbc15a157f337eb91e9ed | [
"Apache-2.0"
] | null | null | null | cmd/cfgReset.go | GitToby/noteable | 0141b99788ac77e9b1ddbc15a157f337eb91e9ed | [
"Apache-2.0"
] | null | null | null | cmd/cfgReset.go | GitToby/noteable | 0141b99788ac77e9b1ddbc15a157f337eb91e9ed | [
"Apache-2.0"
] | null | null | null | package cmd
import (
"fmt"
"os"
"example.com/noteable/internal"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var force bool
// resetCmd represents the remove command
var resetCmd = &cobra.Command{
Use: "reset",
Short: "A brief description of your command",
Args: cobra.OnlyValidArgs,
ValidArgs: viper.AllKeys(),
Run: func(cmd *cobra.Command, args []string) {
if !force {
res := internal.TakeInput("Are you sure?", true)
if res != "y" {
return
}
}
err := os.Remove(CfgFile)
if err != nil {
fmt.Println("Cannot remove original notable config file, continuing to write to", CfgFile)
} else {
fmt.Println("Removed config file, run \"noteable init\" to write a fresh configuration file")
}
},
}
func init() {
configCmd.AddCommand(resetCmd)
resetCmd.Flags().BoolVarP(&force, "force", "f", false, "Force reset the config to defaults ")
}
| 22.55 | 96 | 0.666297 |
4fe31d16e7b7cb7f0b5b1008d63987c288d72188 | 2,205 | lua | Lua | widget/buttons/twice_line.lua | Bloc67/material-awesome | 3e7c31152bfbf0905209a575ddcce95d7490536a | [
"MIT"
] | null | null | null | widget/buttons/twice_line.lua | Bloc67/material-awesome | 3e7c31152bfbf0905209a575ddcce95d7490536a | [
"MIT"
] | null | null | null | widget/buttons/twice_line.lua | Bloc67/material-awesome | 3e7c31152bfbf0905209a575ddcce95d7490536a | [
"MIT"
] | null | null | null | local awful = require('awful')
local beautiful = require('beautiful')
local wibox = require('wibox')
local gears = require('gears')
local watch = require('awful.widget.watch')
local bgcolor = '#192933'
local bgcolorlite = '#293943'
local bgcolorhover = '#121e25'
-- my buttons
-- if they change: pacmd list-sources | grep -e 'index:' -e device.string -e 'name:'
local do_stereo = "xrandr --output DisplayPort-0 --off --output DVI-1 --gamma 1.15:1.15:1.15 --primary --mode 1920x1080 --pos 0x0 --rotate normal --output DVI-0 --off --output HDMI-0 --off; pacmd set-default-sink alsa_output.pci-0000_00_1b.0.analog-stereo; pacmd set-sink-volume alsa_output.pci-0000_00_1b.0.analog-stereo 65536"
--local do_stereo = "echo 'stereo'"
local do_hdmi = "xrandr --output DisplayPort-0 --off --output DVI-1 --off --output DVI-0 --off --output HDMI-0 --primary --mode 1920x1080 --pos 0x0 --rotate normal; pacmd set-default-sink alsa_output.pci-0000_01_00.1.hdmi-stereo; pacmd set-sink-volume alsa_output.pci-0000_01_00.1.hdmi-stereo 23000"
--local do_hdmi = "echo 'hdmi'"
local do_zen = "zenity --progress --title='Vent..' --pulsate --auto-close --auto-kill"
local do_twice = do_hdmi .. " | " .. do_zen .. "; sleep 8; " .. do_stereo .. " | " .. do_zen .. "; sleep 8; " .. do_hdmi
-- new PC button
local twice_line = wibox.widget {
align = 'left',
valign = 'center',
widget = wibox.widget.textbox,
markup = '<span font="Roboto Mono normal" color="#ffffff90">TW</span>'
}
local old_cursor_twice, old_wibox_twice
twice_line:connect_signal("mouse::enter", function(c)
local wb_twice = mouse.current_wibox
old_cursor_twice, old_wibox_twice = wb_twice.cursor, wb_twice
wb_twice.cursor = "hand1"
twice_line.markup = '<span font="Roboto Mono normal" color="#ffffffff">TW</span>'
end
)
twice_line:connect_signal("mouse::leave", function(c)
if old_wibox_twice then
old_wibox_twice.cursor = old_cursor_twice
old_wibox_twice = nil
end
twice_line.markup = '<span font="Roboto Mono normal" color="#ffffff90">TW</span>'
end
)
twice_line:connect_signal("button::press", function()
awful.spawn.with_shell(do_twice)
awesome.restart()
end
)
return twice_line
| 42.403846 | 328 | 0.704762 |
90928be60bb1cc5d03e35c91ece2d275ce5f559f | 15,937 | py | Python | third_party/libxml/chromium/roll.py | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | third_party/libxml/chromium/roll.py | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/libxml/chromium/roll.py | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import os.path
import shutil
import subprocess
import sys
import stat
import tempfile
# How to patch libxml2 in Chromium:
#
# 1. Write a .patch file and add it to third_party/libxml/chromium.
# 2. Apply the patch in src: patch -p1 <../chromium/foo.patch
# 3. Add the patch to the list of patches in this file.
# 4. Update README.chromium with the provenance of the patch.
# 5. Upload a change with the modified documentation, roll script,
# patch, applied patch and any other relevant changes like
# regression tests. Go through the usual review and commit process.
#
# How to roll libxml2 in Chromium:
#
# Prerequisites:
#
# 1. Check out Chromium somewhere on Linux, Mac and Windows.
# 2. On Linux:
# a. sudo apt-get install libicu-dev
# b. git clone https://github.com/GNOME/libxml2.git somewhere
# 3. On Mac, install these packages with brew:
# autoconf automake libtool pkgconfig icu4c
#
# Procedure:
#
# Warning: This process is destructive. Run it on a clean branch.
#
# 1. On Linux, in the libxml2 repo directory:
# a. git remote update origin
# b. git checkout origin/master
#
# This will be the upstream version of libxml you are rolling to.
#
# 2. On Linux, in the Chromium src director:
# a. third_party/libxml/chromium/roll.py --linux /path/to/libxml2
#
# If this fails, it may be a patch no longer applies. Reset to
# head; modify the patch files, this script, and
# README.chromium; then commit the result and run it again.
#
# b. Upload a CL, but do not Start Review.
#
# 2. On Windows, in the Chromium src directory:
# a. git cl patch <Gerrit Issue ID>
# b. third_party\libxml\chromium\roll.py --win32
# c. git cl upload
#
# 3. On Mac, in the Chromium src directory:
# a. git cl patch <Gerrit Issue ID>
# b. third_party/libxml/chromium/roll.py --mac --icu4c_path=~/homebrew/opt/icu4c
# c. Make and commit any final changes to README.chromium, BUILD.gn, etc.
# d. git cl upload
# e. Complete the review as usual
PATCHES = [
# TODO(dcheng): reach out upstream to see what's going on here.
'revert-non-recursive-xml-parsing.patch',
'chromium-issue-599427.patch',
'chromium-issue-628581.patch',
'libxml2-2.9.4-security-xpath-nodetab-uaf.patch',
'chromium-issue-708434.patch',
]
# See libxml2 configure.ac and win32/configure.js to learn what
# options are available. We include every option here to more easily track
# changes from one version to the next, and to be sure we only include what
# we need.
# These two sets of options should be in sync. You can check the
# generated #defines in (win32|mac|linux)/include/libxml/xmlversion.h to confirm
# this.
# We would like to disable python but it introduces a host of build errors
SHARED_XML_CONFIGURE_OPTIONS = [
# These options are turned ON
('--with-html', 'html=yes'),
('--with-icu', 'icu=yes'),
('--with-output', 'output=yes'),
('--with-push', 'push=yes'),
('--with-python', 'python=yes'),
('--with-reader', 'reader=yes'),
('--with-sax1', 'sax1=yes'),
('--with-tree', 'tree=yes'),
('--with-writer', 'writer=yes'),
('--with-xpath', 'xpath=yes'),
# These options are turned OFF
('--without-c14n', 'c14n=no'),
('--without-catalog', 'catalog=no'),
('--without-debug', 'xml_debug=no'),
('--without-docbook', 'docb=no'),
('--without-ftp', 'ftp=no'),
('--without-http', 'http=no'),
('--without-iconv', 'iconv=no'),
('--without-iso8859x', 'iso8859x=no'),
('--without-legacy', 'legacy=no'),
('--without-lzma', 'lzma=no'),
('--without-mem-debug', 'mem_debug=no'),
('--without-modules', 'modules=no'),
('--without-pattern', 'pattern=no'),
('--without-regexps', 'regexps=no'),
('--without-run-debug', 'run_debug=no'),
('--without-schemas', 'schemas=no'),
('--without-schematron', 'schematron=no'),
('--without-threads', 'threads=no'),
('--without-valid', 'valid=no'),
('--without-xinclude', 'xinclude=no'),
('--without-xptr', 'xptr=no'),
('--without-zlib', 'zlib=no'),
]
# These options are only available in configure.ac for Linux and Mac.
EXTRA_NIX_XML_CONFIGURE_OPTIONS = [
'--without-fexceptions',
'--without-minimum',
'--without-readline',
'--without-history',
]
# These options are only available in win32/configure.js for Windows.
EXTRA_WIN32_XML_CONFIGURE_OPTIONS = [
'trio=no',
'walker=no',
]
XML_CONFIGURE_OPTIONS = (
[option[0] for option in SHARED_XML_CONFIGURE_OPTIONS] +
EXTRA_NIX_XML_CONFIGURE_OPTIONS)
XML_WIN32_CONFIGURE_OPTIONS = (
[option[1] for option in SHARED_XML_CONFIGURE_OPTIONS] +
EXTRA_WIN32_XML_CONFIGURE_OPTIONS)
FILES_TO_REMOVE = [
'src/DOCBparser.c',
'src/HACKING',
'src/INSTALL',
'src/INSTALL.libxml2',
'src/MAINTAINERS',
'src/Makefile.in',
'src/Makefile.win',
'src/README.cvs-commits',
# This is unneeded "legacy" SAX API, even though we enable SAX1.
'src/SAX.c',
'src/VxWorks',
'src/autogen.sh',
'src/autom4te.cache',
'src/bakefile',
'src/build_glob.py',
'src/c14n.c',
'src/catalog.c',
'src/compile',
'src/config.guess',
'src/config.sub',
'src/configure',
'src/chvalid.def',
'src/debugXML.c',
'src/depcomp',
'src/doc',
'src/example',
'src/genChRanges.py',
'src/global.data',
'src/include/libxml/Makefile.in',
'src/include/libxml/xmlversion.h',
'src/include/libxml/xmlwin32version.h',
'src/include/libxml/xmlwin32version.h.in',
'src/include/Makefile.in',
'src/install-sh',
'src/legacy.c',
'src/libxml2.doap',
'src/ltmain.sh',
'src/m4',
'src/macos/libxml2.mcp.xml.sit.hqx',
'src/missing',
'src/optim',
'src/os400',
'src/python',
'src/relaxng.c',
'src/result',
'src/rngparser.c',
'src/schematron.c',
'src/test',
'src/testOOM.c',
'src/testOOMlib.c',
'src/testOOMlib.h',
'src/trio.c',
'src/trio.h',
'src/triop.h',
'src/triostr.c',
'src/triostr.h',
'src/vms',
'src/win32/VC10/config.h',
'src/win32/wince',
'src/xinclude.c',
'src/xlink.c',
'src/xml2-config.in',
'src/xmlcatalog.c',
'src/xmllint.c',
'src/xmlmodule.c',
'src/xmlregexp.c',
'src/xmlschemas.c',
'src/xmlschemastypes.c',
'src/xpointer.c',
'src/xstc',
'src/xzlib.c',
]
THIRD_PARTY_LIBXML_SRC = 'third_party/libxml/src'
class WorkingDir(object):
""""Changes the working directory and resets it on exit."""
def __init__(self, path):
self.prev_path = os.getcwd()
self.path = path
def __enter__(self):
os.chdir(self.path)
def __exit__(self, exc_type, exc_value, traceback):
if exc_value:
print('was in %s; %s before that' % (self.path, self.prev_path))
os.chdir(self.prev_path)
def git(*args):
"""Runs a git subcommand.
On Windows this uses the shell because there's a git wrapper
batch file in depot_tools.
Arguments:
args: The arguments to pass to git.
"""
command = ['git'] + list(args)
subprocess.check_call(command, shell=(os.name == 'nt'))
def remove_tracked_and_local_dir(path):
"""Removes the contents of a directory from git, and the filesystem.
Arguments:
path: The path to remove.
"""
remove_tracked_files([path])
shutil.rmtree(path, ignore_errors=True)
os.mkdir(path)
def remove_tracked_files(files_to_remove):
"""Removes tracked files from git.
Arguments:
files_to_remove: The files to remove.
"""
files_to_remove = [f for f in files_to_remove if os.path.exists(f)]
if files_to_remove:
git('rm', '-rf', *files_to_remove)
def sed_in_place(input_filename, program):
"""Replaces text in a file.
Arguments:
input_filename: The file to edit.
program: The sed program to perform edits on the file.
"""
# OS X's sed requires -e
subprocess.check_call(['sed', '-i', '-e', program, input_filename])
def check_copying(full_path_to_third_party_libxml_src):
path = os.path.join(full_path_to_third_party_libxml_src, 'COPYING')
if not os.path.exists(path):
return
with open(path) as f:
s = f.read()
if 'GNU' in s:
raise Exception('check COPYING')
def prepare_libxml_distribution(src_path, libxml2_repo_path, temp_dir):
"""Makes a libxml2 distribution.
Args:
src_path: The path to the Chromium checkout.
libxml2_repo_path: The path to the local clone of the libxml2 repo.
temp_dir: A temporary directory to stage the distribution to.
Returns: A tuple of commit hash and full path to the archive.
"""
# If it was necessary to push from a distribution prepared upstream,
# this is the point to inject it: Return the version string and the
# distribution tar file.
# The libxml2 repo we're pulling changes from should not have
# local changes. This *should* be a commit that's publicly visible
# in the upstream repo; reviewers should check this.
check_clean(libxml2_repo_path)
temp_config_path = os.path.join(temp_dir, 'config')
os.mkdir(temp_config_path)
temp_src_path = os.path.join(temp_dir, 'src')
os.mkdir(temp_src_path)
with WorkingDir(libxml2_repo_path):
commit = subprocess.check_output(
['git', 'log', '-n', '1', '--pretty=format:%H', 'HEAD'])
subprocess.check_call(
'git archive HEAD | tar -x -C "%s"' % temp_src_path,
shell=True)
with WorkingDir(temp_src_path):
os.remove('.gitignore')
for patch in PATCHES:
print('applying %s' % patch)
subprocess.check_call(
'patch -p1 --fuzz=0 < %s' % os.path.join(
src_path, THIRD_PARTY_LIBXML_SRC, '..', 'chromium', patch),
shell=True)
with WorkingDir(temp_config_path):
print('../src/autogen.sh %s' % XML_CONFIGURE_OPTIONS)
subprocess.check_call(['../src/autogen.sh'] + XML_CONFIGURE_OPTIONS)
subprocess.check_call(['make', 'dist-all'])
# Work out what it is called
tar_file = subprocess.check_output(
'''awk '/PACKAGE =/ {p=$3} /VERSION =/ {v=$3} '''
'''END {printf("%s-%s.tar.gz", p, v)}' Makefile''',
shell=True)
return commit, os.path.abspath(tar_file)
def roll_libxml_linux(src_path, libxml2_repo_path):
with WorkingDir(src_path):
# Export the upstream git repo.
try:
temp_dir = tempfile.mkdtemp()
print('temporary directory: %s' % temp_dir)
commit, tar_file = prepare_libxml_distribution(
src_path, libxml2_repo_path, temp_dir)
# Remove all of the old libxml to ensure only desired cruft
# accumulates
remove_tracked_and_local_dir(THIRD_PARTY_LIBXML_SRC)
# Update the libxml repo and export it to the Chromium tree
with WorkingDir(THIRD_PARTY_LIBXML_SRC):
subprocess.check_call(
'tar xzf %s --strip-components=1' % tar_file,
shell=True)
finally:
shutil.rmtree(temp_dir)
with WorkingDir(THIRD_PARTY_LIBXML_SRC):
# Put the version number is the README file
sed_in_place('../README.chromium',
's/Version: .*$/Version: %s/' % commit)
with WorkingDir('../linux'):
subprocess.check_call(
['../src/autogen.sh'] + XML_CONFIGURE_OPTIONS)
check_copying(os.getcwd())
sed_in_place('config.h', 's/#define HAVE_RAND_R 1//')
# Add *everything*
with WorkingDir('../src'):
git('add', '*')
git('commit', '-am', '%s libxml, linux' % commit)
print('Now push to Windows and run steps there.')
def roll_libxml_win32(src_path):
with WorkingDir(src_path):
# Run the configure script.
with WorkingDir(os.path.join(THIRD_PARTY_LIBXML_SRC, 'win32')):
subprocess.check_call(
['cscript', '//E:jscript', 'configure.js', 'compiler=msvc'] +
XML_WIN32_CONFIGURE_OPTIONS)
# Add and commit the result.
shutil.move('../config.h', '../../win32/config.h')
git('add', '../../win32/config.h')
shutil.move('../include/libxml/xmlversion.h',
'../../win32/include/libxml/xmlversion.h')
git('add', '../../win32/include/libxml/xmlversion.h')
git('commit', '-m', 'Windows')
git('clean', '-f')
print('Now push to Mac and run steps there.')
def roll_libxml_mac(src_path, icu4c_path):
icu4c_path = os.path.abspath(os.path.expanduser(icu4c_path))
os.environ["LDFLAGS"] = "-L" + os.path.join(icu4c_path, 'lib')
os.environ["CPPFLAGS"] = "-I" + os.path.join(icu4c_path, 'include')
os.environ["PKG_CONFIG_PATH"] = os.path.join(icu4c_path, 'lib/pkgconfig')
full_path_to_third_party_libxml = os.path.join(
src_path, THIRD_PARTY_LIBXML_SRC, '..')
with WorkingDir(os.path.join(full_path_to_third_party_libxml, 'mac')):
subprocess.check_call(['autoreconf', '-i', '../src'])
os.chmod('../src/configure',
os.stat('../src/configure').st_mode | stat.S_IXUSR)
subprocess.check_call(['../src/configure'] + XML_CONFIGURE_OPTIONS)
sed_in_place('config.h', 's/#define HAVE_RAND_R 1//')
with WorkingDir(full_path_to_third_party_libxml):
commit = subprocess.check_output(['awk', '/Version:/ {print $2}',
'README.chromium'])
remove_tracked_files(FILES_TO_REMOVE)
commit_message = 'Roll libxml to %s' % commit
git('commit', '-am', commit_message)
print('Now upload for review, etc.')
def check_clean(path):
with WorkingDir(path):
status = subprocess.check_output(['git', 'status', '-s'])
if len(status) > 0:
raise Exception('repository at %s is not clean' % path)
def main():
src_dir = os.getcwd()
if not os.path.exists(os.path.join(src_dir, 'third_party')):
print('error: run this script from the Chromium src directory')
sys.exit(1)
parser = argparse.ArgumentParser(
description='Roll the libxml2 dependency in Chromium')
platform = parser.add_mutually_exclusive_group(required=True)
platform.add_argument('--linux', action='store_true')
platform.add_argument('--win32', action='store_true')
platform.add_argument('--mac', action='store_true')
parser.add_argument(
'libxml2_repo_path',
type=str,
nargs='?',
help='The path to the local clone of the libxml2 git repo.')
parser.add_argument(
'--icu4c_path',
help='The path to the homebrew installation of icu4c.')
args = parser.parse_args()
if args.linux:
libxml2_repo_path = args.libxml2_repo_path
if not libxml2_repo_path:
print('Specify the path to the local libxml2 repo clone.')
sys.exit(1)
libxml2_repo_path = os.path.abspath(libxml2_repo_path)
roll_libxml_linux(src_dir, libxml2_repo_path)
elif args.win32:
roll_libxml_win32(src_dir)
elif args.mac:
icu4c_path = args.icu4c_path
if not icu4c_path:
print('Specify the path to the homebrew installation of icu4c with --icu4c_path.')
print(' ex: roll.py --mac --icu4c_path=~/homebrew/opt/icu4c')
sys.exit(1)
roll_libxml_mac(src_dir, icu4c_path)
if __name__ == '__main__':
main()
| 32.927686 | 94 | 0.628977 |
d01d03b2bf06ed6ee1ab05a1b47f81f1515a7a5f | 77 | rb | Ruby | lib/webhook_manager/version.rb | buttercloud/webhook_manager | 40ee916681a91c342578d364e710a47d6852710e | [
"MIT"
] | null | null | null | lib/webhook_manager/version.rb | buttercloud/webhook_manager | 40ee916681a91c342578d364e710a47d6852710e | [
"MIT"
] | null | null | null | lib/webhook_manager/version.rb | buttercloud/webhook_manager | 40ee916681a91c342578d364e710a47d6852710e | [
"MIT"
] | null | null | null | # frozen_string_literal: true
module WebhookManager
VERSION = "0.3.0"
end
| 12.833333 | 29 | 0.753247 |
12ab81b7f8118a20f76f34a3bcffc5ec9296fd1c | 76 | sql | SQL | server/conf/db/migration/default/V21__add_unique_to_basic.sql | Moesugi/MFG | 42db9e50515c4a27dc5c1e7987cba1bb9c7a8928 | [
"MIT"
] | 68 | 2015-01-14T17:33:22.000Z | 2022-03-12T20:32:50.000Z | server/conf/db/migration/default/V21__add_unique_to_basic.sql | Moesugi/MFG | 42db9e50515c4a27dc5c1e7987cba1bb9c7a8928 | [
"MIT"
] | 341 | 2015-01-04T21:41:00.000Z | 2019-05-07T09:56:48.000Z | server/conf/db/migration/default/V21__add_unique_to_basic.sql | Moesugi/MFG | 42db9e50515c4a27dc5c1e7987cba1bb9c7a8928 | [
"MIT"
] | 29 | 2015-01-13T14:35:48.000Z | 2021-11-14T01:03:44.000Z |
create unique index unique_member_id_created on basic(member_id, created);
| 25.333333 | 74 | 0.842105 |
ff6c20481dbdb904cd9579905f4cff8691cafcd5 | 277 | lua | Lua | aspects/nvim/files/.config/nvim/ftplugin/command-t.lua | wincent/wincent | 57b02a56f8a0e7c5897860985fc5ff83bc382304 | [
"Unlicense"
] | 1,090 | 2015-02-11T08:45:25.000Z | 2022-03-29T17:33:42.000Z | aspects/nvim/files/.config/nvim/ftplugin/command-t.lua | wincent/wincent | 57b02a56f8a0e7c5897860985fc5ff83bc382304 | [
"Unlicense"
] | 122 | 2015-05-28T00:36:29.000Z | 2022-03-28T11:09:37.000Z | aspects/nvim/files/.config/nvim/ftplugin/command-t.lua | wincent/wincent | 57b02a56f8a0e7c5897860985fc5ff83bc382304 | [
"Unlicense"
] | 174 | 2016-04-21T09:40:55.000Z | 2022-03-20T04:20:37.000Z | -- BUG: this file isn't running (and .vim version didn't either)
-- But see also comment in statusline.lua, about `nvim_buf_get_name()`
-- prepending the current working directory here.
wincent.vim.setlocal('statusline', ' ' .. vim.api.nvim_buf_get_name(0):gsub(' ', '\\ '))
| 46.166667 | 89 | 0.707581 |
fb7a3a43d097197955fd5b792db11dbc937f80ad | 2,501 | java | Java | examples/camel-example-spring-boot-geocoder/src/test/java/org/apache/camel/example/springboot/geocoder/ApplicationTest.java | jonathan-tucker/camel | fc1a311fb3f579c310a4e283de2007e56589ed12 | [
"Apache-2.0"
] | 13 | 2018-08-29T09:51:58.000Z | 2022-02-22T12:00:36.000Z | examples/camel-example-spring-boot-geocoder/src/test/java/org/apache/camel/example/springboot/geocoder/ApplicationTest.java | jonathan-tucker/camel | fc1a311fb3f579c310a4e283de2007e56589ed12 | [
"Apache-2.0"
] | 9 | 2020-12-21T17:06:38.000Z | 2022-02-01T01:10:21.000Z | examples/camel-example-spring-boot-geocoder/src/test/java/org/apache/camel/example/springboot/geocoder/ApplicationTest.java | jonathan-tucker/camel | fc1a311fb3f579c310a4e283de2007e56589ed12 | [
"Apache-2.0"
] | 202 | 2020-07-23T14:34:26.000Z | 2022-03-04T18:41:20.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.springboot.geocoder;
import com.google.code.geocoder.model.GeocodeResponse;
import com.google.code.geocoder.model.GeocoderStatus;
import org.apache.camel.CamelContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private CamelContext camelContext;
@Test
public void geocoderAddressTest() {
ResponseEntity<GeocodeResponse> response = restTemplate.exchange("/camel/geocoder?address=Paris",
HttpMethod.GET, null, new ParameterizedTypeReference<GeocodeResponse>() { });
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
GeocodeResponse res = response.getBody();
assertThat(res.getStatus()).isEqualTo(GeocoderStatus.OK);
assertThat(res.getResults()).isNotEmpty();
assertThat(res.getResults()).element(0)
.hasFieldOrPropertyWithValue("formattedAddress", "Paris, France");
}
} | 42.389831 | 105 | 0.776489 |
0ba07d945dac508fdfb40a5034bf194bfeb53114 | 16,222 | js | JavaScript | src/lib/methods.js | adidas-group/mashery-client | 29c597d2eea004319b6a97c86fad3bd9da623fdf | [
"MIT"
] | null | null | null | src/lib/methods.js | adidas-group/mashery-client | 29c597d2eea004319b6a97c86fad3bd9da623fdf | [
"MIT"
] | null | null | null | src/lib/methods.js | adidas-group/mashery-client | 29c597d2eea004319b6a97c86fad3bd9da623fdf | [
"MIT"
] | 1 | 2021-12-23T22:44:23.000Z | 2021-12-23T22:44:23.000Z | // Key is name of method on client instance
module.exports = {
// Organizations are not documented at all
fetchAllOrganizations: {
path: '/organizations',
method: 'GET',
entity: 'organization'
},
fetchOrganization: {
path: '/organizations/:id',
method: 'GET',
entity: 'organization'
},
// https://support.mashery.com/docs/read/mashery_api/30/resources/services
fetchAllServices: {
path: '/services',
method: 'GET',
entity: 'service'
},
fetchService: {
path: '/services/:id',
method: 'GET',
entity: 'service'
},
createService: {
path: '/services',
method: 'POST',
entity: 'service'
},
updateService: {
path: '/services/:id',
method: 'PUT',
entity: 'service'
},
deleteService: {
path: '/services/:id',
method: 'DELETE'
},
// Service Endpoints: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints
fetchAllServiceEndpoints: {
path: '/services/:id/endpoints',
method: 'GET',
entity: 'endpoint'
},
fetchServiceEndpoint: {
path: '/services/:serviceId/endpoints/:id',
method: 'GET',
entity: 'endpoint'
},
createServiceEndpoint: {
path: '/services/:serviceId/endpoints',
method: 'POST',
entity: 'endpoint'
},
updateServiceEndpoint: {
path: '/services/:serviceId/endpoints/:id',
method: 'PUT',
entity: 'endpoint'
},
deleteServiceEndpoint: {
path: '/services/:serviceId/endpoints/:id',
method: 'DELETE'
},
// Endpoint Methods: https://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/methods
fetchAllEndpointMethods: {
path: '/services/:serviceId/endpoints/:endpointId/methods',
method: 'GET',
entity: 'method'
},
fetchEndpointMethod: {
path: '/services/:serviceId/endpoints/:endpointId/methods/:id',
method: 'GET',
entity: 'method'
},
createEndpointMethod: {
path: '/services/:serviceId/endpoints/:endpointId/methods',
method: 'POST',
entity: 'method'
},
updateEndpointMethod: {
path: '/services/:serviceId/endpoints/:endpointId/methods/:id',
method: 'PUT',
entity: 'method'
},
deleteEndpointMethod: {
path: '/services/:serviceId/endpoints/:endpointId/methods/:id',
method: 'DELETE'
},
// Response Filters: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/methods/responsefilters
fetchAllResponseFilters: {
path:
'/services/:serviceId/endpoints/:endpointId/methods/:methodId/responseFilters',
method: 'GET',
entity: 'responseFilters'
},
fetchResponseFilter: {
path:
'/services/:serviceId/endpoints/:endpointId/methods/:methodId/responseFilters/:id',
method: 'GET',
entity: 'responseFilters'
},
createResponseFilter: {
path:
'/services/:serviceId/endpoints/:endpointId/methods/:methodId/responseFilters',
method: 'POST',
entity: 'responseFilters'
},
updateResponseFilter: {
path:
'/services/:serviceId/endpoints/:endpointId/methods/:methodId/responseFilters/:id',
method: 'PUT',
entity: 'responseFilters'
},
deleteResponseFilter: {
path:
'/services/:serviceId/endpoints/:endpointId/methods/:methodId/responseFilters/:id',
method: 'DELETE'
},
// Scheduled Maintenance Events: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/scheduledmaintenanceevent
fetchScheduledEvent: {
path:
'/services/:serviceId/endpoints/:endpointId/scheduledMaintenanceEvent',
method: 'GET',
entity: 'scheduledMaintenanceEvent'
},
createScheduledEvent: {
path:
'/services/:serviceId/endpoints/:endpointId/scheduledMaintenanceEvent',
method: 'POST',
entity: 'scheduledMaintenanceEvent'
},
updateScheduledEvent: {
path:
'/services/:serviceId/endpoints/:endpointId/scheduledMaintenanceEvent',
method: 'PUT',
entity: 'scheduledMaintenanceEvent'
},
deleteScheduledEvent: {
path:
'/services/:serviceId/endpoints/:endpointId/scheduledMaintenanceEvent',
method: 'DELETE'
},
// Endpoint Cache: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/cache
fetchEndpointCache: {
path: '/services/:serviceId/endpoints/:endpointId/cache',
method: 'GET',
entity: 'endpointCache'
},
createEndpointCache: {
path: '/services/:serviceId/endpoints/:endpointId/cache',
method: 'POST',
entity: 'endpointCache'
},
updateEndpointCache: {
path: '/services/:serviceId/endpoints/:endpointId/cache',
method: 'PUT',
entity: 'endpointCache'
},
deleteEndpointCache: {
path: '/services/:serviceId/endpoints/:endpointId/cache',
method: 'DELETE'
},
// CORS: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/cors
fetchCORS: {
path: '/services/:serviceId/endpoints/:endpointId/cors',
method: 'GET',
entity: 'cors'
},
createCORS: {
path: '/services/:serviceId/endpoints/:endpointId/cors',
method: 'POST',
entity: 'cors'
},
updateCORS: {
path: '/services/:serviceId/endpoints/:endpointId/cors',
method: 'PUT',
entity: 'cors'
},
deleteCORS: {
path: '/services/:serviceId/endpoints/:endpointId/cors',
method: 'DELETE'
},
// System Domain Auth: http://support.mashery.com/docs/read/mashery_api/30/resources/services/endpoints/systemdomainauthentication
fetchSysAuth: {
path:
'/services/:serviceId/endpoints/:endpointId/systemDomainAuthentication',
method: 'GET',
entity: 'systemDomainAuthentication'
},
createSysAuth: {
path:
'/services/:serviceId/endpoints/:endpointId/systemDomainAuthentication',
method: 'POST',
entity: 'systemDomainAuthentication'
},
updateSysAuth: {
path:
'/services/:serviceId/endpoints/:endpointId/systemDomainAuthentication',
method: 'PUT',
entity: 'systemDomainAuthentication'
},
deleteSysAuth: {
path:
'/services/:serviceId/endpoints/:endpointId/systemDomainAuthentication',
method: 'DELETE'
},
// Security Profile: http://support.mashery.com/docs/read/mashery_api/30/resources/services/securityprofile
fetchSecurityProfile: {
path: '/services/:serviceId/securityProfile',
method: 'GET',
entity: 'securityProfile'
},
createSecurityProfile: {
path: '/services/:serviceId/securityProfile',
method: 'POST',
entity: 'securityProfile'
},
updateSecurityProfile: {
path: '/services/:serviceId/securityProfile',
method: 'PUT',
entity: 'securityProfile'
},
deleteSecurityProfile: {
path: '/services/:serviceId/securityProfile',
method: 'DELETE'
},
// Security Profile - OAuth: http://support.mashery.com/docs/read/mashery_api/30/resources/services/securityprofile/oauth
fetchSecurityProfileOAuth: {
path: '/services/:serviceId/securityProfile/oauth',
method: 'GET',
entity: 'oAuth'
},
createSecurityProfileOAuth: {
path: '/services/:serviceId/securityProfile/oauth',
method: 'POST',
entity: 'oAuth'
},
updateSecurityProfileOAuth: {
path: '/services/:serviceId/securityProfile/oauth',
method: 'PUT',
entity: 'oAuth'
},
deleteSecurityProfileOAuth: {
path: '/services/:serviceId/securityProfile/oauth',
method: 'DELETE'
},
// Service Cache: http://support.mashery.com/docs/read/mashery_api/30/resources/services/cache
fetchServiceCache: {
path: '/services/:serviceId/cache',
method: 'GET',
entity: 'cache'
},
createServiceCache: {
path: '/services/:serviceId/cache',
method: 'POST',
entity: 'cache'
},
updateServiceCache: {
path: '/services/:serviceId/cache',
method: 'PUT',
entity: 'cache'
},
deleteServiceCache: {
path: '/services/:serviceId/cache',
method: 'DELETE'
},
// Service Roles: http://support.mashery.com/docs/read/mashery_api/30/resources/services/roles
fetchAllServiceRoles: {
path: '/services/:id/roles',
method: 'GET',
entity: 'roles'
},
fetchServiceRole: {
path: '/services/:serviceId/roles/:id',
method: 'GET',
entity: 'roles'
},
createServiceRole: {
path: '/services/:serviceId/roles',
method: 'POST',
entity: 'roles'
},
updateServiceRole: {
path: '/services/:serviceId/roles/:id',
method: 'PUT',
entity: 'roles'
},
deleteServiceRole: {
path: '/services/:serviceId/roles/:id',
method: 'DELETE'
},
// Error Sets: http://support.mashery.com/docs/read/mashery_api/30/resources/services/errorsets
fetchAllServiceErrorSets: {
path: '/services/:id/errorSets',
method: 'GET',
entity: 'errorSet'
},
fetchServiceErrorSet: {
path: '/services/:serviceId/errorSets/:id',
method: 'GET',
entity: 'errorSet'
},
createServiceErrorSet: {
path: '/services/:serviceId/errorSets',
method: 'POST',
entity: 'errorSet'
},
updateServiceErrorSet: {
path: '/services/:serviceId/errorSets/:id',
method: 'PUT',
entity: 'errorSet'
},
deleteServiceErrorSet: {
path: '/services/:serviceId/errorSets/:id',
method: 'DELETE'
},
// Error Messages: http://support.mashery.com/docs/read/mashery_api/30/resources/services/errorsets/errormessages
fetchAllErrorMessages: {
path: '/services/:serviceId/errorSets/:errorSetId/errorMessages',
method: 'GET',
entity: 'errorMessage'
},
fetchErrorMessage: {
path: '/services/:serviceId/errorSets/:errorSetId/errorMessages/:id',
method: 'GET',
entity: 'errorMessage'
},
createErrorMessage: {
path: '/services/:serviceId/errorSets/:errorSetId/errorMessages',
method: 'POST',
entity: 'errorMessage'
},
updateErrorMessage: {
path: '/services/:serviceId/errorSets/:errorSetId/errorMessages/:id',
method: 'PUT',
entity: 'errorMessage'
},
deleteErrorMessage: {
path: '/services/:serviceId/errorSets/:errorSetId/errorMessages/:id',
method: 'DELETE'
},
// Packages: http://support.mashery.com/docs/read/mashery_api/30/resources/packages
fetchAllPackages: {
path: '/packages',
method: 'GET',
entity: 'package'
},
fetchPackage: {
path: '/packages/:id',
method: 'GET',
entity: 'package'
},
createPackage: {
path: '/packages',
method: 'POST',
entity: 'package'
},
updatePackage: {
path: '/packages/:id',
method: 'PUT',
entity: 'package'
},
deletePackage: {
path: '/packages/:id',
method: 'DELETE'
},
// Package Keys: http://support.mashery.com/docs/read/mashery_api/30/resources/packagekeys
fetchAllPackageKeys: {
path: '/packageKeys',
method: 'GET',
entity: 'packageKey'
},
fetchPackageKey: {
path: '/packageKeys/:id',
method: 'GET',
entity: 'packageKey'
},
updatePackageKey: {
path: '/packageKeys/:id',
method: 'PUT',
entity: 'packageKey'
},
deletePackageKey: {
path: '/packageKeys/:id',
method: 'DELETE'
},
// Plans: http://support.mashery.com/docs/read/mashery_api/30/resources/packages/plans
fetchAllPlans: {
path: '/packages/:packageId/plans',
method: 'GET',
entity: 'plan'
},
fetchPlan: {
path: '/packages/:packageId/plans/:id',
method: 'GET',
entity: 'plan'
},
createPlan: {
path: '/packages/:packageId/plans',
method: 'POST',
entity: 'plan'
},
// Plan Services: http://support.mashery.com/docs/read/mashery_api/30/resources/packages/plans/services
fetchAllPlanServices: {
path: '/packages/:packageId/plans/:planId/services',
method: 'GET',
entity: 'service'
},
fetchAllPlanServicesForService: {
path: '/packages/:packageId/plans/:planId/services/:id',
method: 'GET',
entity: 'service'
},
deletePlanService: {
path: '/packages/:packageId/plans/:planId/services/:id',
method: 'DELETE',
entity: 'service'
},
updatePlanService: {
path: '/packages/:packageId/plans/:planId/services/:id',
method: 'PUT',
entity: 'service'
},
createPlanService: {
path: '/packages/:packageId/plans/:planId/services',
method: 'POST',
entity: 'service'
},
createPlanEndpoint: {
path: '/packages/:packageId/plans/:planId/services/:serviceId/endpoints',
method: 'POST',
entity: 'endpoint'
},
createPlanMethod: {
path:
'/packages/:packageId/plans/:planId/services/:serviceId/endpoints/:endpointId/methods',
method: 'POST',
entity: 'endpoint'
},
// Domains: http://support.mashery.com/docs/read/mashery_api/30/resources/domains
fetchAllDomains: {
path: '/domains',
method: 'GET',
entity: 'domain'
},
fetchDomain: {
path: '/domains/:id',
method: 'GET',
entity: 'domain'
},
createDomain: {
path: '/domains',
method: 'POST',
entity: 'domain'
},
// Public Domains: http://support.mashery.com/docs/read/mashery_api/30/resources/domains/public
fetchPublicDomains: {
path: '/domains/public',
method: 'GET',
entity: 'domain'
},
// Public FQDN: http://support.mashery.com/docs/read/mashery_api/30/resources/domains/public/hostnames
fetchPublicDomainFQDNs: {
path: '/domains/public/hostnames',
method: 'GET',
entity: 'domain'
},
// System Domains: http://support.mashery.com/docs/read/mashery_api/30/resources/domains/system
fetchSystemDomains: {
path: '/domains/system',
method: 'GET',
entity: 'domain'
},
// Roles: http://support.mashery.com/docs/read/mashery_api/30/resources/roles
fetchAllRoles: {
path: '/roles',
method: 'GET',
entity: 'role'
},
// Scheduled Maintenance Events: http://support.mashery.com/docs/read/mashery_api/30/resources/scheduledmaintenanceevents
fetchAllScheduledMaintenance: {
path: '/scheduledMaintenanceEvents',
method: 'GET'
},
fetchScheduledMaintenance: {
path: '/scheduledMaintenanceEvents/:id',
method: 'GET'
},
createScheduledMaintenance: {
path: '/scheduledMaintenanceEvents',
method: 'POST'
},
updateScheduledMaintenance: {
path: '/scheduledMaintenanceEvents/:id',
method: 'PUT'
},
deleteScheduledMaintenance: {
path: '/scheduledMaintenanceEvents/:id',
method: 'DELETE'
},
// Scheduled Maintenance Event Endpoints: http://support.mashery.com/docs/read/mashery_api/30/resources/scheduledmaintenanceevents/endpoints
fetchAllScheduledMaintenanceEndpoints: {
path: '/scheduledMaintenanceEvents/:maintenanceId/endpoints',
method: 'GET'
},
fetchScheduledMaintenanceEndpoint: {
path: '/scheduledMaintenanceEvents/:maintenanceId/endpoints/:id',
method: 'GET'
},
createScheduledMaintenanceEndpoint: {
path: '/scheduledMaintenanceEvents/:maintenanceId/endpoints',
method: 'POST'
},
updateScheduledMaintenanceEndpoint: {
path: '/scheduledMaintenanceEvents/:maintenanceId/endpoints/:id',
method: 'PUT'
},
deleteScheduledMaintenanceEndpoint: {
path: '/scheduledMaintenanceEvents/:maintenanceId/endpoints/:id',
method: 'DELETE'
},
// Email Sets: http://support.mashery.com/docs/read/mashery_api/30/resources/emailtemplatesets
fetchAllEmailTemplateSets: {
path: '/emailTemplateSets',
method: 'GET'
},
fetchEmailTemplateSet: {
path: '/emailTemplateSets/:id',
method: 'GET'
},
createEmailTemplateSet: {
path: '/emailTemplateSets',
method: 'POST'
},
updateEmailTemplateSet: {
path: '/emailTemplateSets/:id',
method: 'PUT'
},
deleteEmailTemplateSet: {
path: '/emailTemplateSets/:id',
method: 'DELETE'
},
// Email Templates: http://support.mashery.com/docs/read/mashery_api/30/resources/emailtemplatesets/emailtemplates
fetchAllEmailTemplates: {
path: '/emailTemplateSets/:emailSetId/emailTemplates',
method: 'GET'
},
fetchEmailTemplate: {
path: '/emailTemplateSets/:emailSetId/emailTemplates/:id',
method: 'GET'
},
createEmailTemplate: {
path: '/emailTemplateSets/:emailSetId/emailTemplates',
method: 'POST'
},
updateEmailTemplate: {
path: '/emailTemplateSets/:emailSetId/emailTemplates/:id',
method: 'PUT'
},
deleteEmailTemplate: {
path: '/emailTemplateSets/:emailSetId/emailTemplates/:id',
method: 'DELETE'
}
}
| 27.402027 | 142 | 0.668845 |
d280a04a542bf4b7b9efb100794bc8f1a61d04a4 | 41,609 | php | PHP | application/views/outlet/view.php | karthik-aavana/svn-aodry | 5f8f7e2b6b4a6af7dd298d02d2cf3c0747392d51 | [
"MIT"
] | 1 | 2020-06-21T15:51:33.000Z | 2020-06-21T15:51:33.000Z | application/views/outlet/view.php | karthik-aavana/svn-aodry | 5f8f7e2b6b4a6af7dd298d02d2cf3c0747392d51 | [
"MIT"
] | 1 | 2020-06-21T17:46:06.000Z | 2020-06-21T17:46:06.000Z | application/views/outlet/view.php | karthik-aavana/svn-aodry | 5f8f7e2b6b4a6af7dd298d02d2cf3c0747392d51 | [
"MIT"
] | 1 | 2020-03-18T13:50:58.000Z | 2020-03-18T13:50:58.000Z | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
$this->load->view('layout/header');
if (!function_exists('precise_amount')) {
$GLOBALS['common_settings_amount_precision'] = $access_common_settings[0]->amount_precision;
function precise_amount($val) {
$val = (float) $val;
// $amt = round($val,$GLOBALS['common_settings_amount_precision']);
$dat = number_format($val, $GLOBALS['common_settings_amount_precision'], '.', '');
return $dat;
}
}
$convert_rate = 1;
?>
<?php $outlet_id = $this->encryption_url->encode($data[0]->outlet_id); ?>
<div class="content-wrapper">
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Outlet Invoice</h3>
<a class="btn btn-sm btn-default pull-right back_button" id="cancel" onclick1="cancel('outlet')">Back</a>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-12">
<h2 class="page-header">
<i class="fa fa-building-o"></i> <?= $branch[0]->firm_name ?>
<small class="pull-right"> <?php
$date = $data[0]->outlet_date;
$c_date = date('d-m-Y', strtotime($date));
echo "Date : " . $c_date;
?></small>
</h2>
</div>
</div>
<div class="row invoice-info">
<div class="col-sm-4">
From
<address>
<strong><?= $branch[0]->firm_name ?></strong>
<?php if (isset($branch[0]->firm_name) && $branch[0]->firm_name != "") { ?>
<?php } ?>
<br/>
<?php if (isset($branch[0]->branch_address) && $branch[0]->branch_address != "") { ?>
Address : <?php
echo str_replace(array(
"\r\n",
"\\r\\n",
"\n",
"\\n"
), "<br>", $branch[0]->branch_address);
?>
<?php } ?>
<br/>
Location :
<?php
if (isset($branch[0]->branch_city_name) && $branch[0]->branch_city_name != "") {
if (isset($branch[0]->branch_city_name) && $branch[0]->branch_city_name != "") {
echo $branch[0]->branch_city_name . ",";
}
if (isset($branch[0]->branch_state_name) && $branch[0]->branch_state_name != "") {
echo $branch[0]->branch_state_name . ",";
}
if (isset($branch[0]->branch_country_name) && $branch[0]->branch_country_name != "") {
echo $branch[0]->branch_country_name;
}
}
?>
<br/>
Mobile: <?php if (isset($branch[0]->branch_mobile) && $branch[0]->branch_mobile != "") { ?>
<?= $branch[0]->branch_mobile ?>
<?php } ?>
<br>
Email: <?php if (isset($branch[0]->branch_email_address) && $branch[0]->branch_email_address != "") { ?>
<?= $branch[0]->branch_email_address ?>
<?php
}
if (isset($branch[0]->branch_gstin_number) && $branch[0]->branch_gstin_number != "") {
?>
<br>
GSTIN: <?= $branch[0]->branch_gstin_number ?>
<?php } ?>
</address>
To
<b class="capitalize">
<?php if (isset($data[0]->company_name) && $data[0]->company_name != "") { ?>
<strong class="capitalize"><?= $data[0]->company_name ?></strong>
<?php } ?>
</b>
<address>
<?php
if (!empty($data[0]->branch_address)) {
echo str_replace(array("\r\n", "\\r\\n", "\n", "\\n"), "<br>", $data[0]->branch_address);
}
?>
<br>
Mobile: <?php if (isset($data[0]->branch_mobile) && $data[0]->branch_mobile != "") { ?>
<?= $data[0]->branch_mobile ?>
<?php } ?>
<br>
Email: <?php if (isset($data[0]->branch_email_address) && $data[0]->branch_email_address != "") { ?>
<?= $data[0]->branch_email_address ?>
<br>
<?php
}
if (isset($data[0]->branch_gstin_number) && $data[0]->branch_gstin_number != "") { ?>
GSTIN: <?= $data[0]->branch_gstin_number; ?>
<?php } ?>
</address>
</div>
<?php
$is_transport = false;
$is_shipment = false;
$order_det = $data[0];
if ($order_det->transporter_name != '' || $order_det->transporter_gst_number != '' || $order_det->lr_no != '' || $order_det->vehicle_no != '')
$is_transport = true;
if ($order_det->mode_of_shipment != '' || $order_det->ship_by != '' || $order_det->net_weight != '' || $order_det->gross_weight != '' || $order_det->origin != '' || $order_det->destination != '' || $order_det->shipping_type != '' || $order_det->shipping_type_place != '' || $order_det->lead_time != '' || $order_det->warranty != '' || $order_det->payment_mode != '')
$is_shipment = true;
if ($is_shipment == false && $is_transport == false) { ?>
<div class="col-sm-4 pr-0"></div>
<?php } ?>
<div class="col-sm-4 pr-0">
<div class="bg-light-table">
<strong>Invoice Details</strong><br>
Invoice Number: <?= $data[0]->outlet_invoice_number; ?><br>
<?php
$date = $data[0]->outlet_date;
$c_date = date('d-m-Y', strtotime($date));
echo "Invoice Date : " . $c_date;
?>
<?php
if (isset($data[0]->place_of_supply)) {
if ($data[0]->place_of_supply != "" || $data[0]->place_of_supply != null) {
echo '<br>Place of Supply : ' . $data[0]->place_of_supply;
}
}
if (isset($data[0]->shipping_address)) {
if ($data[0]->shipping_address != "" || $data[0]->shipping_address != null) {
echo '<br><br><b>Shipping Address</b><br>' . str_replace(array("\r\n", "\\r\\n", "\n", "\\n", "\\"), "", $data[0]->shipping_address);
}
}
if (isset($data[0]->shipping_gstin)) {
if ($data[0]->shipping_gstin != "" || $data[0]->shipping_gstin != null) {
echo '<br>Shipping GSTIN : ' . $data[0]->shipping_gstin;
}
}
?>
<br>
Billing Country :
<span><?php
$Country = (isset($data[0]->billing_country) ? ucfirst($data[0]->billing_country) : '');
if (!empty($billing_address)) {
if ($billing_address[0]->country_name != '')
$Country = ucfirst($billing_address[0]->country_name);
}
echo $Country;
?>
</span>
<br>
Nature of Supply :
<span><?php
if (isset($nature_of_supply)) {
echo $nature_of_supply;
}
?>
</span>
<br>
GST Payable on Reverse Charge:
<span><?php
if (isset($data[0]->outlet_gst_payable)) {
echo ucfirst($data[0]->outlet_gst_payable);
}
?>
</span>
</div>
</div>
<?php
if ($is_shipment == true || $is_transport == true) {
?>
<div class="col-sm-4 pl-0">
<div class="bg-light-table text-right">
<?php if ($is_shipment) { ?>
<b class="capitalize">Shipping Details,</b>
<br />
<?php
if ($order_det->mode_of_shipment != '') {
echo '<span>Mode of Shipment: ' . $order_det->mode_of_shipment . ' </span><br>';
}
if ($order_det->ship_by != '') {
echo '<span>Ship By : ' . $order_det->ship_by . ' </span>';
}
if ($order_det->ship_by != '' && $order_det->net_weight != '')
echo " | ";
if ($order_det->net_weight != '') {
echo '<span>Net Weight : ' . $order_det->net_weight . ' </span>';
}
if ($order_det->ship_by != '' || $order_det->net_weight != '')
echo "<br>";
if ($order_det->gross_weight != '') {
echo '<span>Gross Weight : ' . $order_det->gross_weight . ' </span>';
}
if ($order_det->gross_weight != '' && $order_det->origin != '')
echo " | ";
if ($order_det->origin != '') {
echo '<span>Origin : ' . $order_det->origin . ' </span>';
}
if ($order_det->gross_weight != '' || $order_det->origin != '')
echo "<br>";
if ($order_det->destination != '') {
?>
<?php echo '<span>Destination : ' . $order_det->destination . '</span><br>';
?>
<?php
}
if ($order_det->shipping_type_place != '') {
echo '<span>Shipping Type Place : ' . $order_det->shipping_type_place . '</span><br>';
}
if ($order_det->lead_time != '') {
echo '<span>Lead Time : ' . $order_det->lead_time . ' </span>';
}
if ($order_det->lead_time != '' && $order_det->warranty != '')
echo " | ";
if ($order_det->warranty != '') {
echo '<span>Warranty : ' . $order_det->warranty . ' </span>';
}
if ($order_det->lead_time != '' || $order_det->warranty != '')
echo "<br>";
if ($order_det->payment_mode != '')
echo '<span>Payment Mode : ' . $order_det->payment_mode . '</span><br><br>';
}
if ($is_transport) {
?>
<b class="capitalize">Transporter Details,</b>
<br/>
<?php
if ($order_det->transporter_name != '') {
echo '<span>Name: ' . $order_det->transporter_name . '</span><br>';
}
if ($order_det->transporter_gst_number != '') {
echo '<span>GST Number: ' . $order_det->transporter_gst_number . '</span><br>';
}
if ($order_det->lr_no != '') {
echo '<span>LR Number: ' . $order_det->lr_no . '</span><br>';
}
if ($order_det->vehicle_no != '') {
echo '<span>Vehicle Number: ' . $order_det->vehicle_no . '</span><br>';
}
}
?>
</div>
</div>
<?php } ?>
</div>
<div class="row">
<div class="col-sm-12 table-responsive mt-15">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th height="30px">#</th>
<th>Items</th>
<th>Quantity</th>
<th>Rate</th>
<th>Subtotal</th>
<?php
if ($discount_exist > 0) {
?>
<th>Discount</th>
<?php } ?>
<?php
if ($discount_exist > 0 && ($tax_exist > 0 || $igst_exist > 0 || $cgst_exist > 0 || $sgst_exist > 0 )) {
?>
<th>Taxable Value</th>
<?php } ?>
<?php
if ($tds_exist > 0) {
?>
<th>TCS</th>
<?php } ?>
<?php
if ($tax_exist > 0) {
?>
<th>Tax</th>
<?php } elseif ($igst_exist > 0) { ?>
<th>IGST</th>
<?php } elseif ($cgst_exist > 0 || $sgst_exist > 0) { ?>
<th>CGST</th>
<th><?= ($is_utgst == '1' ? 'UTGST' : 'SGST'); ?></th>
<?php } ?>
<?php if ($cess_exist > 0) { ?>
<th style="text-align: center;">CESS</th>
<?php } ?>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
$quantity = 0;
$price = 0;
$grand_total = $tot_cgst = $tot_sgst = $tot_igst = 0;
foreach ($items as $value) { ?>
<tr>
<td><?php echo $i; ?></td>
<td style="text-align: left;">
<span class="capitalize" style="font-weight: none"><?php echo strtoupper(strtolower($value->product_name)); ?></span>
<br>(HSN/SAC: <?php echo $value->product_hsn_sac_code; ?>)
<?php
if (isset($value->outlet_item_description) && $value->outlet_item_description != "") {
echo "<br/>";
echo $value->outlet_item_description;
}
?><br><?php echo $value->product_batch; ?>
</td>
<td><?php
echo $value->outlet_item_quantity;
if ($value->product_unit != '') {
$unit = explode("-", $value->product_unit);
if($unit[0] != '') echo " <br>(" . $unit[0].')';
}
?></td>
<td style="text-align: right;"><?php echo precise_amount(($value->outlet_item_unit_price * $convert_rate)); ?></td>
<td style="text-align: right;"><?php echo precise_amount(($value->outlet_item_sub_total * $convert_rate)); ?></td>
<?php
if ($discount_exist > 0) {
?>
<td style="text-align: right;"><?php echo precise_amount(($value->outlet_item_discount_amount * $convert_rate)); ?></td>
<?php } ?>
<?php
if ($discount_exist > 0 && ($tax_exist > 0 || $igst_exist > 0 || $cgst_exist > 0 || $sgst_exist > 0 )) {
?>
<td style="text-align: right;"><?php echo precise_amount(($value->outlet_item_taxable_value * $convert_rate)); ?></td>
<?php } ?>
<?php if ($tds_exist > 0) { ?>
<td style="text-align: right;">
<?php
if ($value->outlet_item_tds_amount < 1) {
echo '-';
} else {
?><?= precise_amount($value->outlet_item_tds_amount * $convert_rate); ?><br>(<?= round($value->outlet_item_tds_percentage, 2); ?>%)
<?php } ?>
</td>
<?php } ?>
<?php
if ($tax_exist > 0) {
?>
<td style="text-align: right;">
<?php
if ($value->outlet_item_tax_amount < 1) {
echo '-';
} else {
?>
<?php echo precise_amount(($value->outlet_item_tax_amount * $convert_rate)); ?><br>(<?= ($value->outlet_item_tax_percentage > 0 ? round(abs($value->outlet_item_tax_percentage), 2) . '%' : '-'); ?>)<?php } ?></td>
<?php } elseif ($igst_exist > 0) { ?>
<td style="text-align: right;">
<?php
if ($value->outlet_item_igst_amount < 1) {
echo '-';
} else {
?>
<?= ($value->outlet_item_igst_amount > 0 ? precise_amount($value->outlet_item_igst_amount * $convert_rate) : '-'); ?>
<?= ($value->outlet_item_igst_percentage > 0 ? "<br>(" . round(abs($value->outlet_item_igst_percentage), 2) . '%' : ''); ?>) <?php } ?>
</td>
<?php } elseif ($cgst_exist > 0 || $sgst_exist > 0) { ?>
<td style="text-align: right;">
<?php
if ($value->outlet_item_cgst_amount < 1) {
echo '-';
} else {
?>
<?php echo precise_amount(($value->outlet_item_cgst_amount * $convert_rate)); ?><br>(<?php echo round($value->outlet_item_cgst_percentage, 2); ?>%)<?php } ?></td>
<td style="text-align: right;">
<?php
if ($value->outlet_item_sgst_amount < 1) {
echo '-';
} else {
?><?php echo precise_amount(($value->outlet_item_sgst_amount * $convert_rate)); ?><br>(<?php echo round($value->outlet_item_sgst_percentage, 2); ?>%)<?php } ?></td>
<?php } ?>
<?php if ($cess_exist > 0) { ?>
<td style="text-align: right;">
<?php
if ($value->outlet_item_tax_cess_amount < 1) {
echo '-';
} else {
?><?= precise_amount(($value->outlet_item_tax_cess_amount * $convert_rate)); ?><br>(<?= round($value->outlet_item_tax_cess_percentage, 2); ?>%)<?php } ?></td>
<?php } ?>
<td style="text-align: right;"><?php echo precise_amount(($value->outlet_item_grand_total * $convert_rate)); ?></td>
</tr>
<?php
$i++;
$quantity = bcadd($quantity, $value->outlet_item_quantity);
$price = bcadd($price, $value->outlet_item_unit_price, 2);
$grand_total = bcadd($grand_total, $value->outlet_item_grand_total, 2);
if ($igst_exist > 0) $tot_igst += $value->outlet_item_igst_amount;
if ($sgst_exist > 0) $tot_sgst += $value->outlet_item_sgst_amount;
if ($cgst_exist > 0) $tot_cgst += $value->outlet_item_cgst_amount;
}
?>
<tr>
<th colspan="2"></th>
<th style="text-align: right;"><!-- <?= round($quantity, 2) ?> --></th>
<th style="text-align: right;"><?= precise_amount(($price * $convert_rate)) ?></th>
<th style="text-align: right;"><?= precise_amount(($data[0]->outlet_sub_total * $convert_rate)) ?></th>
<?php
if ($discount_exist > 0) {
?>
<th style="text-align: right;"><?= precise_amount(($data[0]->outlet_discount_amount * $convert_rate)) ?></th>
<?php } ?>
<?php
if ($discount_exist > 0 && ($tax_exist > 0 || $igst_exist > 0 || $cgst_exist > 0 || $sgst_exist > 0 )) {
?>
<th style="text-align: right;"><?= precise_amount(($data[0]->outlet_taxable_value * $convert_rate)) ?></th>
<?php } ?>
<?php
if ($tds_exist > 0) { ?>
<th style="text-align: right;"><?= precise_amount((($data[0]->outlet_tcs_amount) * $convert_rate)) ?></th>
<?php } ?>
<?php
if ($tax_exist > 0) {
?>
<th style="text-align: right;"><?= precise_amount(($data[0]->outlet_tax_amount * $convert_rate)) ?></th>
<?php } elseif ($igst_exist > 0) { ?>
<th style="text-align: right;"><?= precise_amount(($tot_igst * $convert_rate)) ?></th>
<?php } elseif ($cgst_exist > 0 || $sgst_exist > 0) { ?>
<th style="text-align: right;"><?= precise_amount(($tot_cgst * $convert_rate)) ?></th>
<th style="text-align: right;"><?= precise_amount(($tot_sgst * $convert_rate)) ?></th>
<?php } ?>
<?php if ($cess_exist > 0) { ?>
<th style="text-align: right;"><?= precise_amount(($data[0]->outlet_tax_cess_amount * $convert_rate)) ?></th>
<?php } ?>
<th style="text-align: right;"><?= precise_amount($grand_total * $convert_rate); ?></th>
</tr>
</tbody>
</table>
<table id="table-total" class="table table-hover table-bordered table-responsive">
<tbody>
<tr>
<td><b>Total Value (<?= $data[0]->currency_symbol; ?>)</b></td>
<td><?= precise_amount($data[0]->outlet_sub_total); ?></td>
</tr>
<?php if ($discount_exist > 0) { ?>
<tr>
<td>Discount (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( - ) <?= precise_amount($data[0]->outlet_discount_amount); ?></td>
</tr>
<?php } ?>
<?php if ($tds_exist > 0) { ?>
<?php if ($data[0]->outlet_tds_amount > 0) { ?>
<tr>
<td>TDS (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: black;"> <?= precise_amount($data[0]->outlet_tds_amount); ?></td>
</tr>
<?php } ?>
<?php if ($data[0]->outlet_tcs_amount > 0) { ?>
<tr>
<td>TCS (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->outlet_tcs_amount); ?></td>
</tr>
<?php } ?>
<?php } ?>
<?php if ($igst_exist > 0) { ?>
<tr>
<td>IGST (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->outlet_igst_amount); ?></td>
</tr>
<?php } elseif ($cgst_exist > 0 || $sgst_exist > 0) { ?>
<tr>
<td>CGST (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + )<?= precise_amount($data[0]->outlet_cgst_amount); ?>
</td>
</tr>
<tr>
<td><?= ($is_utgst == '1' ? 'UTGST' : 'SGST'); ?> (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->outlet_sgst_amount); ?></td>
</tr>
<?php } elseif ($tax_exist > 0) { ?>
<tr>
<td>TAX (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->outlet_tax_amount); ?></td>
</tr>
<?php } ?>
<?php if ($cess_exist > 0) { ?>
<tr>
<td>Cess (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->outlet_tax_cess_amount); ?></td>
</tr>
<?php } ?>
<?php if ($data[0]->total_freight_charge > 0) { ?>
<tr>
<td>Freight Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->total_freight_charge); ?></td>
</tr>
<?php
}
if ($data[0]->total_insurance_charge > 0) {
?>
<tr>
<td>Insurance Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->total_insurance_charge); ?></td>
</tr>
<?php
}
if ($data[0]->total_packing_charge > 0) {
?>
<tr>
<td>Packing & Forwarding Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->total_packing_charge); ?></td>
</tr>
<?php
}
if ($data[0]->total_incidental_charge > 0) {
?>
<tr>
<td>Incidental Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->total_incidental_charge); ?></td>
</tr>
<?php
}
if ($data[0]->total_inclusion_other_charge > 0) {
?>
<tr>
<td>Other Inclusive Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->total_inclusion_other_charge); ?></td>
</tr>
<?php
}
if ($data[0]->total_exclusion_other_charge > 0) {
?>
<tr>
<td>Other Exclusive Charge (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: green;">( - ) <?= precise_amount($data[0]->total_exclusion_other_charge); ?></td>
</tr>
<?php } ?>
<?php if ($data[0]->round_off_amount > 0) { ?>
<tr>
<td>Round Off (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: green;">( - ) <?= precise_amount($data[0]->round_off_amount); ?></td>
</tr>
<?php } ?>
<?php if ($data[0]->round_off_amount < 0) { ?>
<tr>
<td>Round Off (<?= $data[0]->currency_symbol; ?>)</td>
<td style="color: red;">( + ) <?= precise_amount($data[0]->round_off_amount * -1); ?></td>
</tr>
<?php } ?>
<tr>
<td><b>Grand Total (<?= $data[0]->currency_symbol; ?>)</b></td>
<td><b>( = ) <?= precise_amount($data[0]->outlet_grand_total); ?><b></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
<?php $this->load->view('layout/footer'); ?> | 71.616179 | 394 | 0.266505 |
e3e493509bbe3706cf96fc4584acd6d04378bcdd | 1,121 | sql | SQL | SQL/Availability/tblHrsInPeriod.sql | jaymegordo/SMSEventLog | c4836793709f501d4aa4b84819931c167f14d9b3 | [
"MIT"
] | 1 | 2020-11-14T23:58:47.000Z | 2020-11-14T23:58:47.000Z | SQL/Availability/tblHrsInPeriod.sql | jaymegordo/SMSEventLog | c4836793709f501d4aa4b84819931c167f14d9b3 | [
"MIT"
] | 93 | 2021-03-02T18:27:05.000Z | 2022-03-30T18:48:09.000Z | SQL/Availability/tblHrsInPeriod.sql | jaymegordo/SMSEventLog | c4836793709f501d4aa4b84819931c167f14d9b3 | [
"MIT"
] | null | null | null | SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[tblHrsInPeriod](
@DateLower DATE,
@DateUpper DATE,
@MineSite VARCHAR(255),
@period VARCHAR(10) = 'month')
RETURNS TABLE
AS
RETURN
-- Return Unit and sum of total hrs in system and excluded from system within specified period
SELECT
-- need min and max date per group
CASE WHEN @period = 'month' THEN
CAST(YEAR(c.Date) as VARCHAR) + '-' + CAST(MONTH(c.Date) as VARCHAR)
ELSE
CAST(YEAR(c.Date) as VARCHAR) + '-' + CAST(DATEPART(week, c.Date) as VARCHAR)
END as Period,
c.Unit,
ROUND(SUM(IIF(c.MA = 1, c.Hours, 0)), 0) as ExcludeHours_MA,
ROUND(SUM(c.Hours), 0) as ExcludeHours_PA
FROM
DowntimeExclusions c
LEFT JOIN UnitID a on a.Unit=c.Unit
WHERE
c.Date BETWEEN @DateLower AND @DateUpper and
a.MineSite = @MineSite
GROUP BY
c.Unit,
CASE WHEN @period = 'month' THEN
CAST(YEAR(c.Date) as VARCHAR) + '-' + CAST(MONTH(c.Date) as VARCHAR)
ELSE
CAST(YEAR(c.Date) as VARCHAR) + '-' + CAST(DATEPART(week, c.Date) as VARCHAR)
END
GO
| 22.877551 | 94 | 0.64496 |
c3c84fa6211a2728070705f9d642b0dedbfb4c50 | 43 | sql | SQL | www/html/bitrix/modules/bitrixcloud/install/db/mysql/uninstall.sql | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | 1 | 2020-10-05T04:28:40.000Z | 2020-10-05T04:28:40.000Z | www/html/bitrix/modules/bitrixcloud/install/db/mysql/uninstall.sql | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | null | null | null | www/html/bitrix/modules/bitrixcloud/install/db/mysql/uninstall.sql | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | null | null | null | DROP TABLE if exists b_bitrixcloud_option;
| 21.5 | 42 | 0.860465 |
bcd7be2b3313b08be4fdf080995122147a02cdaf | 713 | js | JavaScript | services/ore/ore-downloads.service.js | Cube-Enix/shields | e3854098d629e9c390196df0c0fd2fd5795b6bca | [
"CC0-1.0"
] | 16,313 | 2015-01-01T12:20:07.000Z | 2022-03-31T22:00:23.000Z | services/ore/ore-downloads.service.js | Cube-Enix/shields | e3854098d629e9c390196df0c0fd2fd5795b6bca | [
"CC0-1.0"
] | 5,688 | 2015-01-01T14:38:26.000Z | 2022-03-31T23:13:32.000Z | services/ore/ore-downloads.service.js | mikscust/shields | aac838934b1767d0696b0141043be07d1fa250e6 | [
"CC0-1.0"
] | 8,174 | 2015-01-03T13:11:17.000Z | 2022-03-31T21:52:28.000Z | import { renderDownloadsBadge } from '../downloads.js'
import { BaseOreService, documentation, keywords } from './ore-base.js'
export default class OreDownloads extends BaseOreService {
static category = 'downloads'
static route = {
base: 'ore/dt',
pattern: ':pluginId',
}
static examples = [
{
title: 'Ore Downloads',
namedParams: { pluginId: 'nucleus' },
staticPreview: renderDownloadsBadge({ downloads: 560891 }),
documentation,
keywords,
},
]
static defaultBadgeData = { label: 'downloads' }
async handle({ pluginId }) {
const { stats } = await this.fetch({ pluginId })
return renderDownloadsBadge({ downloads: stats.downloads })
}
}
| 24.586207 | 71 | 0.653576 |
1dbbda0c6baf7dccc0b00e89a394ec1502b585b0 | 13,202 | dart | Dart | lib/audiopage.dart | KEVINAMAYI/Flutter-Family-App | 79f1aba6e6bd82bc10dccf0d2872992117caf8ef | [
"MIT"
] | null | null | null | lib/audiopage.dart | KEVINAMAYI/Flutter-Family-App | 79f1aba6e6bd82bc10dccf0d2872992117caf8ef | [
"MIT"
] | null | null | null | lib/audiopage.dart | KEVINAMAYI/Flutter-Family-App | 79f1aba6e6bd82bc10dccf0d2872992117caf8ef | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:my_family_app/main.dart';
class MyAudioPage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
backgroundColor:Color.fromRGBO(58,66,86,0.9),
title:Text(
'MyAudio Page'
),
actions: <Widget>[
IconButton(
icon:Icon(Icons.search),
onPressed:(){
showSearch(
context:context,delegate: SearchImplementation()
);
},
)
],),
drawer:MyDrawer(),
body:Container(
padding:EdgeInsets.all(0.0),
child:
new MyListWidget(),
),
);
}
}
/*A list of the audios*/
class MyListWidget extends StatelessWidget
{
Widget build(BuildContext context){
return ListView(
children: <Widget>[
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Marriage and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
onTap:(){
showModalBottomSheet<void>(
context: context,
builder:(BuildContext context)=>
Container(
child:Padding(
padding:EdgeInsets.only(top:20.0),
child:Column(
children: <Widget>[
ListTile(
leading:Icon(
Icons.cloud_download
),
title:Text("Download",
style: TextStyle(
fontSize:17.0,
fontWeight:FontWeight.bold,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:Icon(
Icons.play_arrow
),
title:Text("Play",
style: TextStyle(
fontSize:17.0,
fontWeight:FontWeight.bold,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:Icon(
Icons.share
),
title:Text("Share",
style: TextStyle(
fontSize:17.0,
fontWeight:FontWeight.bold,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:Icon(
Icons.link
),
title:Text("Get Link",
style: TextStyle(
fontSize:17.0,
fontWeight:FontWeight.bold,
color:Color.fromARGB(255,39,55,89),
),),
)
],
))
),
);
},
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Wife and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Husband and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Children and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Dating and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Family and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:Text('Friends and Courtship Explained',
style:TextStyle(
fontWeight:FontWeight.w500,
color:Color.fromARGB(255,39,55,89),
),),
),
],
);
}
}
class SearchImplementation extends SearchDelegate<String>
{
final titles=[
"Marriage and Courtship Explained",
"Wife and Courtship Explained",
"Husband and Courtship Explained",
"Children and Courtship Explained",
"Dating and Courtship Explained",
"Family and Courtship Explained",
"Friends and Courtship Explained"
];
final recenttitles=[
"Dating and Courtship Explained",
"Family and Courtship Explained",
"Friends and Courtship Explained"
];
@override
List<Widget> buildActions(BuildContext context) {
//what to display on the edge of the search bar
return [
IconButton(
icon:Icon(Icons.close),
onPressed:(){
query=null;
},
)
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton
(
icon:AnimatedIcon(
icon:AnimatedIcons.menu_arrow,
progress:transitionAnimation,
),
onPressed:(){
close(context, null);
},
);
}
@override
Widget buildResults(BuildContext context) {
}
@override
Widget buildSuggestions(BuildContext context) {
final suggestion=query.isEmpty?recenttitles:titles.where((p)=> p.startsWith(query)).toList();
return ListView.builder(
itemBuilder:(context,index)=>ListTile(
leading:CircleAvatar(
child:Icon(
Icons.queue_music,
color:Colors.white,
),
backgroundColor:Color.fromARGB(215,39,55,89),
),
title:RichText(
text:TextSpan(
text:suggestion[index].substring(0,query.length),
style:TextStyle(
fontWeight:FontWeight.w500,
color:Colors.black),
children:[
TextSpan(
text:suggestion[index].substring(query.length),
style:TextStyle(
fontWeight:FontWeight.normal,
color:Colors.grey
)
)
]
),
),
),
itemCount:suggestion.length,
);
}
}
| 28.452586 | 98 | 0.398197 |
df0fcb315d68e057ac4e959c887bc92154e786a3 | 263 | sql | SQL | ghcn/11_thunder.sql | k5dru/infovis | 02f7f59d71dd5ccbb74d97de085b602ce8615942 | [
"MIT"
] | null | null | null | ghcn/11_thunder.sql | k5dru/infovis | 02f7f59d71dd5ccbb74d97de085b602ce8615942 | [
"MIT"
] | null | null | null | ghcn/11_thunder.sql | k5dru/infovis | 02f7f59d71dd5ccbb74d97de085b602ce8615942 | [
"MIT"
] | null | null | null | select latitude,
longitude,
elevation,
state,
count(*),
count(distinct station_code) as station_count,
avg(data_value)
from ghcn
where element = 'WT03'
and q_flag IS NULL
group by 1,2,3,4
having count(*) > 10
and avg(data_value) > 0.01
order by 2, 1 desc;
| 17.533333 | 46 | 0.722433 |
25bd0797ecd391c2404bc5ad7c56044e1a96c4c7 | 1,835 | ps1 | PowerShell | Audits/Audit all DC in forest.ps1 | ITChristos/ActiveDirectory | 982e9cfbbd5401f2792691604e3df9aeaae44089 | [
"MIT"
] | 1 | 2021-11-17T16:57:34.000Z | 2021-11-17T16:57:34.000Z | Audits/Audit all DC in forest.ps1 | ITChristos/ActiveDirectory | 982e9cfbbd5401f2792691604e3df9aeaae44089 | [
"MIT"
] | null | null | null | Audits/Audit all DC in forest.ps1 | ITChristos/ActiveDirectory | 982e9cfbbd5401f2792691604e3df9aeaae44089 | [
"MIT"
] | 1 | 2021-12-03T03:07:27.000Z | 2021-12-03T03:07:27.000Z | $GDCList="C:\Temp\DCList.CSV"
$TestCSVFile ="C:\Temp\AuditReport.CSV"
Remove-Item $TestCSVFile
$UniqueTest = "RC"
$CurrentLoc="C:\Temp"
$STR = "Domain Controller, Directory Service Access, Directory Service Changes, Directory Service Replication, Detailed Directory Service Replication"
Add-Content $TestCSVFile $STR
$TotNo=0
$ItemCount=0
$TestText = "Please check result"
$TestStatus="Completed"
$SumVal = "NA"
$AnyGap = "No"
Foreach ($ItemName in Get-Content "$GDCList")
{
$IntOnOrNot = ""
Remove-item $DataFileLocation -ErrorAction SilentlyContinue
$Error.Clear()
$AuditStatus = Invoke-Command -ComputerName $ItemName -Script { exe /get /Category:* /r }
IF ($Error.Count -eq 0)
{
$AuditStatus > $DataFileLocation
$CSV = Import-CSV $DataFileLocation
ForEach ($Item in $CSV)
{
$MName = $Item.Subcategory
$IncSet = $Item.'Inclusion Setting'
IF ($MName -eq "Directory Service Access")
{
$DirSuccessOrNot = "Enabled"
IF ($IncSet -eq "No Auditing")
{
$DirSuccessOrNot = "Not Enabled"
}
}
IF ($MName -eq "Directory Service Changes")
{
$DirChangesOrNot = "Enabled"
IF ($IncSet -eq "No Auditing")
{
$DirChangesOrNot = "Not Enabled"
}
}
IF ($MName -eq "Directory Service Replication")
{
$DirReplOrNot = "Enabled"
IF ($IncSet -eq "No Auditing")
{
$DirReplOrNot = "Not Enabled"
}
}
IF ($MName -eq "Detailed Directory Service Replication")
{
$DirReplDOrNot = "Enabled"
IF ($IncSet -eq "No Auditing")
{
$DirReplDOrNot = "Not Enabled"
}
}
}
$STR = $ItemName+","+$DirSuccessOrNot+","+$DirChangesOrNot+","+$DirReplOrNot+","+$DirReplDOrNot
Add-Content $TestCSVFile $STR
}
else
{
$STR = $ItemName+", ERROR: NOT Reachable"
Add-Content $TestCSVFile $STR
}
}
$AnyGap = "Yes"
IF ($AnyGap -eq "Yes")
{
$TestText = "Please check Domain Controller Auditing result."
$SumVal = ""
$TestStatus="High"
}
else
{
$TestText = " "
$SumVal = ""
$TestStatus="Passed"
} | 22.378049 | 150 | 0.708992 |
e46639f3762269ec0d43b07396b428541b694caa | 906 | swift | Swift | Example/CardScanner/ViewController.swift | askatasuna/CardScanner | 8025f14398bce176a773070320ac9d0ab99be34e | [
"MIT"
] | 144 | 2020-09-30T22:49:24.000Z | 2022-03-21T20:34:49.000Z | Example/CardScanner/ViewController.swift | askatasuna/CardScanner | 8025f14398bce176a773070320ac9d0ab99be34e | [
"MIT"
] | 2 | 2020-10-13T11:10:25.000Z | 2021-06-20T20:01:10.000Z | Example/CardScanner/ViewController.swift | askatasuna/CardScanner | 8025f14398bce176a773070320ac9d0ab99be34e | [
"MIT"
] | 25 | 2020-10-05T03:47:29.000Z | 2022-02-28T12:28:43.000Z | //
// ViewController.swift
// CardScanner
//
// Created by Narlei Moreira on 09/30/2020.
// Copyright (c) 2020 Narlei Moreira. All rights reserved.
//
import UIKit
import CardScanner
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var resultsLabel: UILabel!
@IBAction func scanPaymentCard(_ sender: Any) {
// Add NSCameraUsageDescription to your Info.plist
let scannerView = CardScanner.getScanner { card, date, cvv in
self.resultsLabel.text = "\(card) \(date) \(cvv)"
}
present(scannerView, animated: true, completion: nil)
}
}
| 26.647059 | 80 | 0.65894 |
6b3b1bbfe8af5bfe0914be7b76968965a0608c7a | 1,851 | h | C | CCBReader/CCNode+CCBRelativePositioning.h | shkatulo/CCBReader-for-CCB | b309110db85d98ab6742dbccb9650992a4bfd0bb | [
"MIT",
"Unlicense"
] | 101 | 2015-01-02T07:54:32.000Z | 2021-12-05T15:44:53.000Z | CCBReader/CCNode+CCBRelativePositioning.h | shkatulo/CCBReader-for-CCB | b309110db85d98ab6742dbccb9650992a4bfd0bb | [
"MIT",
"Unlicense"
] | 1 | 2015-06-01T09:09:46.000Z | 2015-06-01T09:09:46.000Z | CCBReader/CCNode+CCBRelativePositioning.h | shkatulo/CCBReader-for-CCB | b309110db85d98ab6742dbccb9650992a4bfd0bb | [
"MIT",
"Unlicense"
] | 44 | 2015-01-09T08:41:04.000Z | 2021-01-15T03:08:55.000Z | //
// CCNode+CCBRelativePositioning.h
// CocosBuilderExample
//
// Created by Viktor Lidholt on 7/6/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "cocos2d.h"
enum
{
kCCBPositionTypeRelativeBottomLeft,
kCCBPositionTypeRelativeTopLeft,
kCCBPositionTypeRelativeTopRight,
kCCBPositionTypeRelativeBottomRight,
kCCBPositionTypePercent,
kCCBPositionTypeMultiplyResolution,
};
enum
{
kCCBSizeTypeAbsolute,
kCCBSizeTypePercent,
kCCBSizeTypeRelativeContainer,
kCCBSizeTypeHorizontalPercent,
kCCBSizeTypeVerticalPercent,
kCCBSizeTypeMultiplyResolution,
};
enum
{
kCCBScaleTypeAbsolute,
kCCBScaleTypeMultiplyResolution
};
extern float ccbResolutionScale;
@interface CCNode (CCBRelativePositioning)
- (float) resolutionScale;
#pragma mark Positions
- (CGPoint) absolutePositionFromRelative:(CGPoint)pt type:(int)type parentSize:(CGSize)containerSize propertyName:(NSString*) propertyName;
- (void) setRelativePosition:(CGPoint)pt type:(int)type parentSize:(CGSize)containerSize propertyName:(NSString*) propertyName;
- (void) setRelativePosition:(CGPoint)position type:(int)type parentSize:(CGSize)parentSize;
- (void) setRelativePosition:(CGPoint)position type:(int)type;
#pragma mark Content Size
- (void) setRelativeSize:(CGSize)size type:(int)type parentSize:(CGSize)containerSize propertyName:(NSString*) propertyName;
- (void) setRelativeSize:(CGSize)size type:(int)type parentSize:(CGSize)parentSize;
- (void) setRelativeSize:(CGSize)size type:(int)type;
#pragma mark Scale
- (void) setRelativeScaleX:(float)x Y:(float)y type:(int)type propertyName:(NSString*)propertyName;
- (void) setRelativeScaleX:(float)x Y:(float)y type:(int)type;
#pragma mark Floats
- (void) setRelativeFloat:(float)f type:(int)type propertyName:(NSString*)propertyName;
@end
| 28.045455 | 139 | 0.78174 |
f5cf43f7747d141d67b82a7b4e7575755e65d97b | 2,617 | swift | Swift | VergeiOS/Controllers/Setup/TorSetup/TorSetup3View.swift | hellc/vIOS | 39e707142e9c7d114f69947481f2db4390c3cb7b | [
"MIT"
] | null | null | null | VergeiOS/Controllers/Setup/TorSetup/TorSetup3View.swift | hellc/vIOS | 39e707142e9c7d114f69947481f2db4390c3cb7b | [
"MIT"
] | null | null | null | VergeiOS/Controllers/Setup/TorSetup/TorSetup3View.swift | hellc/vIOS | 39e707142e9c7d114f69947481f2db4390c3cb7b | [
"MIT"
] | null | null | null | //
// TorSetup3View.swift
// VergeiOS
//
// Created by Swen van Zanten on 08/12/2018.
// Copyright © 2018 Verge Currency. All rights reserved.
//
import UIKit
import MapKit
class TorSetup3View: UIView {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var proceedButton: UIButton!
var viewController: TorViewController!
var applicationRepository: ApplicationRepository!
var torClient: TorClient!
override func awakeFromNib() {
super.awakeFromNib()
self.applicationRepository = Application.container.resolve(ApplicationRepository.self)!
self.torClient = Application.container.resolve(TorClient.self)!
updateIPAddress()
}
@IBAction func changeTorUsage(_ sender: UISwitch) {
self.applicationRepository.useTor = sender.isOn
proceedButton.setTitle(sender.isOn ? "setup.tor.slide3.positiveButton".localized : "setup.tor.slide3.negativeButton".localized, for: .normal)
if sender.isOn {
self.torClient.start {
self.updateIPAddress()
}
} else {
self.torClient.resign()
updateIPAddress()
// Notify the whole application.
NotificationCenter.default.post(name: .didTurnOffTor, object: self)
}
}
func updateIPAddress() {
let url = URL(string: Constants.ipCheckEndpoint)
let task = self.torClient.session.dataTask(with: url!) { data, response, error in
do {
if data != nil {
let ipAddress = try JSONDecoder().decode(IpAddress.self, from: data!)
self.centerMapView(withIpLocation: ipAddress)
}
} catch {
print(error)
}
}
task.resume()
}
func centerMapView(withIpLocation ipAddress: IpAddress) {
let coordinate = CLLocationCoordinate2D(
latitude: CLLocationDegrees(ipAddress.latitude),
longitude: CLLocationDegrees(ipAddress.longitude)
)
let distance: CLLocationDistance = 12000
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: distance, longitudinalMeters: distance)
DispatchQueue.main.async {
self.mapView.setCenter(coordinate, animated: true)
self.mapView.setRegion(region, animated: true)
}
}
@IBAction func proceed(_ sender: Any) {
viewController.performSegue(withIdentifier: "createWallet", sender: self)
}
}
| 30.788235 | 149 | 0.612916 |
bbcb891e269803c95dde0b4e29863ff81066502b | 602 | rs | Rust | native_implemented/web/src/document/body_1.rs | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 2,939 | 2019-08-29T16:52:20.000Z | 2022-03-31T05:42:30.000Z | native_implemented/web/src/document/body_1.rs | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 235 | 2019-08-29T23:44:13.000Z | 2022-03-17T11:43:25.000Z | native_implemented/web/src/document/body_1.rs | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 95 | 2019-08-29T19:11:28.000Z | 2022-01-03T05:14:16.000Z | //! ```elixir
//! case Lumen.Web.Document.body(document) do
//! {:ok, body} -> ...
//! :error -> ...
//! end
//! ```
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::{document, option_to_ok_tuple_or_error};
#[native_implemented::function(Elixir.Lumen.Web.Document:body/1)]
pub fn result(process: &Process, document: Term) -> exception::Result<Term> {
let document_document = document::from_term(document)?;
Ok(option_to_ok_tuple_or_error(
process,
document_document.body(),
))
}
| 26.173913 | 77 | 0.672757 |
12f0d688df6ec3a340019297248ae43444010c13 | 2,720 | html | HTML | css101/dark-model/index.html | kyo6/js-playground | 7f2ce97b32a10f40ca044059ef1b18c99278b1fb | [
"MIT"
] | null | null | null | css101/dark-model/index.html | kyo6/js-playground | 7f2ce97b32a10f40ca044059ef1b18c99278b1fb | [
"MIT"
] | null | null | null | css101/dark-model/index.html | kyo6/js-playground | 7f2ce97b32a10f40ca044059ef1b18c99278b1fb | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="supported-color-schemes" content="dark light">
<meta name="color-scheme" content="dark light">
<meta name="theme-color" content="">
<title>Document</title>
<script>
// If `prefers-color-scheme` is not supported, fall back to light mode.
// In this case, light.css will be downloaded with `highest` priority.
if (!window.matchMedia('(prefers-color-scheme)').matches) {
document.documentElement.style.display = 'none';
document.head.insertAdjacentHTML(
'beforeend',
'<link rel="stylesheet" href="css/light.css" onload="document.documentElement.style.display = ``">'
);
}
</script>
<link rel="stylesheet" href="css/dark.css" media="(prefers-color-scheme: dark)">
<link rel="stylesheet" href="css/light.css" media="(prefers-color-scheme: no-preference),(prefers-color-scheme: light)">
<link rel="stylesheet" href="css/style.css">
<link rel="manifest" href="manifest-light.webmanifest" data-href-light="manifest-light.webmanifest" data-href-dark="manifest-dark.webmanifest">
<link rel="icon" href="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Flight.png" data-href-light="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Flight.png" data-href-dark="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Fdark.png" sizes="144x144">
<script type="module" src="https://googlechromelabs.github.io/dark-mode-toggle/src/dark-mode-toggle.mjs"></script>
<script defer src="darkmode.js"></script>
</head>
<body>
<h1>Some Headline</h1>
<p>
Some body text with a <a href="#">link</a> pointing to nowhere.
</p>
<form>
<input type="text" placeholder="Some input">
<button type="button">Some button</button>
</form>
<figure>
<img src="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Fmockaroon-1333674-unsplash.jpg?1558958450566" alt="Colored candy worms" intrinsicsize="948x733">
<figcaption>Photo by <a href="https://unsplash.com/photos/XVYz_QeiEBw" target="_blank" rel="noopener noreferrer">Mockaroon</a> on <a href="https://unsplash.com/">Unsplash</a>.</figcaption>
</figure>
<p>
<img src="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Fbaseline-wb_incandescent-24px.svg?1558957452117" alt=""> Some icon
<img src="https://cdn.glitch.com/791b2241-459b-4a2e-8cca-c0fdc21f0487%2Fbaseline-wb_sunny-24px.svg?1558957452243" alt=""> Some icon
</p>
<dark-mode-toggle appearance="toggle"></dark-mode-toggle>
</body>
</html> | 55.510204 | 298 | 0.701838 |
c47c51a31f1e622289661c16a788894a446fb4cd | 369 | sql | SQL | SQL/4. Outcome category month year.sql | lajobu/Expenses_tracker | 5197a26ced59373818720a0f8878fd670152d490 | [
"MIT"
] | 1 | 2020-02-17T17:53:56.000Z | 2020-02-17T17:53:56.000Z | SQL/4. Outcome category month year.sql | lajobu/Expenses_tracker | 5197a26ced59373818720a0f8878fd670152d490 | [
"MIT"
] | null | null | null | SQL/4. Outcome category month year.sql | lajobu/Expenses_tracker | 5197a26ced59373818720a0f8878fd670152d490 | [
"MIT"
] | null | null | null | --Total spent by month, year, category (parties):
SELECT SUM(outcome.amount_outcome)
FROM outcome
INNER JOIN CATEGORY
ON outcome.ID_category = category.id
WHERE outcome.ID_user=10
AND category.category_name= "Parties"
AND outcome.date_outcome="Dec"
AND outcome.date_outcome1="2019"
AND outcome.currency_outcome="pln"
| 33.545455 | 49 | 0.696477 |
173cebffd766d5338e1917934f001ec3b4c5c49e | 10,158 | html | HTML | src/shell.html | codewithkyle/custom-components-website | f6a1bf603845bb67754320bc7ed55b4231b05602 | [
"MIT"
] | null | null | null | src/shell.html | codewithkyle/custom-components-website | f6a1bf603845bb67754320bc7ed55b4231b05602 | [
"MIT"
] | 5 | 2019-10-09T14:46:16.000Z | 2019-10-09T14:50:56.000Z | src/shell.html | codewithkyle/web-components-library | f6a1bf603845bb67754320bc7ed55b4231b05602 | [
"MIT"
] | 1 | 2019-09-20T03:16:38.000Z | 2019-09-20T03:16:38.000Z | <!DOCTYPE html>
<html lang="en" class="is-loading" data-cachebust="1567594568180">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Web Components Library</title>
<meta name="description" content="Browse, demo, and download prebuilt web components based around the Atomic Design methodology and Googles Material Design.">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono&display=swap" rel="stylesheet">
<script defer>
var criticalCss = ['colors', 'reset', 'settings', 'layout', 'syntax'];
var stylesheets = [];
var modules = ['navigation-manager', 'source-manager', 'highlight', 'markdown'];
var criticalComponents = ['component-navigation', 'navigation-dropdown-component', 'navigation-component', 'source-view-component', 'tab-component', 'github-link-component', 'github-download-component'];
var components = [];
</script>
<!-- Loading Screen -->
<style>
html.is-loading loading-screen
{
display: flex;
}
loading-screen
{
background-color: #f6f8f9;
position: fixed;
width: 100vw;
height: 100vh;
z-index: 9999;
top: 0;
left: 0;
display: none;
flex-flow: column wrap;
user-select: none;
justify-content: center;
align-items: center;
cursor: wait;
}
loading-screen div
{
display: inline-block;
margin: 0;
opacity: 0.87;
}
circle-loader
{
display: block;
height: 64px;
width: 64px;
box-sizing: border-box;
margin: 0 auto 1rem;
border: 4px hsl(204, 13%, 88%) solid;
border-top: 4px #161b25 solid;
border-radius: 50%;
animation: loadingSpinner 1s infinite linear;
}
loading-screen span
{
font-size: 14px;
color: #879099;
display: block;
width: 100%;
text-align: center;
font-family: 'Roboto', Arial, Helvetica, sans-serif;
}
loading-screen loading-logo
{
font-family: 'Roboto', Arial, Helvetica, sans-serif;
position: absolute;
left: 50%;
bottom: 64px;
transform: translateX(-47%);
font-size: 24px;
color: rgba(135, 144, 153,0.3);
font-weight: 300;
text-align: center;
}
loading-screen loading-logo strong
{
font-weight: 900;
color: rgba(135, 144, 153,0.6);
}
@keyframes loadingSpinner
{
from
{
transform: rotate(0deg);
}
to
{
transform: rotate(359deg);
}
}
</style>
</head>
<body>
<loading-screen>
<div>
<circle-loader></circle-loader>
<span>Loading application...</span>
</div>
<loading-logo>
Web Components by <a style="text-decoration: none; color: inherit;" href="https://kyleandrews.dev/">Kyle Andrews</a>
</loading-logo>
</loading-screen>
<main role="main">
<input type="checkbox" id="components-menu-button" />
<label for="components-menu-button">
<svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="arrow-right" class="svg-inline--fa fa-arrow-right fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M218.101 38.101L198.302 57.9c-4.686 4.686-4.686 12.284 0 16.971L353.432 230H12c-6.627 0-12 5.373-12 12v28c0 6.627 5.373 12 12 12h341.432l-155.13 155.13c-4.686 4.686-4.686 12.284 0 16.971l19.799 19.799c4.686 4.686 12.284 4.686 16.971 0l209.414-209.414c4.686-4.686 4.686-12.284 0-16.971L235.071 38.101c-4.686-4.687-12.284-4.687-16.97 0z"></path></svg>
</label>
<component-navigation>
<a href="/">Web Components Library</a>
<template tag="navigation">
<input type="checkbox">
<label>
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="caret-right" class="svg-inline--fa fa-caret-right fa-w-6" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512"><path fill="currentColor" d="M0 384.662V127.338c0-17.818 21.543-26.741 34.142-14.142l128.662 128.662c7.81 7.81 7.81 20.474 0 28.284L34.142 398.804C21.543 411.404 0 402.48 0 384.662z"></path></svg>
<span></span>
</label>
<components-wrapper></components-wrapper>
</template>
</component-navigation>
<article>
<demo-view class="is-loading">
<circle-loader></circle-loader>
<demo-wrapper>
<!-- Demo HTML -->
REPLACE_WITH_HTML
</demo-wrapper>
</demo-view>
<source-view-component>
<tabs-container></tabs-container>
<source-views></source-views>
</source-view-component>
</article>
<div class="global-buttons">
<a href="https://github.com/codewithkyle/web-components-library/blob/master/CONTRIBUTING.md">
<svg aria-hidden="true" focusable="false" data-prefix="fal" data-icon="code-branch" class="svg-inline--fa fa-code-branch fa-w-12" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M384 144c0-44.2-35.8-80-80-80s-80 35.8-80 80c0 39.2 28.2 71.8 65.5 78.7-.8 17.2-5 30.4-12.7 40-17.5 21.8-53.1 25.2-90.7 28.7-28.2 2.6-57.4 5.4-80.4 16.9-3.4 1.7-6.7 3.6-9.7 5.7V158.4c36.5-7.4 64-39.7 64-78.4 0-44.2-35.8-80-80-80S0 35.8 0 80c0 38.7 27.5 71 64 78.4v195.2C27.5 361 0 393.3 0 432c0 44.2 35.8 80 80 80s80-35.8 80-80c0-36.9-24.9-67.9-58.9-77.2 5-9.6 12.3-14.6 19-18 17.5-8.8 42.5-11.2 68.9-13.7 42.6-4 86.7-8.1 112.7-40.5 12.4-15.5 19-35.5 19.8-60.7C357.3 214 384 182.1 384 144zM32 80c0-26.5 21.5-48 48-48s48 21.5 48 48-21.5 48-48 48-48-21.5-48-48zm96 352c0 26.5-21.5 48-48 48s-48-21.5-48-48c0-26.4 21.4-47.9 47.8-48h.6c26.3.2 47.6 21.7 47.6 48zm187.8-241.5L304 192c-26.5 0-48-21.5-48-48s21.5-48 48-48 48 21.5 48 48c0 22.4-15.4 41.2-36.2 46.5z"></path></svg>
Fork Project
</a>
<github-link-component>
<a href="https://github.com/codewithkyle/web-components-library">
<svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="github" class="svg-inline--fa fa-github fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><path fill="currentColor" d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"></path></svg>
View On Github
</a>
</github-link-component>
<github-download-component>
<a href="JavaScript:Void(0);">
<svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="download" class="svg-inline--fa fa-download fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M528 288h-92.1l46.1-46.1c30.1-30.1 8.8-81.9-33.9-81.9h-64V48c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v112h-64c-42.6 0-64.2 51.7-33.9 81.9l46.1 46.1H48c-26.5 0-48 21.5-48 48v128c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V336c0-26.5-21.5-48-48-48zm-400-80h112V48h96v160h112L288 368 128 208zm400 256H48V336h140.1l65.9 65.9c18.8 18.8 49.1 18.7 67.9 0l65.9-65.9H528v128zm-88-64c0-13.3 10.7-24 24-24s24 10.7 24 24-10.7 24-24 24-24-10.7-24-24z"></path></svg>
Download Component
</a>
</github-download-component>
</div>
</main>
<script type="module" src="/assets/application.js"></script>
<script type="module">
if ('serviceWorker' in navigator && window.location.hostname.toLowerCase() === 'components.codewithkyle.com')
{
navigator.serviceWorker.register(`${ window.location.origin }/worker.js`, { scope: '/' })
.then((reg) => {
if (navigator.serviceWorker.controller)
{
navigator.serviceWorker.controller.postMessage({'application': document.documentElement.dataset.cachebust})
}
}).catch((error) => {
console.error('Registration failed with ' + error);
});
}
</script>
</body>
</html> | 55.813187 | 1,556 | 0.567435 |
c2c01e9b9b6e288308c3385b87a9908ac137b62e | 133,382 | sql | SQL | data/dampDB/pd_Vermin(SZR).sql | dimayaschhuk/test_001 | e17762876508179f19610030e068041ef9d96015 | [
"MIT"
] | null | null | null | data/dampDB/pd_Vermin(SZR).sql | dimayaschhuk/test_001 | e17762876508179f19610030e068041ef9d96015 | [
"MIT"
] | null | null | null | data/dampDB/pd_Vermin(SZR).sql | dimayaschhuk/test_001 | e17762876508179f19610030e068041ef9d96015 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.2.12deb2+deb8u2
-- http://www.phpmyadmin.net
--
-- Хост: localhost
-- Время создания: Фев 08 2019 г., 17:31
-- Версия сервера: 5.5.58-0+deb8u1
-- Версия PHP: 5.6.30-0+deb8u1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- База данных: `pxbipzfo_crm`
--
-- --------------------------------------------------------
--
-- Структура таблицы `pd_Vermin`
--
CREATE TABLE IF NOT EXISTS `pd_Vermin` (
`id` int(11) NOT NULL,
`guid` varchar(100) NOT NULL DEFAULT 'new',
`name` varchar(250) NOT NULL,
`groupId` int(11) NOT NULL,
`photo` varchar(100) NOT NULL DEFAULT '0',
`ord` varchar(255) DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=2128 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `pd_Vermin`
--
INSERT INTO `pd_Vermin` (`id`, `guid`, `name`, `groupId`, `photo`, `ord`) VALUES
(1, '34cae591-4bf3-47a4-9144-f2c967f613e2', 'бульбоочерет', 1, '0', NULL),
(2, 'e25a15fa-5f8a-4d97-a24d-cfed1067d88e', 'монохорія', 1, '0', NULL),
(3, '6abd8be3-c727-49e0-b628-ac647d8fbad1', 'просянки', 1, '0', NULL),
(4, '34190314-9a2a-4d46-ac83-09295fc240b3', 'септоріоз листя', 2, 'septorioz_lustya', NULL),
(5, 'd3ebc079-90c2-4335-ae50-67bc03c1e787', 'бура листкова іржа', 2, '0', NULL),
(6, '4239a048-7410-4b07-bf13-c15b757184a5', 'септоріоз колоса', 2, '0', NULL),
(7, 'e95f52c0-85df-4dd8-81be-f10fbdc6f447', 'фузаріоз колосу', 2, 'fuzarioz_kolosa', NULL),
(8, '9fdbdbf1-cf1b-4649-9263-b68370d12db2', 'кореневі гнилі', 2, 'korenevi_gnuli', NULL),
(9, '542a1a69-3385-4e7a-8718-39256298bba0', 'сітчаста плямистість', 2, '0', NULL),
(10, '4be92a4c-156f-4081-86c1-520b82f45652', 'церкоспороз', 2, 'cerkonosporoz', NULL),
(11, '81d5e0c2-d066-4c48-8ea2-86f7e4dfefb6', 'сіра гниль', 2, 'sira_gnul', NULL),
(12, 'e483e2dd-9a2e-49a0-bdef-0cd75df20389', 'Біла гниль', 2, 'bila_gnul', NULL),
(13, '15775c1b-6c8c-43b7-9fed-309d3e470cae', 'фомоз', 2, 'fomoz', NULL),
(14, 'eadd5ad3-9a85-4efd-a3d9-fa40d91f6dc2', 'Борошниста роса', 2, 'boroshnista_rosa1', NULL),
(15, '70071d58-0998-4225-9c13-b11fc6866850', 'септоріоз', 2, 'septorioz', NULL),
(16, 'cb9d0c19-3249-4cee-b35c-7c480e236271', 'Бура іржа', 2, 'bura_irza', NULL),
(17, '40c0d5ac-9ef1-4974-8971-ee33b7beac31', 'зниження ураження хворобами', 2, '0', NULL),
(18, 'cf59d703-4fd7-4de4-adea-f75f84fbc4c5', 'однорічні злакові бур''яни', 1, '0', NULL),
(19, 'f31e95d6-bbfb-457f-9c3a-56158ea5c4a3', 'багаторічні злакові бур''яни', 1, '0', NULL),
(20, '7c743d0e-d1f7-4962-8c46-0f6a6990e1b6', 'падалиця зернових культур', 1, '0', NULL),
(21, '9b0ba067-bdb8-458e-b3ed-b6366ab55169', '-', 0, '0', NULL),
(22, '3c841ebc-6059-49a6-b0db-f699e7b2fce6', 'однорічні дводольні бур''яни', 1, '0', NULL),
(23, '632ad6b4-b3d0-4c74-a804-49a096fdd119', 'підвищення врожайності', 0, '0', NULL),
(24, '1a6c8041-6432-4958-b01b-6a9c56fe242b', 'каліфорнійська щитівка', 3, '0', NULL),
(25, '877177e7-3379-4dac-abc8-416b823362b2', 'оїдіум', 2, '0', NULL),
(26, '688fc3b5-5d27-483b-b563-744df27ffc39', 'мілдью', 2, '0', NULL),
(27, 'fff47021-5d0e-417e-99bc-ec6e04c6f31c', 'кліщі', 3, 'klishch', NULL),
(28, 'd636cc77-15da-4408-a7e6-db88ea36175f', 'Парша', 2, 'parsha', NULL),
(29, '5db756a8-a0fb-44e9-bae2-cee50e7755c5', 'фітофтороз', 2, 'fitoftoroz', NULL),
(30, 'c5188ecd-0994-458f-b1fe-c2ada61f8fea', 'суха плямистість', 2, '0', NULL),
(31, '039bc8db-aa10-4f36-9160-949bfe2d783d', 'пероноспороз', 2, 'peronosporoz', NULL),
(32, 'b4911304-e8b4-4b39-9f2e-ec8b2757f227', 'несправжня борошниста роса', 2, 'nespravgnya_boroshnysta_rosa', NULL),
(33, '3ec02eb7-eab6-4ac6-9d8f-9eaf6d24bfc3', 'колорадський жук', 3, 'koloradskiy_gyk', NULL),
(34, '31a17964-e636-4565-9d12-17159afcff45', 'попелиці', 3, 'popelizya', NULL),
(35, 'cabe2713-63b3-4052-aab9-ac3dda279508', 'люцерновий довгоносик', 3, '0', NULL),
(36, '4b2097a9-d82a-4633-8d8d-71df385ffa5f', 'п''ядуни', 3, '0', NULL),
(37, '74a4e797-53e7-45df-a1aa-04d23260e876', 'листовійки', 3, 'lustoviyku', NULL),
(38, '98dc8bd9-8845-43c0-95bd-60c7540ccd31', 'галиці', 3, '0', NULL),
(39, '4dfcfcd5-52e0-48e4-babc-fdf012c052b9', 'жуки', 3, '0', NULL),
(40, 'ccafa665-1fd6-4431-992d-61bd1959b67c', 'довгоносики', 3, 'dovgonosiki', NULL),
(41, '5fb4ade4-34ab-4e25-b65d-55dbf0515b48', 'товстоніжки', 3, '0', NULL),
(42, '86b6de2a-09f4-48be-b6d6-9a91168dbb48', 'клопи', 3, 'klop', NULL),
(43, '13fba847-3796-456e-a15d-fb58dbdd840e', 'трипси', 3, 'trips', NULL),
(44, '0b10d617-7d74-4558-bcb2-44140f0f2c58', 'лучний метелик', 3, '0', NULL),
(45, '4baa1ee8-368b-427d-8b16-915477236fc7', 'совки', 3, '0', NULL),
(46, '59b56b6f-c901-47f7-bdd4-fce35e9577e9', 'шавлієвий довгоносик', 3, '0', NULL),
(47, 'edd925a7-747a-442d-a7a6-07a241a0f366', 'бульбочковий довгоносик', 3, '0', NULL),
(48, '798a930c-1c8d-41d7-9b1a-0427e979c9e0', 'листоїд', 3, 'lustoid', NULL),
(49, '4ffb2fc8-abcc-478e-9391-35ad554a9653', 'щитоноски', 3, 'shchitonoska', NULL),
(50, '977ed7bf-acac-46aa-a3e4-33c7f7b5467c', 'блішки', 3, 'blishka', NULL),
(51, '01f73ac5-b46e-49f3-8713-445c5ecff00b', 'цикадки', 3, 'cikadka', NULL),
(52, '49b91552-a4c9-4ecf-86d9-ec39a6f73d0e', 'озима совка', 3, 'ozyma_sovka', NULL),
(53, 'dd3e7be4-c6a2-4dd1-b60c-e0571b2bc97a', 'павутинний кліщ', 3, '0', NULL),
(54, '18e02161-688e-4076-bb06-ec38b486e6b3', 'листяна попелиця', 3, '0', NULL),
(55, 'bc6875fa-9786-40fc-b600-904602cd9d44', 'мертвоїди', 3, '0', NULL),
(56, '035aa8e3-9ea5-404e-aa53-fbcc5590a8b8', 'вишнева муха', 3, '0', NULL),
(57, '822d2e82-b528-4b23-940d-45b329d9dd7c', 'східна плодожерка', 3, '0', NULL),
(58, 'd53cc26d-a484-4776-8496-f0be5f25c7a3', 'білокрилка', 3, '0', NULL),
(59, 'a869d2d6-3381-49af-b3b3-a0ee9f45ba3d', 'Мінуючі мухи', 3, '0', NULL),
(60, '8aef95f3-6ad2-4068-ab77-d4275b85812d', 'сунично-малиновий довгоносик', 3, '0', NULL),
(61, '7ec6a864-3078-476f-8ae5-c01e5537d556', 'подорожникова блішка', 3, '0', NULL),
(62, 'fa9c0e4e-40c5-42a9-8908-02b0543bf49b', 'хрестоцвіті блішки', 3, '0', NULL),
(63, 'f679e485-948a-463d-8952-5a2b43df0212', 'совка гамма', 3, '0', NULL),
(64, '28b124d5-86c1-4877-8cc8-c1e949d73295', 'комарики', 3, '0', NULL),
(65, 'b1eb5286-c7ab-43d9-9e1e-b316f0b3ee63', 'мухи', 3, '0', NULL),
(66, '157e8b16-885f-4034-897a-7de0ddbe7017', 'молі', 3, '0', NULL),
(67, 'e057a8f8-9b2d-422e-bfe3-d782263a8161', 'білянки', 3, '0', NULL),
(68, 'b6405561-f008-43ca-b750-5652b2d92f73', 'гронова листовійка', 3, '0', NULL),
(69, '58e97f0f-6daf-43ce-96e5-6beb25159b79', 'п''явиця', 3, '0', NULL),
(70, '4b6b983d-8c77-4d0c-be93-b93ced18bc64', 'злакові попелиці', 3, '0', NULL),
(71, '8c1709f5-2d8a-4c22-a91a-7f457f78e020', 'клоп шкідлива черепашка', 3, 'klop_shkidluva_cherepashka', NULL),
(72, 'edcb642d-275d-4257-96d1-b2aa08a4507a', 'яблуневий плодовий пильщик', 3, '0', NULL),
(73, '10c24981-872a-4dbd-9c68-4ddb528bb58d', 'яблунева плодожерка', 3, '0', NULL),
(74, 'a4600d0a-8734-4c7e-95ef-48c3f4758614', 'гороховий зерноїд', 3, '0', NULL),
(75, 'a95037c8-0312-4f92-89dd-cdb3e21d8047', 'вогнівка', 3, 'vognivka', NULL),
(76, 'a1e4a7a7-310d-4fc4-977c-847123591f84', 'шкідники запасів', 3, '0', NULL),
(77, '704cbc65-f91e-404f-a2ab-eedb8dc5c225', 'для мобілізації важкодоступного фосфору з ґрунту', 0, '0', NULL),
(78, '91a3a718-4999-47d3-b6d9-dae75627878d', 'стеблова', 0, '0', NULL),
(79, '95921bf8-2a10-46a9-b328-4b77a4f1a17b', 'фітофторозна гниль плодів', 2, '0', NULL),
(80, '6c2e385a-791b-4b9e-be79-e0c83f541fad', 'квіткоїд', 3, '0', NULL),
(81, '85e4e992-0737-43f9-a63a-a5e4e61dfc2c', 'міль', 3, '0', NULL),
(82, 'f723badd-794e-48b0-863c-f684e964b89b', 'саранові', 3, '0', NULL),
(83, '30afb082-c283-41b5-bd6f-58a1aef19d80', 'плодожерки', 3, '0', NULL),
(84, '6cc29895-1fcd-483d-930f-1391f9125934', 'золотогуз', 3, '0', NULL),
(85, '23cacd40-72cb-4bc1-b2e0-9273b5eeb457', 'шовкопряди', 3, '0', NULL),
(86, '1681d2a7-8c75-4e01-b10d-d6ae8c4363b1', 'плямистості листя', 3, '0', NULL),
(87, '123871c6-ee28-4eb3-a73a-441ec6991bff', 'церкоспорельоз', 2, 'cerkosporeloz', NULL),
(88, '948fdde5-da8f-4b3c-a573-82adb513b6ab', 'п''явиці', 3, '0', NULL),
(89, '29aa8b5c-0403-4b47-86f4-ddaec7fc06b9', 'іржа', 2, 'irza', NULL),
(90, '5bda257f-845f-43cd-af25-4437f581fd50', 'прискорення дозрівання', 0, '0', NULL),
(91, '1e92c53b-614d-465e-ba04-d18d631b3fa6', 'покращення товарної якості плодів', 0, '0', NULL),
(92, 'f7693e92-9f7f-4e75-9005-89b6aacc6c24', 'личинки клопа шкідливої черепашки', 3, '0', NULL),
(93, '9519f4e0-ba52-417b-8834-b4e8279d9a27', 'хлібна жужелиця', 3, 'hlibna_gugeluzya', NULL),
(94, '04b27a3a-afa5-4b88-97b9-c62ee7253f26', 'ріпаковий квіткоїд', 3, '0', NULL),
(95, 'cb94a713-d808-431a-90d6-a99ef3ddbe4d', 'яблунева', 3, '0', NULL),
(96, 'dff8b0e9-1c04-46f1-9be3-d02396e05e7b', 'плодожерка', 3, 'plodogerka', NULL),
(97, '1f3dc997-e7a3-4ed3-9e69-965925cf8728', 'комплекс сисних шкідників', 3, '0', NULL),
(98, '50a52930-7f91-435f-bf51-1f1ae30832fc', 'акацієва вогнівка', 3, '0', NULL),
(99, '0ef52f16-29ed-4e02-a149-6e09b931eaf3', 'Трипс пшеничний', 3, '0', NULL),
(100, '6c3503ff-84f5-4416-8878-e6122d6121e0', 'циліндроспоріоз', 2, '0', NULL),
(101, '61f28179-015f-4956-a41b-9a1995745100', 'для фіксації атмосферного азоту', 0, '0', NULL),
(102, '376a360c-74bc-4a21-b039-200e28f0794c', 'альтернаріоз', 2, 'alternarioz', NULL),
(103, '97cbe601-5fe1-457e-9b2c-72d902ad5f30', 'циліндроспороз', 2, 'cylindrosporoz', NULL),
(104, '81d765e6-33a6-43cd-b292-22fbd1969c8d', 'піренофороз', 2, '0', NULL),
(105, 'e644a172-898a-4d32-be81-e8f3cfb69f9d', 'інгібування росту листя та підвищення стійкості до екстремальних умов', 0, '0', NULL),
(106, 'b24a8062-64fd-4a82-a8b5-3cf2f6ae82d7', 'Кузька, або хлібний жук', 3, '0', NULL),
(107, 'c34d5ffd-0154-4acd-99ee-79ea42fe9732', 'чорна плямистість', 2, '0', NULL),
(108, '42b8a6ff-9687-4b83-bdcd-4c6589d778c3', 'антракноз', 2, 'antraktoz_gorohu', NULL),
(109, '1c69e334-c156-497d-9284-4a8b80740b88', 'однорічні та багаторічні злакові та дводольні бур''яни', 1, '0', NULL),
(110, 'cc135791-313d-43d9-a883-0547450949a6', 'плямистості', 2, 'plyamustist', NULL),
(111, '361b1640-c41b-4c17-902a-08143b16c705', 'стеблова іржа', 2, '0', NULL),
(112, '968954a5-4e17-4fa1-93a3-8b5ef906bee6', 'для боротьби з мишовидними гризунами', 3, '0', NULL),
(113, '6a06fec4-b827-46ed-bd4b-2369fdf1b0d3', 'шкідники сходів', 3, '0', NULL),
(114, '8712b4cb-ed9e-444a-b57d-7eb63d3ee9d8', 'боротьба з хворобами', 2, '0', NULL),
(115, 'd5e719b3-3621-40c6-93d9-16c71a7aad2a', 'підвищення імунітету', 0, '0', NULL),
(116, '7e6299a3-d9ca-430a-a914-fb8a5f4b7494', 'жовта іржа', 2, '0', NULL),
(117, '878898a4-37c8-405d-bc56-a48631f7599b', 'однорічні бур''яни', 1, '0', NULL),
(118, '374cd000-4a00-47c4-bb71-b9941147fb73', 'багаторічні бур''яни', 1, '0', NULL),
(119, '9656e810-76b6-41b0-81d2-04b42206f7a1', 'снігова пліснява', 2, 'snigova_plisnyava', NULL),
(120, '130562cc-c6b9-4382-a9bc-406a1101577c', 'фузаріозна коренева гниль', 2, 'fuzariozna_koreneva_gnul', NULL),
(121, 'e996a875-1f67-43f6-9aca-74f2ac225d7a', 'для запобігання вилягання рослин', 0, '0', NULL),
(122, '1c0caad3-3e51-438b-af66-1550564d308f', 'горохова плодожерка', 3, '0', NULL),
(123, '88f28eeb-1e4e-4cdd-96b2-1cbdebf0c2a4', 'листкова попелиця', 3, '0', NULL),
(124, 'db0973c2-7fbe-4af2-9155-e599463e2fd2', 'щитівки', 3, '0', NULL),
(125, '2d8eea46-d9f4-4c62-81b4-2d5658b20812', 'листоблішки', 3, '0', NULL),
(126, '1f65193f-09f4-4b77-bd97-28c748e3947b', 'садові довгоносики', 3, '0', NULL),
(127, '0d3f62bb-7a54-4dcc-9840-96fcd99e202a', 'червиці', 3, '0', NULL),
(128, '9734b415-de96-4289-8772-c578f2acb46b', 'міль картопляна', 3, '0', NULL),
(129, '6d8118a9-37f2-4d57-b7d2-3ba31e778e70', 'товстоніжка люцернова', 3, '0', NULL),
(130, 'c1bed70d-2889-419f-808f-f39c45a2e5ca', 'засвоювання атмосферного азоту', 0, '0', NULL),
(131, '02e68e43-b632-4c0b-ae0e-6033912043f3', 'казарка', 3, '0', NULL),
(132, 'a6ca0fcb-6130-4a63-a65a-37b984df9eee', 'букарка', 3, '0', NULL),
(133, '19bf5e30-8b32-47e5-b1db-792fd0132484', 'яблуневий квіткоїд', 3, '0', NULL),
(134, '0545d640-c8c5-4490-8ee1-73b51289cc9f', 'Мінуючі молі', 3, '0', NULL),
(135, '52f81800-7b0f-45d1-b4bb-9429463ccb12', 'комплекс шкідників', 3, '0', NULL),
(136, '15c57724-083f-4a62-ba0c-e8627963452f', 'злакові мухи', 3, 'zlakova_muha', NULL),
(137, 'eb695f72-1f2d-4de9-b883-ef0897f9fcfc', 'хлібні жуки', 3, 'hlibnuy_guk', NULL),
(138, 'd4c7e008-0494-433b-ad08-f61b2721def5', 'цикади', 3, '0', NULL),
(139, 'd55550d7-9efb-42a8-b344-5ab18f60055d', 'білани', 3, 'bilany', NULL),
(140, '960ce481-9c91-4465-b5ce-f1e05f1d1714', 'стебловий кукурудзяний метелик', 3, '0', NULL),
(141, '977265db-196b-4101-a800-e59df2fff7bb', 'капустяна попелиця', 3, '0', NULL),
(142, '46f7d589-e335-4aa8-b89c-30f306c49cad', 'трав''яний клоп', 3, '0', NULL),
(143, '198c56aa-11c7-449c-b302-48bfadf2baac', 'мишовидні гризуни', 3, '0', NULL),
(144, '2c018f43-0f44-4419-81cb-61905a52254e', 'бурякова попелиця', 3, 'buryakovi_popelizi', NULL),
(145, '4b3b59e3-2c4d-44d6-836d-90f7195ddd31', 'теплична білокрилка', 3, '0', NULL),
(146, '755d8b4b-f8fa-4835-8646-d99a8fd4c056', 'сисні шкідники', 3, '0', NULL),
(147, 'fb5b2a00-77d1-40db-bcfb-091b1b761d37', 'виноградна листовійка', 3, '0', NULL),
(148, '8f515d2a-8178-417d-bf04-25381cc4dcfb', 'листкова форма філоксери', 0, '0', NULL),
(149, 'bdf19453-a348-4bff-9770-6a6dfda06521', 'пліснявіння насіння', 0, 'plisnyzvinnya_nasinnya', NULL),
(150, '410c24a1-5c30-4fda-b313-9c2529b7df35', 'однорічні двосім''ядольні бур''яни', 1, '0', NULL),
(151, 'ba6d469d-916e-40c1-86d1-977a58624c6a', 'сажкові хвороби', 2, '0', NULL),
(152, '866de370-2c9d-494f-8560-58c2dab1242c', 'ринхоспоріоз', 2, '0', NULL),
(153, 'f6289e80-cbdc-4fcf-8658-34c8e19708de', 'хатня миша', 3, 'musha', NULL),
(154, 'f5920d92-e50a-4105-ab48-98274552c2f3', 'пацюки', 3, '0', NULL),
(155, '62a351f0-4b50-44a9-b20a-3dd786fbfb44', 'теплична', 0, '0', NULL),
(156, 'b64ec487-6707-42cd-b15d-877273ecda48', 'дротяники', 3, 'drotyaniki', NULL),
(157, 'fec51d9b-6732-457d-a626-a5bdf2e45c33', 'повитиця', 1, '0', NULL),
(158, 'f1778e49-5bd1-48a8-b224-d582d1697887', 'східний та східний смугастий довгоносики', 3, '0', NULL),
(159, '1e7e31ed-6019-4f0a-b9fe-a5cb6c5dda97', 'звичайний буряковий довгоносик', 3, '0', NULL),
(160, '4a879420-bc90-4f29-9c5e-189bba05f7e4', 'крихітка', 0, '0', NULL),
(161, 'c62036c5-01ff-4288-9912-c5b42d05e115', 'кліщі павутинні', 3, '0', NULL),
(162, '7b2ec14c-9c5b-4d33-ac34-1dfdd10bb175', 'щитівки листовійки', 3, '0', NULL),
(163, '43c8d05c-796e-4636-89c7-a5144b49cb3a', 'капустяний стручковий комарик', 3, '0', NULL),
(164, 'df942509-1d45-484a-aa08-16920009354a', 'ріпаковий пильщик', 3, '0', NULL),
(165, '425e649a-f9be-424d-871c-0cce2f677b90', 'гельмінтоспоріоз', 2, 'helmintosporioz', NULL),
(166, 'a15db82a-d1eb-431d-b570-105545c5bb68', 'Кучерявість', 2, '0', NULL),
(167, 'cd1c0566-8956-41eb-93ae-f172bb57977e', 'клястероспоріоз', 2, '0', NULL),
(168, '6b1621b5-d7ae-4b24-8688-c4f600635b47', 'підгризаючі совки', 3, '0', NULL),
(169, '3b005f14-266f-45d7-80b2-a61a0e62f4a6', 'сірий довгоносик', 3, '0', NULL),
(170, '3c74105a-ae0c-4814-92bc-2a44f59a13a6', 'бурякові блішки', 3, '0', NULL),
(171, '4feccf17-e60b-4fd5-a4fd-7e52524ba1c5', 'совка озима', 3, '0', NULL),
(172, 'c597be43-cb9b-45d7-9e5f-77b44ae9624c', 'бавовникова совка', 3, 'bavovnykova_sovka', NULL),
(173, '0caa56a3-af01-4dbe-838d-4cb7c74736f3', 'соняшникова шипоноска', 3, 'sonyashnukova_shuponoska', NULL),
(174, '4193639a-c717-49f3-9669-1648ad6078c4', 'колосові мухи', 3, '0', NULL),
(175, '8c1d4564-e899-42cb-83e4-764bd9a66b53', 'блоха конопляна', 3, '0', NULL),
(176, '12c81d7b-1e1c-4cd1-a051-5bed42a21dde', 'сірий бруньковий довгоносик', 3, '0', NULL),
(177, 'ac201257-87dd-4eb7-bb64-efdb4d4ff088', 'довгоносик шавлієвий', 3, '0', NULL),
(178, '72813fe2-89cf-4e94-9e4d-e945d967e56d', 'ризоктоніоз', 2, '0', NULL),
(179, 'befb43cf-1be6-4c4a-82b6-ee064d3b2eba', 'листогризучі совки', 3, '0', NULL),
(180, 'e52f12d0-8a85-4f42-86fb-61de68a92b5f', 'соєва плодожерка', 3, '0', NULL),
(181, 'bfb65083-773c-42b0-8fc1-f8d9c027566d', 'тютюновий трипс', 3, '0', NULL),
(182, '49eb013a-42ca-4503-8cfc-fc9e82b84294', 'хрестоцвіті клопи', 3, '0', NULL),
(183, '70f219d3-6292-4fc7-b397-652a77486507', 'ріпаковий білан', 3, '0', NULL),
(184, '6dff7c79-65e5-4df9-9acf-6c2b29f9a058', 'капустяна совка', 3, '0', NULL),
(185, '2ab8238f-a259-4a33-850b-8ef578a5b088', 'попелиця листкова', 3, 'popelizya', NULL),
(186, 'bc4a426b-d429-4dec-ac0f-9da611d176aa', 'фітономус', 3, '0', NULL),
(187, '4e0a38ee-49d7-4a2b-9d71-f66ad8d1c56e', 'саранові (личинки молодших віків)', 3, '0', NULL),
(188, 'ab42f711-fb40-4c9b-89a3-5cb206ca5114', 'плодова гниль', 2, '0', NULL),
(189, '2f0f965c-a5c5-4797-bd86-5e19df5da327', 'горохова попелиця', 3, 'gorohova_popeluzya', NULL),
(190, '9fbdcee2-2272-4cd8-801a-f12075bb5a8f', 'совка капустяна', 3, '0', NULL),
(191, 'fe3833a1-4c98-42c7-94d6-4b5f82910f78', 'квіткоїд ріпаковий', 3, 'kvitkoid_ripakovuy', NULL),
(192, 'c79ae377-affc-438f-b8f0-972be2849967', 'плодожерка соєва', 3, '0', NULL),
(193, 'eea74ecd-c3ad-48f5-83ad-bf1109156b80', 'проти мишей', 3, '0', NULL),
(194, '89cea78a-ed11-4975-8773-26a000681fc5', 'стеблова бура іржа', 2, '0', NULL),
(195, 'ea91ec2b-77c4-4164-9a48-01d1449b813c', 'фузаріоз', 2, 'fuzarioz', NULL),
(196, '5c512d70-8bc0-486f-9419-19d3dc48ca00', 'клоп шкідлива черепашка (личинки молодших віків)', 3, '0', NULL),
(197, '30da2ae3-5d0f-4190-b302-d1a5257d76b6', 'пліснявіння', 2, '0', NULL),
(198, 'a905c9ee-d1bb-4998-9098-35c038711b2d', 'пухирчаста та летюча сажки', 3, '0', NULL),
(199, '10c6fb73-1d2d-4eef-9fc4-3ccde853209c', 'західний кукурудзяний жук', 3, 'zahidnuy_kukurudzyanuy_gyk', NULL),
(200, '22f52975-398a-460a-84cd-3383576f86d0', 'яблуневий пильщик', 3, '0', NULL),
(201, '3a675659-4b7d-4386-9bec-decdba0fc19b', 'склеротініоз', 2, 'sklerotinioz', NULL),
(202, '311b3e9b-9799-4929-9c85-fe3e2158bf55', 'цибулева муха', 3, 'cibuleva_muha', NULL),
(203, 'abbf4ade-9499-4eac-9dab-ef9188dde474', 'динна муха', 3, '0', NULL),
(204, 'dc9a3c2d-e151-4397-be35-1a6b64c0d328', 'нестадні саранові', 3, '0', NULL),
(205, '2abfbdc5-5b6d-445d-8643-ad72f3f61597', 'бура плямистість', 2, '0', NULL),
(206, '063e5631-430f-41c3-b83c-b414fbb8f3cf', 'фузаріозне в''янення', 2, 'fuzariozne_vyanennya', NULL),
(207, '94e9f786-4ffc-4975-8d74-586998b97fe5', 'летюча сажка', 2, 'letyucha_sagka', NULL),
(208, '29662256-89c3-4387-8fd6-019072f2491c', 'підвищує продуктивність рослин', 0, '0', NULL),
(209, 'cec92bfd-5846-4bea-ad71-25289ce4ff08', 'багаторічні дводольні коренепаросткові (осоти) бур''яни', 1, '0', NULL),
(210, '81172032-3f13-45b4-b911-500add410c3e', 'темно-бура плямистість', 2, '0', NULL),
(211, 'e3e3f418-d197-49df-8af8-e821cb206192', 'хлібні клопи', 3, '0', NULL),
(212, '24348627-0cd2-40e2-aa3f-8fe3bbeeda3b', 'листомінуючі молі', 3, '0', NULL),
(213, '8675d6d9-1f2a-4d33-9b50-4ab6ae564888', 'для кращого вкорінення саджанців', 0, '0', NULL),
(214, 'b60b5ed9-5056-428a-9bf3-1d68b7c0f0f3', 'комплекс шкідників сходів', 3, '0', NULL),
(215, '27988b2d-a884-4201-ba0e-b45436a31891', 'пурпурова плямистість', 2, '0', NULL),
(216, '856aa342-01c4-4647-a609-d0701735494e', 'комплекс ґрунтових шкідників', 3, '0', NULL),
(217, '0d770449-c404-4740-8667-bba32ba46106', 'льонова блішка', 3, '0', NULL),
(218, 'fb8fcf1a-6d4b-4f03-b065-6d68b7ffeaa7', 'чорнотілки', 3, '0', NULL),
(219, '5333e851-da53-49ca-bc02-005c158c966f', 'шведська муха', 3, 'shvedska_muha', NULL),
(220, 'c5518f0b-854d-47b1-aa21-fadc29871cc2', 'мідляки', 3, '0', NULL),
(221, '963f9a92-60d5-4ea0-98a0-0294946fe8be', 'ґрунтові шкідники', 3, '0', NULL),
(222, '5bac8a80-9135-4c47-b68b-157c79e6ad2f', 'чорна ніжка', 2, 'chorna_nigka', NULL),
(223, '28eb2583-c620-41e7-b191-141b1daeb24d', 'макроспоріоз', 2, 'makrosporioz', NULL),
(224, '2ed78850-0523-4ccc-a8b5-b64a271c3857', 'рання суха плямистість', 2, '0', NULL),
(225, '07875793-7bb6-4829-b961-697e68e6a1c9', 'хвороби листя', 2, '0', NULL),
(226, 'f469b3df-e2e8-4713-8551-d20d1e308883', 'тверда сажка', 2, 'tverda_sagka', NULL),
(227, 'b0701181-11cc-4429-90c8-098a48f625e9', 'аскохітоз', 2, '', NULL),
(228, '990ae3a2-870b-48b0-a844-0ea8719fd65a', 'грушова медяниця', 3, '0', NULL),
(229, 'eb566e64-e81d-4409-92cf-27ac16f912f0', 'гронова листовійка, 1 генерація', 3, '0', NULL),
(230, 'b59bb7d4-80e4-49ae-b2a8-d340c228c6d0', 'коренеїд', 2, '0', NULL),
(231, 'a6456c24-107c-469f-ad08-778bf33cd94c', 'пірикуляріоз', 2, '0', NULL),
(232, '4a5a9db1-016e-4b72-9362-e5467fc56015', 'бурякова листкова попелиця', 3, '0', NULL),
(233, 'e24b426b-2473-4f40-8469-313ec00130bf', 'піщаний мідляк', 3, '0', NULL),
(234, '74dce728-2a98-4e4d-a3d7-fb8527bf02a2', 'бурякова мінуюча міль', 3, '0', NULL),
(235, '68b117d2-b1bb-4b2d-aa07-a39dc886f884', 'хмелева попелиця', 3, '0', NULL),
(236, '4b922c9c-ddfc-4d12-acb1-0e3e14161e58', 'медяниці', 3, '0', NULL),
(237, '2fd80507-a4b1-4d66-8cad-b177d75a98f9', 'капустяна міль', 3, '0', NULL),
(238, '1e946236-96d9-45d6-9b61-b697580e2739', 'личинки 1-3 віків', 3, '0', NULL),
(239, '32a6df49-ed16-4807-aa2f-e6da4833a6f3', 'Бактеріоз', 2, '0', NULL),
(240, '58a0fd3f-d035-4d91-b33a-3780f5ff0e46', 'сіра гниль плодів', 2, '0', NULL),
(241, 'e64879b9-e7bc-4c2c-9cce-979d98669746', 'капустяний стручковий прихованохоботник', 3, '0', NULL),
(242, 'e2f9b9a3-0433-4e74-86c9-4ab047f35cce', 'листкова бурякова попелиця', 3, '0', NULL),
(243, '8988d873-ae49-46d9-9528-a2ff08292510', 'чорний довгоносик', 3, '0', NULL),
(244, '544447a7-9daf-43c0-b4cd-ac7fd1dc3007', 'бруньковий довгоносик', 3, '0', NULL),
(245, 'a5050db9-4474-44a9-920c-9be39e843002', 'яблуневий трач', 3, '0', NULL),
(246, 'd14ceaf6-c8b4-407b-acba-95273dbf259f', 'комплекс листовійок', 3, '0', NULL),
(247, 'e6ac2063-7839-437d-a70b-77e5cb62fddd', 'основні шкідники сходів', 3, '0', NULL),
(248, 'cb2cdf0f-cb19-4249-b37a-0aa3e0cc4fe6', 'звичайна злакова попелиця', 3, '0', NULL),
(249, '17a3b65b-feb9-4e72-a516-cf924b9a3c34', 'сажки', 2, '0', NULL),
(250, '11a48c9c-2da8-4750-b528-c82f0e5954a6', 'плодові кліщі', 3, '0', NULL),
(251, '2a5ce0db-17d1-49e2-8c46-8786f89eedb4', 'розанова листовійка', 3, '0', NULL),
(252, 'c7498e18-a608-4c85-a9f7-0181fbb77685', 'грушева медяниця', 3, '0', NULL),
(253, '574fbd0a-418d-40fb-a85b-da8199d0c510', 'глодовий кліщ', 3, '0', NULL),
(254, '45cac721-96af-4ec5-b773-58ce77bbcc07', 'несправжні дротяники', 3, '0', NULL),
(255, '9573a141-7559-4e05-aa1b-b0923622307d', 'личинки підгризаючих совок', 3, '0', NULL),
(256, '2b49581b-7723-4867-ac5a-a86eba660fde', 'домові миші', 3, '0', NULL),
(257, 'fa4bca18-3d09-4bf8-8769-189148bec774', 'полівки', 3, '0', NULL),
(258, '9a08cb27-0e3e-4c46-a670-a162cfe0e9eb', 'формування стандартних пагонів', 0, '0', NULL),
(259, '7b41a7be-0588-419f-960e-35ea1536cd64', 'підвищення їх урожайності', 0, '0', NULL),
(260, 'ff6da907-2556-4b26-b578-80a960445352', 'рамуляріоз', 2, 'ramulyarioz', NULL),
(261, '1eea4596-487b-4baa-afed-0355e0e9ea9b', 'для запобігання вилягання посівів', 0, '0', NULL),
(262, '3d276ac9-1a8b-49a8-b6a9-3f53fee03623', 'польові мишовидні гризуни', 3, '0', NULL),
(263, '93b8a42d-7c9d-4538-8d7c-1cd5725e9367', 'американська борошниста роса', 2, '0', NULL),
(264, '97586d59-73d6-47ca-b748-fd00f37f7474', 'бурякова мінуюча муха', 3, '0', NULL),
(265, 'bd583b3c-3e14-43c1-b765-cd91358b0f0f', 'кукурудзяний метелик', 3, 'kukurudzyanuy_metelyk', NULL),
(266, '14a4ac57-2bd0-4eb3-9b59-d21d5ccb4771', 'моніліоз', 2, '0', NULL),
(267, '4e071f6f-69b2-4461-80cb-e8c4401326b2', 'карликова іржа', 2, '0', NULL),
(268, '56ad1e4b-eeae-4341-8861-1d2bef2fa1a8', 'хлібні блішки', 3, '0', NULL),
(269, '23f5c976-da6b-40d3-adc3-d151ccacc97d', 'пітіозна коренева гниль', 2, '0', NULL),
(270, 'f40e7c4d-4f87-4133-9edb-d01bffaed635', 'коккомікоз', 2, '0', NULL),
(271, 'e9de904f-2eb8-43e3-a248-acdf7c1ff3ff', 'побуріння листя', 2, '0', NULL),
(272, '7d9cd493-1494-4869-b56d-1ec1d88bc32e', 'для кращого зберігання', 0, '0', NULL),
(273, 'bc8b88c1-790f-4ec2-89ac-83140d39e7e2', 'альтернаріоз колоса', 2, '0', NULL),
(274, '3d0b33a9-3703-470c-9f30-bc2e6856dd82', 'проти вилягання рослин', 0, '0', NULL),
(275, '849b7c7e-cc48-4c61-9973-7333a9ecd036', 'коренеїд східний', 3, '0', NULL),
(276, 'd4cc696c-3446-4aa6-b62c-faf7853ac8e3', 'блішки хлібні', 3, '0', NULL),
(277, 'cf2c0a84-23fc-476f-9076-f7b3e098f036', 'Злакова листовійка', 3, '0', NULL),
(278, 'e9892044-ea43-4e9c-8a11-f86db287a323', 'совка зернова', 3, '0', NULL),
(279, '8d627d00-3c98-4093-aaff-f4784839879e', 'трач ріпаковий', 3, '0', NULL),
(280, 'ee9d818d-05ed-4c38-8955-a95991c3eca0', 'фомопсис', 2, 'fomopsis', NULL),
(281, 'd46b9fa6-2452-47da-a516-af8ce4ced3fb', 'гниль плодів', 2, '0', NULL),
(282, 'cbfb8a31-d6ba-44fd-8c1b-e8d18805462d', 'кила капусти', 2, '0', NULL),
(283, '230a4f7c-11c2-4604-a847-98c8d2add894', 'звичайний павутинний кліщ', 3, '0', NULL),
(284, '36fcfd48-1fb4-4e09-ad37-d788a5952366', 'пухирчаста сажка', 2, '0', NULL),
(285, 'a0b97db7-c1dc-4116-a8b2-f61043527f2b', 'горохова зернівка', 2, '0', NULL),
(286, '1f22abde-eeab-4f26-a010-2cb4ea317ac2', 'гельмінтоспоріозна плямистість листя', 2, '0', NULL),
(287, '7cdb6d88-c6c0-47c6-b0c1-ea00cc4c405c', 'зернівка горохова', 3, 'zernivka_gorohova', NULL),
(288, '699bd147-5904-4e8e-addf-76c62dad65b6', 'блішки хрестоцвіті', 3, '0', NULL),
(289, '19f25c0c-b28e-40c7-828e-d5b95cfb8fea', 'інфекційне засихання', 2, '0', NULL),
(290, 'e1c6ab5a-cfed-48bd-8153-71c870882036', 'для кращого зв''язування атмосферного азоту бульбочковими бактеріями', 0, '0', NULL),
(291, '8d26328b-f9e6-4399-a1e3-79861e5be974', 'для боротьби з хворобами', 2, '0', NULL),
(292, '09f0c716-f7ca-4ab4-ad41-1a34b0763cad', 'бурякова крихітка', 3, '0', NULL),
(293, '7b7161fa-7c77-4948-aac8-5c1f92701e86', 'плодожерка горохова', 3, 'plodogerka_gorohova', NULL),
(294, 'b42171cc-d63c-493d-a22b-9dff6a5cca1c', 'приховано хоботник насіннєвий', 3, '0', NULL),
(295, '9bb146bf-1c5d-4d16-9eda-f94deb88d701', 'грибні мухи', 3, '0', NULL),
(296, '686b2706-fcb7-47ab-a870-ca69edd06b3e', 'зернівка', 3, '0', NULL),
(297, 'ce86fed4-3c03-499f-ae06-831170b16979', 'капустяний листоїд', 3, '0', NULL),
(298, '912f2ffa-7c99-445f-9f62-65577e9e0b58', 'для запобігання виляганню сходів зернових', 0, '0', NULL),
(299, '9d8e1b28-921a-405c-bd40-c00d6ac86c35', 'для кращого вкорінення', 0, '0', NULL),
(300, '79091b3c-839a-4d5d-86e7-ba31365c2841', 'бурякові щитоноски', 3, '0', NULL),
(301, '4a3e32ce-e479-48b0-b2dd-99795fa2e4e2', 'звичайний буряковий довгоносик', 3, '0', NULL),
(302, '2a51d4e8-6e71-4443-9d2d-59b90f674886', 'попелиця горохова', 3, 'popelizya', NULL),
(303, '14916a81-08f6-4ee2-8f55-93d84ee6090b', 'Мертвоїд матовий', 3, '0', NULL),
(304, 'dc52cff5-1109-4470-98e9-cd5f30b7690d', 'Багаторічні злакові', 1, '0', NULL),
(305, '0ad4ecb8-639c-4f88-80b4-b8ef053e02b8', 'рудий сосновий пильщик', 3, '0', NULL),
(306, 'f4460b3c-2567-4a8c-b816-b7b4fc09bf7b', 'непарний шовкопряд', 3, '0', NULL),
(307, '47a1e094-96b8-49df-935e-3dbb24ab02e8', 'звичайний сосновий пильщик', 3, '0', NULL),
(308, 'aae1b0da-322d-49b0-a440-338d84e15ac7', 'чагарники', 1, '0', NULL),
(309, 'f5ae2e4e-e467-4881-9d46-bff074fc2ccd', 'трав''яна рослинність', 1, '0', NULL),
(310, '81458648-2aaf-457f-a079-a63654e7b141', 'гельмінтоспоріозна коренева гниль', 2, 'gelminosporozna_koreneva_gnul', NULL),
(311, 'fc6c2fe9-9bbd-40ca-861a-437caeb8cc81', 'засвоювання атмоферного азоту', 0, '0', NULL),
(312, 'b77e5831-2b5b-42c6-8235-6989c03ca027', 'захист проти хвороб', 2, '0', NULL),
(313, '4f7ab8d8-39a7-4655-bcae-98069a4b9aad', 'захист проти шкідників та хвороб', 0, '0', NULL),
(314, 'ed7c01d8-c4cd-432e-8f61-c16f588666ce', 'захист проти шкідників', 3, '0', NULL),
(315, '19ab09a2-8c7a-40b6-844a-0812c0d3fad6', 'фіксація атмосферного азоту', 0, '0', NULL),
(316, '3a62e631-9d80-4e38-b85e-7023e3537332', 'прискорення мінералізаціїі', 0, '0', NULL),
(317, 'e3a0bce1-2909-4869-bdc4-fe13b209c028', 'піреноспороз', 2, '0', NULL),
(318, '7aec7ff6-6966-443d-a33a-c4fe21f9675e', 'комплекс збудників хвороб', 2, '0', NULL),
(319, 'd8af6307-9d90-4dc7-9c00-4be781f7b886', 'підвищення польової схожості насіння та продуктивності посівів', 0, '0', NULL),
(320, 'bcda5a10-5150-449e-ad08-5fdf5330600e', 'інгібування росту листя (рістрегулююча дія)', 0, '0', NULL),
(321, 'ca2bdc12-f109-42bb-a32a-85c8f311d78d', 'гусінь лускокрилих', 3, '0', NULL),
(322, 'bf8d3219-d141-4ff7-a62e-638cf4917579', 'жук-кузька', 3, '0', NULL),
(323, '93d09ee7-3930-4c0d-84af-f94b04edbbd4', 'капустяна муха', 3, '0', NULL),
(324, '1974c8a6-68d1-4285-be0a-73e8bc219989', 'зерниця горохова', 2, '0', NULL),
(325, '9e3ab1c3-458c-49b1-a8f4-9fe712f47e7c', 'клоп шкідлива черепашка (личинки І-ІІ віку)', 3, '0', NULL),
(326, 'f0b37ad6-2c36-4b90-ac2d-274a2e5c39c1', 'комплекс збудників кореневих гнилей', 2, '0', NULL),
(327, 'afef125f-333f-4170-bdfe-d7c7624e0d76', 'летюча і тверда сажки', 3, '0', NULL),
(328, 'e7d084c6-9906-4d9f-a519-cdd350019f44', 'інгібітор росту', 0, '0', NULL),
(329, '93baa2c1-93b7-4123-af58-2a637c1e309c', 'листкові попелиці', 3, '0', NULL),
(330, '628c81be-08b0-4681-822e-681a01630893', 'гусінь листогризучих шкідників', 3, '0', NULL),
(331, '9a764c7c-a5b5-42a5-aaa4-f47a48c3187f', 'звичайна парша', 2, '0', NULL),
(332, '67402dca-076e-4773-8a4f-f431e3ef7c90', 'смугаста плямистість', 2, '0', NULL),
(333, '1aa41432-aeb9-44a7-8d45-729312cfc262', 'облямівкова плямистість', 2, '0', NULL),
(334, 'eb5fd2ec-f1fb-47f5-9bf5-a6959e73ced6', 'для прискорення дозрівання плодів', 0, '0', NULL),
(335, 'b491f700-bc9d-4667-a256-deba3bdc68e3', 'треда сажки', 2, '0', NULL),
(336, '133db468-f766-4ce1-88db-241514956663', 'нігроспоріоз', 2, '0', NULL),
(337, 'c920221f-dc8b-4eb5-a7f6-67dfc2c2f5d9', 'гельмінтоспоріоз листя', 2, '0', NULL),
(338, 'bf5246e2-5442-497d-b678-b7a45162cccd', 'для запобігання виляганню (від низького до середнього ступеню)', 0, '0', NULL),
(339, '79e8a179-c63a-4bb2-b793-b10a2107cb41', 'для запобігання виляганню (від середнього до високого ступеню)', 0, '0', NULL),
(340, '01c6fd0b-4e85-4dd5-88d1-612f99687dfe', 'боротьба з мишовидними гризунами', 3, '0', NULL),
(341, '6229ae50-293a-4c90-98b4-b669ad2a31e4', 'пасмо', 2, '0', NULL),
(342, 'd408e8b9-1ec5-4595-b1ba-956f36e952e0', 'чорна коренева гниль', 2, '0', NULL),
(343, '8ad3cdec-f325-444e-8301-c22614a2d6cf', 'стеблова сажка', 2, '0', NULL),
(344, '236f705d-7b04-4cc6-b428-a71b6add817e', 'хлібний турун', 3, '0', NULL),
(345, '58cbfc40-eea3-4b76-910b-380dda7848fd', 'вишнева попелиця', 2, '0', NULL),
(346, '36233f56-2f74-47b7-8133-14111ff9afe2', 'Колорадський', 3, '0', NULL),
(347, 'd92a5dae-ae88-46ca-b02b-48af113352bf', 'метлюг звичайний', 1, 'metlyuh', NULL),
(348, 'a77a0be7-6f73-4b66-ad74-eb05901d2ba6', 'багаторічні дводольні бур''яни', 1, '0', NULL),
(349, 'd979bfff-3d15-4771-9c26-5159b05f7608', 'західний квітковий трипс', 3, '0', NULL),
(350, 'fc315fea-7db9-4187-ac3c-abb9dc73f855', 'корончаста іржа', 2, '0', NULL),
(351, 'f81cf6ce-67b1-4b75-a134-b9074c61643e', 'комплекс саранових', 3, '0', NULL),
(352, 'e779531b-d54d-4963-9ecd-34fbe8a204e4', 'зелена яблунева попелиця', 3, '0', NULL),
(353, '8ff77e92-2280-4b65-ae91-04519680c3dc', 'личинки хрущів', 3, 'lushunku_hryshcha', NULL),
(354, '9b81f1d8-c76e-454d-8c78-47170f765dd8', 'багатоїдний трубкокрут', 3, '0', NULL),
(355, '1e49df80-c635-4661-8904-76871d76f3be', 'скосар кримський', 3, '0', NULL),
(356, '1cd0fa66-0dcc-4d1a-80c9-d3fb54a4d4ca', 'яблунева зелена попелиця', 3, '0', NULL),
(357, '69492ee7-7454-4293-a848-0fd9977e831a', 'велика картопляна попелиця', 3, '0', NULL),
(358, 'a7a56dc9-36a9-47e4-ac99-6d76cdc5bf03', 'геліхризова попелиця', 3, '0', NULL),
(359, '85ecfcef-1d40-45a2-a78d-48e9f3c9115f', 'шипоноска соняшникова', 3, '0', NULL),
(360, '325397af-445d-4d34-a7f4-f0f00e147e26', 'Стебловий (кукурудзяний) метелик', 3, '0', NULL),
(361, '2ede0443-7322-4078-9c2f-913e57327201', 'гнилі при зберіганні', 0, '0', NULL),
(362, 'c1b21bde-2326-4c59-9dab-1c2acb4092bf', 'сітчастий гельмінтоспоріоз', 2, '0', NULL),
(363, 'b5488bad-9edc-4f59-9460-2fb4ec32847a', 'інгібування росту рослин', 0, '0', NULL),
(364, 'd294a7c0-4568-4581-9464-2c8aea9b19f6', 'підвищення стійкості до екстремальних погодних умов', 0, '0', NULL),
(365, '23dd99c5-c1cc-47fb-bd15-175488eab5a1', 'одночасність цвітіння', 0, '0', NULL),
(366, '49cb9ac1-6647-45f5-8dcb-ac1b7cd58b7c', 'личинки хлібних жуків', 3, '0', NULL),
(367, '6baa6bc0-fd0f-4520-8cd9-4748526ad576', 'туруни', 3, '0', NULL),
(368, 'b9f2f280-bb93-45a1-b763-327e2cd83d54', 'хлібна п''явиця', 2, '0', NULL),
(369, '066817b9-b11e-4a9f-9931-ed00bfa04ae0', 'картопляна міль', 3, '0', NULL),
(370, 'e73c4c27-6e8d-4872-9148-98200c6d877c', 'яблуневиий квіткоїд', 3, '0', NULL),
(371, '77da780f-c02c-4586-b79a-f64a45be3627', 'пильщик', 3, 'pylshchik', NULL),
(372, '08f3edf0-d1e2-412b-ae95-058823630dd2', 'брунькоїд', 3, '0', NULL),
(373, '6179fec3-b574-443d-bf7d-1f06b25aa1b0', 'червоно-бура плямистість', 2, '0', NULL),
(374, '29ac2cab-9352-4cd9-bff9-781cd787775b', 'опік листка', 2, '0', NULL),
(375, 'd02ad024-94d5-4a9e-b80c-089dc837d035', 'іржасті хвороби', 2, '0', NULL),
(376, '559da380-aca5-4b59-a968-25970152670c', 'інфекційне засихання кущів', 2, '0', NULL),
(377, '28b85e04-8d7c-4cfd-9fec-29b93bb810e1', 'чорноколосиця', 3, '0', NULL),
(378, 'a5f8648b-903f-4f99-847d-9a9c735aef39', 'сірий буряковий довгоносик', 3, '0', NULL),
(379, 'bccb5607-3411-45b8-9ee7-323c2d2386b7', 'ковалики (дротяники)', 3, '0', NULL),
(380, '5420dd9c-0734-47ba-a43b-c400361d99fe', 'кравчик-головач', 3, '0', NULL),
(382, '40b28a84-7499-40a8-a4f8-cd18268e53fd', 'грушевий плодовий трач', 3, '0', NULL),
(383, '98e9443a-de4d-4de3-a8cd-8e424e4eb612', 'ріпаковий довгоносик', 3, '0', NULL),
(384, '994d974e-09ca-43cb-95f7-f6b056564704', 'личинки травневого жука', 3, '0', NULL),
(385, 'b876ae33-675c-4eab-8749-a6459546fd8d', 'прихованохоботник', 3, 'prihovanohobotnyk', NULL),
(386, '8d6dc171-18b0-4082-9951-294bca1bdaaf', 'Картопляна, або болотна, совка', 3, '0', NULL),
(387, '62770d96-ba8f-4c24-b1e7-f5a3ba98170d', 'Капустяний клоп', 3, '0', NULL),
(388, '64f8c992-c1b2-424a-8df4-7646654c6c7e', 'капустяні блішки', 3, '0', NULL),
(389, 'fec18e54-ff54-471e-bf21-f06f9fa043b4', 'стебловий прихованохоботник', 3, '0', NULL),
(390, 'acfc0a07-00f4-43b2-a94c-3d3c39a0f0d6', 'капустяна літня муха', 3, '0', NULL),
(391, '86b7b17f-ad4b-486f-928d-e98bd38722ad', 'насіннєвий прихованохоботник', 3, '0', NULL),
(392, 'b2856e92-62b5-4b89-b4f8-91d23eca5cdb', 'білан капустяний', 3, '0', NULL),
(393, '4d54b56a-9561-45e7-a4df-ac811f6ae271', 'кладоспоріоз', 2, '0', NULL),
(394, '7c3d125d-8dae-4f74-b781-8fc2467b4b1b', 'комплекс хвороб', 2, '0', NULL),
(395, 'b2de76a5-8c9a-4357-91f1-ad81888bd178', 'суха гниль', 2, '0', NULL),
(396, '0aa9a1ad-b9a0-4d77-8db2-8be419d5295e', 'червона гниль', 2, '0', NULL),
(397, '81622f3e-ab17-42dd-8b06-3460eac3adc1', 'великий люцерновий довгоносик', 3, '0', NULL),
(398, 'eaf1a092-96b3-4438-a2ca-41d3b84e24ce', 'Цикадка зелена', 3, '0', NULL),
(399, '385c57ac-6cb6-4d3f-b7c2-f40981d1d794', 'стебловий метелик', 3, '0', NULL),
(400, 'ef4260ad-bbbd-4aec-9a1d-bcef62df98dd', 'золотогузка', 3, '0', NULL),
(401, '6f795639-4088-4657-ab5a-111a8f458b5f', 'Білан жилкуватий', 3, '0', NULL),
(402, '5edeae95-a786-4fd5-9bf9-a1134df0f5ab', 'червіця в''їдлива', 3, '0', NULL),
(403, 'cb519a69-3d09-4d9d-8fc1-fd64b034142c', 'листовійка конопляна', 3, '0', NULL),
(404, '2f17ab72-17c9-4b5c-b49e-c9720cc61e15', 'совка бавовникова', 3, '0', NULL),
(405, '59885eb2-7a56-4ada-a8c6-2fb126eefc30', 'оленка волохата', 3, '0', NULL),
(406, '1374ce9f-3b67-4470-92ba-30d25b25b7a8', 'гороховий комарик', 3, '0', NULL),
(407, '7b791d40-dd1e-43c7-9b30-27ce2a325d15', 'люцернова товстоніжка', 3, '0', NULL),
(408, '6c7dd5c6-d4f1-415c-8c4f-510c6a5f3268', 'американський білий метелик', 3, '0', NULL),
(409, 'c451ac16-e6a0-4271-ab4d-2f41084a3902', 'личинки цикадки-пінниці', 3, '0', NULL),
(410, 'a18f84d0-85dd-47aa-8097-b705d67f2abc', 'стадні саранові, личинки 1-3 віків', 3, '0', NULL),
(411, '8d852b15-023e-4d6f-8464-6bda4fd2c259', 'Рисовий комарик (дзвінець рисовий)', 3, '0', NULL),
(412, '8bf23a92-d9e9-4596-bf14-08139fe2ee11', 'ячмінний мінер', 3, '0', NULL),
(413, 'f51ebcdf-b296-4490-b5f1-07ff34f101e5', 'листкова іржа', 2, '0', NULL),
(414, 'dd59db9a-fa90-4c22-80a7-0c5bb5e30f1a', 'гронова листовійка, 2-3 генерації', 3, '0', NULL),
(415, 'ed776f21-dd8d-4545-9a50-0fef508c3f42', 'несправжні щитівки', 3, '0', NULL),
(416, 'f70863e7-98ec-440c-b435-f5b7afc407ab', 'стручковий комарик', 3, 'struchkovuy_komarik', NULL),
(417, 'd59f04bf-0105-4e90-8c81-6821fa44c5dc', 'ріпаковий квітоїд', 3, '0', NULL),
(418, '8e5590b2-8a49-481c-99c4-459561452f90', 'вертицильоз', 2, '0', NULL),
(419, '1cb2dc16-c4c8-4d26-8bf8-a89a3345373a', 'гнилі', 0, 'gnuli', NULL),
(420, '434746b2-35fe-4a13-9f30-90bc95d84b75', 'хвороби плодів під час їхнього здерігання у сховищах', 2, '0', NULL),
(421, '195c5bbf-ce5c-4d48-b20d-c915d76fa4eb', 'перикуляріоз', 2, '0', NULL),
(422, '70adca39-a0de-4a1d-8b67-ce0743cbbc4d', 'білан ріпаковий', 3, '0', NULL),
(423, '358843fd-01b3-4e15-9a3c-bd30ed3f04e6', 'крапчастість сім''ядолей', 2, '0', NULL),
(424, 'c5987b3f-9783-49bc-a58e-f1f5ca73ab13', 'кам''яна сажка', 2, '0', NULL),
(425, '24cb9f45-261a-4464-886f-f99672c3739b', 'інгібування росту листя', 0, '0', NULL),
(426, 'c8a0cb35-b478-4b9d-9839-37d908929eec', 'совка', 3, 'sovka', NULL),
(427, 'e8e7f731-43d6-4f6b-962d-d730b3de95a5', 'жужелиця', 3, '0', NULL),
(428, 'f7d3e872-e74b-428b-9b2e-18f680ede852', 'антидот до S-метолахлору для насіння сорго', 0, '0', NULL),
(429, 'cdc89ee7-a55d-4895-8c82-8252928d0785', 'комплекс ґрунтових шкідників сходів', 3, '0', NULL),
(430, '13a5c950-fd2a-428b-9257-fea96621a205', 'гельмінтоспороз', 2, '0', NULL),
(431, 'd9520068-94de-46ce-88a8-82970326f3b8', 'збудники кореневих гнилей', 2, '0', NULL),
(432, 'e13c5bba-a7aa-41ad-898c-61d1b63bc880', 'ризоктонія', 2, '0', NULL),
(433, 'f226e094-e4d3-45ea-8db5-1f4b80eb5349', 'пітіум', 2, '0', NULL),
(434, 'e5354883-d5b7-47ed-896a-bcafbe075150', 'офіобольоз', 2, 'ofioboloz', NULL),
(435, 'be758d79-995a-4ecf-ab83-cbc30e243205', 'дводольні однорічні бур''яни', 1, '0', NULL),
(436, '1ae825b0-8dfe-495f-9dbd-bb71be65b86b', 'дводольні бур''яни', 1, '0', NULL),
(437, 'be946416-b575-4dd0-a786-11cb2a27bc73', 'підвищення врожайності та покращення якості зерна', 0, '0', NULL),
(438, '14ca34e3-21f2-4ce3-bc7f-5433ff322a9d', 'прискорення дозрівання, покращення товарної якості плодів', 0, '0', NULL),
(439, '095a34f4-0b8f-41e3-86d3-543ae426af50', 'запобігання переростання культури та покращення переземівлі', 0, '0', NULL),
(440, 'c2e7d80f-7b97-47c6-80dc-8c8dc1a0329a', 'проти вилягання та оптимізації габітусу', 0, '0', NULL),
(441, '8294b5cf-ce09-431d-bd0a-fd85a55619a0', 'запобігання проростання бульб', 0, '0', NULL),
(442, '1d254902-3e4f-47f5-9289-3d088aedfd95', 'однорічні однодольні бур''яни', 1, '0', NULL),
(443, 'f7f21fbf-78d0-4218-b0d3-828204cb635d', 'багаторічні однодольні бур''яни', 1, '0', NULL),
(444, 'c90ba6bb-a00e-4d20-a047-6c68393b9554', 'злакові бур''яни', 1, '0', NULL),
(445, '0a71e675-05bf-45a5-bb22-ca74878599ce', 'прискорення мінералізації', 0, '0', NULL),
(446, '92bd6b30-03d9-4112-8231-29b83aeef882', 'для прискорення розкладання післяжнивних решток', 0, '0', NULL),
(447, 'a173465f-520b-4a7f-bea8-5ee5d46c023c', 'оздоровлення ґрунту', 0, '0', NULL),
(448, '89573838-81a3-41cc-adfc-a704094df21e', 'пригнічення фітопатогенних грибів', 0, '0', NULL),
(449, 'c258e321-14b5-4cca-a436-5a47e40e9855', 'баштанна попелиця', 3, '0', NULL),
(450, 'c7645727-ed6c-45aa-9ee7-7423e1e41f07', 'Бактеріальний опік', 2, '0', NULL),
(451, 'fe160cdc-6328-49ee-9e06-ddc0e11182fa', 'бактеріальні хвороби', 2, '0', NULL),
(452, '2e568706-439c-4417-9c09-61043111ffb0', 'капустяні білани', 3, '0', NULL),
(453, '945a80b2-de73-4c6c-9929-af2b93f12cbe', 'яблунева міль', 3, '0', NULL),
(454, 'c0b0a68e-731a-43fd-bd1c-273be6aa7837', 'сіра зернова совка', 3, '0', NULL),
(455, '06b96d2c-6766-4b45-b8a6-3862c3cb799c', 'для боротьби з комплексом хвороб', 2, '0', NULL),
(456, '390af73a-683d-4deb-9ae2-a556e4c192ff', 'для покращення мінерального живлення', 0, '0', NULL),
(457, 'a0fc3a43-0fa1-41bc-9e52-0c75622ad7a1', 'смугаста цикадка', 3, '0', NULL),
(458, '6ff8b8cf-bbbf-46a4-9ccf-8a4bb10ace2b', 'п''явиця звичайна', 3, 'pyavuzya_zvuchayna', NULL),
(459, '2d0535a0-d718-4ea1-aa9e-1b6553e20b33', 'тля', 3, '0', NULL),
(460, 'aeda37e6-6797-4253-b816-d85247732042', 'скосар малий чорний', 3, '0', NULL),
(461, '6a1ead1b-0a38-4872-b796-5b96b9644aa1', 'для зв''язування атмосферного азоту', 0, '0', NULL),
(462, 'd238a572-d62b-4530-ad1f-db4b526b13c9', 'проти збудників грибних і бактеріальних хвороб', 2, '0', NULL),
(463, '81b33d64-487f-426b-9d32-09501b96d339', 'сиза пліснява', 2, '0', NULL),
(464, '4d138d91-8a82-4a6a-aae8-a4eeab9ca42c', 'багаторічні коренепаросткові бур''яни', 1, '0', NULL),
(465, '84aa7499-eeaa-4479-b629-ff409b1e9c57', 'частуха', 1, '0', NULL),
(466, 'd0659532-cefc-4eb1-98ec-a5b6f36781aa', 'болотні бур''яни', 1, '0', NULL),
(467, '51632d91-9975-4081-9a79-ad7587899eeb', 'двосім''ядольні бур''яни', 1, '0', NULL),
(468, 'df3cc8cf-b0da-49b8-aed3-ee2d85ff71f7', 'широколисті болотні бур''яни', 1, '0', NULL),
(469, '61dee7ee-d45e-463f-a448-ee7213636e8f', 'однодольні бур''яни', 1, '0', NULL),
(470, 'f110d8a5-4679-4efb-8738-df8ad67cf1e5', 'отруйна', 0, '0', NULL),
(471, 'ef1c8c5a-d82d-4ab1-ac89-9415be7986ad', 'небажана рослинність', 0, '0', NULL),
(472, '282940a5-e2de-4c2a-8162-2a6931e18e16', 'багаторічні двосім''ядольні бур''яни', 1, '0', NULL),
(473, 'f171b029-438b-4859-a339-c1e6bfc8285c', 'фузаріозна гниль', 2, '0', NULL),
(474, '19bf1e61-cfcf-4b8a-aa50-cc534fc03b26', 'альтернаріозна гниль', 2, '0', NULL),
(475, 'bf957961-bff8-4344-b7b7-bd7cc6a59c95', 'мокра гниль', 2, '0', NULL),
(476, '6c99e85c-43e8-49ca-945d-bee198a0831a', 'біла плямистість', 2, '0', NULL),
(477, '65b6250a-7e68-467e-b74e-5249ca0184fc', 'карликова сажка', 2, '0', NULL),
(478, 'faf17b75-55e8-48b5-928c-35efab5341a5', 'стеблові гнилі', 2, '0', NULL),
(479, 'f8e3dfee-ced3-4db2-94b1-e74a13631458', 'чорна сажка', 2, '0', NULL),
(480, 'cfaf0ca5-ff02-4265-842f-9a2718b7fcde', 'парша звичайна', 2, '0', NULL),
(481, '07537af4-3f58-44eb-a90f-bccd8a9017d2', 'філостиктоз (бура плямистість)', 2, '0', NULL),
(482, '1a999de3-491e-4b83-b16f-186c53918be2', 'фузараіозне в''янення', 2, '0', NULL),
(483, '1d29855b-7416-4963-9a42-4fdf176667ad', 'вертицильозне в''янення ', 2, '0', NULL),
(484, 'd894a205-f197-45f7-918b-52b8209c9b0a', 'офіобольозна коренева гниль', 2, '0', NULL),
(485, '17293fc9-d59d-43f9-a1cf-bcb93f87bd8a', 'церкоспорельозна коренева гниль', 2, '0', NULL),
(486, 'd38a8447-28cc-49d7-b897-004e30548b01', 'червоний плодовий кліщ', 3, '0', NULL),
(487, '1ccf704d-8b70-4dc4-97f7-4308ada63ddf', 'парша срібляста ', 2, '0', NULL),
(488, '86351027-bf8a-4fc2-8b9f-d6305e3adfa8', 'підвищення стійкості до хвороб', 2, '0', NULL),
(489, '0bdfa5da-549c-4cf2-bf7a-516da1f0b4bc', 'бурий плодовий кліщ', 3, '0', NULL),
(490, '5dc7e411-6124-4543-9764-97c8064e4f96', 'рослиноїдний павутинний кліщ', 3, '0', NULL),
(491, '20f5bf25-31c1-430b-96a4-b13ff8398952', 'туркестанський павутинний кліщ', 3, '0', NULL),
(492, 'd7787d9c-ce1e-4154-b14c-808dc176acf3', 'середземноморська плодова муха', 2, '0', NULL),
(493, '749ec024-a608-4c0e-8365-db5b2bbb4a59', 'грушева плодожерка', 3, '0', NULL),
(494, '6e554342-3237-4328-8c58-20902110eded', 'яблунева попелиця', 3, '0', NULL),
(495, 'e83410c9-1111-4fa0-a5f8-8049f8a295e9', 'капустяний стебловий прихованохоботник', 3, '0', NULL);
INSERT INTO `pd_Vermin` (`id`, `guid`, `name`, `groupId`, `photo`, `ord`) VALUES
(496, 'd95d665e-6ccc-4135-a132-5af9b2d033b3', 'ріпаковий стебловий прихованохоботник', 3, '0', NULL),
(497, 'a714b7c2-f150-4303-a3a9-ebb6f06c6450', 'комплекс наземних шкідників сходів', 0, '0', NULL),
(498, 'f2ec38c1-2f13-4c01-ab9c-8b9619d7f3ed', 'листогризучі шкідники', 3, '0', NULL),
(499, 'afdc2452-0ff3-4122-86f9-a942e18af064', 'червневий хрущ', 3, '0', NULL),
(500, '0b964e2f-377c-4af8-990f-63247d83f7d3', 'травневий хрущ', 3, '0', NULL),
(501, 'd800fa4a-8560-44ea-b859-504fea06a616', 'волохатий хрущ', 3, '0', NULL),
(502, 'ccf522b6-5c13-4672-8abe-a41fa2427f67', 'травневий волохатий хрущ', 3, '0', NULL),
(503, 'e72fc424-17b2-491b-8a63-ef6f949d607c', 'Личинки пластинчатовусих', 3, '0', NULL),
(504, '8646481d-faa3-4dc4-9b20-b6b9f5e3015e', 'Совка люцернова, або льонова', 3, '0', NULL),
(505, 'b19bc689-d920-4d0d-966a-7461fa1ac17f', 'шкідливі гризуни', 3, '0', NULL),
(506, '79f8115d-e855-4319-9cd8-24f04ecae6ca', 'сітчаста листовійка', 3, '0', NULL),
(507, '29c64ca3-2bb1-492e-ac4f-c4d5a24bdef6', 'садові трубокрути', 3, '0', NULL),
(508, '0a4b4d38-8c50-481a-9ef5-c2f75f1ab500', 'сажкові хвороби за значного заспорення', 2, '0', NULL),
(509, 'ee9d16ac-01c5-4b64-b438-f5aa116c4db9', 'пітумна коренева гниль', 3, '0', NULL),
(510, '3c61b688-b7a0-4f04-aac3-db3b89ae14d4', 'шкідливі комахи', 3, '0', NULL),
(511, 'a27de277-e7ed-4336-92b6-0e048b9b4cbd', 'південний буряковий довгоносик', 3, '0', NULL),
(512, 'e0058151-1a15-43b4-a74d-cc6200264ee2', 'совка карадрина', 3, '0', NULL),
(513, '77ea99e6-63b0-4689-abde-747c3b5af53a', 'саранові стадні', 3, '0', NULL),
(514, '3b0cab4c-d921-4ed5-af9b-7bb5a601cc8d', 'червець комстока', 3, '0', NULL),
(515, '46c87806-2f10-427f-a925-d7f374d52aa8', 'сливова плодожерка', 3, '0', NULL),
(516, 'cb64f591-68f4-43f0-ad98-937cda9e486f', 'сливова попелиця', 3, '0', NULL),
(517, '6da54c57-97c1-41c5-8103-e7fd73d9fd2d', 'грушевий квіткоїд', 3, '0', NULL),
(518, '528d93a5-311c-4f7c-a9d0-677498137b8a', 'кагатна гниль', 2, '0', NULL),
(519, '6861eefd-02e9-4932-9ed9-892d2b9c6a6d', 'ооспороз', 2, '0', NULL),
(520, '2ef4b5d3-0382-488e-b2fe-c41d1fe00cce', 'попелиця', 3, 'popelizya', NULL),
(521, '825b71fa-9df5-4942-b17d-b0b10d380bf7', 'мероміза', 3, '0', NULL),
(522, '594d174d-1dd5-4ffa-9af0-a899393afa5d', 'блохи', 3, '0', NULL),
(523, '6075a288-2165-46b4-b02d-0b28338486a7', 'совка городня', 3, '0', NULL),
(524, 'c4fc39c4-2833-4014-93e7-6ee3b7e7c96b', 'оранжерейна білокрилка', 3, '0', NULL),
(525, 'eea8ea69-cac4-40d8-81c7-cbfadd6794dc', 'звичайна картопляна попелиця', 3, '0', NULL),
(526, 'f40608a0-a114-4ab1-9b8d-5f2db6442535', 'цибулевий трипс', 3, 'cibulevuy_trips', NULL),
(527, '0f781e9b-9980-468a-a28a-ba25e1e16926', 'оранжерейний трипс', 3, '0', NULL),
(528, '4a57813c-5103-41be-87ac-74619cd4e0de', 'розанова цикадка', 3, '0', NULL),
(529, '22dcea69-738c-4404-ba7b-ab1663ee0df6', 'зелена розанова попелиця', 3, '0', NULL),
(530, 'f5cb15e5-17be-4734-88df-aaa152c99055', 'розанова білокрилка', 3, '0', NULL),
(531, '5988fea5-56b0-4252-9a66-6114ccc33232', 'розановий пильщик', 3, '0', NULL),
(532, '692898ea-3dce-4ad5-8905-39aae3c313a2', 'Озимі совки', 3, '0', NULL),
(533, '2f78cfe4-3942-4eed-afb8-831b128426eb', 'зерновий довгоносик', 3, '0', NULL),
(534, 'f2d894a1-f680-4847-aedf-4f288b2e39fe', 'гронова листокрутка', 3, '0', NULL),
(535, 'dfa7f53f-3ccb-4987-9524-24b8a2cc92e4', 'буряковий клоп', 3, '0', NULL),
(536, '23fe1685-45c8-4e7f-96aa-b8acc2d20a30', 'бурякова щитоноска', 3, '0', NULL),
(537, '6b716e0f-ab0e-4a03-b623-acbd57ebaa51', 'гельмінтоспоріозні плямистості', 2, '0', NULL),
(538, 'aa13eb50-86a4-4e42-9ba3-b7a583ab3fe0', 'зимуючі стадії кліщів', 3, '0', NULL),
(539, '344349b3-c1bc-4147-bb09-bebfec056c40', 'парша яблуні', 2, '0', NULL),
(540, '37b266a9-e7fe-4815-be6a-5de5c4a0517e', 'листкова плямистість', 2, '0', NULL),
(541, '9b9384b8-fbb7-4cb1-9dc4-56b88c08584a', 'Коренева гниль ', 2, 'koreneva_gnul', NULL),
(542, '9eee0365-fffe-4c8b-9643-31cdbdd843e8', 'смугастий гельмінтоспоріоз', 2, '0', NULL),
(543, '25ce8b2b-a08b-4646-93dd-ee1873381b9a', 'деревочагарникова рослинність', 1, '0', NULL),
(544, '5e36e71e-4fda-436b-b899-1135a3aab19e', 'бур''яни', 1, '0', NULL),
(545, '9393eabb-cb22-4f57-a1eb-bcbe15e8d274', 'Чорна гниль', 2, '0', NULL),
(546, '19af5b3e-b541-4027-9a7b-8acd092ad022', 'пирій повзучий', 1, 'puriy_povzuchiy', NULL),
(547, '0b9e3fb1-ef82-4605-80e0-1b66b2f5892e', 'личинки каліфорнійської щитівки', 3, '0', NULL),
(548, 'eca68ad7-1c0b-437c-8c74-f1764050f5a1', 'злакові цикадки', 2, '0', NULL),
(549, '216047e4-7044-4a05-bf66-4e6a656a4de0', 'горностаєва міль', 3, '0', NULL),
(550, '6ff86403-efe5-43f1-8222-b8f079e6011b', 'мінуюча міль', 3, '0', NULL),
(551, '7fb7b56c-4c2e-4c67-8cbf-19dc347ac088', 'яблунева листоблішка', 3, '0', NULL),
(552, 'a66571e0-08b3-4ed0-9de0-b1999aa24f55', 'філлостіктоз', 2, '0', NULL),
(553, '1f380925-070a-4778-9360-f8eea0231ad2', 'мінуюча муха', 3, '0', NULL),
(554, '799efbd8-c586-4351-ac3c-4764811025d4', 'мохи', 0, '0', NULL),
(555, '65bf852b-526a-45ea-836c-3ac6a3284f80', 'лишайники', 3, '0', NULL),
(556, '788e3efa-3912-4a1c-bc92-db55ed6e854f', 'бокальчаста іржа', 2, '0', NULL),
(557, '967cc824-66d9-4317-921f-31fd2c5c0644', 'Бактеріальний рак', 3, '0', NULL),
(558, '972e9f02-f81e-4af1-ad47-39704027bc37', 'Бактеріальна плямистість', 2, '0', NULL),
(559, '3d049e73-d62a-4042-8862-fedb17ba3dc9', 'гниль листкових піхв', 2, '0', NULL),
(560, 'f9b2f8d7-10d7-4d4e-9795-83ab4d17fc58', 'інші плямистості', 2, '0', NULL),
(561, 'd34192ef-e421-409b-8a6a-c724a01068d1', 'збудники піренофорозу', 2, '0', NULL),
(562, '386c4aa1-723f-4d14-b8b6-7a38291ae67b', 'збудники септоріозу', 3, '0', NULL),
(563, '63ad4d79-019c-4a42-8489-98396cb39eea', 'збудники фузаріоз', 3, '0', NULL),
(564, '044bb2df-2fee-4835-8022-16fea898ae79', 'Бактеріальний рак кори', 2, '0', NULL),
(565, '2ff8c2a4-f2ee-4ac5-ae01-cd899f9e1e84', 'личинки колорадського жука', 3, 'koloradskiy_gyk', NULL),
(566, 'c773c942-4b14-4ffb-83a6-33cc77a2a367', 'ризоктоніозна коренева гниль', 2, '0', NULL),
(567, 'f8d7ddaf-7bc3-48dc-b834-0428701ba9d2', 'пліснявіння початків', 2, '0', NULL),
(568, '16473f42-5588-4b1f-81e3-411f3a3bb69d', 'медведки', 3, '0', NULL),
(569, 'f258ea14-1361-42e6-b649-aea0ce9d37f7', 'інші шкідливі види комах', 3, '0', NULL),
(570, '93c18504-44d1-473c-9501-208e59858ecc', 'довгоносик ( види)', 3, 'dovgonosik1', NULL),
(571, 'be626749-23d6-4224-808e-24de40aaf3f4', 'росткова муха', 3, '0', NULL),
(572, '71d4b01b-d256-41b8-9523-c4679564dc7f', 'злакова рисова попелиця', 3, '0', NULL),
(573, '705bf69d-455f-4a9f-a85d-56d0d9d59b07', 'злакова муха', 3, '0', NULL),
(574, '09c79821-94d0-43dc-b0d9-a273ff4b6111', 'личинки пластинчатовусих жуків', 3, '0', NULL),
(575, '202f7133-1827-4aba-af6b-34a961b6b238', 'гусениці підгризаючих совок', 3, '0', NULL),
(576, '077a85c2-8cb2-43a8-9781-1af59b87f3dd', 'личинки коваликів', 3, '0', NULL),
(577, 'c9bdca68-5e06-4de3-96ca-1ea5a6fdf283', 'комплекс підгризаючих шкідників', 3, '0', NULL),
(578, '9ad4a1b2-37b7-4162-80d9-f46ecd7ae23d', 'Комплекс ґрунтоживучих шкыдників', 3, '0', NULL),
(579, '2bc92f18-af7e-4082-952f-fc4b4038d3df', 'однорічні та деякі багаторічні дводольні, у т.ч. стійкі до 2,4-Д бур''яни', 1, '0', NULL),
(580, 'd1b6830f-037d-422f-b07f-6d880f7d4afe', 'однорічні дводольні, в т.ч. стійкі до 2,4-Д бур''яни', 1, '0', NULL),
(581, '43762a38-3447-4e63-a4c6-e1c417dd7279', 'однорічні дводольні бур''яни, в т.ч. стійкі до 2,4-Д і МЦПА', 1, '0', NULL),
(582, 'ee36ee7f-54ee-4b41-b28a-d60085940a98', 'падалиця ріпаку', 2, 'padaluzya_ripaku', NULL),
(583, 'a6745994-bd7d-4b90-81fe-56dd4d276160', 'падалиця соняшника', 1, 'padaluzya_sonyashniku', NULL),
(584, '7495b49d-5415-4d1c-a674-08bf93901e29', 'сажка', 3, '0', NULL),
(585, 'e3affddc-356d-4254-bf7d-50a745ce35bf', 'ріжки', 3, '0', NULL),
(586, '45070541-847b-4b7f-b077-218d938e45d4', 'однорічні та деякі багаторічні дводольні бур''яни', 1, '0', NULL),
(587, 'be2a51ac-b30f-47a1-97d7-fa19d05f96d8', 'личинки кукурудзяного жука', 3, '0', NULL),
(588, 'ff449fb6-7895-41e3-a843-dc138d294904', 'Дводольні злакові бур''яни', 1, '0', NULL),
(589, 'c4332dd1-bb52-488d-a8db-2f6fbd2d0230', 'підвищення енергії проростання і схожості насіння, стимуляція росту, знищення поверхневої інфекції', 0, '0', NULL),
(590, 'a6f338fb-ba52-4fef-bf54-463becc15cb0', 'підвищення урожайності, стійкості рослин до хвороб', 2, '0', NULL),
(591, 'b4d97f3e-7248-4e65-af61-0a823b07993f', 'покращення якості продукції для кращого зберігання', 0, '0', NULL),
(592, '5874619d-b1c7-4ff6-9deb-71bbb3eab449', 'підвищення кількості вкорінених живців, цибулин. квіткових рослин', 0, '0', NULL),
(593, 'ce25b87a-e015-4cc0-ab82-cc862350e225', 'ґрунтопокращуюча суміш для висадки ', 0, '0', NULL),
(594, '6b6bb768-7dff-4552-96fe-c45c764bcdb7', 'з метою стимуляції розвитку та росту рослин', 0, '0', NULL),
(595, '7c0f7b23-1d89-46a4-a810-dc3cbed91f90', 'для інгібування росту рослин, покращення морозостійкості', 0, '0', NULL),
(596, 'a96fbc59-effb-4449-9d73-26060fb024dc', 'прискорення і вирівнювання строків дозрівання', 0, '0', NULL),
(597, '277c4a0f-fb92-479e-b623-c743591b8718', 'поращення якості плодів', 0, '0', NULL),
(598, '1eab5db0-9c45-4b6d-be36-eba2dd982adc', 'оптимізація та прискорення дозрівання і забарвленення плодів', 0, '0', NULL),
(599, '05dc820c-62be-4b8f-9e76-369652166073', 'регулювання зав''язі', 0, '0', NULL),
(600, '204742c1-42df-46b9-9c15-13be954c3b0c', 'стимулювання закладки плодових бруньок', 0, '0', NULL),
(601, '874d3ec7-ca69-43a0-acf3-b09d2be929a3', 'однорічні дводольні, у т. ч. стійкі до 2,4-Д та 2М-4Х бур’яни', 1, '0', NULL),
(602, '78fc7f2f-8678-4905-9b2c-b227d770c91f', 'багаторічні бур''яни, у т. ч. гідрофітні', 1, '0', NULL),
(603, 'f1bd363b-4b8f-4d23-b89a-2510fc6247cd', 'десикація', 0, '0', NULL),
(604, '1f1d46dc-68a4-4dfa-b85e-257964c000b0', 'формування стандартних пагонів, підвищення їх врожайності', 0, '0', NULL),
(605, '88f98c34-fb31-4383-836f-76a1625e618a', 'деякі багаторічні дводольні бур''яни', 1, '0', NULL),
(606, 'e98d5d15-e9c3-4fb8-b6b1-be765ce757ab', 'однорічні дводольні бур’яни, в т. ч. стійкі до 2,4-Д і МЦПА та деякі багаторічні дводольні бур’яни', 1, '0', NULL),
(607, 'cc56d358-49f2-48bd-a5f8-281f933b864d', 'однорічні дводольні та деякі злакові бур''яни', 1, '0', NULL),
(608, 'f60b34fd-dec2-4b6a-9563-82d0c9d7fb95', 'однорічні дводольні та деякі злакові види бур’янів', 1, '0', NULL),
(609, '4063ccd7-ef83-4d1f-b80f-5665dcaa4e02', 'однорічні та деякі дводольні бур’яни, в т. ч. стійкі до сульфонілсечовин та 2,4-Д', 1, '0', NULL),
(610, 'c5235e88-6c0d-4e48-ada9-8c7eecb6e06e', 'однорічні злакові та деякі дводольні бур''яни', 1, '0', NULL),
(611, '89166454-da8b-45ba-800d-ce340489e726', 'однорічні та деякі багаторічні дводольні, у т.ч. стійкі до 2,4-Д та 2М-4Х бур’яни', 1, '0', NULL),
(612, 'fc13313d-396e-4715-8797-d79189f84c1f', 'Обприскування посівів у фазі від 3 листків культури до виходу в трубку, залежно від фази розвитку бу', 0, '0', NULL),
(613, 'ef0fd678-1016-4868-bcd1-93e7d807b942', 'однорічні, багаторічні злакові і найбільш поширені однорічні дводольні бур’яни', 1, '0', NULL),
(614, '364ab1e8-b9e5-488d-a323-c30a06676059', 'однорічні та деякі багаторічні дводольні бур’яни, в т.ч. коренепаросткові види', 1, '0', NULL),
(615, 'd53a6150-9c98-4bbd-ac6a-180ac7ea35a6', 'однорічні злакові та дводольні бур’яни, в т.ч. карантинні (види амброзії та повитиць)', 1, '0', NULL),
(616, '8816ffcf-abb1-4f46-8cc9-efd3b308eb34', 'однорічні та деякі багаторічні дводольні бур’яни', 1, '0', NULL),
(617, '496274b0-7bab-4096-b807-af8e50cd4e63', 'усунення дефіциту елементів живлення', 0, '0', NULL),
(618, '509eb4c8-3e6b-4a68-a137-9625cb7b5dc5', 'регуляція ростових процесів та запобігання переростанню', 0, '0', NULL),
(619, '60138aae-64ab-43a5-8e8b-3c869356da13', 'збільшення цукристості коренеплодів', 0, '0', NULL),
(620, 'ffa372ec-fbe2-441c-8c61-9cbace2b2a23', 'запобігання проростанню при зберіганні', 0, '0', NULL),
(621, '16420358-713d-42d4-98f9-35696a8ac266', 'склеювання стручків', 0, '0', NULL),
(622, 'aa23fbc3-88ce-46bc-9e34-90283c52599a', 'кроти', 3, '0', NULL),
(623, '785bd055-3a74-452b-9d1d-603846df77ef', 'основні шкідники хвойних порід', 3, '0', NULL),
(624, '561aab5f-3846-4dc0-a94c-37734a72ff7e', 'грушевий клоп', 3, '0', NULL),
(625, '9388b41f-2e67-4c2f-bc59-372ec5a47a53', 'трояндова щитівка', 3, '0', NULL),
(626, '804e9e17-9e9e-468f-b201-da6573838c3c', 'цибулевий кліщ', 3, '0', NULL),
(627, 'b02a9019-66fb-4912-b9a7-837fb40b84b4', 'моркв''яна муха', 3, '0', NULL),
(628, 'a7f1322a-4ab4-4baf-a05a-be5d8035f4ec', 'листова блішка', 3, '0', NULL),
(629, '9d06110e-8d47-482a-b2d2-74e4db672051', 'червець', 3, '0', NULL),
(630, '836aa4fb-4239-4866-9174-9099a71a9fe6', 'пліснява', 2, '0', NULL),
(631, '68e3400b-4be1-4b97-82ca-987084332cd0', 'коники', 3, '0', NULL),
(632, '775e3158-ec39-452f-b6ce-1deaa77506e7', 'листокрутки', 3, '0', NULL),
(633, 'f7145ba8-7fc8-4e6f-b963-fd20b86db1b9', 'деякі дводольні бур''яни', 1, '0', NULL),
(634, 'cb44540f-93d5-42e1-a466-44a3810c77cb', 'хрущі', 3, '0', NULL),
(635, '3adc59d0-baf5-4c5e-9448-28076b44ffa5', 'сіра кутаста гниль', 2, '0', NULL),
(636, 'd18424fc-ffa7-4386-a3a7-c31cc7fdbc2a', 'антракоз', 2, '0', NULL),
(637, 'd717d356-5e8a-4ba4-88ca-7408a0f4c4ae', 'цибулева гниль', 3, '0', NULL),
(638, '0512b0b6-bb99-4f3e-9805-7a906558a0da', 'чагарникова рослиність ', 1, '0', NULL),
(639, '83f804bd-8db8-4e53-89f8-a683d980fca1', 'карантинні', 0, '0', NULL),
(640, 'a39e5f50-b719-47e1-baab-194b26ee9e0c', 'будяк польовий', 1, '0', NULL),
(641, '1f52cbae-266a-493e-8092-c2305706d3b5', 'осот жовтий', 1, '0', NULL),
(642, 'd8c77da9-024e-47b4-8b36-7b8e72bd542b', 'кульбаба', 1, '0', NULL),
(643, '748a10a4-b199-47d3-b587-f7d407e3d815', 'комахи', 3, '0', NULL),
(644, '9b4f969f-dda8-43cd-8597-bbab2954b70c', 'садові мурахи', 3, '0', NULL),
(645, '3cba2397-1a21-4180-ab18-0722bcc20a95', 'підмаренник чіпкий', 3, '0', NULL),
(646, '83d1ded8-40c0-42a4-a842-c83864278c7f', 'таргани', 3, '0', NULL),
(647, 'df6eec7f-7313-4254-a322-b35e9470dc32', 'види будяків', 1, '0', NULL),
(648, '3517a218-6e3a-4a4d-a7e0-74f126621872', 'жовтецеві', 0, '0', NULL),
(649, '3aef69a8-fce1-415f-814b-87169f434c71', 'види осотів', 0, '0', NULL),
(650, 'ac1b1ba7-cc82-4fcc-a285-b4da4a61c0f0', 'берізки', 1, '0', NULL),
(651, '7c586e7a-51c8-41e6-9559-a30025ca06db', 'конюшина', 1, '0', NULL),
(652, '4ce3b3fa-cd25-4b42-9d00-ae7259e2da10', 'подорожники', 1, '0', NULL),
(653, 'd4459d1e-53a0-4fc8-a50c-bf336340fe5e', 'мурахи', 3, '0', NULL),
(654, 'df3bf997-3082-4321-b00e-8e3cc54edae5', 'слимаки', 3, '0', NULL),
(655, '87113d08-d65a-4537-8d53-3a69fa0baad7', 'рижі мурахи', 3, '0', NULL),
(656, '62562524-457f-4488-a8ec-297b472ff119', 'листові блішки', 3, '0', NULL),
(657, 'f3fe45de-978d-4956-8b01-7079db8ef505', 'Покращення та підсилення ефективності дії пестицидів та агрохімікатів, зменшення поверхневого натягу', 0, '0', NULL),
(658, '9bbaa844-dd8a-4a94-933e-6b39ad9c186b', 'Пліснява (профілактика)', 3, '0', NULL),
(659, '63db4387-1f94-4a35-afba-f751e02c3bfc', 'у т.ч. стійкі до 2,4-Д', 0, '0', NULL),
(660, 'e92ac201-b8b3-47e2-8a56-e9892161cd6f', 'у т.ч. стійкі до МЦПА', 0, '0', NULL),
(661, '839887a6-7014-4ed1-a52d-81b443e06ff8', 'паросткова муха', 3, '0', NULL),
(663, '9be1e4ad-55f6-4da6-9704-4a4f1ff8c83e', 'щурі', 3, '0', NULL),
(664, 'b253059e-5da6-40de-be77-d1a69953b88b', 'Щур водяний', 3, '0', NULL),
(668, '2', 'Полівка', 3, '0', NULL),
(669, '3', 'Пацюк', 3, '0', NULL),
(670, '4', 'Щур', 3, '0', NULL),
(671, '5', 'Білокрилка теплична', 3, '0', NULL),
(672, '6', 'Садові мухи', 3, '0', NULL),
(673, '7', 'Капустянка (медведка)', 3, '0', NULL),
(674, '8', 'Колорадський жук та його личинки', 3, '0', NULL),
(675, '9', 'Дротяник', 3, '0', NULL),
(676, '10', 'Личинки хруща', 3, '0', NULL),
(677, '11', 'Парша (види)', 2, '0', NULL),
(678, '12', 'Міль-листокрутка', 3, '0', NULL),
(679, '13', 'Білянка', 3, '0', NULL),
(680, '14', 'Кліщ червоний цитрусовий', 3, '0', NULL),
(681, '15', 'Кліщ червоний плодовий', 3, '0', NULL),
(682, '16', 'Фітофтороз томату', 2, '0', NULL),
(683, '17', 'Щириця', 1, '0', NULL),
(684, '18', 'Щириця (види)', 1, '0', NULL),
(685, '19', 'Плоскуха звичайна', 1, '0', NULL),
(686, '20', 'Гірчиця звичайна', 1, '0', NULL),
(687, '21', 'Гірчак', 1, '0', NULL),
(688, '22', 'Лобода біла', 1, '0', NULL),
(689, '23', 'Редька дика', 1, '0', NULL),
(690, '24', 'Альтернаріоз картоплі', 2, '0', NULL),
(691, '25', 'Фітофтороз картоплі', 2, '0', NULL),
(692, '26', 'Альтернаріоз томату', 2, '0', NULL),
(693, '27', 'Рак', 2, '0', NULL),
(694, '28', 'Сіра гниль винограду', 2, '0', NULL),
(695, '29', 'Кила', 2, '0', NULL),
(696, '30', 'Парша персику', 2, '0', NULL),
(697, '31', 'Моніоліоз (плодова гниль)', 2, '0', NULL),
(698, '32', 'Пероноспороз цибулі', 2, '0', NULL),
(699, '33', 'Грястиця збірна', 1, '0', NULL),
(700, '34', 'Будяк', 1, '0', NULL),
(701, '35', 'Волошка синя', 1, '0', NULL),
(702, '36', 'Ячмінь мишачий', 1, '0', NULL),
(703, '37', 'Житняк гребінчастий', 1, '0', NULL),
(704, '38', 'Берізка польова', 1, '0', NULL),
(705, '39', 'Гірчиця польова', 1, '0', NULL),
(706, '40', 'Лобода', 1, '0', NULL),
(707, '41', 'Зірочник середній, або мокрець (Stellaria media L.).', 1, '0', NULL),
(708, '42', 'Осот рожевий', 1, '0', NULL),
(709, '43', 'Ромашка (види)', 1, '0', NULL),
(710, '44', 'Петрушка собача', 1, '0', NULL),
(711, '45', 'Грицики звичайні', 1, '0', NULL),
(712, '46', 'Фіалка польова', 1, '0', NULL),
(713, '47', 'Галінсога дрібноквіткова', 1, '0', NULL),
(714, '48', 'Мишій сизий', 1, '0', NULL),
(715, '49', 'Талабан польовий', 1, '0', NULL),
(717, '51', 'Амброзія полинолиста', 1, '0', NULL),
(718, '52', 'Плискуха звичайний', 1, '0', NULL),
(719, '53', 'Спориш', 1, '0', NULL),
(721, '55', 'Гусятник малий', 1, '0', NULL),
(722, '56', 'Свинорий пальчастий', 1, '0', NULL),
(723, '57', 'Щавель', 1, '0', NULL),
(724, '58', 'Деревій', 1, '0', NULL),
(725, '59', 'Портулак городній', 1, '0', NULL),
(726, '60', 'Вівсюг (овес дикий)', 1, '0', NULL),
(727, '61', 'Лопух великий', 1, '0', NULL),
(728, '62', 'Буркун', 1, '0', NULL),
(729, '63', 'Молокан татарський', 1, '0', NULL),
(730, '64', 'Роман польовий', 1, '0', NULL),
(731, '65', 'Просо куряче', 1, '0', NULL),
(732, '66', 'Капустянка', 1, '0', NULL),
(734, 'bc777b8b-397b-4a2a-862c-71067daaae2b', 'Знищувачі літаючих комах (Fly killer) серії LTD-003A, LTD-004A, LTD 009, LTD 006', 0, '0', NULL),
(741, '68', 'Вівсюг', 1, '0', NULL),
(742, '69', 'Ромашка', 1, '0', NULL),
(743, '70', 'Пімаренник чіпкий', 1, '0', NULL),
(820, 'new', 'Однорічні злакові бур''яни , в т. ч. падалиця зернових культур', 1, '0', NULL),
(821, 'new', 'Багаторічні злакові бур''яни, в т. ч. падалиця зернових культур', 1, '0', NULL),
(822, 'new', 'Однорічні злакові та дводольні бур''яни', 1, '0', NULL),
(823, 'new', 'Однорічні та багаторічні бур''яни', 1, '0', NULL),
(824, 'new', 'Багаторічні злакові та дводольні бур''яни', 1, '0', NULL),
(825, 'new', 'Однорічні та багаторічні бур''яни в т.ч. гідрофітні', 1, '0', NULL),
(826, 'new', 'Однорічні дводольні та злакові бур''яни', 1, '0', NULL),
(827, 'new', 'Злаковi та дводольнi бур''яни', 1, '0', NULL),
(828, 'new', 'Однорічні та багаторічні злакові та деякі дводольні бур''яни', 1, '0', NULL),
(829, 'new', 'Однорічні (в т.ч. підмаренник чіпкий) та деякі багаторічні дводольні бур''яни (в т.ч. берізка польова)', 1, '0', NULL),
(830, 'new', 'Однорічні дводольні та злакові види бур''янів', 1, '0', NULL),
(831, 'new', 'Рання суха плямистість (альтернаріоз)', 2, '0', NULL),
(833, 'new', 'Борошниста роса та частковий контроль септоріозу, іржі, фузаріозу, алтернаріозу', 2, '0', NULL),
(834, 'new', 'Борошниста роса та частковий контроль септоріозу, іржі, сітчастої, темно-бурої та смугастої плямистості листя', 2, '0', NULL),
(835, 'new', 'Інгібування росту листя та підвищення стійкості до екстремальних погодних умов', 0, '0', NULL),
(836, 'new', 'фузаріозно-гельмінтоспоріозна коренева гниль', 2, '0', NULL),
(837, 'new', 'садові трубкокрути (казарка, букарка)', 3, '0', NULL),
(838, 'new', 'Попелиця червоноголова (або сіра яблунева), попелиця зелена яблунева', 3, '0', NULL),
(839, 'new', 'Довгоносик сірий, бруньковий (або брунькоїд), квіткоїд яблуневий, казарка, яблуневий плодовий пильщик (трач), листовійка сітчаста, листовійка розанова, оленка волохата, бронзівка смердюча, бронзівка золотиста, бронзівка велика зелена, плодожерка яблу', 3, '0', NULL),
(840, 'new', 'соняшникова вогнівка', 3, '0', NULL),
(841, 'new', 'Комплекс наземних та ґрунтових шкідників сходів', 0, '0', NULL),
(843, 'new', 'Однорічні та багаторічні дводольні та злакові бур’яни', 1, '0', NULL),
(844, 'new', 'однорічні дводольні (у т. ч. стійкі до дії 2,4-Д та 2М-4Х) та злакові бур’яни', 1, '0', NULL),
(1037, '', 'Широкий спектр однорічних і багаторічних дводольних бур’янів', 1, '', NULL),
(1038, '', 'Однорічні та багаторічні злакові бур’яни', 1, '', NULL),
(1039, '', 'Однорічні злакові бур’яни (види мишію, плоскуха звичайна, просо посівне, вівсюг, метлюг звичайний та ін.)', 1, '', NULL),
(1040, 'new', 'Смугаста плямистість', 2, '0', NULL),
(1041, 'new', 'Підмаренник чіпкий і широкий спектр дводольних бур’янів, у тому числі стійких до 2,4-Д і МЦПА', 1, '0', NULL),
(1042, 'new', 'Однорічні дводольні та злакові, в т. ч. підмаренник чіпкий', 1, '0', NULL),
(1043, 'new', 'Однорічні та багаторічні дводольні бур’яни, в т. ч. підмаренник чіпкий, види ромашки, гірчаку, щириці, лобода (види), гречка березкоподібна, види осотів та інші', 1, '0', NULL),
(1044, 'new', 'Однорічні дводольні, у тому числі щириця жминдоподібна, хрестоцвіті, види гірчаку, падалиця соняшнику', 1, '0', NULL),
(1045, 'new', 'Однорічні та багаторічні дводольні бур’яни, в т. ч. види ромашки, гірчаку, осоту', 1, '0', NULL),
(1046, 'new', 'Запобігання виляганню', 2, '0', NULL),
(1047, 'new', 'септоріоз на початкових етапах розвитку культури', 2, '0', NULL),
(1048, 'new', 'чорниші', 3, '0', NULL),
(1049, 'new', 'насіннєва інфекція', 2, '0', NULL),
(1050, 'new', 'альтернаріозна насіннєва інфекція', 2, '0', NULL),
(1051, 'new', 'хвороби зберігання', 2, '0', NULL),
(1052, 'new', 'види іржі', 2, '0', NULL),
(1053, 'new', 'лускокрилі шкідники', 3, '0', NULL),
(1054, 'new', 'кореневі гнилі (фузаріозна, гельмінтоспоріозна, церкоспорельозна)', 2, '0', NULL),
(1055, 'new', 'хвороби зерна і сходів', 2, '0', NULL),
(1056, 'new', 'плямистість листя (Сітчаста плямистість, лінійна плямистість)', 2, '0', NULL),
(1057, 'new', 'запобігання переростанню культури та покращення перезимівлі', 0, '0', NULL),
(1058, 'new', 'проти хвороб, для покращення розвитку кореневої системи, збiльшення гiлкування, рiвномiрного цвiтiння, мiцнiшого та коротшого стебла', 2, '0', NULL),
(1059, 'new', 'велика злакова попелиця', 3, '0', NULL),
(1060, 'new', 'інші види попелиць', 3, '0', NULL),
(1061, 'new', 'регуляція росту: вкорочення пагонів та утворення меншої кiлькостi неплодоносних пагонiв, полiпшення утворення зав’язi, пiдвищення свiтлопроникностi крони', 0, '0', NULL),
(1062, 'new', 'Однорічні дводольні та злакові бур’яни', 1, '0', NULL),
(1063, 'new', 'Вівсюг, види', 1, '0', NULL),
(1064, 'new', 'Вівсюг, види (Avena spp.)', 1, '0', NULL),
(1065, 'new', 'Метлюг звичайний (Apera spica-venti)', 1, '0', NULL),
(1066, 'new', 'Лисохвіст польовий (Alopecurus myosuroides)', 1, '0', NULL),
(1067, 'new', 'Тонконіг однорічний (Poa annua)', 1, '0', NULL),
(1068, 'new', 'Мишій, види (Setaria spp.)', 1, '0', NULL),
(1069, 'new', 'Куряче просо (Echinocloa crus-galli)', 1, '0', NULL),
(1070, 'new', 'Просо волосоподібне (Panicum spp.)', 1, '0', NULL),
(1071, 'new', 'Росичка, види (Digitaria sanguinalis)', 1, '0', NULL),
(1072, 'new', 'Кукурудза, падалиця (Zea)', 1, '0', NULL),
(1073, 'new', 'Лускокрилі (совки, білани, молі)', 3, '0', NULL),
(1074, 'new', 'Стебловий метелик, лучний метелик, бавовникова совка', 3, '0', NULL),
(1075, 'new', 'Лускокрилі (лучний метелик, бавовникова совка)', 3, '0', NULL),
(1076, 'new', 'Клоп шкідлива черепашка', 3, '0', NULL),
(1077, 'new', 'листовійка', 3, '0', NULL),
(1078, 'new', 'ріпаковий клоп', 3, '0', NULL),
(1079, 'new', 'шипоноска', 3, '0', NULL),
(1080, 'new', 'цибулева муха-дзюрчалка', 3, '0', NULL),
(1081, 'new', 'цибулевий прихованохоботник', 3, '0', NULL),
(1082, 'new', 'Морквяна муха', 3, '0', NULL),
(1083, 'new', 'прихованохоботники', 3, '0', NULL),
(1084, 'new', 'малинно-суничний довгоносик', 3, '0', NULL),
(1085, 'new', 'муха бурякова мінувальна', 3, '0', NULL),
(1086, 'new', 'Бурякова мінуюча міль', 3, '0', NULL),
(1087, 'new', 'клопи (щитники, сліпняки)', 3, '0', NULL),
(1088, 'new', 'комплекс шкідників, у т. ч. трипси', 3, '0', NULL),
(1089, 'new', 'клопи види', 3, '0', NULL),
(1090, 'new', 'бурякові довгоносики', 3, '0', NULL),
(1091, 'new', 'звичайна бурякова блішка', 3, '0', NULL),
(1092, 'new', 'плямистості (сітчаста, темно-бура, смугаста)', 2, '0', NULL),
(1093, 'new', 'листові плямистості', 2, '0', NULL),
(1094, 'new', 'хвороби колосу і зерна', 2, '0', NULL),
(1095, 'new', 'Парша срібляста (Helminthosporium solani)', 2, '0', NULL),
(1096, 'new', 'Парша срібляста (Helminthosporium solani)', 2, '0', NULL),
(1097, 'new', 'Парша звичайна Ризоктоніоз (Rhizoctonia solani)', 2, '0', NULL),
(1098, 'new', 'моніліальна гниль', 2, '0', NULL),
(1099, 'new', 'моніліальний опік', 2, '0', NULL),
(1100, 'new', 'кокомікоз', 2, '0', NULL),
(1101, 'new', 'фузаріоз листя', 2, '0', NULL),
(1102, 'new', 'види іржастих хвороб', 2, '0', NULL),
(1103, 'new', 'побічна дія проти краснухи і чорної гнилі', 2, '0', NULL),
(1104, 'new', 'побічна дія проти антракнозу, борошнистої роси, кладоспоріозу', 2, '0', NULL),
(1105, 'new', 'пірікуляріоз', 2, '0', NULL),
(1106, 'new', 'склеротиніоз', 2, '0', NULL),
(1107, 'new', 'хвороби колосу', 2, '0', NULL),
(1108, 'new', 'моніліальна гниль плодів', 2, '0', NULL),
(1109, 'new', 'стемфіліум', 2, '0', NULL),
(1110, 'new', 'Комплекс наземних і ґрунтових шкідників сходів', 3, '0', NULL),
(1111, 'new', 'Комплекс наземних та ґрунтових шкідників сходів, в т.ч.: Злакові мухи, цикадки, попелиці, блішки, хлібна жужелиця, трипси', 3, '0', NULL),
(1112, 'new', 'Комплекс ґрунтових та наземних шкідників сходів', 3, '0', NULL),
(1113, 'new', 'личинки коваликів (дротяники)', 3, '0', NULL),
(1114, 'new', 'комплекс кореневих гнилей', 2, '0', NULL),
(1115, 'new', 'хрестоцвітні блішки', 3, '0', NULL),
(1116, 'new', 'Збудники пероноспорозу, чорної ніжки, альтернаріозу, фомозу', 2, '0', NULL),
(1117, 'new', 'Збудники несправжньої борошнистої роси, фомозу, фомопсису', 2, '0', NULL),
(1118, 'new', 'ґрунтові шкідники на початкових стадіях', 3, '0', NULL),
(1119, 'new', 'Фузаріозні та пітіозні кореневі та пристеблові гнилі', 2, '0', NULL),
(1120, 'new', 'плеснявіння насіння', 2, '0', NULL),
(1121, 'new', 'збудники летючої сажки', 2, '0', NULL),
(1122, 'new', 'септоріоз сходів', 2, '0', NULL),
(1123, 'new', 'комплекс хвороб насіння, сходів та вегетуючих рослин', 2, '0', NULL),
(1124, 'new', 'Чорна, або несправжня, сажка', 2, '0', NULL),
(1125, 'new', 'фітофтороз суниці', 2, '0', NULL),
(1126, 'new', 'фітофторозна гниль кореневої шийки', 2, '0', NULL),
(1127, 'new', 'грибний комарик', 3, '0', NULL),
(1128, 'new', 'хвоєгризучі шкідники', 3, '0', NULL),
(1129, 'new', 'Стебловий капустяний прихованохоботник', 3, '0', NULL),
(1130, 'new', 'стебловий комарик', 3, '0', NULL),
(1131, 'new', 'сіра плямистість', 2, '0', NULL),
(1132, 'new', 'бурі плодові кліщі', 3, '0', NULL),
(1133, 'new', 'галові кліщі', 3, '0', NULL),
(1134, 'new', 'Десикація культури', 0, '0', NULL),
(1135, 'new', ' Знищення бур’янів', 1, '0', NULL),
(1136, 'new', 'Інгібітор росту та захист від комплексу хвороб', 0, '0', NULL),
(1137, 'new', 'циліндроспоріоз', 2, '0', NULL),
(1138, 'new', 'фузаріози', 2, '0', NULL),
(1139, 'new', 'побуріння стебел', 2, '0', NULL),
(1140, 'new', 'садовий павутинний кліщ', 3, '0', NULL),
(1141, 'new', 'інші кліщі', 3, '0', NULL),
(1142, 'new', 'Листова форма філоксери', 3, '0', NULL),
(1143, 'new', 'Супутня дія — грушевий галовий кліщ, медяниці, щитівки', 3, '0', NULL),
(1144, 'new', 'виноградний зудень', 3, '0', NULL),
(1145, 'new', 'суничний кліщ', 3, '0', NULL),
(1146, 'new', 'хлібні мухи', 3, '0', NULL),
(1147, 'new', 'личинки підгризаючих та листогризучих совок', 2, '0', NULL),
(1148, 'new', 'Для уповільнення росту та підвищення зимостійкості', 0, '0', NULL),
(1149, 'new', 'Для запобігання виляганню посівів та зламуванню колоса', 0, '0', NULL),
(1150, 'new', 'яблунева медяниця', 3, '0', NULL),
(1151, 'new', 'попелиці (в т. ч. кров’яна)', 3, '0', NULL),
(1152, 'new', 'щитівки (в т. ч. каліфорнійська)', 3, '0', NULL),
(1153, 'new', 'філоксера', 3, '0', NULL),
(1154, 'new', 'борошнистий червець', 3, '0', NULL),
(1155, 'new', 'білокрилки', 3, '0', NULL),
(1156, 'new', 'Для підвищення врожаю та поліпшення його якості', 0, '0', NULL),
(1157, 'new', 'зменшення фітотоксичності у культури після використання пестицидів та погодних аномалій', 0, '0', NULL),
(1158, 'new', 'подолання cтресових явищ у рослин після тимчасових знижень температури повітря', 0, '0', NULL),
(1159, 'new', 'Запобігання розтріскуванню стручків', 0, '0', NULL),
(1160, 'new', 'Запобігання розтріскуванню стручків', 0, '0', NULL),
(1161, 'new', 'сприяє акумуляції рослиною азоту в доступній формі завдяки підвищенню симбіотичного потенціалу рослини з бульбочковими бактеріями', 0, '0', NULL),
(1162, 'new', 'бурякова коренева попелиця', 3, '0', NULL),
(1163, 'new', 'личинки совок', 3, '0', NULL),
(1164, 'new', 'види вівсюга (Avena spp.)', 2, '0', NULL),
(1165, 'new', 'види лисохвосту (Alopecurus spp.)', 2, '0', NULL),
(1166, 'new', 'види очеретянки (Phalaris spp.)', 2, '0', NULL),
(1167, 'new', 'види пажитниці (Lolium spp.)', 1, '0', NULL),
(1168, 'new', 'Для запобігання поляганню посівів', 0, '0', NULL),
(1169, 'new', 'Високочутливі бур’яни (Амброзія полинолиста, Бородавник звичайний/ Празелень звичайний, Вероніка, Воловик лікарський, Волошка синя, Галінсога дрібноквіткова, Гірчак звичайний, Гірчиця польова, Глуха кропива, Грицики звичайні, Дурман звичайний, Жабрій', 1, '0', NULL),
(1170, 'new', 'Помірно чутливі бур’яни (Абутилон, Теофаста, Петрушка собача, Ромашка звичайна, Ромашка собача польова, Ріпак падалиця, Соняшник падалиця та інші) ', 1, '0', NULL),
(1171, 'new', 'інші види шкідливих комах', 3, '0', NULL),
(1172, 'new', 'Комплекс шкідників, в тому числі саранові, довгоносики, щитоноски, попелиці', 3, '0', NULL),
(1173, 'new', 'Однорічні та багаторічні дводольні у т.ч. стійкі до 2,4-Д', 1, '0', NULL),
(1174, 'new', 'Інгібування росту рослин та підвищення стійкості до екстремальних погодних умов', 0, '0', NULL),
(1175, 'new', 'прикореневі гнилі', 2, '0', NULL),
(1176, 'new', 'борошниста роса (росторегулююча дія)', 2, '0', NULL),
(1177, 'new', 'інгібування росту стебла', 0, '0', NULL),
(1178, 'new', 'покращення гілкування', 0, '0', NULL),
(1179, 'new', 'Листкові плямистості:борошниста роса, іржасті збудники піренофорозу, септоріозу, фузаріозу', 2, '0', NULL),
(1180, 'new', 'альтернаріоз колосу', 2, '0', NULL),
(1181, 'new', 'хлібні жуки', 3, '0', NULL),
(1182, 'new', 'Однорічні та багаторічні дводольні бур’яни, у т.ч. стійкі до препаратів на основі тільки 2,4-Д та МЦПА', 1, '0', NULL),
(1183, 'new', 'Бородавник звичайний', 1, '0', NULL),
(1184, 'new', 'Празелень звичайний', 1, '0', NULL),
(1185, 'new', 'Вероніка', 0, '0', NULL),
(1186, 'new', 'Воловик лікарський', 1, '0', NULL),
(1187, 'new', 'Гірчак звичайний', 1, '0', NULL),
(1188, 'new', 'Глуха кропива', 1, '0', NULL),
(1189, 'new', 'Дурман звичайний', 1, '0', NULL),
(1190, 'new', 'Жабрій звичайний', 1, '0', NULL),
(1191, 'new', 'Жовтозілля звичайне', 1, '0', NULL),
(1192, 'new', 'Королиця звичайна', 1, '0', NULL),
(1193, 'new', 'Кропива жалка', 1, '0', NULL),
(1194, 'new', 'Курай руський', 1, '0', NULL),
(1195, 'new', 'Курячі очка польові', 1, '0', NULL),
(1196, 'new', 'Лутига розлога', 1, '0', NULL),
(1197, 'new', ' Мак дикий', 1, '0', NULL),
(1198, 'new', 'Незабудка польова', 1, '0', NULL),
(1199, 'new', 'Паслін чорний', 1, '0', NULL),
(1200, 'new', 'Переліска однорічна', 1, '0', NULL),
(1201, 'new', 'Рутка лікарська', 1, '0', NULL),
(1202, 'new', 'Талабан польовий', 1, '0', NULL),
(1203, 'new', 'Шпергель звичайний', 1, '0', NULL),
(1204, 'new', ' Фіалка польова', 1, '0', NULL),
(1205, 'new', 'Щириця', 1, '0', NULL),
(1206, 'new', 'Високочутливі бур’яни', 1, '0', NULL),
(1207, 'new', 'Помірно чутливі бур’яни ', 1, '0', NULL),
(1208, 'new', 'Абутилон', 0, '0', NULL),
(1209, 'new', 'Теофаста', 0, '0', NULL),
(1210, 'new', 'Однорічні злакові й деякі дводольні бур’яни', 1, '0', NULL),
(1211, 'new', 'Однорічні та багаторічні дводольні бур’яни, у т. ч. викорінювальна дія проти осотів', 1, '0', NULL),
(1212, 'new', 'IMI та ALS–стійка падалиця соняшнику', 0, '0', NULL),
(1213, 'new', 'Однорічні дводольні, в т.ч. стійкі до 2,4-Д, та багаторічні коренепаросткові бур’яни', 1, '0', NULL),
(1214, 'new', 'Однорічні та багаторічні дводольні бур’яни', 1, '0', NULL),
(1215, 'new', 'Обприскування вегетуючих бур’янів у фазі розетки (висота осотів — 15–20 см) від фази 2–х листків культури', 1, '0', NULL),
(1216, 'new', 'Обприскування вегетуючих бур’янів у фазі розетки (висота осотів — 15–20 см) від фази 2–х листків культури', 1, '0', NULL),
(1217, 'new', 'Однорічні та багаторічні злакові (гумай, пирій) і найпоширеніші однорічні дводольні бур’яни', 1, '0', NULL),
(1218, 'new', 'комплекс совок', 3, '0', NULL),
(1219, 'new', 'краснуха', 2, '0', NULL),
(1220, 'new', 'Однорічні та деякі багаторічні дводольні бур’яни, в т. ч. стійкі до 2,4–Д і МЦПА', 1, '0', NULL),
(1221, 'new', 'курчавість', 2, '0', NULL),
(1222, 'new', 'Кутаста плямистість', 2, '0', NULL),
(1223, 'new', 'більшість найбільш поширених дводольних бур’янів', 1, '0', NULL),
(1224, 'new', 'гусені яблуневої плодожерки', 3, '0', NULL),
(1225, 'new', 'розанна листокрутка', 3, '0', NULL),
(1226, 'new', 'сітчаста листокрутка', 3, '0', NULL),
(1227, 'new', 'Оранжерейна, або персикова, попелиця', 3, '0', NULL),
(1228, 'new', 'персикова попелиця', 3, '0', NULL),
(1229, 'new', 'плодові гнилі', 2, '0', NULL),
(1230, 'new', 'Стримування росту листя та підвищення стійкості до екстремальних погодних умов (інгібітор росту)', 0, '0', NULL),
(1231, 'new', 'слизистий бактеріоз', 2, '0', NULL),
(1232, 'new', 'судинний бактеріоз', 2, '0', NULL),
(1233, 'new', 'Чорна бактеріальна плямистість або бородавчастість', 2, '0', NULL),
(1234, 'new', 'Яблунева парша', 2, '0', NULL),
(1235, 'new', 'бура гниль кісточкових', 2, '0', NULL),
(1236, 'new', 'дрібна плямистість листя', 2, '0', NULL),
(1237, 'new', 'Бактеріальний опік дерев', 2, '0', NULL),
(1238, 'new', 'бура гниль зерняткових', 2, '0', NULL),
(1239, 'new', 'Бактеріальний рак кісточкових', 2, '0', NULL),
(1240, 'new', 'діркуватість листя (філостиктоз)', 2, '0', NULL),
(1241, 'new', 'стовпчаста іржа чорної смородини', 2, '0', NULL),
(1242, 'new', 'опадання листя', 2, '0', NULL),
(1243, 'new', 'Багаторічні широко-листяні бур`яни та інші багаторічні злакові ', 1, '0', NULL),
(1244, 'new', 'Десикація культури та контрольоднорічних бур`янів', 1, '0', NULL),
(1245, 'new', 'Однорічні злакові, підсушування стебел та листя культури', 1, '0', NULL),
(1246, 'new', 'Однорічні дводольні, в т.ч. щириця та деякі злакові бур’яни', 1, '0', NULL),
(1247, 'new', 'Багаторічні злакові (гумай, пирій) бур’яни', 1, '0', NULL),
(1248, 'new', 'Злісні багаторічні (свинорий, гумай, берізка, осот)', 1, '0', NULL),
(1249, 'new', 'Злісні багаторічні (свинорий, гумай, берізка, осот)', 1, '0', NULL),
(1250, 'new', 'Десикація культури та знищення багаторічних бурянів', 1, '0', NULL),
(1251, 'new', 'Однорічні злакові та дводольні бур’яни у т.ч. стійкі до 2,4-Д і МЦПА', 1, '0', NULL),
(1252, 'new', 'Багаторічні злакові та дводольні бур’яни у т.ч. стійкі до 2,4-Д і МЦПА', 1, '0', NULL),
(1253, 'new', 'Одно- та багаторічні злакови та дводольні бур’яни у т.ч. стійкі до 2,4-Д і МЦПА', 1, '0', NULL),
(1254, 'new', 'Деякі багаторічні бур’яни', 1, '0', NULL),
(1255, 'new', 'Однорічні та багаторічні дводольні бур’яни, в тому числі стійкі до 2,4-Д', 1, '0', NULL),
(1256, 'new', 'Стадні та нестадні види саранових', 3, '0', NULL),
(1257, 'new', 'Однорічні злакові та деякі двосім’ядольні', 1, '0', NULL),
(1258, 'new', 'Однорічні та багаторічні злакові та двосім''ядольні бур’яни', 1, '0', NULL),
(1259, 'new', 'Однорічні та багаторічні злакові та двосім''ядольні бур’яни', 1, '0', NULL),
(1260, 'new', 'Однорічні та багаторічні злакові та двосім’ядольні бур’яни', 1, '0', NULL),
(1261, 'new', 'Однорічні , багаторічні злакові та двосім’ядольні бур’яни', 1, '0', NULL),
(1262, 'new', 'Однорічні злакові та двосім’ядольні бур’яни', 1, '0', NULL),
(1263, 'new', 'шкідлива черепашка', 3, '0', NULL),
(1264, 'new', 'муха і міль, минуючі', 3, '0', NULL),
(1265, 'new', 'Комплекс шкідливих об’єктів (п’явиці, хлібна жужелиця, клоп шкідлива черепашка, злакова попелиця, злакові мухи та ін.)', 3, '0', NULL),
(1266, 'new', 'ріпаковий прихованохоботник', 3, '0', NULL),
(1267, 'new', 'картопляна муха', 3, '0', NULL),
(1268, 'new', 'кукурудзяний жук (діабротика)', 3, '0', NULL),
(1269, 'new', 'саранові та інші сисні і листогризучі шкідники', 3, '0', NULL),
(1270, 'new', 'інші сисні і листогризучі шкідники', 3, '0', NULL),
(1271, 'new', 'сітчаста та темнобура плямистості', 2, '0', NULL),
(1272, 'new', 'запобігання виляганню рослин', 0, '0', NULL),
(1273, 'new', 'тверда головня', 2, '0', NULL),
(1274, 'new', 'летюча головня', 2, '0', NULL),
(1275, 'new', ' снігова цвіль', 2, '0', NULL),
(1276, 'new', 'септоріаз проростків', 2, '0', NULL),
(1277, 'new', 'пилова сажка', 2, '0', NULL),
(1278, 'new', 'фузаріозні і гельмінтоспоріозні кореневі гнилі', 2, '0', NULL);
INSERT INTO `pd_Vermin` (`id`, `guid`, `name`, `groupId`, `photo`, `ord`) VALUES
(1279, 'new', 'Десикація культурних рослин', 0, '0', NULL),
(1280, 'new', 'підсушування насіння', 0, '0', NULL),
(1281, 'new', 'часткове знищення бур’янів', 1, '0', NULL),
(1282, 'new', 'сірий і південний буряковий довгоносики', 2, '0', NULL),
(1283, 'new', 'медляки', 3, '0', NULL),
(1284, 'new', 'фузаріозна та гельмінтоспоріозна кореневі гнилі', 3, '0', NULL),
(1285, 'new', 'Комплекс шкідливих комах (колорадський жук, дротяники, несправжньодротяники, гусениці совки, личинки капустянки та хрущів, попелиці та трипси)', 3, '0', NULL),
(1286, 'new', 'Комплекс хвороб (звичайна парша, ризоктоніоз (чорна парша)', 2, '0', NULL),
(1287, 'new', 'Комплекс шкідливих комах, комплекс хвороб; фузаріозна сажка, кореневі гнилі та ін.', 0, '0', NULL),
(1288, 'new', 'ріпакова блішка', 3, '0', NULL),
(1289, 'new', 'ріпаковий листоїд', 3, '0', NULL),
(1290, 'new', 'однорічні дводольні та деякі багаторічні дводольні, в т.ч. стій- ки до 2,4-Д бур’яни', 1, '0', NULL),
(1291, 'new', 'однорічні дводольні, в т.ч. щириця', 1, '0', NULL),
(1292, 'new', 'деякі злакові бур’яни', 1, '0', NULL),
(1293, 'new', 'однодольні і дводольні бур’яни', 1, '0', NULL),
(1294, 'new', ' іржа (види)', 2, '0', NULL),
(1295, 'new', 'Передпосівна обробка насіння', 0, '0', NULL),
(1296, 'new', 'Позакореневе підживлення ', 0, '0', NULL),
(1297, 'new', 'Широколисті бур’яни', 1, '0', NULL),
(1298, 'new', 'Однорічні широколисті та деякі злакові бур’яни', 1, '0', NULL),
(1299, 'new', 'однорічні широколисті бур’яни', 1, '0', NULL),
(1300, 'new', 'однорічні і багаторічні широколисті бур’яни', 1, '0', NULL),
(1301, 'new', 'Однорічні широколисті та злакові бур''яни', 1, '0', NULL),
(1302, 'new', 'однорічні і багаторічні дводольні і злакові бур’яни', 1, '0', NULL),
(1303, 'new', 'рип’яшниця', 3, '0', NULL),
(1304, 'new', 'ріпакова галиця', 3, '0', NULL),
(1305, 'new', 'літаючі комахи', 3, '0', NULL),
(1306, 'new', 'повзаючі комахи', 3, '0', NULL),
(1307, 'new', 'повзаючі комахи', 3, '0', NULL),
(1308, 'new', 'тифульоз', 2, '0', NULL),
(1309, 'new', 'нематоди', 3, '0', NULL),
(1310, 'new', 'Фітофторозна гниль кореня і стовбура', 2, '0', NULL),
(1311, 'new', 'кучерявість листків персика', 2, '0', NULL),
(1312, 'new', 'Потужний фунгіцид та росторегулятор (інгібітор росту надземної частини рослин)', 0, '0', NULL),
(1313, 'new', 'Оптимізація та прискорення дозрівання і забарвлення плодів', 0, '0', NULL),
(1314, 'new', 'Регулювання утворення зав’язі, стимуляція закладання плодових бруньок', 0, '0', NULL),
(1315, 'new', 'Прискорення і вирівнювання дозрівання', 0, '0', NULL),
(1316, 'new', 'Запобігання виляганню посівів', 2, '0', NULL),
(1317, 'new', 'однорічні та багаторічні види бур’янів (злакові та дводольні)', 1, '0', NULL),
(1318, 'new', 'хвороби зернових колосових культур', 2, '0', NULL),
(1319, 'new', 'переноспороз', 2, '0', NULL),
(1320, 'new', 'Однорічні двосім’ядольні бур’яни', 1, '0', NULL),
(1321, 'new', 'Просо волосовидне', 1, '0', NULL),
(1322, 'new', 'гумай', 1, '0', NULL),
(1323, 'new', 'пирій', 1, '0', NULL),
(1324, 'new', 'Покращення контролю септоріозу, церкоспорельзу, ринхоспоріозу, гельмінтоспоріозів, іржі в разі використання в бакових сумішах з іншими фунгіцидами', 2, '0', NULL),
(1325, 'new', 'бура плямистість (філостиктоз)', 2, '0', NULL),
(1326, 'new', 'для запобігання виляганню посівів та підвищення врожайності', 0, '0', NULL),
(1327, 'new', 'Багаторічні кореневищні та коренепаросткові', 1, '0', NULL),
(1328, 'new', 'Стеблові хвороби', 2, '0', NULL),
(1329, 'new', 'шкідники', 3, '0', NULL),
(1330, 'new', 'хвороби', 2, '0', NULL),
(1331, 'new', 'Посіви, сильно забур’янені однорічними та багаторічними (в т.ч. перерослими) бур’янами', 1, '0', NULL),
(1332, 'new', 'Чутливі та середньочутливі види двосім’ядольних бур’янів', 1, '0', NULL),
(1333, 'new', 'осокові та болотні широколистяні бур’яни', 1, '0', NULL),
(1334, 'new', 'інші лускокрилі шкідники', 3, '0', NULL),
(1335, 'new', 'Кукурудзяний стебловий метелик', 3, '0', NULL),
(1336, 'new', 'Комплекс вогнівок', 3, '0', NULL),
(1337, 'new', 'томатна совка', 3, '0', NULL),
(1338, 'new', 'підвищення ефективності пестицидів', 0, '0', NULL),
(1339, 'new', 'види Amaranthus', 3, '0', NULL),
(1340, 'new', 'бур’яни, що зійшли у випадку нульової технології', 1, '0', NULL),
(1341, 'new', 'Амброзія', 2, '0', NULL),
(1342, 'new', 'Cirsium arvense', 3, '0', NULL),
(1343, 'new', 'отруйна та небажана рослинність', 1, '0', NULL),
(1344, 'new', 'Однорічні та деякі багаторічні дводольні, в т.ч. стійкі до 2,4-Д та МЦПА ', 1, '0', NULL),
(1345, 'new', 'великий ріпаковий прихованохоботник', 3, '0', NULL),
(1346, 'new', 'гельмінтоспоріозна, фузаріозна і пітіозна кореневі гнилі', 2, '0', NULL),
(1347, 'new', 'тверда і летюча сажка', 2, '0', NULL),
(1348, 'new', 'пліснявіння сходів', 0, '0', NULL),
(1349, 'new', 'комплекс збудників кореневих і стеблових гнилей', 3, '0', NULL),
(1350, 'new', 'Комплекс насіннєвих та грунтових збудників хвороб: сажки, пліснявіння насіння, кореневі гнилі, септоріоз, листова іржа, борошниста роса. Комплекс грунтових шкідників та шкідників посівів: дротяники, совка озима, турун хлібний, злакові мухи, блішки, ц', 0, '0', NULL),
(1351, 'new', 'Комплекс насіннєвих та грунтових збудників хвороб: сажки, пліснявіння насіння, кореневі гнилі, септоріоз, листова іржа, борошниста роса, плямистість, гельмінтоспоріоз. Комплекс грунтових шкідників та шкідників посівів: дротяники, совка озима, турун х', 2, '0', NULL),
(1352, 'new', 'Біла і сіра гнилі', 2, '0', NULL),
(1353, 'new', 'Обприскування вегетуючих бур’янів', 1, '0', NULL),
(1354, 'new', 'Обприскування вегетуючих бур’янів восени, після збирання попередника або навесні, за 2 тижні до висівання', 1, '0', NULL),
(1355, 'new', 'Однорічні та багаторічні рослини', 1, '0', NULL),
(1356, 'new', 'Однорічні та багаторічні двосім’ядольні, у тому числі стійкі до препаратів на основі тільки 2, 4-Д та 2М-4Х кислот', 1, '0', NULL),
(1357, 'new', 'Однорічні злакові та двосім’ядольні, а також проростки багаторічних бур’янів з насіння', 1, '0', NULL),
(1358, 'new', 'Однорічні та деякі багаторічні двосім’ядольні бур’яни', 1, '0', NULL),
(1359, 'new', 'Однорічні двосім’ядольні та багаторічні, в т. ч. коренепаросткові бур’яни', 1, '0', NULL),
(1360, 'new', 'Однорічні двосім’ядольні, в т. ч. стійкі до 2, 4-Д та багаторічні коренепаросткові бур’яни', 1, '0', NULL),
(1361, 'new', 'Однорічні та деякі багаторічні двосім’ядольні, у т. ч. стійкі до 2, 4-Д бур’яни', 1, '0', NULL),
(1362, 'new', 'Однорічні двосім’ядольні та злакові', 1, '0', NULL),
(1363, 'new', 'Злакові та однорічні двосім’ядольні бур’яни', 1, '0', NULL),
(1364, 'new', 'п’явиці, злакові попелиці, трипси, клоп шкідлива черепашка', 3, '0', NULL),
(1365, 'new', 'п’явиці, попелиці, трипси', 3, '0', NULL),
(1366, 'new', 'попелиця листова, блішки', 3, '0', NULL),
(1367, 'new', 'зернівка горохова, вогнівки, попелиці', 3, '0', NULL),
(1368, 'new', 'павутинні кліщі, яблуневий плодовий пильщик', 3, '0', NULL),
(1369, 'new', 'кліщі, гронова листовійка', 3, '0', NULL),
(1370, 'new', 'кліщі попелиці', 3, '0', NULL),
(1371, 'new', 'борошниста роса плямистості септоріоз стеблова бура іржа кореневі гнилі фузаріоз', 2, '0', NULL),
(1372, 'new', 'борошниста роса церкоспороз', 2, '0', NULL),
(1373, 'new', 'борошниста роса парша', 2, '0', NULL),
(1374, 'new', 'Підсушування культурних рослин та знищення бур´янів', 1, '0', NULL),
(1375, 'new', 'Підсушування культурних рослин та знищення бур’янів', 1, '0', NULL),
(1376, 'new', 'Однорічні дводольні (у фазі 2-6 листків)', 1, '0', NULL),
(1377, 'new', 'Багаторічні дводольні (у фазі розетки)', 1, '0', NULL),
(1378, 'new', 'Підмаренник чіпкий (до 4-х кілець)', 1, '0', NULL),
(1379, 'new', 'Посіви, сильно забур''янені однорічними та багаторічними бур’янами', 1, '0', NULL),
(1380, 'new', 'Чутливі одно- та багаторічні бур’яни', 1, '0', NULL),
(1381, 'new', 'Метлюг звичайний (пригнічення)', 1, '0', NULL),
(1382, 'new', 'Проблемні бур’яни: щириця (види), гірчаки, паслін чорний, підмаренник чіпкий та капустяні бур’яни', 1, '0', NULL),
(1384, 'new', 'Чутливі багаторічні дводольні бур’яни (в т.ч. осоти, підмаренник чіпкий)', 1, '0', NULL),
(1385, 'new', 'Чутливі однорічні дводольні бур''яни', 1, '0', NULL),
(1386, 'new', 'Гербіциди та інсектициди виробництва FMC на польових та спеціальних культурах', 0, '0', NULL),
(1387, 'new', 'пітієва коренева гниль', 2, '0', NULL),
(1388, 'new', 'листоїдна гусінь', 3, '0', NULL),
(1389, 'new', 'луговий метелик', 3, '0', NULL),
(1390, 'new', 'лозова листокрутка', 3, '0', NULL),
(1391, 'new', 'хлібний пильщик', 3, '0', NULL),
(1392, 'new', 'ріпаковий комарик', 3, '0', NULL),
(1393, 'new', 'яблунева плодожерка (личинки 1 та 2 поколінь)', 3, '0', NULL),
(1394, 'new', 'Десикація для застосування наземним транспортом та авіаційним методом', 0, '0', NULL),
(1395, 'new', 'Однорічні злакові та однорічні дводольні бур’яни', 1, '0', NULL),
(1396, 'new', 'Двудольні бур’яни в т.ч. стійкі до 2,4 Д', 1, '0', NULL),
(1397, 'new', 'септоріоз паростків', 2, '0', NULL),
(1398, 'new', 'Фузаріозна плямистість листків', 2, '0', NULL),
(1399, 'new', 'покрита сажка', 2, '0', NULL),
(1401, 'new', 'фузаріозні кореневі та прикореневі гнилі', 2, '0', NULL),
(1402, 'new', 'крапчастість', 2, '0', NULL),
(1403, 'new', 'фузаріоз (коренева форма)', 2, '0', NULL),
(1404, 'new', 'личинки чорнишів', 3, '0', NULL),
(1405, 'new', 'сажка волоті', 2, '0', NULL),
(1406, 'new', 'Культури та бур''яни', 1, '0', NULL),
(1407, 'new', 'Злакові та дводольні бур’яни', 1, '0', NULL),
(1408, 'new', ' Однорічні, багаторічні злакові та дводольні бур’яни', 1, '0', NULL),
(1409, 'new', 'Однорічні дводольні та деякі інші бур’яни, в т.ч. стійкі до десмедифаму та фенмедифаму', 1, '0', NULL),
(1410, 'new', 'Однорічні та багаторічні дводольні, в т.ч. стійкі до 2,4-Д, бур‘яни, падалиця соняшнику, стійкого до трибенурон-метилу', 1, '0', NULL),
(1411, 'new', 'Однорічні та багаторічні злакові й дводольні бур’яни, в т.ч. стійкі до 2,4-Д, бур’яни', 1, '0', NULL),
(1412, 'new', 'Однорічні, багаторічні злакові та деякі однорічні дводольні бур’яни', 1, '0', NULL),
(1413, 'new', 'Десикація культури та знищення бур’янів', 0, '0', NULL),
(1415, 'new', 'Однорічні дводольні, в т.ч. стійкі до 2,4-Д, та багаторічні коренепаросткові бур’яни, падалиця соняшнику стійкого до трибенурон-метилу', 1, '0', NULL),
(1416, 'new', 'Однорічні дводольні в.т.ч. стійкі до 2.4Д і МЦПА, і деякі багаторічні дводольні, включаючи осоти, бур''яни', 1, '0', NULL),
(1417, 'new', 'бульбоочерет та інші болотні бур’яни', 1, '0', NULL),
(1418, 'new', 'Для припинення активного наростання наземної маси, накопичення пластичних речовин та прискорення росту кореневої системи восени', 2, '0', NULL),
(1419, 'new', 'капустяний комарик', 0, '0', NULL),
(1420, 'new', 'клопи-сліпняки', 0, '0', NULL),
(1421, 'new', 'сірий бруньковий довгоносик (брунькоїд)', 0, '0', NULL),
(1422, 'new', 'Полістигмоз', 0, '0', NULL),
(1423, 'new', 'Ріпний білан', 0, '0', NULL),
(1424, 'new', 'Кліщі (в т.ч. яйця)', 3, '0', NULL),
(1425, 'new', 'інші види щитівок', 0, '0', NULL),
(1426, 'new', 'Підсушування культури та часткове знищення бур’янів ', 0, '0', NULL),
(1427, 'new', 'Підвищення дружності та прискорення дозрівання плодів ', 0, '0', NULL),
(1428, 'new', 'Лінійна, або стеблова іржа', 2, '0', NULL),
(1429, 'new', 'Чина бульбиста (Lathyrus tuberosum L.)', 1, '0', '0'),
(1430, 'new', 'Перстач гусячий (Potentilla anserina L.)', 1, '0', '0'),
(1431, 'new', 'Резеда жовта (Reseda lutea L.)', 1, '0', '0'),
(1432, 'new', 'Повитиця польова (Cuscuta campestris Junk.)', 1, '0', '0'),
(1433, 'new', 'Повитиця льонова (Cuscuta epilinum Weiche.)', 1, '0', '0'),
(1434, 'new', 'Вовчок соняшниковий (Orobanche cumana Wallr.)', 1, '0', '0'),
(1435, 'new', 'Дзвінець великий (Rhinanthus major L)', 1, '0', '0'),
(1436, 'new', 'Бульбокомиш приморський (Bolboschoenus maritimus L.)', 1, '0', '0'),
(1437, 'new', 'Щавель кінський (Rumex confertus Willd. L.)', 1, '0', '0'),
(1438, 'new', 'Чистотіл звичайний (Chelidonium majus L.)', 1, '0', '0'),
(1439, 'new', 'Хондрила ситниковидна (Chondrilla juncea L.)', 1, '0', '0'),
(1440, 'new', 'Миколайчики польові (Eryngium campestre L. )', 1, '0', '0'),
(1441, 'new', 'Гравілат міський (Geum urbanum L.)', 1, '0', '0'),
(1442, 'new', 'Хрінниця крупковидна (Lepidium (cardaria) draba L.)', 1, '0', '0'),
(1443, 'new', 'Хвилівник звичайний (Aristolochia clematitis L.)', 1, '0', '0'),
(1444, 'new', 'Хаменерій вузьколистий (Chamaenerium angustifolium Scop.)', 1, '0', '0'),
(1445, 'new', 'Молочай лозяний (Euphorbia virgata W.K.)', 1, '0', '0'),
(1446, 'new', 'Льонок звичайний (Linaria vulgaris Milk.)', 1, '0', '0'),
(1447, 'new', 'Чистець болотний (Stachys palustris L.)', 1, '0', '0'),
(1448, 'new', 'Сить бульбоносна (Cyperus rotundus L.)', 1, '0', '0'),
(1449, 'new', 'Ластовень гострий (Cynanchum acutum L.)', 1, '0', '0'),
(1450, 'new', 'Кропива дводомна (Urtica dioica L.)', 1, '0', '0'),
(1451, 'new', 'Квасениця прямостояча (Xanthoxalis fontana)', 1, '0', '0'),
(1452, 'new', 'Чорнокорінь лікарський (Cynoglossum officinale L.)', 1, '0', '0'),
(1453, 'new', 'Татарник звичайний (Onopordon acanthium L. )', 1, '0', '0'),
(1454, 'new', 'Суріпиця звичайна (Barbarea vulgaris R.Br.)', 1, '0', '0'),
(1455, 'new', 'Скереда покрівельна (Crepis tectorum L.)', 1, '0', '0'),
(1456, 'new', 'Свербига східна (Bunias orientalis L. )', 1, '0', '0'),
(1457, 'new', 'Петрушка собача звичайна (Aethusa cynapium)', 1, '0', '0'),
(1458, 'new', 'Морква дика (Daucus carota L. )', 1, '0', '0'),
(1459, 'new', 'Липучка їжакова (Lappula squarrosa (Retz.) Dumort)', 1, '0', '0'),
(1460, 'new', 'Куколиця біла (Melandrium album Mill.)', 1, '0', '0'),
(1461, 'new', 'Кропива глуха пурпурова (Lamium purpureum L.)', 1, '0', '0'),
(1462, 'new', 'Енотера дворічна (Oenothera biennis L.)', 1, '0', '0'),
(1463, 'new', 'Гикавка сіра (Berteroa incana L.)', 1, '0', '0'),
(1464, 'new', 'Вероніка плющолиста (Veronica hederifolia L. )', 1, '0', '0'),
(1465, 'new', 'Будяк акантовидний (Carduus acanthoides L.)', 1, '0', '0'),
(1466, 'new', 'Болиголов плямистий (Conium maculatum L.)', 1, '0', '0'),
(1467, 'new', 'Блекота чорна (Hyoscyamus niger L)', 1, '0', '0'),
(1468, 'new', 'Чистець однорічний (Stachys annua L.)', 1, '0', '0'),
(1469, 'new', 'Хрінниця смердюча (Lepidium ruderale L.)', 1, '0', '0'),
(1470, 'new', 'Хориспора ніжна (Chorispora tenella (Pall.) DC.)', 1, '0', '0'),
(1471, 'new', 'Фіалка триколірна (Viola tricolor L.)', 1, '0', '0'),
(1472, 'new', 'Фіалка польова (Viola arvensis Murr.)', 1, '0', '0'),
(1473, 'new', 'Сухоребрик льозеліїв (Sisymbrium Loeselii L.)', 1, '0', '0'),
(1474, 'new', 'Мак дикий (Papaver rhoeas L.)', 1, '0', '0'),
(1475, 'new', 'Грабельки звичайні (Erodium cicutarium)', 1, '0', '0'),
(1476, 'new', 'Латук дикий компасний (Lactuca serriola L.)', 1, '0', '0'),
(1477, 'new', 'Кривоцвіт польовий (Lycopsis arvensis L.)', 1, '0', '0'),
(1478, 'new', 'Злинка канадська (Erigeron canadensis L.)', 1, '0', '0'),
(1479, 'new', 'Глуха кропива стеблеобгортаюча (Lamium amplexicaule L.)', 1, '0', '0'),
(1480, 'new', 'Чіплянка питицева (Tragus racemosus L.)', 1, '0', '0'),
(1481, 'new', 'Червець однорічний (Scleranthus annuus L.)', 1, '0', '0'),
(1482, 'new', 'Наземка польова (Polycnemum arvense A.Br. )', 1, '0', '0'),
(1483, 'new', 'Редька дика (Raphanus raphanistrum L.)', 1, '0', '0'),
(1484, 'new', 'Пажитниця льонова (Lolium remotum Schrank)', 1, '0', '0'),
(1485, 'new', 'Кукіль звичайний (Agrostemma githago L. )', 1, '0', '0'),
(1486, 'new', 'Гібіск трійчастий (Hibiscus trionum L.)', 1, '0', '0'),
(1487, 'new', 'Горошок волохатий (Vicia villosa Routh. )', 1, '0', '0'),
(1488, 'new', 'Біфора промениста (Bifora radians Bierb.)', 1, '0', '0'),
(1489, 'new', 'Щириця жминдовидна (Amaranthus Blifoides S. Wats.)', 1, '0', '0'),
(1490, 'new', 'Щириця біла (Amaranthus albus L. )', 1, '0', '0'),
(1491, 'new', 'Чорнощир звичайний (Cyclachaena xanthifolia Fresen.)', 1, '0', '0'),
(1492, 'new', 'Череда трироздільна (Bidens tripartita L.)', 1, '0', '0'),
(1493, 'new', 'Соняшник смітний (Helianthus lenticularis Dougl.)', 1, '0', '0'),
(1494, 'new', 'Ситник жаб’ячий (Juncus bufonius L.)', 1, '0', '0'),
(1495, 'new', 'Просо волосовидне (Panicum capillare L.)', 1, '0', '0'),
(1496, 'new', 'Паслін чорний (Solanum nigrum L.)', 1, '0', '0'),
(1497, 'new', 'Пальчатка кровоспиняюча (Digitaria ischaemum Schreb.)', 1, '0', '0'),
(1498, 'new', 'Очка курячі польові (Anagallis arvensis L.)', 1, '0', '0'),
(1499, 'new', 'Остудник голий (Herniaria glabra L.)', 1, '0', '0'),
(1500, 'new', 'Нетреба звичайна (Xanthium strumarium L.)', 1, '0', '0'),
(1501, 'new', 'Кропива жалка (Urtica urens L.)', 1, '0', '0'),
(1502, 'new', 'Коноплі дикі (Cannabis ruderalis Janisch.)', 1, '0', '0'),
(1503, 'new', 'Комеліна звичайна (Commelina communis L.)', 1, '0', '0'),
(1504, 'new', 'Капуста польова (синкольза) (Brassica campestris L.)', 1, '0', '0'),
(1505, 'new', 'Залізниця гірська (Sideritis montana L.)', 1, '0', '0'),
(1506, 'new', 'Жабрій ладанний (Galeopsis ladanum L.)', 1, '0', '0'),
(1507, 'new', 'Жабрій звичайний (Galeopsis tetrahit L. )', 1, '0', '0'),
(1508, 'new', 'Дурман звичайний (Datura stramonium L.)', 1, '0', '0'),
(1509, 'new', 'Геліотроп європейський (Heliotropium europaeum L.)', 1, '0', '0'),
(1510, 'new', 'Гостриця лежача (Asperugo procumbens L.)', 1, '0', '0'),
(1511, 'new', 'Цибуля Вальдштейна (Allium Waldsteinii L.).', 1, '0', '0'),
(1512, 'new', 'Подорожник великий (Plantago major L.).', 1, '0', '0'),
(1513, 'new', 'Жовтець повзучий (Ranunculus repens L.).', 1, '0', '0'),
(1514, 'new', 'Полин звичайний (Artemisia vulgaris L.) та полин гіркий (Artemisia absinthium L.).', 1, '0', '0'),
(1515, 'new', 'Подорожник ланцетолистий (Plantago lanceolata L.).', 1, '0', '0'),
(1516, 'new', 'Кульбаба лікарська (Taraxacum officinale).', 1, '0', '0'),
(1517, 'new', 'Щавель горобиний (Rumex acetosella L.).', 1, '0', '0'),
(1518, 'new', 'Осот рожевий польовий (Cirsium arvense L.).', 1, '0', '0'),
(1519, 'new', 'Осот жовтий польовий (Sonchus arvensis L.).', 1, '0', '0'),
(1520, 'new', 'Гірчак степовий звичайний (Acroptilon repens Pall.).', 1, '0', '0'),
(1521, 'new', 'Березка польова (Convolvulus arvensis L.).', 1, '0', '0'),
(1522, 'new', 'Хвощ польовий (Equisetum arvense L.).', 1, '0', '0'),
(1523, 'new', 'Свинорий пальчастий (Cynodon dactylon L.).', 1, '0', '0'),
(1524, 'new', 'Гумай, сорго алепське (Sorghum halepense L.).', 1, '0', '0'),
(1525, 'new', 'Деревій звичайний (Achillea millefolium L.).', 1, '0', '0'),
(1526, 'new', 'Пирій повзучий (Elytrigia repens L.).', 1, '0', '0'),
(1527, 'new', 'Синяк звичайний (Echium vulgare L.).', 1, '0', '0'),
(1528, 'new', 'Буркун лікарський (Melilotus officinalis L.).', 1, '0', '0'),
(1529, 'new', 'Талабан польовий (Thlaspi arvense L.).', 1, '0', '0'),
(1530, 'new', 'Сокирки польові (Delphinium consolida Consolida regalis).', 1, '0', '0'),
(1531, 'new', 'Кучерявець Софи (Descurainia Sophia L.).', 1, '0', '0'),
(1532, 'new', 'Триреберник непахучий', 1, '0', '0'),
(1533, 'new', 'Жовтозілля весняне (Senecio vernalis Waldst).', 1, '0', '0'),
(1534, 'new', 'Грицики звичайні (Capsella bursa pastoris L.)', 1, '0', '0'),
(1535, 'new', 'Волошка синя (Centaurea cyanus L.)', 1, '0', '0'),
(1536, 'new', 'Метлюг звичайний (Apera spica venti L.).', 1, '0', '0'),
(1537, 'new', 'Бромус житній', 1, '0', '0'),
(1538, 'new', 'Портулак городній (Portulaca oleraceae L.)', 1, '0', '0'),
(1539, 'new', 'Курай руський (Salsola ruthenica Jlijin.)', 1, '0', '0'),
(1540, 'new', 'Шпергель звичайний (Spergula vulgaris Boenn.).', 1, '0', '0'),
(1541, 'new', 'Галінсога дрібноквіткова', 1, '0', '0'),
(1542, 'new', 'Щириця звичайна (Amaranthus retroflexus L.).', 1, '0', '0'),
(1543, 'new', 'Спориш звичайний (Polygonum aviculare L.).', 1, '0', '0'),
(1544, 'new', 'Осот жовтий городній (Sonchus oleraceus L.).', 1, '0', '0'),
(1545, 'new', 'Гірчак шорсткий (Polygonum scabrum Moench.).', 1, '0', '0'),
(1546, 'new', 'Амброзія трироздільна (Ambrosia trifida L.).', 1, '0', '0'),
(1547, 'new', 'Амброзія полинолиста (Ambrosia artemisiifolia L.).', 1, '0', '0'),
(1548, 'new', 'Ценхрус якірцевий (Cenchrus paucijlorus Benth.).', 1, '0', '0'),
(1549, 'new', 'Плоскуха звичайна (Echinochloa crus-galli L.).', 1, '0', '0'),
(1550, 'new', 'Мишій зелений (Setaria viridis L.).', 1, '0', '0'),
(1551, 'new', 'Мишій сизий (Setaria glauca L.', 1, '0', '0'),
(1552, 'new', 'Якірці сланкі (Tribulus terrestris L.).', 1, '0', '0'),
(1553, 'new', 'Рутка лікарська (Fumaria officinalis L.).', 1, '0', '0'),
(1554, 'new', 'Підмаренник чіпкий (Galium aparine L.).', 1, '0', '0'),
(1555, 'new', 'Лобода біла (Chenopodium album L.).', 1, '0', '0'),
(1556, 'new', 'Гречка татарська (Polygonum tataricum L. Fagopyrum tataricum L.).', 1, '0', '0'),
(1557, 'new', 'Гірчиця польова (Sinapis arvensis L.).', 1, '0', '0'),
(1558, 'new', 'Гірчак березковидний (Polygonum convolvulus L.)', 1, '0', '0'),
(1559, 'new', 'Вівсюг звичайний (Avena fatua L.)', 1, '0', '0'),
(1560, 'new', 'Тонконіг однорічний (Poa annua L.).', 1, '0', '0'),
(1561, 'new', 'Комірна міль', 3, '0', '0'),
(1562, 'new', 'Зернова міль', 3, '0', '0'),
(1563, 'new', 'Південна комірна вогнівка', 3, '0', '0'),
(1564, 'new', 'Борошняна вогнівка', 3, '0', '0'),
(1565, 'new', 'Млинова вогнівка', 3, '0', '0'),
(1566, 'new', 'Зерновий точильник (зерновий шашіль)', 3, '0', '0'),
(1567, 'new', 'Мавританська кузька', 3, '0', '0'),
(1568, 'new', 'Суринамський борошноїд', 3, '0', '0'),
(1569, 'new', 'Облудник злодій', 3, '0', '0'),
(1570, 'new', 'Хлібний точильник', 3, '0', '0'),
(1571, 'new', 'Булавовусий малий борошняний хрущак', 3, '0', '0'),
(1572, 'new', 'Малий борошняний хрущак', 3, '0', '0'),
(1573, 'new', 'Борошняний хрущак', 3, '0', '0'),
(1574, 'new', 'Рисовий довгоносик', 3, '0', '0'),
(1575, 'new', 'Комірний довгоносик', 3, '0', '0'),
(1576, 'new', 'Сосновий зірчастий пильщик ткач', 3, '0', '0'),
(1577, 'new', 'Шовкопряд монашка', 3, '0', '0'),
(1578, 'new', 'П’ядун сосновий', 3, '0', '0'),
(1579, 'new', 'Сосновий шовкопряд', 3, '0', '0'),
(1580, 'new', 'Звійниця літня', 3, '0', '0'),
(1581, 'new', 'Звійниця зимова', 3, '0', '0'),
(1582, 'new', 'Звійниця пагінцева', 3, '0', '0'),
(1583, 'new', 'Великий хвойний рогохвіст', 3, '0', '0'),
(1584, 'new', 'Сірий довговусий вусач', 3, '0', '0'),
(1585, 'new', 'Чорний сосновий вусач', 3, '0', '0'),
(1586, 'new', 'Синя соснова златка', 3, '0', '0'),
(1587, 'new', 'Малий сосновий лубоїд або малий лісовий садівник', 3, '0', '0'),
(1588, 'new', 'Великий сосновий лубоїд або великий лісовий садівник', 3, '0', '0'),
(1589, 'new', 'Вершинний короїд', 3, '0', '0'),
(1590, 'new', 'Великий сосновий довгоносик', 3, '0', '0'),
(1591, 'new', 'Підкоровик сосновий', 3, '0', '0'),
(1592, 'new', 'Великий березовий пильщик', 3, '0', '0'),
(1593, 'new', 'Ясеневий білокрапковий пильщик, або макрофія ясенева', 3, '0', '0'),
(1594, 'new', 'Тополевий, або осиковий, строкатий пильщик', 3, '0', '0'),
(1595, 'new', 'Вербова горностаєва міль', 3, '0', '0'),
(1596, 'new', 'Дубовий похідний шовкопряд', 3, '0', '0'),
(1597, 'new', 'Червонохвіст', 3, '0', '0'),
(1598, 'new', 'Вербова хвилянка', 3, '0', '0'),
(1599, 'new', 'П’ядун жовтовусий', 3, '0', '0'),
(1600, 'new', 'П’ядунобдирало плодовий', 3, '0', '0'),
(1601, 'new', 'Лунка срібляста (зубниця буцефал срібляста)', 3, '0', '0'),
(1602, 'new', 'Дубова чубатка', 3, '0', '0'),
(1603, 'new', 'Зелена дубова листовійка', 3, '0', '0'),
(1604, 'new', 'Велика склівка', 3, '0', '0'),
(1605, 'new', 'Тремекс березовий, або великий березовий рогохвіст', 3, '0', '0'),
(1606, 'new', 'Тополевий вусач, або великий осиковий скрипун', 3, '0', '0'),
(1607, 'new', 'Кліт поперечносмугастий', 3, '0', '0'),
(1608, 'new', 'Дубовий заболонник', 3, '0', '0'),
(1609, 'new', 'Лубоїд ясеневий строкатий', 3, '0', '0'),
(1610, 'new', 'Тополевий листоїд', 3, '0', '0'),
(1611, 'new', 'Дубова блішка (альтика дубова)', 3, '0', '0'),
(1612, 'new', 'Грушева плодова галиця', 3, '0', '0'),
(1613, 'new', 'Сливова товстоніжка', 3, '0', '0'),
(1614, 'new', 'Грушевий пильщик-ткач', 3, '0', '0'),
(1615, 'new', 'Вишневий слизистий пильщик', 3, '0', '0'),
(1616, 'new', 'Сливовий чорний пильщик', 3, '0', '0'),
(1617, 'new', 'Грушевий плодовий пильщик', 3, '0', '0'),
(1618, 'new', 'Садова совка', 3, '0', '0'),
(1619, 'new', 'Жовтобура рання совка', 3, '0', '0'),
(1620, 'new', 'Совка синьоголівка', 3, '0', '0'),
(1621, 'new', 'Кільчастий шовкопряд', 3, '0', '0'),
(1622, 'new', 'П’ядун сливовий', 3, '0', '0'),
(1623, 'new', 'П’ядун шовкопряд буросмугастий', 3, '0', '0'),
(1624, 'new', 'Зимовий п’ядун', 3, '0', '0'),
(1625, 'new', 'Підкорова листовійка', 3, '0', '0'),
(1626, 'new', 'Листовійка смородинова кривовуса', 3, '0', '0'),
(1627, 'new', 'Листовійка мінлива плодова', 3, '0', '0'),
(1628, 'new', 'Листовійка різнокольорова плодова', 3, '0', '0'),
(1629, 'new', 'Листовійка приморозкова', 3, '0', '0'),
(1630, 'new', 'Листовійка товстунка глодова', 3, '0', '0'),
(1631, 'new', 'Листкова звійниця', 3, '0', '0'),
(1632, 'new', 'Плодова чохликова міль', 3, '0', '0'),
(1633, 'new', 'Яблунева нижньобокова мінуюча міль', 3, '0', '0'),
(1634, 'new', 'Верхньобокова плодова мінуюча міль', 3, '0', '0'),
(1635, 'new', 'Яблунева біла мількрихітка', 3, '0', '0'),
(1636, 'new', 'Глодова кружкова міль', 3, '0', '0'),
(1637, 'new', 'Яблунева мільмалятко', 3, '0', '0'),
(1638, 'new', 'Плодова горностаєва міль', 3, '0', '0'),
(1639, 'new', 'Яблунева горностаєва міль', 3, '0', '0'),
(1640, 'new', 'Яблунева склівка', 3, '0', '0'),
(1641, 'new', 'Червиця пахуча', 3, '0', '0'),
(1642, 'new', 'Червиця в’їдлива', 3, '0', '0'),
(1643, 'new', 'Плодовий заболонник', 3, '0', '0'),
(1644, 'new', 'Златка чорна', 3, '0', '0'),
(1645, 'new', 'Довгоносик короїд плодовий', 3, '0', '0'),
(1646, 'new', 'Яблуневий квіткоїд', 3, '0', '0'),
(1647, 'new', 'Трубкокрут вишневий', 3, '0', '0'),
(1648, 'new', 'Великий грушевий трубкокрут', 3, '0', '0'),
(1649, 'new', 'Глодовий червонокрилий трубкокрут', 3, '0', '0'),
(1650, 'new', 'Сливова несправжньощитівка', 3, '0', '0'),
(1651, 'new', 'Акацієва несправжньощитівка', 3, '0', '0'),
(1652, 'new', 'Червона грушева щитівка', 3, '0', '0'),
(1653, 'new', 'Несправжня каліфорнійська щитівка', 3, '0', '0'),
(1654, 'new', 'Яблунева комоподібна щитівка', 3, '0', '0'),
(1655, 'new', 'Кров’яна попелиця', 3, '0', '0'),
(1656, 'new', 'Сливова обпилена попелиця', 3, '0', '0'),
(1657, 'new', 'Бура грушевозонтична попелиця', 3, '0', '0'),
(1658, 'new', 'Червоногалова сіра яблунева попелиця', 3, '0', '0'),
(1659, 'new', 'Зелена яблунева попелиця', 3, '0', '0'),
(1660, 'new', 'Грушева листоблішка', 3, '0', '0'),
(1661, 'new', 'Малинна муха', 3, '0', '0'),
(1662, 'new', 'Малинна стеблова галиця', 3, '0', '0'),
(1663, 'new', 'Малинна листкова галиця', 3, '0', '0'),
(1664, 'new', 'Малинна пагонова галиця', 3, '0', '0'),
(1665, 'new', 'Малинний мінуючий пильщик', 3, '0', '0'),
(1666, 'new', 'Малинний гребінчатовусий пильщик', 3, '0', '0'),
(1667, 'new', 'Суничний чорноплямистий пильщик', 3, '0', '0'),
(1668, 'new', 'Малинна брунькова міль', 3, '0', '0'),
(1669, 'new', 'Малинна склівка', 3, '0', '0'),
(1670, 'new', 'Сірий, або землистий, кореневий довгоносик', 3, '0', '0'),
(1671, 'new', 'Малинний довгоносик', 3, '0', '0'),
(1672, 'new', 'Малинний жук', 3, '0', '0'),
(1673, 'new', 'Малинна пагонова попелиця', 3, '0', '0'),
(1674, 'new', 'Смородинна квіткова галиця', 3, '0', '0'),
(1675, 'new', 'Смородинна листкова галиця', 3, '0', '0'),
(1676, 'new', 'Смородинна стеблова галиця', 3, '0', '0'),
(1677, 'new', 'Аґрусовий блідоногий пильщик', 3, '0', '0'),
(1678, 'new', 'Червоносмородинний жовтий пильщик', 3, '0', '0'),
(1679, 'new', 'Чорносмородинний жовтий пильщик', 3, '0', '0'),
(1680, 'new', 'Смородинна брунькова міль', 3, '0', '0'),
(1681, 'new', 'Смородинна склівка', 3, '0', '0'),
(1682, 'new', 'Аґрусова вогнівка', 3, '0', '0'),
(1683, 'new', 'Аґрусовий п’ядун', 3, '0', '0'),
(1684, 'new', 'Смородинна вузькотіла златка', 3, '0', '0'),
(1685, 'new', 'Листкова, або червоносмородинна, попелиця', 3, '0', '0'),
(1686, 'new', 'Аґрусова попелиця', 3, '0', '0'),
(1687, 'new', 'Виноградна галиця', 3, '0', '0'),
(1688, 'new', 'Кукурудзяний гнойовик', 3, '0', '0'),
(1689, 'new', 'Виноградний каптурник', 3, '0', '0'),
(1690, 'new', 'Златка вузькотіла виноградна', 3, '0', '0'),
(1691, 'new', 'Трипс виноградний', 3, '0', '0'),
(1692, 'new', 'Червонокрила цикадка', 3, '0', '0'),
(1693, 'new', 'Виноградна кружкова міль', 3, '0', '0'),
(1694, 'new', 'Листовійка двольотна', 3, '0', '0'),
(1695, 'new', 'Падучка темна', 3, '0', '0'),
(1696, 'new', 'Трубкокрут багатоїдний, або грушевий', 3, '0', '0'),
(1697, 'new', 'Виноградний борошнистий червець', 3, '0', '0'),
(1698, 'new', 'Цибулева дзюрчалка / горбкувата дзюрчала', 3, '0', '0'),
(1699, 'new', 'Цибулева мінуюча муха', 3, '0', '0'),
(1700, 'new', 'Цибулева тріщалка', 3, '0', '0'),
(1701, 'new', 'Звичайна, степова і звертаюча мокриці', 3, '0', '0'),
(1702, 'new', 'Ківсяк крапчастий', 3, '0', '0'),
(1703, 'new', 'Південна галова нематода', 3, '0', '0'),
(1704, 'new', 'Облямований, польовий, сітчастий слимаки', 3, '0', '0'),
(1705, 'new', 'Біла подура / Грибна (пасльонова) подура', 3, '0', '0'),
(1706, 'new', 'Пасльонова мінуюча муха', 3, '0', '0'),
(1707, 'new', 'Велика картопляна попелиця', 3, '0', '0'),
(1708, 'new', 'Звичайна картопляна попелиця', 3, '0', '0'),
(1709, 'new', 'Блідий лучний метелик', 3, '0', '0'),
(1710, 'new', 'Зонтична міль', 3, '0', '0'),
(1711, 'new', 'Морквяна листоблішка', 3, '0', '0'),
(1712, 'new', 'Конопляна плодожерка', 3, '0', '0'),
(1713, 'new', 'Горбатка конопляна', 3, '0', '0'),
(1714, 'new', 'Конопляна блішка', 3, '0', '0'),
(1715, 'new', 'Галиця шавлієва', 3, '0', '0'),
(1716, 'new', 'Систоле опушена', 3, '0', '0'),
(1717, 'new', 'Насіннєїд коріандровий', 3, '0', '0'),
(1718, 'new', 'М’яка цикадка', 3, '0', '0'),
(1719, 'new', 'Трояндовий бутонний пильщик', 3, '0', '0'),
(1720, 'new', 'Трояндовий східний пильщик', 3, '0', '0'),
(1721, 'new', 'Жовтий трояндовий пильщик', 3, '0', '0'),
(1722, 'new', 'Шавлієва совка', 3, '0', '0'),
(1723, 'new', 'Кминна міль', 3, '0', '0'),
(1724, 'new', 'М’ятний стрибун', 3, '0', '0'),
(1725, 'new', 'Щитоноска зелена', 3, '0', '0'),
(1726, 'new', 'Листоїд м’ятний', 3, '0', '0'),
(1727, 'new', 'Галерука садова', 3, '0', '0'),
(1728, 'new', 'Вузькотіла розанна златка', 3, '0', '0'),
(1729, 'new', 'Трипс шавлієвий', 3, '0', '0'),
(1730, 'new', 'Листкова трояндова попелиця', 3, '0', '0'),
(1731, 'new', 'Велика трояндова попелиця', 3, '0', '0'),
(1732, 'new', 'Строката цикадка', 3, '0', '0'),
(1733, 'new', 'Селеноцефалус блідий', 3, '0', '0'),
(1734, 'new', 'Агалматіум дволопатевий', 3, '0', '0'),
(1735, 'new', 'Лепіронія жукоподібна', 3, '0', '0'),
(1736, 'new', 'Люцернова квіткова галиця, люцерновий комарик', 3, '0', '0'),
(1737, 'new', 'Еспарцетний насіннєїд', 3, '0', '0'),
(1738, 'new', 'Люцерновий насіннєїд', 3, '0', '0'),
(1739, 'new', 'Конюшинний насіннєїд', 3, '0', '0'),
(1740, 'new', 'Зернівка еспарцетна', 3, '0', '0'),
(1741, 'new', 'Золотистий буркуновий насіннєїд', 3, '0', '0'),
(1742, 'new', 'Буркуновий листовий галовий довгоносик', 3, '0', '0'),
(1743, 'new', 'Люцерновий жовтий або сірий насіннєїд', 3, '0', '0'),
(1744, 'new', 'Скосар люцерновий, кореневий люцерновий довгоносик', 3, '0', '0'),
(1745, 'new', 'Конюшинний листовий довгоносик', 3, '0', '0'),
(1746, 'new', 'Степовий люцерновий довгоносик', 3, '0', '0'),
(1747, 'new', 'Листовий люцерновий довгоносик', 3, '0', '0'),
(1748, 'new', 'Буркуновий стеблоїд', 3, '0', '0'),
(1749, 'new', 'Еспарцетний бруньковий довгоносик', 3, '0', '0'),
(1750, 'new', 'Конюшинний стебловий довгоносик', 3, '0', '0'),
(1751, 'new', 'Конюшинний насіннєїд (апіон)', 3, '0', '0'),
(1752, 'new', 'Люцерновий клоп', 3, '0', '0'),
(1753, 'new', 'Льняна листовійка, або плодожерка льняна', 3, '0', '0'),
(1754, 'new', 'Синя льняна блішка', 3, '0', '0'),
(1755, 'new', 'Льняний трипс', 3, '0', '0'),
(1756, 'new', 'Естерія', 3, '0', '0'),
(1757, 'new', 'Щитневий рачок', 3, '0', '0'),
(1758, 'new', 'Прибережна муха (береговушка узбережна)', 3, '0', '0'),
(1759, 'new', 'Трипс пустоцвітий', 3, '0', '0'),
(1760, 'new', 'Злаковий клопик', 3, '0', '0'),
(1761, 'new', 'Соргова попелиця', 3, '0', '0'),
(1762, 'new', 'Цикадка темна', 3, '0', '0'),
(1763, 'new', 'Південна бурякова блішка', 3, '0', '0'),
(1764, 'new', 'Амарантовий стеблоїд', 3, '0', '0'),
(1765, 'new', 'Смугастий буряковий довгоносик', 3, '0', '0'),
(1766, 'new', 'Коренева цикадка', 3, '0', '0'),
(1767, 'new', 'Літня капустяна муха', 3, '0', '0'),
(1768, 'new', 'Весняна капустяна муха', 3, '0', '0'),
(1769, 'new', 'Шкідлива довгоніжка', 3, '0', '0'),
(1770, 'new', 'Стручкова (обпалена) вогнівка', 3, '0', '0'),
(1771, 'new', 'Капустяна вогнівка', 3, '0', '0'),
(1772, 'new', 'Зелений бруквяний барид', 3, '0', '0'),
(1773, 'new', 'Блішка хвиляста', 3, '0', '0'),
(1774, 'new', 'Горбатка соняшникова', 3, '0', '0'),
(1775, 'new', 'Горохова галиця', 3, '0', '0'),
(1776, 'new', 'Горохова совка', 3, '0', '0'),
(1777, 'new', 'Плодожерка горохова білоплямиста', 3, '0', '0'),
(1778, 'new', 'П’ятикрапковий довгоносик', 3, '0', '0'),
(1779, 'new', 'Щетинистий бульбочковий довгоносик', 3, '0', '0'),
(1780, 'new', 'Смугастий бульбочковий довгоносик', 3, '0', '0'),
(1781, 'new', 'Зернівка квасолева', 3, '0', '0'),
(1782, 'new', 'Трипс гороховий', 3, '0', '0'),
(1783, 'new', 'Озима муха', 3, '0', '0'),
(1784, 'new', 'Муха яра', 3, '0', '0'),
(1785, 'new', 'Пшенична (чорна злакова) муха', 3, '0', '0'),
(1786, 'new', 'Зеленоочка', 3, '0', '0'),
(1787, 'new', 'Шведські мухи (вівсяна, ячмінна)', 3, '0', '0'),
(1788, 'new', 'Опоміза пшенична', 3, '0', '0'),
(1789, 'new', 'Просяний комарик', 3, '0', '0'),
(1790, 'new', 'Гессенська муха', 3, '0', '0'),
(1791, 'new', 'Пильщик (трач) хлібний чорний', 3, '0', '0'),
(1792, 'new', 'Пильщик (трач) хлібний звичайний', 3, '0', '0'),
(1793, 'new', 'Льняна листовійка, або плодожерка льняна', 3, '0', '0'),
(1794, 'new', 'Південна стеблова совка', 3, '0', '0'),
(1795, 'new', 'Звичайна зернова совка', 3, '0', '0'),
(1796, 'new', 'Звичайна стеблова блішка', 3, '0', '0'),
(1797, 'new', 'Смугаста хлібна блішка', 3, '0', '0'),
(1798, 'new', 'П’явиця синя', 3, '0', '0'),
(1799, 'new', 'Красун, або хрущ польовий', 3, '0', '0'),
(1800, 'new', 'Жук хрестоносець', 3, '0', '0'),
(1801, 'new', 'Просяна жужелиця', 3, '0', '0'),
(1802, 'new', 'Трипс вівсяний', 3, '0', '0'),
(1803, 'new', 'Елія носата', 3, '0', '0'),
(1804, 'new', 'Елія гостроголова', 3, '0', '0'),
(1805, 'new', 'Австрійська черепашка', 3, '0', '0'),
(1806, 'new', 'Маврська черепашка', 3, '0', '0'),
(1807, 'new', 'Черемхова попелиця', 3, '0', '0'),
(1808, 'new', 'Ячмінна попелиця', 3, '0', '0'),
(1809, 'new', 'Темна цикадка', 3, '0', '0'),
(1810, 'new', 'Смугаста цикадка', 3, '0', '0'),
(1811, 'new', 'Шестикрапкова цикадка', 3, '0', '0'),
(1812, 'new', '«Відьмині мітли» вишні', 2, '0', ' '),
(1813, 'new', '«Шарка» сливи', 2, '0', ' '),
(1814, 'new', 'Альтернаріоз, або оливкова плямистість', 2, '0', ' '),
(1815, 'new', 'Англійська огіркова мозаїка', 2, '0', ' '),
(1816, 'new', 'Андийський фомоз', 2, '0', ' '),
(1817, 'new', 'Базальний бактеріоз', 2, '0', ' '),
(1818, 'new', 'Базальний, або ореольний, бактеріоз', 2, '0', ' '),
(1819, 'new', 'Бактеріальна рябуха', 2, '0', ' '),
(1820, 'new', 'Бактеріальна смугастість, або штрихуватість', 2, '0', ' '),
(1821, 'new', 'Бактеріальна стеблова гниль', 2, '0', ' '),
(1822, 'new', 'Бактеріальне в''янення', 2, '0', ' '),
(1823, 'new', 'Бактеріальні стеблові гнилі', 2, '0', ' '),
(1824, 'new', 'Біла строкатість', 2, '0', ' '),
(1825, 'new', 'Біло-жовта смугаста плямистість, або склероспороз', 2, '0', ' '),
(1826, 'new', 'Біль качанів', 2, '0', ' '),
(1827, 'new', 'Біль, або біла іржа', 2, '0', ' '),
(1828, 'new', 'Блідий (блідоплямистий) аскохітоз', 2, '0', ' '),
(1829, 'new', 'Бородавчастість', 2, '0', ' '),
(1830, 'new', 'Борознистість деревини', 2, '0', ' '),
(1831, 'new', 'Бронзовість', 2, '0', ' '),
(1832, 'new', 'Бронзовість томату', 2, '0', ' '),
(1833, 'new', 'Бугорчата парша', 2, '0', ' '),
(1834, 'new', 'Бура бактеріальна плямистість', 2, '0', ' '),
(1835, 'new', 'Бура гниль', 2, '0', ' '),
(1836, 'new', 'Бура плямистість, або альтернаріоз', 2, '0', ' '),
(1837, 'new', 'Бура плямистість, або гельмінтоспоріоз', 2, '0', ' '),
(1838, 'new', 'Бура суха гниль кошиків', 2, '0', ' '),
(1839, 'new', 'Бура суха плямистість, або альтернаріоз', 2, '0', ' '),
(1840, 'new', 'Бура, або суха, плямистість', 2, '0', ' '),
(1841, 'new', 'Бурий бактеріоз', 2, '0', ' '),
(1842, 'new', 'Бурий бактеріоз, або ореольний опік', 2, '0', ' '),
(1843, 'new', 'Бурувата іржа', 2, '0', ' '),
(1844, 'new', 'Бурувата плямистість', 2, '0', ' '),
(1845, 'new', 'Бурувата плямистість, або гельмінтоспоріоз', 2, '0', ' '),
(1846, 'new', 'Буруватість листків', 2, '0', ' '),
(1847, 'new', 'Буруватість листків груші', 2, '0', ' '),
(1848, 'new', 'В’янення', 2, '0', ' '),
(1849, 'new', 'В’янення кормових трав', 2, '0', ' '),
(1850, 'new', 'Веретеноподібність бульб, або готика', 2, '0', ' '),
(1851, 'new', 'Верхівкова гниль', 2, '0', ' '),
(1852, 'new', 'Випрівання', 2, '0', ' '),
(1853, 'new', 'Відмирання сходів', 2, '0', ' '),
(1854, 'new', 'Вірусний хлороз', 2, '0', ' '),
(1855, 'new', 'Вкрита сажка', 2, '0', ' ');
INSERT INTO `pd_Vermin` (`id`, `guid`, `name`, `groupId`, `photo`, `ord`) VALUES
(1856, 'new', 'Вовчок', 2, '0', ' '),
(1857, 'new', 'Водяниста мокра гниль', 2, '0', ' '),
(1858, 'new', 'Водяниста плямистість', 2, '0', ' '),
(1859, 'new', 'Волохатість, або реверсія, смородини', 2, '0', ' '),
(1860, 'new', 'Вугільна гниль', 2, '0', ' '),
(1861, 'new', 'Вуглувата плямистість', 2, '0', ' '),
(1862, 'new', 'Вузьколистість', 2, '0', ' '),
(1863, 'new', 'В''янення', 2, '0', ' '),
(1864, 'new', 'В''янення пасльонових', 2, '0', ' '),
(1865, 'new', 'В''янення, або вертицильоз', 2, '0', ' '),
(1866, 'new', 'Гіллястий вовчок', 2, '0', ' '),
(1867, 'new', 'Гутаперчивість деревини', 2, '0', ' '),
(1868, 'new', 'Дендрофомоз', 2, '0', ' '),
(1869, 'new', 'Деформуюча мозаїка', 2, '0', ' '),
(1870, 'new', 'Диплодіоз', 2, '0', ' '),
(1871, 'new', 'Ділофоспороз', 2, '0', ' '),
(1872, 'new', 'Дрібнопузирчаста сажка', 2, '0', ' '),
(1873, 'new', 'Дрібноспорова сажка', 2, '0', ' '),
(1874, 'new', 'Дуплистість бульб', 2, '0', ' '),
(1875, 'new', 'Дуплистість коренів', 2, '0', ' '),
(1876, 'new', 'Ензимо-мікозне виснаження зерна', 2, '0', ' '),
(1877, 'new', 'Жовта карликовість ячменю', 2, '0', ' '),
(1878, 'new', 'Жовта мозаїка', 2, '0', ' '),
(1879, 'new', 'Жовта плямистість', 2, '0', ' '),
(1880, 'new', 'Жовта плямистість листя, або церкоспороз', 2, '0', ' '),
(1881, 'new', 'Жовта смугастість, або карликовість', 2, '0', ' '),
(1882, 'new', 'Жовта штрихуватість', 2, '0', ' '),
(1883, 'new', 'Жовтий, або слизуватий, бактеріоз', 2, '0', ' '),
(1884, 'new', 'Жовто-бура плямистість, або сколекотрихоз', 2, '0', ' '),
(1885, 'new', 'Жовтуха', 2, '0', ' '),
(1886, 'new', 'Жовтяниця', 2, '0', ' '),
(1887, 'new', 'Залізиста, або іржава, плямистість бульб', 2, '0', ' '),
(1888, 'new', 'Заляльковування', 2, '0', ' '),
(1889, 'new', 'Заляльковування вівса, або заляльковування злаків', 2, '0', ' '),
(1890, 'new', 'Звичайна гниль', 2, '0', ' '),
(1891, 'new', 'Звичайна мозаїка', 2, '0', ' '),
(1892, 'new', 'Звичайна огіркова мозаїка', 2, '0', ' '),
(1893, 'new', 'Звичайна сажка', 2, '0', ' '),
(1894, 'new', 'Звичайна, або зелена, мозаїка квасолі', 2, '0', ' '),
(1895, 'new', 'Звичайний, або європейський, рак', 2, '0', ' '),
(1896, 'new', 'Зморшкувата мозаїка', 2, '0', ' '),
(1897, 'new', 'Зморшкуватість листя', 2, '0', ' '),
(1898, 'new', 'Зобуватість коренів, або рак', 2, '0', ' '),
(1899, 'new', 'Зональна плямистість, або фомоз листя', 2, '0', ' '),
(1900, 'new', 'Ізростання', 2, '0', ' '),
(1901, 'new', 'Індійська сажка', 2, '0', ' '),
(1902, 'new', 'Інфекційна стерильність', 2, '0', ' '),
(1903, 'new', 'Інфекційний хлороз', 2, '0', ' '),
(1904, 'new', 'Інфекційний хлороз (жовта мозаїка, ряболистість)', 2, '0', ' '),
(1905, 'new', 'Іржасті захворювання', 2, '0', ' '),
(1906, 'new', 'Карликова мозаїка', 2, '0', ' '),
(1907, 'new', 'Карликовість', 2, '0', ' '),
(1908, 'new', 'Квіткова плісень', 2, '0', ' '),
(1909, 'new', 'Кишеньки слив', 2, '0', ' '),
(1910, 'new', 'Концентрична плямистість', 2, '0', ' '),
(1911, 'new', 'Коренева, або пленодомусна, гниль', 2, '0', ' '),
(1912, 'new', 'Кореневий рак, або зобуватість коренів', 2, '0', ' '),
(1913, 'new', 'Коричнева плямистість', 2, '0', ' '),
(1914, 'new', 'Коричнева плямистість, або гетероспороз', 2, '0', ' '),
(1915, 'new', 'Коротковузля', 2, '0', ' '),
(1916, 'new', 'Крапчаста, або звичайна, мозаїка', 2, '0', ' '),
(1917, 'new', 'Крапчастість сім''ядолей', 2, '0', ' '),
(1918, 'new', 'Крапчастість, або білолистковість, рису', 2, '0', ' '),
(1919, 'new', 'Крупна плямистість, або бактеріальний опік', 2, '0', ' '),
(1920, 'new', 'Листкова сажка', 2, '0', ' '),
(1921, 'new', 'Листковий опік стоколосу', 2, '0', ' '),
(1922, 'new', 'Листова бактеріальна крапчастість', 2, '0', ' '),
(1923, 'new', 'Меланоз', 2, '0', ' '),
(1924, 'new', 'Меланоммоз', 2, '0', ' '),
(1925, 'new', 'Міжжилкова мозаїка', 2, '0', ' '),
(1926, 'new', 'Мільдью', 2, '0', ' '),
(1927, 'new', 'Мозаїка', 2, '0', ' '),
(1928, 'new', 'Мозаїка, або жовтуха', 2, '0', ' '),
(1929, 'new', 'Мозаїка, або облямівка жилок', 2, '0', ' '),
(1930, 'new', 'Мокра бактеріальна гниль', 2, '0', ' '),
(1932, 'new', 'Молочний блиск', 2, '0', ' '),
(1933, 'new', 'Моніліоз, або плодова гниль', 2, '0', ' '),
(1934, 'new', 'Неінфекційний хлороз', 2, '0', ' '),
(1935, 'new', 'Некроз судин', 2, '0', ' '),
(1936, 'new', 'Непаразитарні хвороби', 2, '0', ' '),
(1937, 'new', 'Несправжня борошниста роса, або мільдью', 2, '0', ' '),
(1938, 'new', 'Несправжня борошниста роса, або пероноспороз', 2, '0', ' '),
(1939, 'new', 'Несправжня сажка рису', 2, '0', ' '),
(1940, 'new', 'Нігроспороз', 2, '0', ' '),
(1941, 'new', 'Облямівка жилок', 2, '0', ' '),
(1942, 'new', 'Овуляріоз', 2, '0', ' '),
(1943, 'new', 'Огіркова мозаїка', 2, '0', ' '),
(1944, 'new', 'Оливкова плісень', 2, '0', ' '),
(1945, 'new', 'Оливкова плісень', 2, '0', ' '),
(1946, 'new', 'Опік коріння льону', 2, '0', ' '),
(1947, 'new', 'Опік плодових дерев', 2, '0', ' '),
(1948, 'new', 'Опік стрижня колосу', 2, '0', ' '),
(1949, 'new', 'Південний стовбур', 2, '0', ' '),
(1950, 'new', 'Північний стовбур', 2, '0', ' '),
(1951, 'new', 'Пітіозна гниль', 2, '0', ' '),
(1952, 'new', 'Пліснявіння качанів і зерна', 2, '0', ' '),
(1953, 'new', 'Плямистий бактеріоз', 2, '0', ' '),
(1954, 'new', 'Плямистий некроз', 2, '0', ' '),
(1955, 'new', 'Побуріння', 2, '0', ' '),
(1956, 'new', 'Побуріння, або ламкість стебел', 2, '0', ' '),
(1957, 'new', 'Повстяна гниль, або ризоктоніоз', 2, '0', ' '),
(1958, 'new', 'Пожовтіння жилок груші', 2, '0', ' '),
(1959, 'new', 'Позеленіння квітів', 2, '0', ' '),
(1960, 'new', 'Позеленіння пелюстків', 2, '0', ' '),
(1961, 'new', 'Позеленіння пелюсток', 2, '0', ' '),
(1962, 'new', 'Поліферація яблуні', 2, '0', ' '),
(1963, 'new', 'Попеляста гниль', 2, '0', ' '),
(1964, 'new', 'Порохувата парша', 2, '0', ' '),
(1965, 'new', 'Почорніння серцевини бульб', 2, '0', ' '),
(1966, 'new', 'Почорніння судинних пучків, або цефалоспороз', 2, '0', ' '),
(1967, 'new', 'Прижилкова мозаїка', 2, '0', ' '),
(1968, 'new', 'Пурпурова плямистість', 2, '0', ' '),
(1969, 'new', 'Пурпурова штрихувата плямистість', 2, '0', ' '),
(1970, 'new', 'Пурпуровий церкоспороз', 2, '0', ' '),
(1971, 'new', 'Рак стебла, або опік сої', 2, '0', ' '),
(1972, 'new', 'Ризоктоніозна гниль', 2, '0', ' '),
(1973, 'new', 'Ризоманія', 2, '0', ' '),
(1974, 'new', 'Різка мозаїка', 2, '0', ' '),
(1975, 'new', 'Рожева гниль', 2, '0', ' '),
(1976, 'new', 'Рожева суха гниль кошиків', 2, '0', ' '),
(1977, 'new', 'Рожеве пліснявіння', 2, '0', ' '),
(1978, 'new', 'Сажкові захворювання', 2, '0', ' '),
(1979, 'new', 'Сіра і біла гнилі', 2, '0', ' '),
(1980, 'new', 'Сіро-зелене пліснявіння', 2, '0', ' '),
(1981, 'new', 'Склероспороз', 2, '0', ' '),
(1982, 'new', 'Склероціальна гниль', 2, '0', ' '),
(1983, 'new', 'Сколекотрихоз', 2, '0', ' '),
(1984, 'new', 'Скручення листків', 2, '0', ' '),
(1985, 'new', 'Скручення, або кропивоподібність, листків', 2, '0', ' '),
(1986, 'new', 'Слизуватий бактеріоз капусти', 2, '0', ' '),
(1987, 'new', 'Смугаста мозаїка', 2, '0', ' '),
(1988, 'new', 'Смугастий бактеріоз', 2, '0', ' '),
(1989, 'new', 'Смугастий бактеріоз, або смугастий опік', 2, '0', ' '),
(1990, 'new', 'Смугастий, або лінійний, бактеріоз', 2, '0', ' '),
(1991, 'new', 'Смугастість', 2, '0', ' '),
(1992, 'new', 'Снігова крупка', 2, '0', ' '),
(1993, 'new', 'Срібна хвороба', 2, '0', ' '),
(1994, 'new', 'Стовбур, або мокрий монтар', 2, '0', ' '),
(1995, 'new', 'Стовпчаста іржа', 2, '0', ' '),
(1996, 'new', 'Суха, або чорна, коренева гниль', 2, '0', ' '),
(1997, 'new', 'Сухий склероціоз', 2, '0', ' '),
(1998, 'new', 'Тверда сажка, або зона', 2, '0', ' '),
(1999, 'new', 'Тверда, або вкрита, сажка', 2, '0', ' '),
(2000, 'new', 'Тверда, або кам яна, сажка', 2, '0', ' '),
(2001, 'new', 'Тверда, або смердюча, сажка', 2, '0', ' '),
(2002, 'new', 'Темне пліснявіння', 2, '0', ' '),
(2003, 'new', 'Темний (плямистий) аскохітоз', 2, '0', ' '),
(2004, 'new', 'Трахеобактеріальне в''янення', 2, '0', ' '),
(2005, 'new', 'Трахеомікозне в''янення', 2, '0', ' '),
(2006, 'new', 'Туберкульоз кореня', 2, '0', ' '),
(2007, 'new', 'Тютюнова мозаїка', 2, '0', ' '),
(2008, 'new', 'Усихання стебел, або фомопсис', 2, '0', ' '),
(2009, 'new', 'Філодія конюшини', 2, '0', ' '),
(2010, 'new', 'Філостиктоз', 2, '0', ' '),
(2011, 'new', 'Фомоз, або бура гниль', 2, '0', ' '),
(2012, 'new', 'Фомоз, або суха гниль', 2, '0', ' '),
(2013, 'new', 'Фузаріоз, або фузаріозне в янення', 2, '0', ' '),
(2014, 'new', 'Фузаріозне побуріння', 2, '0', ' '),
(2015, 'new', 'Хвостова гниль', 2, '0', ' '),
(2016, 'new', 'Хлороз', 2, '0', ' '),
(2017, 'new', 'Хлороз неінфекційний', 2, '0', ' '),
(2018, 'new', 'Хлоротична кільцева плямистість кісточкових', 2, '0', ' '),
(2019, 'new', 'Хлоротична плямистість листя', 2, '0', ' '),
(2020, 'new', 'Цитоспороз', 2, '0', ' '),
(2021, 'new', 'Чернь', 2, '0', ' '),
(2022, 'new', 'Чорна ніжка, або гниль розсади', 2, '0', ' '),
(2023, 'new', 'Чорна ніжка,або коренева гниль', 2, '0', ' '),
(2024, 'new', 'Чорна парша', 2, '0', ' '),
(2026, 'new', 'Чорна плямистість, або альтернаріоз', 2, '0', ' '),
(2027, 'new', 'Чорна плямистість, або ембелізія', 2, '0', ' '),
(2028, 'new', 'Чорна, або колоскова, сажка', 2, '0', ' '),
(2029, 'new', 'Чорний бактеріоз, або бактеріальний опік', 2, '0', ' '),
(2030, 'new', 'Чорний зародок', 2, '0', ' '),
(2031, 'new', 'Чорний плямистий бактеріоз', 2, '0', ' '),
(2032, 'new', 'Чорний рак', 2, '0', ' '),
(2033, 'new', 'Чорнувата плямистість', 2, '0', ' '),
(2034, 'new', 'Чохлуватість', 2, '0', ' '),
(2035, 'new', 'Шийкова гниль', 2, '0', ' '),
(2036, 'new', 'Шоколадна плямистість', 2, '0', ' '),
(2037, 'new', 'Штрихувата мозаїка, або несправжня штрихуватість ячменю', 2, '0', ' '),
(2038, 'new', 'Штрихувата, або червоно-коричнева плямистість', 2, '0', ' '),
(2039, 'new', 'Штрихуватість', 2, '0', ' '),
(2040, 'new', 'Штрихуватість, або стрик', 2, '0', ' '),
(2041, 'new', 'Мозаїка стоколосу', 2, '0', '0'),
(2042, 'new', 'Соснова совка', 3, '0', '0'),
(2043, 'new', 'Зелена вузькотіла златка', 3, '0', '0'),
(2044, 'new', 'Пістрянка (строкатка) виноградна', 3, '0', '0'),
(2045, 'new', 'Виноградна філоксера', 3, '0', '0'),
(2046, 'new', 'Цибулева міль', 3, '0', '0'),
(2047, 'new', 'Бурий помідорний кліщ', 3, '0', '0'),
(2048, 'new', 'Огірковий комарик', 3, '0', '0'),
(2049, 'new', 'Ріпаковий, або насіннєвий, прихованохоботник', 3, '0', '0'),
(2050, 'new', 'Вусач соняшниковий, або агапантія соняшникова', 3, '0', '0'),
(2051, 'new', 'Хетокнема стеблова, хлібна стеблова блішка, велика стеблова блішка', 3, '0', '0'),
(2052, 'new', 'П’явиця червоногруда (звичайна)', 3, '0', '0'),
(2053, 'new', 'Совка оклична', 3, '0', '0'),
(2054, 'new', 'Довгоносик сірий південний', 3, '0', '0'),
(2055, 'new', 'Пилкоїд дагестанський', 3, '0', '0'),
(2056, 'new', 'Мідляк степовий', 3, '0', '0'),
(2057, 'new', 'Мідляк широкогрудий', 3, '0', '0'),
(2058, 'new', 'Мідляк кукурудзяний', 3, '0', '0'),
(2059, 'new', 'Мідляк піщаний', 3, '0', '0'),
(2060, 'new', 'Ковалик чорний', 3, '0', '0'),
(2061, 'new', 'Ковалик степовий', 3, '0', '0'),
(2062, 'new', 'Темний ковалик', 3, '0', '0'),
(2063, 'new', 'Ковалик смугастий', 3, '0', '0'),
(2064, 'new', 'Ковалик посівний', 3, '0', '0'),
(2065, 'new', 'Кравець', 3, '0', '0'),
(2066, 'new', 'Мармуровий хрущ', 3, '0', '0'),
(2067, 'new', 'Західний травневий хрущ / Східний травневий хрущ', 3, '0', '0'),
(2068, 'new', 'Капустянка одношипа', 3, '0', '0'),
(2069, 'new', 'Капустянка звичайна', 3, '0', '0'),
(2070, 'new', 'Цвіркун стебловий', 3, '0', '0'),
(2071, 'new', 'Цвіркун степовий', 3, '0', '0'),
(2072, 'new', 'Ізофія кримська', 3, '0', '0'),
(2073, 'new', 'Коник зелений', 3, '0', '0'),
(2074, 'new', 'Коник єгипетський', 3, '0', '0'),
(2075, 'new', 'Коник блакитнокрилий', 3, '0', '0'),
(2076, 'new', 'Пустельна сарана, або шистоцерка', 3, '0', '0'),
(2077, 'new', 'Сарана мароккська', 3, '0', '0'),
(2078, 'new', 'Сарана перелітна, або азіатська', 3, '0', '0'),
(2079, 'new', 'Малий сосновий лубоїд, або малий лісовий садівник', 3, '0', '0'),
(2080, 'new', 'Великий сосновий лубоїд, або великий лісовий садівник', 3, '0', '0'),
(2081, 'new', 'Суничний листоїд', 3, '0', '0'),
(2082, 'new', 'Листовійка виноградна', 3, '0', '0'),
(2083, 'new', 'Щитоноска бурякова', 3, '0', '0'),
(2084, 'new', 'Вогнівка соняшникова, або соняшникова метелиця', 3, '0', '0'),
(2085, 'new', 'Жужелиця хлібна мала', 3, '0', '0'),
(2086, 'new', 'Прус, або сарана італійська', 3, '0', '0'),
(2089, 'new', 'Мозаїка хлорозна', 2, '0', '0'),
(2090, 'new', 'Мозаїка', 2, '0', '0'),
(2091, 'new', 'Кучерявість листків вишні', 2, '0', '0'),
(2092, 'new', 'Септоріоз, або плямистість листків груші', 2, '0', '0'),
(2093, 'new', 'Чорна бактеріальна плямистість, або бородавчастість', 2, '0', '0'),
(2094, 'new', 'Фітофтороз, або бура гниль', 2, '0', '0'),
(2095, 'new', 'Септоріоз, або біла плямистість листків', 2, '0', '0'),
(2096, 'new', 'Чорна кільцева плямистість', 2, '0', '0'),
(2097, 'new', 'Фузаріоз, або фузаріозне в''янення', 2, '0', '0'),
(2098, 'new', 'Суха гниль бульб', 2, '0', '0'),
(2099, 'new', 'Срібляста парша', 2, '0', '0'),
(2100, 'new', 'Фітофтороз, або картопляна гниль', 2, '0', '0'),
(2101, 'new', 'Бактеріоз кореня', 2, '0', '0'),
(2102, 'new', 'Червона гниль, або ризоктоніоз', 2, '0', '0'),
(2103, 'new', 'Суха коренева гниль', 2, '0', '0'),
(2104, 'new', 'Бактеріальне в’янення', 2, '0', '0'),
(2105, 'new', 'Вертицильозне в’янення', 2, '0', '0'),
(2106, 'new', 'Позеленіння пелюстків квітів, або стовбур', 2, '0', '0'),
(2107, 'new', 'Льонова повитиця', 2, '0', '0'),
(2108, 'new', 'Фузаріоз по іржі', 2, '0', '0'),
(2109, 'new', 'М’яка бура гниль', 2, '0', '0'),
(2110, 'new', 'Іржава плямистість, або септоріоз', 2, '0', '0'),
(2111, 'new', 'Дрібна, або штрихувата плямистість', 2, '0', '0'),
(2112, 'new', 'Зливний аскохітоз', 2, '0', '0'),
(2113, 'new', 'Облямівкова плямистість, або ринхоспоріоз', 2, '0', '0'),
(2114, 'new', 'Біла плямистість, або мастигоспоріоз', 2, '0', '0'),
(2115, 'new', 'Гниль піхв листя', 2, '0', '0'),
(2116, 'new', 'Мозаїка стоколосу безостого', 2, '0', '0'),
(2117, 'new', 'Лінійна, або стеблова, іржа', 2, '0', '0'),
(2118, 'new', 'Тифульоз, або крапчаста снігова плісень', 2, '0', '0'),
(2119, 'new', 'Снігова плісень', 2, '0', '0'),
(2120, 'new', 'Карликовість пшениці', 2, '0', '0'),
(2121, 'new', 'Смугаста мозаїка', 2, '0', '0'),
(2122, 'new', 'Мозаїка озимої пшениці, або російська мозаїка пшениці', 2, '0', '0'),
(2123, 'new', 'Офіобольозна гниль', 2, '0', '0'),
(2124, 'new', 'Церкоспорельозна гниль', 2, '0', '0'),
(2125, 'new', 'Яра совка', 3, '0', '0'),
(2126, 'new', 'Фузаріозна гниль, або фузаріоз', 2, '0', '0'),
(2127, 'new', 'Жовта мозаїка квасолі', 2, '0', '0');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `pd_Vermin`
--
ALTER TABLE `pd_Vermin`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `pd_Vermin`
--
ALTER TABLE `pd_Vermin`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2128;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 70.016798 | 282 | 0.644285 |
c7c874dd64e023ef97934c77e6f714b0809ae51b | 192 | py | Python | vbbot/urls.py | kirichk/crewing_platform | a7d227811588a91e5db789d7d252c172b0ba3b58 | [
"MIT"
] | null | null | null | vbbot/urls.py | kirichk/crewing_platform | a7d227811588a91e5db789d7d252c172b0ba3b58 | [
"MIT"
] | 1 | 2022-02-16T18:34:19.000Z | 2022-02-16T18:34:19.000Z | vbbot/urls.py | kirichk/crewing_platform | a7d227811588a91e5db789d7d252c172b0ba3b58 | [
"MIT"
] | null | null | null | from django.urls import path
from django.conf import settings
from vbbot import views
app_name = 'vbbot'
token = settings.VIBER_TOKEN
urlpatterns = [
path(token, views.viber_app),
]
| 17.454545 | 33 | 0.744792 |
bc16d8e44efcb0646b8645685711a46f1e280286 | 27,113 | rs | Rust | src/auto/dom_html_table_element.rs | whizsid/webkit2gtk-webextension-rs | d3b93a015ecb5cb2ade8483d3f9ce78c6bb84a98 | [
"MIT"
] | 1 | 2020-02-12T16:40:24.000Z | 2020-02-12T16:40:24.000Z | src/auto/dom_html_table_element.rs | whizsid/webkit2gtk-webextension-rs | d3b93a015ecb5cb2ade8483d3f9ce78c6bb84a98 | [
"MIT"
] | null | null | null | src/auto/dom_html_table_element.rs | whizsid/webkit2gtk-webextension-rs | d3b93a015ecb5cb2ade8483d3f9ce78c6bb84a98 | [
"MIT"
] | null | null | null | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use glib;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::GString;
use glib_sys;
use libc;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use std::ptr;
use webkit2_webextension_sys;
use DOMElement;
use DOMEventTarget;
use DOMHTMLCollection;
use DOMHTMLElement;
use DOMHTMLTableCaptionElement;
use DOMHTMLTableSectionElement;
use DOMNode;
use DOMObject;
glib_wrapper! {
pub struct DOMHTMLTableElement(Object<webkit2_webextension_sys::WebKitDOMHTMLTableElement, webkit2_webextension_sys::WebKitDOMHTMLTableElementClass, DOMHTMLTableElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_table_element_get_type(),
}
}
pub const NONE_DOMHTML_TABLE_ELEMENT: Option<&DOMHTMLTableElement> = None;
pub trait DOMHTMLTableElementExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn create_caption(&self) -> Option<DOMHTMLElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn create_t_foot(&self) -> Option<DOMHTMLElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn create_t_head(&self) -> Option<DOMHTMLElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn delete_caption(&self);
#[cfg_attr(feature = "v2_22", deprecated)]
fn delete_row(&self, index: libc::c_long) -> Result<(), glib::Error>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn delete_t_foot(&self);
#[cfg_attr(feature = "v2_22", deprecated)]
fn delete_t_head(&self);
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_align(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_bg_color(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_border(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_caption(&self) -> Option<DOMHTMLTableCaptionElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_cell_padding(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_cell_spacing(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_rows(&self) -> Option<DOMHTMLCollection>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_rules(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_summary(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_t_bodies(&self) -> Option<DOMHTMLCollection>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_t_foot(&self) -> Option<DOMHTMLTableSectionElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_t_head(&self) -> Option<DOMHTMLTableSectionElement>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_width(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn insert_row(&self, index: libc::c_long) -> Result<DOMHTMLElement, glib::Error>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_align(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_bg_color(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_border(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_caption<P: IsA<DOMHTMLTableCaptionElement>>(&self, value: &P)
-> Result<(), glib::Error>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_cell_padding(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_cell_spacing(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_rules(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_summary(&self, value: &str);
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_t_foot<P: IsA<DOMHTMLTableSectionElement>>(&self, value: &P) -> Result<(), glib::Error>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_t_head<P: IsA<DOMHTMLTableSectionElement>>(&self, value: &P) -> Result<(), glib::Error>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_width(&self, value: &str);
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_bg_color_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_border_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_caption_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_cell_padding_notify<F: Fn(&Self) + 'static>(&self, f: F)
-> SignalHandlerId;
fn connect_property_cell_spacing_notify<F: Fn(&Self) + 'static>(&self, f: F)
-> SignalHandlerId;
fn connect_property_rows_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_rules_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_summary_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_t_bodies_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_t_foot_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_t_head_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLTableElement>> DOMHTMLTableElementExt for O {
fn create_caption(&self) -> Option<DOMHTMLElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_create_caption(
self.as_ref().to_glib_none().0,
),
)
}
}
fn create_t_foot(&self) -> Option<DOMHTMLElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_create_t_foot(
self.as_ref().to_glib_none().0,
),
)
}
}
fn create_t_head(&self) -> Option<DOMHTMLElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_create_t_head(
self.as_ref().to_glib_none().0,
),
)
}
}
fn delete_caption(&self) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_delete_caption(
self.as_ref().to_glib_none().0,
);
}
}
fn delete_row(&self, index: libc::c_long) -> Result<(), glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = webkit2_webextension_sys::webkit_dom_html_table_element_delete_row(
self.as_ref().to_glib_none().0,
index,
&mut error,
);
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
fn delete_t_foot(&self) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_delete_t_foot(
self.as_ref().to_glib_none().0,
);
}
}
fn delete_t_head(&self) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_delete_t_head(
self.as_ref().to_glib_none().0,
);
}
}
fn get_align(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_align(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_bg_color(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_bg_color(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_border(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_border(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_caption(&self) -> Option<DOMHTMLTableCaptionElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_get_caption(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_cell_padding(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_cell_padding(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_cell_spacing(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_cell_spacing(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_rows(&self) -> Option<DOMHTMLCollection> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_rows(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_rules(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_rules(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_summary(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_summary(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_t_bodies(&self) -> Option<DOMHTMLCollection> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_t_bodies(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_t_foot(&self) -> Option<DOMHTMLTableSectionElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_get_t_foot(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_t_head(&self) -> Option<DOMHTMLTableSectionElement> {
unsafe {
from_glib_none(
webkit2_webextension_sys::webkit_dom_html_table_element_get_t_head(
self.as_ref().to_glib_none().0,
),
)
}
}
fn get_width(&self) -> Option<GString> {
unsafe {
from_glib_full(
webkit2_webextension_sys::webkit_dom_html_table_element_get_width(
self.as_ref().to_glib_none().0,
),
)
}
}
fn insert_row(&self, index: libc::c_long) -> Result<DOMHTMLElement, glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let ret = webkit2_webextension_sys::webkit_dom_html_table_element_insert_row(
self.as_ref().to_glib_none().0,
index,
&mut error,
);
if error.is_null() {
Ok(from_glib_none(ret))
} else {
Err(from_glib_full(error))
}
}
}
fn set_align(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_align(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_bg_color(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_bg_color(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_border(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_border(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_caption<P: IsA<DOMHTMLTableCaptionElement>>(
&self,
value: &P,
) -> Result<(), glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = webkit2_webextension_sys::webkit_dom_html_table_element_set_caption(
self.as_ref().to_glib_none().0,
value.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
fn set_cell_padding(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_cell_padding(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_cell_spacing(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_cell_spacing(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_rules(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_rules(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_summary(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_summary(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn set_t_foot<P: IsA<DOMHTMLTableSectionElement>>(&self, value: &P) -> Result<(), glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = webkit2_webextension_sys::webkit_dom_html_table_element_set_t_foot(
self.as_ref().to_glib_none().0,
value.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
fn set_t_head<P: IsA<DOMHTMLTableSectionElement>>(&self, value: &P) -> Result<(), glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let _ = webkit2_webextension_sys::webkit_dom_html_table_element_set_t_head(
self.as_ref().to_glib_none().0,
value.as_ref().to_glib_none().0,
&mut error,
);
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
fn set_width(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_table_element_set_width(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::align\0".as_ptr() as *const _,
Some(transmute(notify_align_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_bg_color_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_bg_color_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::bg-color\0".as_ptr() as *const _,
Some(transmute(notify_bg_color_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_border_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_border_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::border\0".as_ptr() as *const _,
Some(transmute(notify_border_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_caption_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_caption_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::caption\0".as_ptr() as *const _,
Some(transmute(notify_caption_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_cell_padding_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_cell_padding_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::cell-padding\0".as_ptr() as *const _,
Some(transmute(
notify_cell_padding_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_cell_spacing_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_cell_spacing_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::cell-spacing\0".as_ptr() as *const _,
Some(transmute(
notify_cell_spacing_trampoline::<Self, F> as usize,
)),
Box_::into_raw(f),
)
}
}
fn connect_property_rows_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_rows_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::rows\0".as_ptr() as *const _,
Some(transmute(notify_rows_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_rules_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_rules_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::rules\0".as_ptr() as *const _,
Some(transmute(notify_rules_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_summary_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_summary_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::summary\0".as_ptr() as *const _,
Some(transmute(notify_summary_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_t_bodies_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_t_bodies_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::t-bodies\0".as_ptr() as *const _,
Some(transmute(notify_t_bodies_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_t_foot_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_t_foot_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::t-foot\0".as_ptr() as *const _,
Some(transmute(notify_t_foot_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_t_head_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_t_head_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::t-head\0".as_ptr() as *const _,
Some(transmute(notify_t_head_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_width_trampoline<P, F: Fn(&P) + 'static>(
this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableElement,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<DOMHTMLTableElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLTableElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::width\0".as_ptr() as *const _,
Some(transmute(notify_width_trampoline::<Self, F> as usize)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLTableElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLTableElement")
}
}
| 33.597274 | 264 | 0.550585 |
ba1e15d6133d82d487e94e918b276d791a324bd0 | 247 | sql | SQL | src/test/resources/tpch_test_query/presto_new/query13.sql | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 82 | 2016-05-06T22:15:41.000Z | 2018-03-26T17:10:07.000Z | src/test/resources/tpch_test_query/presto_new/query13.sql | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 65 | 2016-05-07T20:36:32.000Z | 2018-03-22T21:30:53.000Z | src/test/resources/tpch_test_query/presto_new/query13.sql | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 23 | 2016-07-02T17:14:09.000Z | 2018-03-23T17:48:14.000Z | select
c.custkey,
count(o.orderkey) as c_count
from
TPCH_SCHEMA.customer c inner join SCRAMBLE_SCHEMA.orders o
on c.custkey = o.custkey
and o."comment" not like '%unusual%'
group by
c.custkey
order by
c.custkey
| 20.583333 | 62 | 0.668016 |
819cad99ecd037a887560ab5b9c7aa2872185d03 | 12,124 | rs | Rust | src/blockchain/ethereum/signature.rs | ethereumproject/emerald-rs | f4e7c36813094129b3b2364edf2b66fc8fe08805 | [
"Apache-2.0"
] | 28 | 2017-02-23T15:36:12.000Z | 2018-02-23T20:34:55.000Z | src/blockchain/ethereum/signature.rs | ethereumproject/emerald-rs | f4e7c36813094129b3b2364edf2b66fc8fe08805 | [
"Apache-2.0"
] | 142 | 2017-03-07T15:57:02.000Z | 2018-02-27T14:01:45.000Z | src/blockchain/ethereum/signature.rs | ethereumproject/emerald-rs | f4e7c36813094129b3b2364edf2b66fc8fe08805 | [
"Apache-2.0"
] | 17 | 2017-02-23T14:43:37.000Z | 2017-11-05T20:18:00.000Z | /*
Copyright 2019 ETCDEV GmbH
Copyright 2020 EmeraldPay, 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.
*/
//! # Account ECDSA signatures using the SECG curve secp256k1
use super::{EthereumAddress};
use crate::{convert::error::ConversionError, error::VaultError, trim_bytes, util::{keccak256, to_arr, KECCAK256_BYTES}};
use hex;
use rand::{rngs::OsRng, Rng};
use secp256k1::{
key::{PublicKey, SecretKey},
Message,
Secp256k1,
SignOnly,
};
use std::{convert::TryFrom, fmt, ops, str};
use rlp::RlpStream;
use crate::chains::EthereumChainId;
/// Private key length in bytes
pub const PRIVATE_KEY_BYTES: usize = 32;
/// ECDSA crypto signature length in bytes
pub const ECDSA_SIGNATURE_BYTES: usize = 65;
lazy_static! {
static ref ECDSA: Secp256k1<SignOnly> = Secp256k1::signing_only();
}
/// Transaction sign data (see Appendix F. "Signing Transactions" from Yellow Paper)
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EthereumBasicSignature {
/// ‘recovery id’, a 1 byte value specifying the sign and finiteness of the curve point
pub v: u8,
/// ECDSA signature first point (0 < r < secp256k1n)
pub r: [u8; 32],
/// ECDSA signature second point (0 < s < secp256k1n ÷ 2 + 1)
pub s: [u8; 32],
}
///
/// Signature for EIP-2930 type of transactions
///
/// See: https://eips.ethereum.org/EIPS/eip-2930
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EthereumEIP2930Signature {
/// Y-coord bit on the curve
pub y_parity: u8,
/// ECDSA signature first point (0 < r < secp256k1n)
pub r: [u8; 32],
/// ECDSA signature second point (0 < s < secp256k1n ÷ 2 + 1)
pub s: [u8; 32],
}
pub trait EthereumSignature {
///
/// Append the signature to an rlp-encoded transaction
fn append_to_rlp(&self, chain: EthereumChainId, rlp: &mut RlpStream);
}
impl EthereumSignature for EthereumBasicSignature {
fn append_to_rlp(&self, chain_id: EthereumChainId, rlp: &mut RlpStream) {
let mut v = u16::from(self.v);
// [Simple replay attack protection](https://github.com/ethereum/eips/issues/155)
// Can be already applied by HD wallet.
// TODO: refactor to avoid this check
let stamp = u16::from(chain_id.as_chainid() * 2 + 35 - 27);
if v + stamp <= 0xff {
v += stamp;
}
rlp.append(&(v as u8));
rlp.append(&trim_bytes(&self.r[..]));
rlp.append(&trim_bytes(&self.s[..]));
}
}
impl EthereumSignature for EthereumEIP2930Signature {
fn append_to_rlp(&self, _chain: EthereumChainId, rlp: &mut RlpStream) {
rlp.append(&self.y_parity);
rlp.append(&trim_bytes(&self.r[..]));
rlp.append(&trim_bytes(&self.s[..]));
}
}
impl From<[u8; ECDSA_SIGNATURE_BYTES]> for EthereumBasicSignature {
fn from(data: [u8; ECDSA_SIGNATURE_BYTES]) -> Self {
let mut sign = EthereumBasicSignature::default();
sign.v = data[0];
sign.r.copy_from_slice(&data[1..(1 + 32)]);
sign.s.copy_from_slice(&data[(1 + 32)..(1 + 32 + 32)]);
sign
}
}
impl Into<(u8, [u8; 32], [u8; 32])> for EthereumBasicSignature {
fn into(self) -> (u8, [u8; 32], [u8; 32]) {
(self.v, self.r, self.s)
}
}
impl Into<String> for EthereumBasicSignature {
fn into(self) -> String {
format!(
"0x{:X}{}{}",
self.v,
hex::encode(self.r),
hex::encode(self.s)
)
}
}
/// Private key used as x in an ECDSA signature
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct EthereumPrivateKey(pub [u8; PRIVATE_KEY_BYTES]);
impl EthereumPrivateKey {
/// Generate a new `PrivateKey` at random (`rand::OsRng`)
pub fn gen() -> Self {
Self::gen_custom(&mut OsRng::new().expect("Randomness is not ready"))
}
/// Generate a new `PrivateKey` with given custom random generator
pub fn gen_custom<R: Rng + ?Sized + secp256k1::rand::RngCore>(rng: &mut R) -> Self {
EthereumPrivateKey::from(SecretKey::new(rng))
}
/// Extract `Address` from current private key.
pub fn to_address(self) -> EthereumAddress {
let key = PublicKey::from_secret_key(&ECDSA, &self.into());
EthereumAddress::from(key)
}
/// Sign hash from message (Keccak-256)
pub fn sign_hash<S>(&self, hash: [u8; KECCAK256_BYTES]) -> Result<S, VaultError> where S: SignatureMaker<S> {
let msg = Message::from_slice(&hash)?;
let key = SecretKey::from_slice(self)?;
S::sign(msg, key)
}
}
pub trait SignatureMaker<T> {
fn sign(msg: Message, sk: SecretKey) -> Result<T, VaultError>;
}
impl SignatureMaker<EthereumBasicSignature> for EthereumBasicSignature {
fn sign(msg: Message, sk: SecretKey) -> Result<EthereumBasicSignature, VaultError> {
let s = ECDSA.sign_recoverable(&msg, &sk);
let (rid, sig) = s.serialize_compact();
let mut buf = [0u8; ECDSA_SIGNATURE_BYTES];
buf[0] = (rid.to_i32() + 27) as u8;
buf[1..65].copy_from_slice(&sig[0..64]);
Ok(EthereumBasicSignature::from(buf))
}
}
impl SignatureMaker<EthereumEIP2930Signature> for EthereumEIP2930Signature {
fn sign(msg: Message, sk: SecretKey) -> Result<EthereumEIP2930Signature, VaultError> {
let s = ECDSA.sign_recoverable(&msg, &sk);
let (rid, sig) = s.serialize_compact();
let mut buf = [0u8; ECDSA_SIGNATURE_BYTES];
buf[0] = (rid.to_i32() + 27) as u8;
buf[1..65].copy_from_slice(&sig[0..64]);
let mut r = [0u8; 32];
r.copy_from_slice(&sig[0..32]);
let mut s = [0u8; 32];
s.copy_from_slice(&sig[32..64]);
let sig = EthereumEIP2930Signature {
y_parity: rid.to_i32() as u8,
r, s
};
if sig.y_parity > 1 {
// technically it's y-coord side, so can have only two possible values.
// if we've got something different we did something completely wrong
panic!("y_parity can be only 0 or 1. Found: {:}", sig.y_parity)
}
Ok(sig)
}
}
impl ops::Deref for EthereumPrivateKey {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<[u8; PRIVATE_KEY_BYTES]> for EthereumPrivateKey {
fn from(bytes: [u8; PRIVATE_KEY_BYTES]) -> Self {
EthereumPrivateKey(bytes)
}
}
impl From<SecretKey> for EthereumPrivateKey {
fn from(key: SecretKey) -> Self {
EthereumPrivateKey(to_arr(&key[0..PRIVATE_KEY_BYTES]))
}
}
impl Into<SecretKey> for EthereumPrivateKey {
fn into(self) -> SecretKey {
SecretKey::from_slice(&self).expect("Expect secret key")
}
}
impl TryFrom<&[u8]> for EthereumPrivateKey {
type Error = VaultError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
if value.len() != PRIVATE_KEY_BYTES {
return Err(VaultError::InvalidPrivateKey);
}
Ok(EthereumPrivateKey(to_arr(value)))
}
}
impl str::FromStr for EthereumPrivateKey {
type Err = VaultError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != PRIVATE_KEY_BYTES * 2 && !s.starts_with("0x") {
return Err(VaultError::ConversionError(ConversionError::InvalidLength));
}
let value = if s.starts_with("0x") {
s.split_at(2).1
} else {
s
};
EthereumPrivateKey::try_from(hex::decode(&value)?.as_slice())
}
}
impl fmt::Display for EthereumPrivateKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "0x{}", hex::encode(self.0))
}
}
fn message_hash(msg: &str) -> [u8; KECCAK256_BYTES] {
bytes_hash(msg.as_bytes())
}
fn bytes_hash(data: &[u8]) -> [u8; KECCAK256_BYTES] {
let mut v = prefix(data).into_bytes();
v.extend_from_slice(data);
keccak256(&v)
}
/// [internal/ethapi: add personal sign method](https://github.com/ethereum/go-ethereum/pull/2940)
fn prefix(data: &[u8]) -> String {
format!("\x19Ethereum Signed Message:\x0a{}", data.len())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::*;
#[test]
fn should_convert_into_address() {
let key = EthereumPrivateKey(to_32bytes(
"00b413b37c71bfb92719d16e28d7329dea5befa0d0b8190742f89e55617991cf",
));
assert_eq!(
key.to_address().to_string(),
"0x3f4e0668c20e100d7c2a27d4b177ac65b2875d26"
);
}
#[test]
fn should_sign_hash() {
let key = EthereumPrivateKey(to_32bytes(
"3c9229289a6125f7fdf1885a77bb12c37a8d3b4962d936f7e3084dece32a3ca1",
));
let s = key
.sign_hash::<EthereumBasicSignature>(to_32bytes(
"82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28",
))
.unwrap();
assert_eq!(s.v, 27);
assert_eq!(
s.r,
to_32bytes("99e71a99cb2270b8cac5254f9e99b6210c6c10224a1579cf389ef88b20a1abe9",)
);
assert_eq!(
s.s,
to_32bytes("129ff05af364204442bdb53ab6f18a99ab48acc9326fa689f228040429e3ca66",)
);
}
#[test]
fn should_calculate_message_hash() {
assert_eq!(
message_hash("Hello world"),
to_32bytes("8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede",)
);
}
#[test]
fn sign_eip2930() {
let key = to_32bytes(
"4646464646464646464646464646464646464646464646464646464646464646",
);
let hash = to_32bytes("57c3588c6ef4be66e68464a5364cef58fe154f57b2ff8d8d89909ac10cd0527b");
let sig = EthereumEIP2930Signature::sign(
Message::from_slice(hash.as_ref()).unwrap(), SecretKey::from_slice(key.as_ref()).unwrap()
);
assert!(sig.is_ok());
let sig = sig.unwrap();
assert_eq!(sig.y_parity, 1);
assert_eq!(hex::encode(sig.r), "38c8eb279a4b6c4b806258389e1b5906b28418e3eff9e0fc81173f54fa37a255");
assert_eq!(hex::encode(sig.s), "3acaa2b6d5e4edb561b918b4cb49cf1dbae9972ca90df7af6364598353a2c125");
}
#[test]
fn sign_eip2930_2() {
let key = to_32bytes(
"4646464646464646464646464646464646464646464646464646464646464646",
);
let hash = to_32bytes("aef1156bbd124793e5d76bdf9fe9464e9ef79f2432abbaf0385e57e8ae8e8d5c");
let sig = EthereumEIP2930Signature::sign(
Message::from_slice(hash.as_ref()).unwrap(), SecretKey::from_slice(key.as_ref()).unwrap()
);
assert!(sig.is_ok());
let sig = sig.unwrap();
assert_eq!(sig.y_parity, 0);
assert_eq!(hex::encode(sig.r), "b935047bf9b8464afec5bda917281610b2aaabd8de4b01d2eba6e876c934ca7a");
assert_eq!(hex::encode(sig.s), "431b406eb13aefca05a0320c3595700b9375df6fac8cc8ec5603ac2e42af4894");
}
#[test]
fn sign_eip2930_3() {
let key = to_32bytes(
"4646464646464646464646464646464646464646464646464646464646464646",
);
let hash = to_32bytes("68fe011ba5be4a03369d51810e7943abab15fbaf757f9296711558aee8ab772b");
let sig = EthereumEIP2930Signature::sign(
Message::from_slice(hash.as_ref()).unwrap(), SecretKey::from_slice(key.as_ref()).unwrap()
);
assert!(sig.is_ok());
let sig = sig.unwrap();
assert_eq!(sig.y_parity, 1);
assert_eq!(hex::encode(sig.r), "f0b3347ec48e78bf5ef6075b332334518ebc2f90d2bf0fea080623179936382e");
assert_eq!(hex::encode(sig.s), "5c58c5beeafb2398d5e79b40b320421112a9672167f27e7fc55e76d2d7d11062");
}
}
| 31.905263 | 120 | 0.637496 |
774ae712a30456492ba393902719c6bca5fd9b83 | 862 | html | HTML | index.html | Numulix/charizards | b563cc86040e6d2a9db8268c1ed3b9144014a853 | [
"MIT"
] | null | null | null | index.html | Numulix/charizards | b563cc86040e6d2a9db8268c1ed3b9144014a853 | [
"MIT"
] | null | null | null | index.html | Numulix/charizards | b563cc86040e6d2a9db8268c1ed3b9144014a853 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="style.css">
<title>Charizard Cards</title>
<style>
body {
font-family: sans-serif;
}
#cards {
display: flex;
flex-wrap: wrap;
width: 90%;
margin: 0 auto;
justify-content: space-between;
}
img {
margin: 1rem;
}
</style>
</head>
<body>
<form>
<label for="poke-name">Search Pokemon cards:</label>
<input type="text" id="search-term" name="search-term">
<button type="submit">Search</button>
</form>
<div id="cards"></div>
<script src="app.js"></script>
</body>
</html> | 24.628571 | 103 | 0.610209 |
5b2843e89509622acf94a13619ed38aa387c84df | 24,377 | sql | SQL | sql/update0526.sql | liurunkaiGit/asset | ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff | [
"MIT"
] | null | null | null | sql/update0526.sql | liurunkaiGit/asset | ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff | [
"MIT"
] | 3 | 2021-02-03T19:36:18.000Z | 2021-09-20T21:00:33.000Z | sql/update0526.sql | liurunkaiGit/asset | ab49be8ce1700d23ebf8ba3492a7bdd1c87bbcff | [
"MIT"
] | 1 | 2020-11-24T01:06:00.000Z | 2020-11-24T01:06:00.000Z | alter table cur_assets_package drop column twentyFourCD;
alter table cur_assets_package drop column BLK;
alter table cur_assets_package drop column productLine;
alter table cur_assets_package drop column rmb_last_jkje;
alter table cur_assets_package drop column rmb_cd;
alter table cur_assets_package drop column rmb_zhycjkr;
alter table cur_assets_package drop column rmb_zhhkbs;
alter table cur_assets_package drop column rmb_yhbj1;
alter table cur_assets_package drop column rmb_yhbj2;
alter table cur_assets_package drop column rmb_yhfx1;
alter table cur_assets_package drop column rmb_yhfx2;
alter table cur_assets_package drop column rmb_yhfy1;
alter table cur_assets_package drop column rmb_yhfy2;
alter table cur_assets_package drop column rmb_gded;
alter table cur_assets_package drop column code;
alter table cur_assets_package drop column zx_type;
alter table cur_assets_package drop column stop_card;
alter table cur_assets_package drop column stop_jxrq;
alter table cur_assets_package drop column cs_company;
alter table cur_assets_package drop column gz_flag;
alter table cur_assets_package drop column fq_flag;
alter table cur_assets_package drop column syhx_qtfy;
alter table cur_assets_package drop column syhx_sxf;
alter table cur_assets_package drop column syhx_bj;
alter table cur_assets_package drop column syhx_znf;
alter table cur_assets_package drop column syhx_yqx;
alter table cur_assets_package drop column syhx_jehj;
alter table cur_assets_package drop column cs_remark_his;
alter table cur_assets_package drop column csjggs_his;
alter table cur_assets_package drop column qx_flag;
alter table cur_assets_package drop column st_company;
alter table cur_assets_package drop column accept_firm;
alter table cur_assets_package drop column accept_city;
alter table cur_assets_package drop column accept_wd;
alter table cur_assets_package drop column accept_wd_code;
alter table cur_assets_package drop column dzhxrq;
alter table cur_assets_package drop column remark;
alter table cur_assets_package drop column wb_yhfxze;
alter table cur_assets_package drop column wb_yhlxze;
alter table cur_assets_package drop column wb_yhbj1;
alter table cur_assets_package drop column wb_yhbj2;
alter table cur_assets_package drop column wb_yhbjzje;
alter table cur_assets_package drop column wb_yhfx1;
alter table cur_assets_package drop column wb_yhfx2;
alter table cur_assets_package drop column wb_yhfy1;
alter table cur_assets_package drop column wb_yhfy2;
alter table cur_assets_package drop column wb_yhfyze;
alter table cur_assets_package drop column wb_zdyhe;
alter table cur_assets_package drop column wb_qkzje;
alter table cur_assets_package drop column tx_flag;
alter table cur_assets_package drop column ww_company_code;
alter table cur_assets_package drop column ww_jh_enddate;
alter table cur_assets_package drop column ww_qsrq;
alter table cur_assets_package drop column ww_pc;
alter table cur_assets_package drop column bill_address_postcode;
alter table cur_assets_package drop column yhk_date;
alter table cur_assets_package drop column start_yq_date;
alter table cur_assets_package drop column kh_date;
alter table cur_assets_package drop column ts_flag;
alter table cur_assets_package drop column credit_value;
alter table cur_assets_package drop column tj_city;
alter table cur_assets_package drop column shhx_sxf;
alter table cur_assets_package drop column shhx_bj;
alter table cur_assets_package drop column shhx_znf;
alter table cur_assets_package drop column shhx_fy;
alter table cur_assets_package drop column shhx_yqx;
alter table cur_assets_package drop column shhx_jehj;
alter table cur_assets_package drop column zh_30_day;
alter table cur_assets_package drop column zh_x_day;
alter table cur_assets_package drop column is_zc;
alter table cur_assets_package drop column is_zwcz;
alter table cur_assets_package drop column is_jx;
alter table cur_assets_package drop column is_sx;
alter table cur_assets_package drop column zjyq_month;
alter table cur_assets_package drop column hx_sxfcs;
alter table cur_assets_package drop column hx_shzt;
alter table cur_assets_package drop column hx_bjcs;
alter table cur_assets_package drop column hx_znfcs;
alter table cur_assets_package drop column hx_fycs;
alter table cur_assets_package drop column hx_yqlxcs;
alter table cur_assets_package drop column hx_jehjcs;
alter table cur_assets_package drop column aj_hz_date;
alter table cur_assets_package drop column xfjzzh;
alter table cur_assets_package drop column tsaj_type;
alter table cur_assets_package drop column tj_date;
alter table cur_assets_package drop column dollar_ye;
alter table cur_assets_package drop column dollar_CD;
alter table cur_assets_package drop column dollar_zdyjkje;
alter table cur_assets_package drop column dollar_zhycjkr;
alter table cur_assets_package drop column dollar_zhycjkje;
alter table cur_assets_package drop column dollar_hkrhkbs;
alter table cur_assets_package drop column hkfs;
alter table cur_assets_package drop column hkqd;
alter table cur_assets_package drop column xwpf;
alter table cur_assets_package drop column account_yebj;
alter table cur_assets_package drop column account_jqrq;
alter table cur_assets_package drop column fzzb;
alter table cur_assets_package drop column revert_card_no;
alter table cur_assets_package drop column revert_card_blank;
alter table cur_assets_package drop column jjqd;
alter table cur_assets_package drop column overdue_flag;
alter table cur_assets_package drop column cwcs;
alter table cur_assets_package drop column quota_product;
alter table cur_assets_package drop column quota_code;
alter table cur_assets_package drop column quota_date;
alter table cur_assets_package drop column risk;
alter table cur_assets_package drop column first_fk_date;
alter table cur_assets_package drop column certificate_type;
alter table cur_assets_package drop column birthday;
alter table cur_assets_package drop column city;
alter table cur_assets_package drop column economy;
alter table cur_assets_package drop column cur_income;
alter table cur_assets_package drop column new_address;
alter table cur_assets_package drop column customer_no;
alter table cur_assets_package drop column customer_home_postcode;
alter table cur_assets_package drop column card_post_address;
alter table cur_assets_package drop column job;
alter table cur_assets_package drop column dept_name;
alter table cur_assets_package drop column indust;
alter table cur_assets_package drop column work_postcode;
alter table cur_assets_package drop column sjrq;
alter table cur_assets_package drop column hth ;
alter table cur_assets_package drop column jjh ;
alter table cur_assets_package drop column dqsyb_yj;
alter table cur_assets_package drop column dqsyb_ej;
alter table cur_assets_package drop column csjd;
alter table cur_assets_package drop column wbjb;
alter table cur_assets_package drop column ys_khjlmc ;
alter table cur_assets_package drop column khjlmc ;
alter table cur_assets_package drop column xfldycpmc;
alter table cur_assets_package drop column qxrq;
alter table cur_assets_package drop column dqrq;
alter table cur_assets_package drop column dkye;
alter table cur_assets_package drop column wbbs ;
alter table cur_assets_package drop column yqje;
alter table cur_assets_package drop column yqbj;
alter table cur_assets_package drop column yqlx;
alter table cur_assets_package drop column yqsxf;
alter table cur_assets_package drop column qdmc;
alter table cur_assets_package drop column wbsb;
alter table cur_assets_package drop column wbqs;
alter table cur_assets_package drop column fpsj;
alter table cur_assets_package drop column Expand1;
alter table cur_assets_package drop column Expand2;
alter table cur_assets_package drop column Expand3;
alter table cur_assets_package drop column Expand4;
alter table cur_assets_package drop column Expand5;
alter table cur_assets_package drop column Expand6;
alter table cur_assets_package drop column Expand7;
alter table cur_assets_package drop column Expand8;
alter table cur_assets_package drop column Expand9;
alter table cur_assets_package drop column Expand10;
alter table cur_assets_package drop column Expand11;
alter table cur_assets_package drop column Expand12;
alter table cur_assets_package drop column Expand13;
alter table cur_assets_package drop column Expand14;
alter table cur_assets_package drop column Expand15;
alter table cur_assets_package drop column Expand16;
alter table cur_assets_package drop column Expand17;
alter table cur_assets_package drop column Expand18;
alter table cur_assets_package drop column Expand19;
alter table cur_assets_package drop column Expand20;
alter table cur_assets_package add column account_age varchar(64) DEFAULT NULL COMMENT '账龄';
alter table cur_assets_package add column la_flag varchar(20) DEFAULT NULL COMMENT '留案标签';
alter table cur_assets_package add column fx_flag varchar(20) DEFAULT NULL COMMENT '风险标签';
alter table cur_assets_package add column htlx varchar(20) DEFAULT NULL COMMENT '合同类型';
alter table cur_assets_package add column jmbq varchar(20) DEFAULT NULL COMMENT '减免标签';
alter table cur_assets_package add column fcbq varchar(20) DEFAULT NULL COMMENT '法催标签';
alter table cur_assets_package add column fxsfbh varchar(20) DEFAULT NULL COMMENT '罚息是否变化';
alter table cur_assets_package add column remark varchar(255) DEFAULT NULL COMMENT '备注';
alter table cur_assets_package add column tar date DEFAULT NULL COMMENT '退案日';
alter table cur_assets_package add column jkrq date DEFAULT NULL COMMENT '借款日期';
alter table cur_assets_package add column zhychkr date DEFAULT NULL COMMENT '最近一次还款日';
alter table cur_assets_package add column mqhkje decimal(20,2) DEFAULT NULL COMMENT '每期还款金额';
alter table cur_assets_package add column dqqkje decimal(20,2) DEFAULT NULL COMMENT '当期欠款金额';
alter table cur_assets_package add column ljyhje decimal(20,2) DEFAULT NULL COMMENT '累计已还金额';
alter table cur_assets_package add column sfje decimal(20,2) DEFAULT NULL COMMENT '首付金额';
alter table cur_assets_package add column zdhkzh1 varchar(64) DEFAULT NULL COMMENT '指定还款账号1';
alter table cur_assets_package add column zdhkzh2 varchar(64) DEFAULT NULL COMMENT '指定还款账号2';
alter table cur_assets_package add column zdhkzhhm1 varchar(64) DEFAULT NULL COMMENT '指定还款账户户名1';
alter table cur_assets_package add column zdhkzhhm2 varchar(64) DEFAULT NULL COMMENT '指定还款账户户名2';
alter table cur_assets_package add column zdhkqd1 varchar(64) DEFAULT NULL COMMENT '指定还款渠道1';
alter table cur_assets_package add column zdhkqd2 varchar(64) DEFAULT NULL COMMENT '指定还款渠道2';
alter table cur_assets_package add column khmb varchar(64) DEFAULT NULL COMMENT '考核目标';
alter table cur_assets_package add column spjg decimal(20,2) DEFAULT NULL COMMENT '商品价格';
alter table cur_assets_package add column dklx varchar(20) DEFAULT NULL COMMENT '贷款类型';
alter table cur_assets_package add column jkbs varchar(20) DEFAULT NULL COMMENT '借款笔数';
alter table cur_assets_package add column spxx varchar(128) DEFAULT NULL COMMENT '商品信息';
alter table cur_assets_package add column wacs varchar(20) DEFAULT NULL COMMENT '委案次数';
alter table cur_assets_package add column ykqs varchar(20) DEFAULT NULL COMMENT '已还期数';
alter table cur_assets_package add column work_dept varchar(64) DEFAULT NULL COMMENT '工作部门';
alter table cur_assets_package add column customer_mobile2 varchar(64) DEFAULT NULL COMMENT '客户电话2';
alter table cur_assets_package add column customer_mobile3 varchar(64) DEFAULT NULL COMMENT '客户电话3';
alter table cur_assets_package add column customer_mobile4 varchar(64) DEFAULT NULL COMMENT '客户电话4';
alter table cur_assets_package add column fourth_liaison_name varchar(64) DEFAULT NULL COMMENT '联系人4姓名';
alter table cur_assets_package add column fourth_liaison_relation varchar(64) DEFAULT NULL COMMENT '联系人4关系';
alter table cur_assets_package add column fourth_liaison_mobile varchar(64) DEFAULT NULL COMMENT '联系人4电话';
alter table cur_assets_package add column fifth_liaison_name varchar(64) DEFAULT NULL COMMENT '联系人5姓名';
alter table cur_assets_package add column fifth_liaison_relation varchar(64) DEFAULT NULL COMMENT '联系人5关系';
alter table cur_assets_package add column fifth_liaison_mobile varchar(64) DEFAULT NULL COMMENT '联系人5电话';
alter table cur_assets_package_temp drop column twentyFourCD;
alter table cur_assets_package_temp drop column BLK;
alter table cur_assets_package_temp drop column productLine;
alter table cur_assets_package_temp drop column rmb_last_jkje;
alter table cur_assets_package_temp drop column rmb_cd;
alter table cur_assets_package_temp drop column rmb_zhycjkr;
alter table cur_assets_package_temp drop column rmb_zhhkbs;
alter table cur_assets_package_temp drop column rmb_yhbj1;
alter table cur_assets_package_temp drop column rmb_yhbj2;
alter table cur_assets_package_temp drop column rmb_yhfx1;
alter table cur_assets_package_temp drop column rmb_yhfx2;
alter table cur_assets_package_temp drop column rmb_yhfy1;
alter table cur_assets_package_temp drop column rmb_yhfy2;
alter table cur_assets_package_temp drop column rmb_gded;
alter table cur_assets_package_temp drop column code;
alter table cur_assets_package_temp drop column zx_type;
alter table cur_assets_package_temp drop column stop_card;
alter table cur_assets_package_temp drop column stop_jxrq;
alter table cur_assets_package_temp drop column cs_company;
alter table cur_assets_package_temp drop column gz_flag;
alter table cur_assets_package_temp drop column fq_flag;
alter table cur_assets_package_temp drop column syhx_qtfy;
alter table cur_assets_package_temp drop column syhx_sxf;
alter table cur_assets_package_temp drop column syhx_bj;
alter table cur_assets_package_temp drop column syhx_znf;
alter table cur_assets_package_temp drop column syhx_yqx;
alter table cur_assets_package_temp drop column syhx_jehj;
alter table cur_assets_package_temp drop column cs_remark_his;
alter table cur_assets_package_temp drop column csjggs_his;
alter table cur_assets_package_temp drop column qx_flag;
alter table cur_assets_package_temp drop column st_company;
alter table cur_assets_package_temp drop column accept_firm;
alter table cur_assets_package_temp drop column accept_city;
alter table cur_assets_package_temp drop column accept_wd;
alter table cur_assets_package_temp drop column accept_wd_code;
alter table cur_assets_package_temp drop column dzhxrq;
alter table cur_assets_package_temp drop column remark;
alter table cur_assets_package_temp drop column wb_yhfxze;
alter table cur_assets_package_temp drop column wb_yhlxze;
alter table cur_assets_package_temp drop column wb_yhbj1;
alter table cur_assets_package_temp drop column wb_yhbj2;
alter table cur_assets_package_temp drop column wb_yhbjzje;
alter table cur_assets_package_temp drop column wb_yhfx1;
alter table cur_assets_package_temp drop column wb_yhfx2;
alter table cur_assets_package_temp drop column wb_yhfy1;
alter table cur_assets_package_temp drop column wb_yhfy2;
alter table cur_assets_package_temp drop column wb_yhfyze;
alter table cur_assets_package_temp drop column wb_zdyhe;
alter table cur_assets_package_temp drop column wb_qkzje;
alter table cur_assets_package_temp drop column tx_flag;
alter table cur_assets_package_temp drop column ww_company_code;
alter table cur_assets_package_temp drop column ww_jh_enddate;
alter table cur_assets_package_temp drop column ww_qsrq;
alter table cur_assets_package_temp drop column ww_pc;
alter table cur_assets_package_temp drop column bill_address_postcode;
alter table cur_assets_package_temp drop column yhk_date;
alter table cur_assets_package_temp drop column start_yq_date;
alter table cur_assets_package_temp drop column kh_date;
alter table cur_assets_package_temp drop column ts_flag;
alter table cur_assets_package_temp drop column credit_value;
alter table cur_assets_package_temp drop column tj_city;
alter table cur_assets_package_temp drop column shhx_sxf;
alter table cur_assets_package_temp drop column shhx_bj;
alter table cur_assets_package_temp drop column shhx_znf;
alter table cur_assets_package_temp drop column shhx_fy;
alter table cur_assets_package_temp drop column shhx_yqx;
alter table cur_assets_package_temp drop column shhx_jehj;
alter table cur_assets_package_temp drop column zh_30_day;
alter table cur_assets_package_temp drop column zh_x_day;
alter table cur_assets_package_temp drop column is_zc;
alter table cur_assets_package_temp drop column is_zwcz;
alter table cur_assets_package_temp drop column is_jx;
alter table cur_assets_package_temp drop column is_sx;
alter table cur_assets_package_temp drop column zjyq_month;
alter table cur_assets_package_temp drop column hx_sxfcs;
alter table cur_assets_package_temp drop column hx_shzt;
alter table cur_assets_package_temp drop column hx_bjcs;
alter table cur_assets_package_temp drop column hx_znfcs;
alter table cur_assets_package_temp drop column hx_fycs;
alter table cur_assets_package_temp drop column hx_yqlxcs;
alter table cur_assets_package_temp drop column hx_jehjcs;
alter table cur_assets_package_temp drop column aj_hz_date;
alter table cur_assets_package_temp drop column xfjzzh;
alter table cur_assets_package_temp drop column tsaj_type;
alter table cur_assets_package_temp drop column tj_date;
alter table cur_assets_package_temp drop column dollar_ye;
alter table cur_assets_package_temp drop column dollar_CD;
alter table cur_assets_package_temp drop column dollar_zdyjkje;
alter table cur_assets_package_temp drop column dollar_zhycjkr;
alter table cur_assets_package_temp drop column dollar_zhycjkje;
alter table cur_assets_package_temp drop column dollar_hkrhkbs;
alter table cur_assets_package_temp drop column hkfs;
alter table cur_assets_package_temp drop column hkqd;
alter table cur_assets_package_temp drop column xwpf;
alter table cur_assets_package_temp drop column account_yebj;
alter table cur_assets_package_temp drop column account_jqrq;
alter table cur_assets_package_temp drop column fzzb;
alter table cur_assets_package_temp drop column revert_card_no;
alter table cur_assets_package_temp drop column revert_card_blank;
alter table cur_assets_package_temp drop column jjqd;
alter table cur_assets_package_temp drop column overdue_flag;
alter table cur_assets_package_temp drop column cwcs;
alter table cur_assets_package_temp drop column quota_product;
alter table cur_assets_package_temp drop column quota_code;
alter table cur_assets_package_temp drop column quota_date;
alter table cur_assets_package_temp drop column risk;
alter table cur_assets_package_temp drop column first_fk_date;
alter table cur_assets_package_temp drop column certificate_type;
alter table cur_assets_package_temp drop column birthday;
alter table cur_assets_package_temp drop column city;
alter table cur_assets_package_temp drop column economy;
alter table cur_assets_package_temp drop column cur_income;
alter table cur_assets_package_temp drop column new_address;
alter table cur_assets_package_temp drop column customer_no;
alter table cur_assets_package_temp drop column customer_home_postcode;
alter table cur_assets_package_temp drop column card_post_address;
alter table cur_assets_package_temp drop column job;
alter table cur_assets_package_temp drop column dept_name;
alter table cur_assets_package_temp drop column indust;
alter table cur_assets_package_temp drop column work_postcode;
alter table cur_assets_package_temp drop column sjrq;
alter table cur_assets_package_temp drop column hth ;
alter table cur_assets_package_temp drop column jjh ;
alter table cur_assets_package_temp drop column dqsyb_yj;
alter table cur_assets_package_temp drop column dqsyb_ej;
alter table cur_assets_package_temp drop column csjd;
alter table cur_assets_package_temp drop column wbjb;
alter table cur_assets_package_temp drop column ys_khjlmc ;
alter table cur_assets_package_temp drop column khjlmc ;
alter table cur_assets_package_temp drop column xfldycpmc;
alter table cur_assets_package_temp drop column qxrq;
alter table cur_assets_package_temp drop column dqrq;
alter table cur_assets_package_temp drop column dkye;
alter table cur_assets_package_temp drop column wbbs ;
alter table cur_assets_package_temp drop column yqje;
alter table cur_assets_package_temp drop column yqbj;
alter table cur_assets_package_temp drop column yqlx;
alter table cur_assets_package_temp drop column yqsxf;
alter table cur_assets_package_temp drop column qdmc;
alter table cur_assets_package_temp drop column wbsb;
alter table cur_assets_package_temp drop column wbqs;
alter table cur_assets_package_temp drop column fpsj;
alter table cur_assets_package_temp add column account_age varchar(64) DEFAULT NULL COMMENT '账龄';
alter table cur_assets_package_temp add column la_flag varchar(20) DEFAULT NULL COMMENT '留案标签';
alter table cur_assets_package_temp add column fx_flag varchar(20) DEFAULT NULL COMMENT '风险标签';
alter table cur_assets_package_temp add column htlx varchar(20) DEFAULT NULL COMMENT '合同类型';
alter table cur_assets_package_temp add column jmbq varchar(20) DEFAULT NULL COMMENT '减免标签';
alter table cur_assets_package_temp add column fcbq varchar(20) DEFAULT NULL COMMENT '法催标签';
alter table cur_assets_package_temp add column fxsfbh varchar(20) DEFAULT NULL COMMENT '罚息是否变化';
alter table cur_assets_package_temp add column remark varchar(255) DEFAULT NULL COMMENT '备注';
alter table cur_assets_package_temp add column tar varchar(64) DEFAULT NULL COMMENT '退案日';
alter table cur_assets_package_temp add column jkrq varchar(64) DEFAULT NULL COMMENT '借款日期';
alter table cur_assets_package_temp add column zhychkr varchar(64) DEFAULT NULL COMMENT '最近一次还款日';
alter table cur_assets_package_temp add column mqhkje varchar(64) DEFAULT NULL COMMENT '每期还款金额';
alter table cur_assets_package_temp add column dqqkje varchar(64) DEFAULT NULL COMMENT '当期欠款金额';
alter table cur_assets_package_temp add column ljyhje varchar(64) DEFAULT NULL COMMENT '累计已还金额';
alter table cur_assets_package_temp add column sfje varchar(64) DEFAULT NULL COMMENT '首付金额';
alter table cur_assets_package_temp add column zdhkzh1 varchar(64) DEFAULT NULL COMMENT '指定还款账号1';
alter table cur_assets_package_temp add column zdhkzh2 varchar(64) DEFAULT NULL COMMENT '指定还款账号2';
alter table cur_assets_package_temp add column zdhkzhhm1 varchar(64) DEFAULT NULL COMMENT '指定还款账户户名1';
alter table cur_assets_package_temp add column zdhkzhhm2 varchar(64) DEFAULT NULL COMMENT '指定还款账户户名2';
alter table cur_assets_package_temp add column zdhkqd1 varchar(64) DEFAULT NULL COMMENT '指定还款渠道1';
alter table cur_assets_package_temp add column zdhkqd2 varchar(64) DEFAULT NULL COMMENT '指定还款渠道2';
alter table cur_assets_package_temp add column khmb varchar(64) DEFAULT NULL COMMENT '考核目标';
alter table cur_assets_package_temp add column spjg varchar(64) DEFAULT NULL COMMENT '商品价格';
alter table cur_assets_package_temp add column dklx varchar(20) DEFAULT NULL COMMENT '贷款类型';
alter table cur_assets_package_temp add column jkbs varchar(20) DEFAULT NULL COMMENT '借款笔数';
alter table cur_assets_package_temp add column spxx varchar(128) DEFAULT NULL COMMENT '商品信息';
alter table cur_assets_package_temp add column wacs varchar(20) DEFAULT NULL COMMENT '委案次数';
alter table cur_assets_package_temp add column ykqs varchar(20) DEFAULT NULL COMMENT '已还期数';
alter table cur_assets_package_temp add column work_dept varchar(64) DEFAULT NULL COMMENT '工作部门';
alter table cur_assets_package_temp add column customer_mobile2 varchar(64) DEFAULT NULL COMMENT '客户电话2';
alter table cur_assets_package_temp add column customer_mobile3 varchar(64) DEFAULT NULL COMMENT '客户电话3';
alter table cur_assets_package_temp add column customer_mobile4 varchar(64) DEFAULT NULL COMMENT '客户电话4';
alter table cur_assets_package_temp add column fourth_liaison_name varchar(64) DEFAULT NULL COMMENT '联系人4姓名';
alter table cur_assets_package_temp add column fourth_liaison_relation varchar(64) DEFAULT NULL COMMENT '联系人4关系';
alter table cur_assets_package_temp add column fourth_liaison_mobile varchar(64) DEFAULT NULL COMMENT '联系人4电话';
alter table cur_assets_package_temp add column fifth_liaison_name varchar(64) DEFAULT NULL COMMENT '联系人5姓名';
alter table cur_assets_package_temp add column fifth_liaison_relation varchar(64) DEFAULT NULL COMMENT '联系人5关系';
alter table cur_assets_package_temp add column fifth_liaison_mobile varchar(64) DEFAULT NULL COMMENT '联系人5电话';
-- alter table t_lc_call_record add column agent_name varchar(64) DEFAULT NULL COMMENT '坐席名称';
| 61.558081 | 113 | 0.861099 |
479d1d749fd021c6b1903f82acf245e65aad0556 | 126 | ps1 | PowerShell | vs2017_testing/install_dotnet_35.ps1 | sparerd/vagrant | 85ddc2b7c66d707ba1e52cf5e8f2a114fcbd0d83 | [
"MIT"
] | null | null | null | vs2017_testing/install_dotnet_35.ps1 | sparerd/vagrant | 85ddc2b7c66d707ba1e52cf5e8f2a114fcbd0d83 | [
"MIT"
] | null | null | null | vs2017_testing/install_dotnet_35.ps1 | sparerd/vagrant | 85ddc2b7c66d707ba1e52cf5e8f2a114fcbd0d83 | [
"MIT"
] | null | null | null | # To be PS 2.0 compatible, dont use Invoke-WebRequest
Import-Module ServerManager
Add-WindowsFeature "NET-Framework-Features" | 31.5 | 53 | 0.81746 |
6dd564329a7a4f8721f33c03fa6b131901031af5 | 49 | kt | Kotlin | app/src/main/java/in/ceeq/lyte/data/FirebaseRepo.kt | rachitmishra/lyte | b966e705440ce46384fd709839c587c2e6aba216 | [
"MIT"
] | null | null | null | app/src/main/java/in/ceeq/lyte/data/FirebaseRepo.kt | rachitmishra/lyte | b966e705440ce46384fd709839c587c2e6aba216 | [
"MIT"
] | null | null | null | app/src/main/java/in/ceeq/lyte/data/FirebaseRepo.kt | rachitmishra/lyte | b966e705440ce46384fd709839c587c2e6aba216 | [
"MIT"
] | null | null | null | package `in`.ceeq.lyte.data
object FirebaseRepo
| 12.25 | 27 | 0.795918 |
fae34c4b28667753350406745064ae583c587d2a | 15,155 | sql | SQL | database/database.sql | LIARALab/java-activity-recognition-platform | 73366bd3b423554c958b1ec807dfd19f04ca03f9 | [
"MIT"
] | null | null | null | database/database.sql | LIARALab/java-activity-recognition-platform | 73366bd3b423554c958b1ec807dfd19f04ca03f9 | [
"MIT"
] | null | null | null | database/database.sql | LIARALab/java-activity-recognition-platform | 73366bd3b423554c958b1ec807dfd19f04ca03f9 | [
"MIT"
] | null | null | null | -- MySQL dump 10.13 Distrib 8.0.12, for Linux (x86_64)
--
-- Host: localhost Database: sapa
-- ------------------------------------------------------
-- Server version 8.0.12
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8mb4 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `nodes`
--
DROP TABLE IF EXISTS `nodes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `nodes` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`depth` int(11) NOT NULL,
`set_end` int(11) NOT NULL,
`set_start` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `nodes`
--
LOCK TABLES `nodes` WRITE;
/*!40000 ALTER TABLE `nodes` DISABLE KEYS */;
/*!40000 ALTER TABLE `nodes` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sensors`
--
DROP TABLE IF EXISTS `sensors`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `sensors` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`configuration` varchar(255) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`node_identifier` bigint(20) NOT NULL,
`type` varchar(255) NOT NULL,
`unit` varchar(255) DEFAULT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sensors`
--
LOCK TABLES `sensors` WRITE;
/*!40000 ALTER TABLE `sensors` DISABLE KEYS */;
/*!40000 ALTER TABLE `sensors` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `state_correlations`
--
DROP TABLE IF EXISTS `state_correlations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `state_correlations` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`end_state_identifier` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`start_state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`),
CONSTRAINT `state_correlations_start_to_states` FOREIGN KEY (`start_state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `state_correlations_end_to_states` FOREIGN KEY (`end_state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `state_correlations`
--
LOCK TABLES `state_correlations` WRITE;
/*!40000 ALTER TABLE `state_correlations` DISABLE KEYS */;
/*!40000 ALTER TABLE `state_correlations` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states`
--
DROP TABLE IF EXISTS `states`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`emitted_at` datetime(6) NOT NULL,
`sensor_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`),
KEY `temporal_key` (`emitted_at` ASC),
KEY `reversed_temporal_key` (`emitted_at` DESC),
KEY `sensor_key` (`sensor_identifier` ASC),
CONSTRAINT `states_to_sensors` FOREIGN KEY (`sensor_identifier`) REFERENCES `sensors` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states`
--
LOCK TABLES `states` WRITE;
/*!40000 ALTER TABLE `states` DISABLE KEYS */;
/*!40000 ALTER TABLE `states` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_boolean`
--
DROP TABLE IF EXISTS `states_boolean`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_boolean` (
`value` bit(1) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_boolean_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_boolean`
--
LOCK TABLES `states_boolean` WRITE;
/*!40000 ALTER TABLE `states_boolean` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_boolean` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_byte`
--
DROP TABLE IF EXISTS `states_byte`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_byte` (
`value` tinyint(4) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_byte_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_byte`
--
LOCK TABLES `states_byte` WRITE;
/*!40000 ALTER TABLE `states_byte` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_byte` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_double`
--
DROP TABLE IF EXISTS `states_double`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_double` (
`value` double DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_double_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_double`
--
LOCK TABLES `states_double` WRITE;
/*!40000 ALTER TABLE `states_double` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_double` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_float`
--
DROP TABLE IF EXISTS `states_float`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_float` (
`value` float DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_float_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_float`
--
LOCK TABLES `states_float` WRITE;
/*!40000 ALTER TABLE `states_float` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_float` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_integer`
--
DROP TABLE IF EXISTS `states_integer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_integer` (
`value` int(11) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_integer_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_integer`
--
LOCK TABLES `states_integer` WRITE;
/*!40000 ALTER TABLE `states_integer` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_integer` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_label`
--
DROP TABLE IF EXISTS `states_label`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_label` (
`end` datetime(6) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`start` datetime(6) NOT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_label_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_label`
--
LOCK TABLES `states_label` WRITE;
/*!40000 ALTER TABLE `states_label` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_label` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_long`
--
DROP TABLE IF EXISTS `states_long`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_long` (
`value` bigint(20) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_long_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_long`
--
LOCK TABLES `states_long` WRITE;
/*!40000 ALTER TABLE `states_long` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_long` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_short`
--
DROP TABLE IF EXISTS `states_short`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_short` (
`value` smallint(6) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_short_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_short`
--
LOCK TABLES `states_short` WRITE;
/*!40000 ALTER TABLE `states_short` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_short` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_string`
--
DROP TABLE IF EXISTS `states_string`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_string` (
`value` varchar(255) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`),
CONSTRAINT `states_string_to_states` FOREIGN KEY (`state_identifier`) REFERENCES `states` (`identifier`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_string`
--
LOCK TABLES `states_string` WRITE;
/*!40000 ALTER TABLE `states_string` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_string` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `states_values`
--
DROP TABLE IF EXISTS `states_values`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `states_values` (
`value` int(11) DEFAULT NULL,
`state_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`state_identifier`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `states_values`
--
LOCK TABLES `states_values` WRITE;
/*!40000 ALTER TABLE `states_values` DISABLE KEYS */;
/*!40000 ALTER TABLE `states_values` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `tag_relations`
--
DROP TABLE IF EXISTS `tag_relations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `tag_relations` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`entity_identifier` bigint(20) NOT NULL,
`entity_type` varchar(255) NOT NULL,
`tag_identifier` bigint(20) NOT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `tag_relations`
--
LOCK TABLES `tag_relations` WRITE;
/*!40000 ALTER TABLE `tag_relations` DISABLE KEYS */;
/*!40000 ALTER TABLE `tag_relations` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `tags`
--
DROP TABLE IF EXISTS `tags`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `tags` (
`identifier` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`deleted_at` datetime(6) DEFAULT NULL,
`uuid` varchar(255) NOT NULL,
`updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
`name` varchar(255) NOT NULL,
PRIMARY KEY (`identifier`),
UNIQUE KEY `uuid_key` (`uuid`),
UNIQUE KEY `name_key` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `tags`
--
LOCK TABLES `tags` WRITE;
/*!40000 ALTER TABLE `tags` DISABLE KEYS */;
/*!40000 ALTER TABLE `tags` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-04-17 16:57:27 | 33.307692 | 160 | 0.732102 |
6b2b2f528e79dd12cf7b5de90fef7a90b7f1619f | 684 | html | HTML | app/views/strata-odcudzenie/op/docasny.html | pomali/navody-prototype-kit | 98641cb6d10fec5affab4e2978afe3f09609f9ce | [
"MIT"
] | null | null | null | app/views/strata-odcudzenie/op/docasny.html | pomali/navody-prototype-kit | 98641cb6d10fec5affab4e2978afe3f09609f9ce | [
"MIT"
] | 4 | 2018-12-01T17:55:27.000Z | 2022-02-13T23:42:12.000Z | app/views/strata-odcudzenie/op/docasny.html | pomali/navody-prototype-kit | 98641cb6d10fec5affab4e2978afe3f09609f9ce | [
"MIT"
] | 7 | 2018-11-30T20:22:56.000Z | 2019-01-22T13:53:34.000Z | {% extends "strata-odcudzenie/op/layout_step_by_step_nav.html" %}
{% block pageTitle %} {{serviceName}} {% endblock %}
{% block mainContent %}
<h1 class="govuk-heading-l">
Vystavenie dočasného občianskeho preukazu - potvrdenia o OP
</h1>
<p>
Na vyzvanie sa treba osobne dostaviť na PZ spísať zápis o strate, prevziať potvrdenie o OP,
zápis do evidencie stratených a odcudzených dokladov.
Na príslušnom útvare Policajného zboru alebo na zastupiteľskom úrade vám bude vydané potvrdenie
o občianskom preukaze, ktoré dočasne slúži ako náhrada dokladu a zároveň sa predkladá na
vyhotovenie nového občianskeho preukazu, maximálne však 90 dní.
</p>
{% endblock %}
| 38 | 99 | 0.752924 |
0ec9fb77d9a5a65318d527313cc3f3c9fbbd3730 | 1,715 | h | C | src/s1ap/asn1c/asnGenFiles/UE-RetentionInformation.h | kanchankanchan/openmme | 2e48ed40be2f362141e00d011300df0568672f30 | [
"Apache-2.0"
] | 46 | 2019-02-19T07:47:54.000Z | 2022-03-12T13:16:26.000Z | src/s1ap/asn1c/asnGenFiles/UE-RetentionInformation.h | kanchankanchan/openmme | 2e48ed40be2f362141e00d011300df0568672f30 | [
"Apache-2.0"
] | 93 | 2020-03-05T07:34:10.000Z | 2022-03-31T15:14:02.000Z | src/s1ap/asn1c/asnGenFiles/UE-RetentionInformation.h | kanchankanchan/openmme | 2e48ed40be2f362141e00d011300df0568672f30 | [
"Apache-2.0"
] | 41 | 2020-02-26T10:41:19.000Z | 2022-01-13T13:45:37.000Z | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "S1AP-IEs"
* found in "./asn1c/S1AP-IEs.asn"
* `asn1c -fcompound-names -fno-include-deps -gen-PER -findirect-choice -pdu=S1AP-PDU`
*/
#ifndef _UE_RetentionInformation_H_
#define _UE_RetentionInformation_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeEnumerated.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum UE_RetentionInformation {
UE_RetentionInformation_ues_retained = 0
/*
* Enumeration is extensible
*/
} e_UE_RetentionInformation;
/* UE-RetentionInformation */
typedef long UE_RetentionInformation_t;
/* Implementation */
extern asn_per_constraints_t asn_PER_type_UE_RetentionInformation_constr_1;
extern asn_TYPE_descriptor_t asn_DEF_UE_RetentionInformation;
extern const asn_INTEGER_specifics_t asn_SPC_UE_RetentionInformation_specs_1;
asn_struct_free_f UE_RetentionInformation_free;
asn_struct_print_f UE_RetentionInformation_print;
asn_constr_check_f UE_RetentionInformation_constraint;
ber_type_decoder_f UE_RetentionInformation_decode_ber;
der_type_encoder_f UE_RetentionInformation_encode_der;
xer_type_decoder_f UE_RetentionInformation_decode_xer;
xer_type_encoder_f UE_RetentionInformation_encode_xer;
oer_type_decoder_f UE_RetentionInformation_decode_oer;
oer_type_encoder_f UE_RetentionInformation_encode_oer;
per_type_decoder_f UE_RetentionInformation_decode_uper;
per_type_encoder_f UE_RetentionInformation_encode_uper;
per_type_decoder_f UE_RetentionInformation_decode_aper;
per_type_encoder_f UE_RetentionInformation_encode_aper;
#ifdef __cplusplus
}
#endif
#endif /* _UE_RetentionInformation_H_ */
#include <asn_internal.h>
| 30.625 | 87 | 0.853061 |
8a6a3638f53dd9bdc2a725901b812188f8f22621 | 401 | asm | Assembly | programs/oeis/194/A194273.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/194/A194273.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | programs/oeis/194/A194273.asm | jmorken/loda | 99c09d2641e858b074f6344a352d13bc55601571 | [
"Apache-2.0"
] | null | null | null | ; A194273: Concentric triangular numbers (see Comments lines for definition).
; 0,1,3,6,9,12,15,19,24,30,36,42,48,55,63,72,81,90,99,109,120,132,144,156,168,181,195,210,225,240,255,271,288,306,324,342,360,379,399,420,441,462,483,505,528,552,576,600,624,649,675,702,729,756,783,811
mov $2,$0
lpb $2
lpb $4
sub $2,1
sub $4,$3
lpe
add $1,$2
sub $2,1
mov $3,$4
sub $3,1
add $4,1
lpe
| 25.0625 | 201 | 0.650873 |
fbbb79afd04c171d3ddb1cbbc0fa992ca399c982 | 33,927 | c | C | dhcp-relay.c | eait-itig/dhcp-relay | 9b765f60f340e02f1190c2bae7fca30f44deafd5 | [
"BSD-3-Clause"
] | 5 | 2017-12-06T02:07:04.000Z | 2021-06-16T13:58:39.000Z | dhcp-relay.c | eait-itig/dhcp-relay | 9b765f60f340e02f1190c2bae7fca30f44deafd5 | [
"BSD-3-Clause"
] | null | null | null | dhcp-relay.c | eait-itig/dhcp-relay | 9b765f60f340e02f1190c2bae7fca30f44deafd5 | [
"BSD-3-Clause"
] | null | null | null | /* $OpenBSD: tftpd.c,v 1.39 2017/05/26 17:38:46 florian Exp $ */
/*
* Copyright (c) 2017 The University of Queensland
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2004 Henning Brauer <henning@cvs.openbsd.org>
* Copyright (c) 1997, 1998, 1999 The Internet Software Consortium.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of The Internet Software Consortium nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software has been written for the Internet Software Consortium
* by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
* Enterprises. To learn more about the Internet Software Consortium,
* see ``http://www.vix.com/isc''. To learn more about Vixie
* Enterprises, see ``http://www.vix.com''.
*/
/*
* This code was largely rewritten by David Gwynne <dlg@uq.edu.au>
* as part of the Information Technology Infrastructure Group in the
* Faculty of Engineering, Architecture and Information Technology.
*/
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <net/if_types.h>
#include <net/bpf.h>
#include <arpa/inet.h> /* inet_ntoa */
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <err.h>
#include <ctype.h>
#include <errno.h>
#include <event.h>
#include <fcntl.h>
#include <paths.h>
#include <poll.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <assert.h>
#include <stddef.h>
#include "dhcp.h"
#include "log.h"
#define SERVER_PORT 67
#define CLIENT_PORT 68
#define DHCP_USER "_dhcp"
#define CHADDR_SIZE 16
struct dhcp_opt_header {
uint8_t code;
uint8_t len;
} __packed;
#define DHCP_MAX_MSG (DHCP_MTU_MAX - \
(sizeof(struct ip) + sizeof(struct udphdr)))
#define ETHER_FMT "%02x:%02x:%02x:%02x:%02x:%02x"
#define ETHER_ARGS(_e) (_e)[0], (_e)[1], (_e)[2], (_e)[3], (_e)[4], (_e)[5]
#define streq(_a, _b) (strcmp(_a, _b) == 0)
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
#define sin2sa(_sin) (struct sockaddr *)(_sin)
#define sa2sin(_sa) (struct sockaddr_in *)(_sa)
struct iface;
struct dhcp_helper {
TAILQ_ENTRY(dhcp_helper) dh_entry;
char *dh_name;
};
TAILQ_HEAD(dhcp_helpers, dhcp_helper);
struct dhcp_giaddr {
struct iface *gi_if;
struct sockaddr_in gi_sin;
struct event gi_ev;
const char *gi_name;
};
struct dhcp_server {
struct sockaddr_in ds_addr; /* must be first */
const char *ds_name;
unsigned int ds_helper;
};
struct iface {
const char *if_name;
unsigned int if_index;
int if_nakfilt;
struct dhcp_server *if_servers;
unsigned int if_nservers;
uint8_t if_hwaddr[16];
unsigned int if_hwaddrlen;
struct dhcp_giaddr *if_giaddrs;
unsigned int if_ngiaddrs;
uint8_t if_hoplim;
uint8_t *if_rai;
unsigned int if_railen;
void (*if_dhcp_relay)(struct iface *,
struct dhcp_packet *, size_t);
void (*if_srvr_relay)(struct iface *iface,
struct dhcp_giaddr *, const char *,
struct dhcp_packet *, size_t);
struct event if_bpf_ev;
uint8_t *if_bpf_buf;
unsigned int if_bpf_len;
struct event if_siginfo;
uint64_t if_bpf_short;
uint64_t if_ether_len;
uint64_t if_ip_len;
uint64_t if_ip_cksum;
uint64_t if_udp_len;
uint64_t if_udp_cksum;
uint64_t if_dhcp_len;
uint64_t if_dhcp_opt_len;
uint64_t if_dhcp_hlen;
uint64_t if_dhcp_op;
uint64_t if_dhcp_hops;
uint64_t if_dhcp_nakfilt;
uint64_t if_srvr_op;
uint64_t if_srvr_giaddr;
uint64_t if_srvr_unknown;
};
__dead void usage(void);
int rdaemon(int);
struct iface *iface_get(const char *);
void iface_bpf_open(struct iface *);
void iface_rai_set(struct iface *, const char *, const char *);
void iface_rai_add(struct iface *, uint8_t, const char *,
const char *);
int iface_cmp(const void *, const void *);
void iface_servers(struct iface *, int, char *[]);
void iface_helpers(struct iface *, struct dhcp_helpers *);
void iface_siginfo(int, short, void *);
void dhcp_input(int, short, void *);
void dhcp_pkt_input(struct iface *, const uint8_t *, size_t);
void dhcp_relay(struct iface *, const void *, size_t);
void dhcp_if_relay(struct iface *, struct dhcp_packet *, size_t);
void dhcp_if_relay_rai(struct iface *, struct dhcp_packet *,
size_t);
void srvr_input(int, short, void *);
void srvr_relay_rai(struct iface *, struct dhcp_giaddr *,
const char *, struct dhcp_packet *, size_t);
void srvr_relay(struct iface *, struct dhcp_giaddr *,
const char *, struct dhcp_packet *, size_t);
static uint32_t cksum_add(const void *, size_t, uint32_t);
static uint16_t cksum_fini(uint32_t);
static inline uint32_t
cksum_word(uint16_t word, uint32_t cksum)
{
return (cksum + htons(word));
}
#define cksum(_b, _l) cksum_fini(cksum_add((_b), (_l), 0))
__dead void
usage(void)
{
extern char *__progname;
fprintf(stderr, "usage: %s [-dv] "
"[-C circuit] [-R remote] [-H hoplim] [-h helper]\n"
" -i interface destination ...\n",
__progname);
exit(1);
}
int verbose = 0;
int
main(int argc, char *argv[])
{
const char *errstr;
const char *ifname = NULL;
const char *circuit = NULL;
const char *remote = NULL;
int nakfilt = 0;
int debug = 0;
int hoplim = -1;
struct dhcp_helpers helpers = TAILQ_HEAD_INITIALIZER(helpers);
int ch;
struct passwd *pw;
int devnull = -1;
struct iface *iface;
struct dhcp_helper *dh;
unsigned int i;
while ((ch = getopt(argc, argv, "C:dh:H:i:NR:v")) != -1) {
switch (ch) {
case 'C':
if (circuit != NULL)
usage();
circuit = optarg;
break;
case 'd':
debug = verbose = 1;
break;
case 'h':
dh = malloc(sizeof(*dh));
if (dh == NULL)
err(1, NULL);
dh->dh_name = optarg;
TAILQ_INSERT_TAIL(&helpers, dh, dh_entry);
break;
case 'H':
if (hoplim != -1)
usage();
hoplim = strtonum(optarg, 1, 16, &errstr);
if (errstr != NULL)
errx(1, "hop limit: %s", errstr);
break;
case 'i':
if (ifname != NULL)
usage();
ifname = optarg;
break;
case 'N':
nakfilt = 1;
break;
case 'R':
if (remote != NULL)
usage();
remote = optarg;
break;
case 'v':
verbose = 1;
break;
default:
usage();
/* NOTREACHED */
}
}
if (ifname == NULL)
usage();
argc -= optind;
argv += optind;
if (argc == 0)
usage();
if (geteuid() != 0)
errx(1, "need root privileges");
pw = getpwnam(DHCP_USER);
if (pw == NULL)
errx(1, "no %s user", DHCP_USER);
iface = iface_get(ifname);
if (iface->if_index == 0)
errx(1, "Ethernet interface %s not found", ifname);
if (iface->if_ngiaddrs == 0)
errx(1, "interface %s no IPv4 addresses", ifname);
if (hoplim != -1)
iface->if_hoplim = hoplim;
iface_bpf_open(iface);
iface_rai_set(iface, circuit, remote);
iface->if_bpf_buf = malloc(iface->if_bpf_len * 2);
if (iface->if_bpf_buf == NULL)
err(1, "BPF buffer");
for (i = 0; i < iface->if_ngiaddrs; i++) {
struct dhcp_giaddr *gi = &iface->if_giaddrs[i];
struct sockaddr_in *sin = &gi->gi_sin;
int fd;
int opt;
gi->gi_name = strdup(inet_ntoa(sin->sin_addr));
if (gi->gi_name == NULL)
err(1, "gi name alloc");
sin->sin_port = htons(SERVER_PORT);
fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0);
if (fd == -1)
err(1, "socket");
opt = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT,
&opt, sizeof(opt)) == -1)
err(1, "setsockopt(SO_REUSEPORT)");
if (bind(fd, sin2sa(sin), sizeof(*sin)) == -1)
err(1, "bind to %s", inet_ntoa(sin->sin_addr));
iface->if_giaddrs[i].gi_ev.ev_fd = fd;
}
iface_servers(iface, argc, argv);
iface_helpers(iface, &helpers);
qsort(iface->if_servers, iface->if_nservers,
sizeof(*iface->if_servers), iface_cmp);
if (debug) {
printf("interface address(es):");
for (i = 0; i < iface->if_ngiaddrs; i++) {
struct dhcp_giaddr *gi = &iface->if_giaddrs[i];
printf(" %s", gi->gi_name);
}
printf("\n");
printf("server address(es):");
for (i = 0; i < iface->if_nservers; i++) {
struct dhcp_server *ds = &iface->if_servers[i];
printf(" %s", ds->ds_name);
if (ds->ds_helper)
printf(" (helper)");
}
printf("\n");
printf("BPF buffer length: %d\n", iface->if_bpf_len);
} else {
extern char *__progname;
logger_syslog(__progname);
devnull = open(_PATH_DEVNULL, O_RDWR, 0);
if (devnull == -1)
err(1, "%s", _PATH_DEVNULL);
}
if (chroot(pw->pw_dir) == -1)
err(1, "chroot %s", pw->pw_dir);
if (chdir("/") == -1)
err(1, "chdir %s", pw->pw_dir);
if (setgroups(1, &pw->pw_gid) ||
setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
errx(1, "can't drop privileges");
if (!debug && rdaemon(devnull) == -1)
err(1, "unable to daemonize");
event_init();
event_set(&iface->if_bpf_ev, iface->if_bpf_ev.ev_fd,
EV_READ | EV_PERSIST, dhcp_input, iface);
event_add(&iface->if_bpf_ev, NULL);
for (i = 0; i < iface->if_ngiaddrs; i++) {
struct dhcp_giaddr *gi = &iface->if_giaddrs[i];
event_set(&gi->gi_ev, gi->gi_ev.ev_fd, EV_READ | EV_PERSIST,
srvr_input, gi);
event_add(&gi->gi_ev, NULL);
}
iface->if_nakfilt = nakfilt;
signal_set(&iface->if_siginfo, SIGINFO, iface_siginfo, iface);
signal_add(&iface->if_siginfo, NULL);
event_dispatch();
return (0);
}
void
iface_siginfo(int sig, short events, void *arg)
{
struct iface *iface = arg;
linfo("iface:%s bpf_short:%llu ether_len:%llu "
"ip_len:%llu ip_cksum:%llu "
"udp_len:%llu udp_cksum:%llu "
"dhcp_len:%llu dhcp_opt_len:%llu dhcp_op:%llu "
"dhcp_hops:%llu dhcp_nakfilt:%llu "
"srvr_op:%llu srvr_giaddr:%llu srvr_unknown:%llu",
iface->if_name, iface->if_bpf_short, iface->if_ether_len,
iface->if_ip_len, iface->if_ip_cksum,
iface->if_udp_len, iface->if_udp_cksum,
iface->if_dhcp_len, iface->if_dhcp_opt_len, iface->if_dhcp_op,
iface->if_dhcp_hops, iface->if_dhcp_nakfilt,
iface->if_srvr_op, iface->if_srvr_giaddr, iface->if_srvr_unknown);
}
#if 0
static void
hexdump(const void *d, size_t datalen)
{
const uint8_t *data = d;
size_t i, j = 0;
for (i = 0; i < datalen; i += j) {
printf("%4zu: ", i);
for (j = 0; j < 16 && i+j < datalen; j++)
printf("%02x ", data[i + j]);
while (j++ < 16)
printf(" ");
printf("|");
for (j = 0; j < 16 && i+j < datalen; j++)
putchar(isprint(data[i + j]) ? data[i + j] : '.');
printf("|\n");
}
}
#endif
struct iface *
iface_get(const char *ifname)
{
struct iface *iface;
struct ifaddrs *ifas, *ifa;
struct sockaddr_in *sin;
struct dhcp_giaddr *giaddrs;
struct sockaddr_dl *sdl;
struct if_data *ifi;
unsigned int o, n;
iface = malloc(sizeof(*iface));
if (iface == NULL)
err(1, "iface alloc");
memset(iface, 0, sizeof(*iface));
if (getifaddrs(&ifas) == -1)
err(1, "getifaddrs");
for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
if ((ifa->ifa_flags & IFF_LOOPBACK) ||
(ifa->ifa_flags & IFF_POINTOPOINT))
continue;
if (!streq(ifa->ifa_name, ifname))
continue;
switch (ifa->ifa_addr->sa_family) {
case AF_INET:
sin = (struct sockaddr_in *)ifa->ifa_addr;
if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
break;
o = iface->if_ngiaddrs;
n = o + 1;
giaddrs = reallocarray(iface->if_giaddrs, n,
sizeof(*giaddrs));
if (giaddrs == NULL)
err(1, "giaddrs alloc");
giaddrs[o].gi_if = iface;
giaddrs[o].gi_sin = *sin;
iface->if_giaddrs = giaddrs;
iface->if_ngiaddrs = n;
break;
case AF_LINK:
ifi = (struct if_data *)ifa->ifa_data;
if (ifi->ifi_type != IFT_ETHER &&
ifi->ifi_type != IFT_CARP)
break;
sdl = (struct sockaddr_dl *)ifa->ifa_addr;
if (sdl->sdl_alen > sizeof(iface->if_hwaddr))
break; /* ? */
iface->if_index = sdl->sdl_index;
memcpy(iface->if_hwaddr, LLADDR(sdl), sdl->sdl_alen);
iface->if_hwaddrlen = sdl->sdl_alen;
break;
default:
break;
}
}
freeifaddrs(ifas);
iface->if_name = ifname;
iface->if_hoplim = 16;
iface->if_dhcp_relay = dhcp_if_relay;
iface->if_srvr_relay = srvr_relay;
return (iface);
}
int
iface_cmp(const void *a, const void *b)
{
const struct dhcp_server *dsa = a, *dsb = b;
const struct sockaddr_in *sina = &dsa->ds_addr;
const struct sockaddr_in *sinb = &dsb->ds_addr;
in_addr_t ina = ntohl(sina->sin_addr.s_addr);
in_addr_t inb = ntohl(sinb->sin_addr.s_addr);
if (ina > inb)
return (1);
if (ina < inb)
return (-1);
return (0);
}
void
iface_servers(struct iface *iface, int argc, char *argv[])
{
const struct addrinfo hints = {
.ai_family = AF_INET,
.ai_socktype = SOCK_DGRAM,
};
struct addrinfo *res0, *res;
const char *host;
int error;
int i;
for (i = 0; i < argc; i++) {
host = argv[i];
error = getaddrinfo(host, "bootps", &hints, &res0);
if (error != 0)
errx(1, "%s: %s", host, gai_strerror(error));
for (res = res0; res != NULL; res = res->ai_next) {
struct dhcp_server *servers, *server;
unsigned int o, n;
if (res->ai_addrlen > sizeof(servers->ds_addr)) {
/* XXX */
continue;
}
o = iface->if_nservers;
n = o + 1;
servers = reallocarray(iface->if_servers,
n, sizeof(*servers));
if (servers == NULL)
err(1, "server alloc");
server = &servers[o];
server->ds_addr = *sa2sin(res->ai_addr);
server->ds_name = strdup(
inet_ntoa(server->ds_addr.sin_addr));
if (server->ds_name == NULL)
err(1, "server name alloc");
server->ds_helper = 0;
iface->if_servers = servers;
iface->if_nservers = n;
}
freeaddrinfo(res0);
}
if (iface->if_nservers == 0)
errx(1, "unable to resolve servers");
}
void
iface_helpers(struct iface *iface, struct dhcp_helpers *helpers)
{
const struct addrinfo hints = {
.ai_family = AF_INET,
.ai_socktype = SOCK_DGRAM,
};
struct addrinfo *res0, *res;
struct dhcp_helper *dh;
char *host, *port;
int error;
while ((dh = TAILQ_FIRST(helpers)) != NULL) {
TAILQ_REMOVE(helpers, dh, dh_entry);
port = dh->dh_name;
free(dh);
host = strsep(&port, ":");
error = getaddrinfo(host, port, &hints, &res0);
if (error != 0) {
errx(1, "%s port %s: %s", host, port ? port : "*",
gai_strerror(error));
}
for (res = res0; res != NULL; res = res->ai_next) {
struct dhcp_server *servers, *server;
unsigned int o, n;
if (res->ai_addrlen > sizeof(servers->ds_addr)) {
/* XXX */
continue;
}
o = iface->if_nservers;
n = o + 1;
servers = reallocarray(iface->if_servers,
n, sizeof(*servers));
if (servers == NULL)
err(1, "server alloc");
server = &servers[o];
server->ds_addr = *sa2sin(res->ai_addr);
server->ds_name = strdup(
inet_ntoa(server->ds_addr.sin_addr));
if (server->ds_name == NULL)
err(1, "server name alloc");
server->ds_helper = 1;
iface->if_servers = servers;
iface->if_nservers = n;
}
freeaddrinfo(res0);
}
}
/*
* Packet filter program: 'ip and udp and dst port SERVER_PORT'
*/
/* const */ struct bpf_insn dhcp_bpf_rfilter[] = {
/* Make sure this is "locally delivered" packet, ie, mcast/bcast */
BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 0),
BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 1, 0, 10),
/* Make sure this is an IP packet... */
BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),
/* Make sure it's a UDP packet... */
BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),
/* Make sure this isn't a fragment... */
BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),
/* Get the IP header length... */
BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
/* Make sure it's to the right port... */
BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, SERVER_PORT, 0, 1),
/* If we passed all the tests, ask for the whole packet. */
BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
/* Otherwise, drop it. */
BPF_STMT(BPF_RET+BPF_K, 0),
};
void
iface_bpf_open(struct iface *iface)
{
struct ifreq ifr;
struct bpf_version v;
struct bpf_program p;
int opt;
int fd;
fd = open("/dev/bpf", O_RDWR|O_NONBLOCK);
if (fd == -1)
err(1, "/dev/bpf");
if (ioctl(fd, BIOCVERSION, &v) == -1)
err(1, "get BPF version");
if (v.bv_major != BPF_MAJOR_VERSION || v.bv_minor < BPF_MINOR_VERSION)
errx(1, "kerel BPF version is too high, recompile!");
memset(&ifr, 0, sizeof(ifr));
if (strlcpy(ifr.ifr_name, iface->if_name, sizeof(ifr.ifr_name)) >=
sizeof(ifr.ifr_name))
errx(1, "interface name is too long");
if (ioctl(fd, BIOCSETIF, &ifr) == -1)
err(1, "unable to set BPF interface to %s", iface->if_name);
opt = 1;
if (ioctl(fd, BIOCIMMEDIATE, &opt) == -1)
err(1, "unable to set BPF immediate mode");
if (ioctl(fd, BIOCGBLEN, &opt) == -1)
err(1, "unable to get BPF buffer length");
if (opt < DHCP_FIXED_LEN) {
errx(1, "BPF buffer length is too short: %d < %d",
opt, DHCP_FIXED_LEN);
}
p.bf_len = nitems(dhcp_bpf_rfilter);
p.bf_insns = dhcp_bpf_rfilter;
if (ioctl(fd, BIOCSETF, &p) == -1)
err(1, "unable to set BPF read filter");
if (ioctl(fd, BIOCLOCK) == -1)
err(1, "unable to lock BPF descriptor");
iface->if_bpf_ev.ev_fd = fd;
iface->if_bpf_len = opt;
}
void
iface_rai_add(struct iface *iface, uint8_t code, const char *value,
const char *name)
{
struct dhcp_opt_header *hdr;
size_t vlen, olen, rlen, nlen;
vlen = strlen(value);
olen = sizeof(*hdr) + vlen;
if (olen > DHCP_OPTION_MAXLEN)
errx(1, "%s: too long", name);
rlen = iface->if_railen;
nlen = rlen + olen;
iface->if_rai = realloc(iface->if_rai, nlen);
if (iface->if_rai == NULL)
err(1, "%s", name);
hdr = (struct dhcp_opt_header *)(iface->if_rai + rlen);
hdr->code = code;
hdr->len = olen;
memcpy(hdr + 1, value, vlen);
iface->if_railen = nlen;
}
void
iface_rai_set(struct iface *iface, const char *circuit, const char *remote)
{
struct dhcp_opt_header *hdr;
size_t len;
if (circuit == NULL && remote == NULL)
return;
iface->if_rai = NULL;
iface->if_railen = sizeof(*hdr);
if (circuit != NULL)
iface_rai_add(iface, RAI_CIRCUIT_ID, circuit, "Circuit ID");
if (remote != NULL)
iface_rai_add(iface, RAI_REMOTE_ID, remote, "Remote ID");
len = iface->if_railen - sizeof(*hdr);
if (len > DHCP_OPTION_MAXLEN)
errx(1, "Relay Agent Information: too long");
hdr = (struct dhcp_opt_header *)iface->if_rai;
hdr->code = DHO_RELAY_AGENT_INFORMATION;
hdr->len = len;
iface->if_dhcp_relay = dhcp_if_relay_rai;
iface->if_srvr_relay = srvr_relay_rai;
}
void
dhcp_input(int fd, short events, void *arg)
{
struct iface *iface = arg;
const struct bpf_hdr *bh;
size_t len, bpflen;
ssize_t rv;
uint8_t *buf = iface->if_bpf_buf;
rv = read(fd, buf, iface->if_bpf_len);
switch (rv) {
case -1:
switch (errno) {
case EINTR:
case EAGAIN:
break;
default:
lerr(1, "%s bpf read", iface->if_name);
/* NOTREACHED */
}
return;
case 0:
lerrx(0, "%s BPF has closed", iface->if_name);
/* NOTREACHED */
default:
break;
}
len = rv;
for (;;) {
/*
* the kernel lied to us.
*/
if (len < sizeof(*bh))
lerrx(1, "%s: short BPF header", iface->if_name);
bh = (const struct bpf_hdr *)buf;
bpflen = bh->bh_hdrlen + bh->bh_caplen;
/*
* If the bpf header plus data doesn't fit in what's
* left of the buffer, we've got a problem...
*/
if (bpflen > len)
lerrx(1, "%s: short BPF read", iface->if_name);
/*
* If the captured data wasn't the whole packet, or if
* the packet won't fit in the input buffer, all we can
* do is skip it.
*/
if (bh->bh_caplen < bh->bh_datalen)
iface->if_bpf_short++;
else {
dhcp_pkt_input(iface,
buf + bh->bh_hdrlen, bh->bh_datalen);
}
bpflen = BPF_WORDALIGN(bpflen);
if (len <= bpflen) {
/* everything is consumed */
break;
}
/* Move the loop to the next packet */
buf += bpflen;
len -= bpflen;
}
}
void
dhcp_pkt_input(struct iface *iface, const uint8_t *pkt, size_t len)
{
const struct ether_header *eh;
struct ip iph;
struct udphdr udph;
unsigned int iplen, udplen;
uint32_t cksum;
uint16_t udpsum;
if (len < sizeof(*eh)) {
iface->if_ether_len++;
return;
}
/* the bpf filter has already checked ether and ip proto types */
eh = (const struct ether_header *)pkt;
pkt += sizeof(*eh);
len -= sizeof(*eh);
if (len < sizeof(iph)) {
iface->if_ip_len++;
return;
}
memcpy(&iph, pkt, sizeof(iph));
iplen = iph.ip_hl << 2;
if (len < iplen) {
iface->if_ip_len++;
return;
}
if (cksum(pkt, iplen) != 0) {
iface->if_ip_cksum++;
return;
}
pkt += iplen;
len -= iplen;
if (len < sizeof(udph)) {
iface->if_udp_len++;
return;
}
memcpy(&udph, pkt, sizeof(udph));
udplen = ntohs(udph.uh_ulen);
if (len < udplen) {
iface->if_udp_len++;
return;
}
udpsum = udph.uh_sum;
if (udpsum) {
cksum = cksum_add(&iph.ip_src,
sizeof(iph.ip_src) + sizeof(iph.ip_dst), 0);
cksum = cksum_word(IPPROTO_UDP, cksum);
cksum = cksum_word(udplen, cksum);
cksum = cksum_add(pkt, len, cksum);
if (cksum_fini(cksum) != 0) {
/* check for 0x0000? */
iface->if_udp_cksum++;
return;
}
}
pkt += sizeof(udph);
len = udplen - sizeof(udph); /* drop extra bytes */
dhcp_relay(iface, pkt, len);
}
void
dhcp_relay(struct iface *iface, const void *pkt, size_t len)
{
uint8_t buf[DHCP_MAX_MSG];
struct dhcp_packet *packet = (struct dhcp_packet *)buf;
ssize_t olen;
uint8_t hops;
/*
* Apple firmware sometimes generates packets without padding the
* options field. Technically not correct, but as long as the
* non-optional fields are there it can work.
*/
if (len < offsetof(struct dhcp_packet, cookie)) {
iface->if_dhcp_len++;
return;
}
if (len > sizeof(buf)) {
iface->if_dhcp_len++;
return;
}
memcpy(packet, pkt, len); /* align packet */
if (packet->op != BOOTREQUEST) {
iface->if_dhcp_op++;
return;
}
hops = packet->hops;
if (hops > iface->if_hoplim) {
iface->if_dhcp_hops++;
return;
}
packet->hops = ++hops;
if (packet->hlen != ETHER_ADDR_LEN) {
iface->if_dhcp_hlen++;
return;
}
if (packet->giaddr.s_addr != htonl(0)) {
/* don't support relay chaining yet */
return;
}
olen = BOOTP_MIN_LEN - len;
if (olen > 0) {
iface->if_dhcp_opt_len++;
memset(buf + len, 0, olen);
len = BOOTP_MIN_LEN;
}
(*iface->if_dhcp_relay)(iface, packet, len);
}
static ssize_t
dhcp_opt_end(const uint8_t *opts, size_t olen, uint8_t match)
{
size_t i = 0;
uint8_t len;
while (i < olen) {
uint8_t code = opts[i];
if (code == match)
return (i);
switch (opts[i]) {
case DHO_PAD:
i++;
break;
case DHO_END:
return (-1);
case DHO_RELAY_AGENT_INFORMATION:
/* relay chaining unsupported */
return (-1);
default:
i++;
if (i >= olen) {
/* too short */
return (-1);
}
len = opts[i];
i += len + 1;
break;
}
}
return (0);
}
void
dhcp_if_relay_rai(struct iface *iface, struct dhcp_packet *packet, size_t len)
{
ssize_t olen;
size_t nlen;
uint8_t *opts;
if (memcmp(packet->cookie, DHCP_OPTIONS_COOKIE,
sizeof(packet->cookie)) != 0) {
/* invalid signature */
return;
}
opts = (uint8_t *)(packet + 1);
olen = dhcp_opt_end(opts, len - sizeof(*packet), DHO_END);
if (olen == -1) {
/* too short or unsupported opts */
return;
}
len = sizeof(*packet) + olen;
nlen = len + iface->if_railen;
if (nlen >= DHCP_MAX_MSG) {
/* not enough space */
return;
}
opts += olen;
memcpy(opts, iface->if_rai, iface->if_railen);
opts += iface->if_railen;
*opts = DHO_END;
if (nlen < BOOTP_MIN_LEN)
nlen = BOOTP_MIN_LEN;
dhcp_if_relay(iface, packet, nlen);
}
void
dhcp_if_relay(struct iface *iface, struct dhcp_packet *packet, size_t len)
{
unsigned int i, j;
int giaddr;
giaddr = packet->giaddr.s_addr == htonl(0);
for (i = 0; i < iface->if_ngiaddrs; i++) {
struct dhcp_giaddr *gi = &iface->if_giaddrs[i];
if (giaddr)
packet->giaddr = gi->gi_sin.sin_addr;
for (j = 0; j < iface->if_nservers; j++) {
struct dhcp_server *ds = &iface->if_servers[j];
struct sockaddr_in *sin;
if (ds->ds_helper)
continue;
sin = &ds->ds_addr;
if (sendto(EVENT_FD(&gi->gi_ev), packet, len, 0,
sin2sa(sin), sizeof(*sin)) == -1) {
switch (errno) {
case EACCES:
case EHOSTUNREACH:
case ENETUNREACH:
case EHOSTDOWN:
case ENETDOWN:
lwarn("%s sendmsg",
inet_ntoa(sin->sin_addr));
/* FALLTHROUGH */
case ENOBUFS:
case EAGAIN:
case EINTR:
/* skip to the next one */
continue;
default:
lerr(1, "%s fatal sendmsg",
inet_ntoa(sin->sin_addr));
}
}
if (verbose) {
linfo("forwarded BOOTREQUEST for "
ETHER_FMT " on %s from %s to %s",
ETHER_ARGS(packet->chaddr),
iface->if_name, gi->gi_name,
ds->ds_name);
}
}
}
}
static uint32_t
cksum_add(const void *buf, size_t len, uint32_t sum)
{
const uint16_t *words = buf;
while (len > 1) {
sum += *words++;
len -= sizeof(*words);
}
if (len == 1) {
const uint8_t *bytes = (const uint8_t *)words;
sum = cksum_word(*bytes << 8, sum);
}
return (sum);
}
static uint16_t
cksum_fini(uint32_t sum)
{
uint16_t cksum;
cksum = sum;
cksum += sum >> 16;
return (~cksum);
}
void
srvr_input(int fd, short events, void *arg)
{
struct dhcp_giaddr *gi = arg;
struct iface *iface = gi->gi_if;
uint8_t buf[4096];
struct dhcp_packet *packet = (struct dhcp_packet *)buf;
struct sockaddr_in sin;
struct dhcp_server *ds;
socklen_t sinlen = sizeof(sin);
ssize_t len;
len = recvfrom(fd, buf, sizeof(buf), 0, sin2sa(&sin), &sinlen);
if (len == -1) {
switch (errno) {
case EAGAIN:
case EINTR:
break;
default:
lerr(1, "udp recv");
/* NOTREACHED */
}
return;
}
if (len < BOOTP_MIN_LEN)
return;
if (sinlen < sizeof(sin))
return;
if (packet->op != BOOTREPLY) {
iface->if_srvr_op++;
return;
}
if (packet->giaddr.s_addr != gi->gi_sin.sin_addr.s_addr) {
/* Filter packet that is not meant for us */
iface->if_srvr_giaddr++;
return;
}
if (packet->hlen != ETHER_ADDR_LEN) {
/* nope */
iface->if_dhcp_hlen++;
return;
}
if (iface->if_nakfilt) {
uint8_t mlen;
uint8_t *opts = (uint8_t *)(packet + 1);
ssize_t olen = dhcp_opt_end(opts, len - sizeof(*packet),
DHO_DHCP_MESSAGE_TYPE);
if (olen == -1) {
/* too short or missing opts */
iface->if_dhcp_len++;
return;
}
olen++; /* move to the len */
if (olen >= len) {
/* too short */
iface->if_dhcp_len++;
return;
}
mlen = opts[olen];
if (mlen != 1) {
/* unknown message length */
iface->if_dhcp_len++;
return;
}
olen++; /* move to the value */
if (olen >= len) {
/* too short */
iface->if_dhcp_len++;
return;
}
if (opts[olen] == DHCPNAK) {
/* filter */
iface->if_dhcp_nakfilt++;
return;
}
}
if (memcmp(packet->cookie, DHCP_OPTIONS_COOKIE,
sizeof(packet->cookie)) != 0) {
/* invalid signature */
return;
}
ds = bsearch(&sin, iface->if_servers, iface->if_nservers,
sizeof(*iface->if_servers), iface_cmp);
if (ds == NULL) {
iface->if_srvr_unknown++;
return;
}
(*iface->if_srvr_relay)(iface, gi, ds->ds_name, packet, len);
}
void
srvr_relay_rai(struct iface *iface, struct dhcp_giaddr *gi,
const char *srvr_name, struct dhcp_packet *packet, size_t len)
{
ssize_t olen;
ssize_t diff;
uint8_t *opts;
if (memcmp(packet->cookie, DHCP_OPTIONS_COOKIE,
sizeof(packet->cookie)) != 0) {
/* invalid signature */
return;
}
opts = (uint8_t *)(packet + 1);
olen = dhcp_opt_end(opts, len - sizeof(*packet),
DHO_RELAY_AGENT_INFORMATION);
if (olen == -1) {
/* too short or missing opts */
return;
}
if ((len - olen) < iface->if_railen) {
/* not enough space */
return;
}
opts += olen;
if (memcmp(opts, iface->if_rai, iface->if_railen) != 0) {
/* option is wrong */
return;
}
*opts = DHO_END;
len -= iface->if_railen;
diff = BOOTP_MIN_LEN - len;
if (diff > 0) {
memset((uint8_t *)packet + len, 0, diff);
len = BOOTP_MIN_LEN;
}
srvr_relay(iface, gi, srvr_name, packet, len);
}
void
srvr_relay(struct iface *iface, struct dhcp_giaddr *gi,
const char *srvr_name, struct dhcp_packet *packet, size_t len)
{
struct ether_header eh;
struct {
struct ip ip;
struct udphdr udp;
} l3h;
struct ip *iph = &l3h.ip;
struct udphdr *udph = &l3h.udp;
struct iovec iov[3];
uint32_t cksum;
uint16_t udplen = sizeof(*udph) + len;
ssize_t rv;
/*
* VMware PXE "ROMs" confuse the DHCP gateway address
* with the IP gateway address. This is a problem if your
* DHCP relay is running on something that's not your
* network gateway.
*
* It is purely informational from the relay to the client
* so we can safely clear it.
*/
packet->giaddr.s_addr = htonl(0);
if (packet->flags & htons(BOOTP_BROADCAST)) {
memset(eh.ether_dhost, 0xff, sizeof(eh.ether_dhost));
iph->ip_dst.s_addr = htonl(INADDR_BROADCAST);
} else {
/*
* We could unicast using sendto() with the giaddr socket,
* but the client may not have an ARP entry yet. Use BPF
* to send it because all the information is already here.
*/
memcpy(eh.ether_dhost, packet->chaddr, sizeof(eh.ether_dhost));
iph->ip_dst = (packet->ciaddr.s_addr != htonl(0)) ?
packet->ciaddr : packet->yiaddr;
}
memcpy(eh.ether_shost, iface->if_hwaddr, sizeof(eh.ether_shost));
eh.ether_type = htons(ETHERTYPE_IP);
iph->ip_v = 4;
iph->ip_hl = sizeof(*iph) >> 2;
iph->ip_tos = IPTOS_LOWDELAY;
iph->ip_len = htons(sizeof(l3h) + len);
iph->ip_id = 0;
iph->ip_off = 0;
iph->ip_ttl = 16;
iph->ip_p = IPPROTO_UDP;
iph->ip_sum = htons(0);
iph->ip_src = gi->gi_sin.sin_addr;
iph->ip_sum = cksum(iph, sizeof(*iph));
udph->uh_sport = gi->gi_sin.sin_port;
udph->uh_dport = htons(CLIENT_PORT);
udph->uh_ulen = htons(udplen);
udph->uh_sum = htons(0);
cksum = cksum_add(&iph->ip_src,
sizeof(iph->ip_src) + sizeof(iph->ip_dst), 0);
cksum = cksum_word(IPPROTO_UDP, cksum);
cksum = cksum_word(udplen, cksum);
cksum = cksum_add(udph, sizeof(*udph), cksum);
cksum = cksum_add(packet, len, cksum);
udph->uh_sum = cksum_fini(cksum);
iov[0].iov_base = &eh;
iov[0].iov_len = sizeof(eh);
iov[1].iov_base = &l3h;
iov[1].iov_len = sizeof(l3h);
iov[2].iov_base = packet;
iov[2].iov_len = len;
rv = writev(EVENT_FD(&iface->if_bpf_ev), iov, nitems(iov));
if (rv == -1) {
switch (errno) {
case EAGAIN:
case EINTR:
case ENOMEM:
case ENOBUFS:
case EHOSTDOWN:
case EHOSTUNREACH:
case ENETDOWN:
case ENETUNREACH:
case EMSGSIZE:
break;
default:
lerr(1, "%s bpf write", iface->if_name);
/* NOTREACHED */
}
/* oh well */
return;
}
if (verbose) {
linfo("forwarded BOOTREPLY for " ETHER_FMT " on %s"
" from %s to %s", ETHER_ARGS(packet->chaddr),
iface->if_name, srvr_name, gi->gi_name);
}
}
/* daemon(3) clone, intended to be used in a "r"estricted environment */
int
rdaemon(int devnull)
{
if (devnull == -1) {
errno = EBADF;
return (-1);
}
if (fcntl(devnull, F_GETFL) == -1)
return (-1);
switch (fork()) {
case -1:
return (-1);
case 0:
break;
default:
_exit(0);
}
if (setsid() == -1)
return (-1);
(void)dup2(devnull, STDIN_FILENO);
(void)dup2(devnull, STDOUT_FILENO);
(void)dup2(devnull, STDERR_FILENO);
if (devnull > 2)
(void)close(devnull);
return (0);
}
| 22.708835 | 78 | 0.644354 |
a2222ea9251887aec569b9ed7bed8c40fbeec805 | 5,403 | ps1 | PowerShell | source/dsclibrary/MEMBER_FILESERVER.DSC.ps1 | stuart475898/LabBuilder | 8e12378ecdfe8a5c1b82ec884423c9e9c00393c6 | [
"MIT"
] | 221 | 2015-10-15T03:18:59.000Z | 2022-03-22T09:02:29.000Z | source/dsclibrary/MEMBER_FILESERVER.DSC.ps1 | stuart475898/LabBuilder | 8e12378ecdfe8a5c1b82ec884423c9e9c00393c6 | [
"MIT"
] | 230 | 2016-02-06T05:20:54.000Z | 2021-11-02T18:16:12.000Z | source/dsclibrary/MEMBER_FILESERVER.DSC.ps1 | stuart475898/LabBuilder | 8e12378ecdfe8a5c1b82ec884423c9e9c00393c6 | [
"MIT"
] | 52 | 2016-02-10T02:42:58.000Z | 2022-01-29T23:27:15.000Z | <###################################################################################################
DSC Template Configuration File For use by LabBuilder
.Title
MEMBER_FILESERVER
.Desription
Builds a Server that is joined to a domain and then made into a File Server.
.Parameters:
DomainName = 'LABBUILDER.COM'
DomainAdminPassword = 'P@ssword!1'
DCName = 'SA-DC1'
PSDscAllowDomainUser = $true
###################################################################################################>
Configuration MEMBER_FILESERVER
{
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName ComputerManagementDsc -ModuleVersion 7.1.0.0
Import-DscResource -ModuleName StorageDsc
Import-DscResource -ModuleName NetworkingDsc
Node $AllNodes.NodeName {
# Assemble the Admin Credentials
if ($Node.DomainAdminPassword)
{
$DomainAdminCredential = New-Object `
-TypeName System.Management.Automation.PSCredential `
-ArgumentList ("$($Node.DomainName)\Administrator", (ConvertTo-SecureString $Node.DomainAdminPassword -AsPlainText -Force))
}
WindowsFeature FileServerInstall
{
Ensure = 'Present'
Name = 'FS-FileServer'
}
WindowsFeature DataDedupInstall
{
Ensure = 'Present'
Name = 'FS-Data-Deduplication'
DependsOn = '[WindowsFeature]FileServerInstall'
}
WindowsFeature BranchCacheInstall
{
Ensure = 'Present'
Name = 'FS-BranchCache'
DependsOn = '[WindowsFeature]DataDedupInstall'
}
WindowsFeature DFSNameSpaceInstall
{
Ensure = 'Present'
Name = 'FS-DFS-Namespace'
DependsOn = '[WindowsFeature]BranchCacheInstall'
}
WindowsFeature DFSReplicationInstall
{
Ensure = 'Present'
Name = 'FS-DFS-Replication'
DependsOn = '[WindowsFeature]DFSNameSpaceInstall'
}
WindowsFeature FSResourceManagerInstall
{
Ensure = 'Present'
Name = 'FS-Resource-Manager'
DependsOn = '[WindowsFeature]DFSReplicationInstall'
}
WindowsFeature FSSyncShareInstall
{
Ensure = 'Present'
Name = 'FS-SyncShareService'
DependsOn = '[WindowsFeature]FSResourceManagerInstall'
}
WindowsFeature StorageServicesInstall
{
Ensure = 'Present'
Name = 'Storage-Services'
DependsOn = '[WindowsFeature]FSSyncShareInstall'
}
WindowsFeature ISCSITargetServerInstall
{
Ensure = 'Present'
Name = 'FS-iSCSITarget-Server'
DependsOn = '[WindowsFeature]StorageServicesInstall'
}
# Wait for the Domain to be available so we can join it.
WaitForAll DC
{
ResourceName = '[ADDomain]PrimaryDC'
NodeName = $Node.DCname
RetryIntervalSec = 15
RetryCount = 60
}
# Join this Server to the Domain
Computer JoinDomain
{
Name = $Node.NodeName
DomainName = $Node.DomainName
Credential = $DomainAdminCredential
DependsOn = '[WaitForAll]DC'
}
# Enable FSRM FireWall rules so we can remote manage FSRM
Firewall FSRMFirewall1
{
Name = 'FSRM-WMI-ASYNC-In-TCP'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall2
{
Name = 'FSRM-WMI-WINMGMT-In-TCP'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall3
{
Name = 'FSRM-RemoteRegistry-In (RPC)'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall4
{
Name = 'FSRM-Task-Scheduler-In (RPC)'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall5
{
Name = 'FSRM-SrmReports-In (RPC)'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall6
{
Name = 'FSRM-RpcSs-In (RPC-EPMAP)'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall7
{
Name = 'FSRM-System-In (TCP-445)'
Ensure = 'Present'
Enabled = 'True'
}
Firewall FSRMFirewall8
{
Name = 'FSRM-SrmSvc-In (RPC)'
Ensure = 'Present'
Enabled = 'True'
}
WaitforDisk Disk2
{
DiskId = 1
RetryIntervalSec = 60
RetryCount = 60
DependsOn = '[Computer]JoinDomain'
}
Disk DVolume
{
DiskId = 1
DriveLetter = 'D'
DependsOn = '[WaitforDisk]Disk2'
}
}
}
| 29.52459 | 140 | 0.488062 |
f14b09eb1de24ac3d8ba423a6c3b1ad3bb308c7a | 544 | dart | Dart | lib/comments/bloc/comment_user_state.dart | redevRx/Resocial_Flutter | 99cc0c83c6bb8a32c3b473476b5a7ea6466e9574 | [
"MIT"
] | 2 | 2021-08-05T10:38:43.000Z | 2021-11-03T17:19:15.000Z | lib/comments/bloc/comment_user_state.dart | redevRx/Resocial_Flutter | 99cc0c83c6bb8a32c3b473476b5a7ea6466e9574 | [
"MIT"
] | null | null | null | lib/comments/bloc/comment_user_state.dart | redevRx/Resocial_Flutter | 99cc0c83c6bb8a32c3b473476b5a7ea6466e9574 | [
"MIT"
] | null | null | null | import 'package:socialapp/comments/models/comment_model.dart';
abstract class CommentState {}
class OnLoadCommentSuccess extends CommentState {
final List<CommentModel> comments;
OnLoadCommentSuccess({this.comments});
@override
String toString() => '${this.comments}';
}
class OnAddCommentSuccess extends CommentState {}
class OnCommnetFaield extends CommentState {
final String message;
OnCommnetFaield({this.message});
@override
String toString() => '${this.message}';
}
class OnCommentProgress extends CommentState {}
| 22.666667 | 62 | 0.766544 |
23b83249606cdd5f241946dc1c0b4ec84d966a54 | 386 | asm | Assembly | programs/oeis/189/A189786.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/189/A189786.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/189/A189786.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A189786: n+[nr/t]+[ns/t]; r=pi/2, s=arcsin(5/13), t=arcsin(12/13).
; 2,4,8,10,12,16,18,20,24,26,28,32,34,36,40,42,44,48,50,52,56,58,60,64,66,68,72,74,76,80,82,84,88,90,92,96,98,100,104,106,108,112,114,116,120,122,124,128,130,132,136,138,140,144,146,148,152,154,156,160,162,164,168,170,172,176,178,180,184,186,188,192,194,196,200,202,204
add $0,1
mul $0,4
div $0,3
mov $1,$0
mul $1,2
| 42.888889 | 269 | 0.660622 |
0d2bf85d158dc13153a6ae2a5fbd67485063025e | 389 | ps1 | PowerShell | Powershell/Mutex/Run-WithLock-SingleFunction.ps1 | pleb/Plebs-Blogging-Stash | 1501aed5cc57422f60ec75a36227076033de5906 | [
"Unlicense"
] | null | null | null | Powershell/Mutex/Run-WithLock-SingleFunction.ps1 | pleb/Plebs-Blogging-Stash | 1501aed5cc57422f60ec75a36227076033de5906 | [
"Unlicense"
] | null | null | null | Powershell/Mutex/Run-WithLock-SingleFunction.ps1 | pleb/Plebs-Blogging-Stash | 1501aed5cc57422f60ec75a36227076033de5906 | [
"Unlicense"
] | 1 | 2021-05-19T01:25:22.000Z | 2021-05-19T01:25:22.000Z | function ExampleFunctionWithLocking {
begin {
$defaultMutexWait = New-TimeSpan -Minutes 1
$mutex = New-Object System.Threading.Mutex($false, "ABCCodeDeploy")
$mutex.WaitOne($defaultMutexWait) | Out-Null
}
process {
Write-Output "Function with locking was executed."
}
end {
$mutex.Dispose()
}
}
ExampleFunctionWithLocking | 25.933333 | 75 | 0.642674 |
21cd4f4bd34501366ccfb9e28eca340b30f4dbee | 282 | rs | Rust | 2019/src/d4.rs | bk2204/adventofcode-work | 1a20ee622aa4d7b02c2204e29185f23d8477d44c | [
"MIT"
] | null | null | null | 2019/src/d4.rs | bk2204/adventofcode-work | 1a20ee622aa4d7b02c2204e29185f23d8477d44c | [
"MIT"
] | null | null | null | 2019/src/d4.rs | bk2204/adventofcode-work | 1a20ee622aa4d7b02c2204e29185f23d8477d44c | [
"MIT"
] | null | null | null | extern crate adventofcode;
use adventofcode::d4::Filter;
use std::io;
fn main() -> io::Result<()> {
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p1(n)).count());
println!("{}", (240_298..784_956).filter(|&n| Filter::validate_p2(n)).count());
Ok(())
}
| 28.2 | 83 | 0.609929 |
57709db7be29ff8c2813ed9cd4f39204515abe8b | 1,303 | asm | Assembly | maps/OlivineHouseBeta.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | 28 | 2019-11-08T07:19:00.000Z | 2021-12-20T10:17:54.000Z | maps/OlivineHouseBeta.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | 13 | 2020-01-11T17:00:40.000Z | 2021-09-14T01:27:38.000Z | maps/OlivineHouseBeta.asm | Dev727/ancientplatinum | 8b212a1728cc32a95743e1538b9eaa0827d013a7 | [
"blessing"
] | 22 | 2020-05-28T17:31:38.000Z | 2022-03-07T20:49:35.000Z | object_const_def ; object_event constants
const OLIVINEHOUSEBETA_TEACHER
const OLIVINEHOUSEBETA_RHYDON
OlivineHouseBeta_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
OlivineHouseBetaTeacherScript:
jumptextfaceplayer OlivineHouseBetaTeacherText
OlivineHouseBetaRhydonScript:
opentext
writetext OlivineHouseBetaRhydonText
cry RHYDON
waitbutton
closetext
end
OlivineHouseBetaBookshelf1:
jumpstd picturebookshelf
OlivineHouseBetaBookshelf2:
jumpstd magazinebookshelf
OlivineHouseBetaTeacherText:
text "When my #MON"
line "got sick, the"
para "PHARMACIST in"
line "ECRUTEAK made some"
cont "medicine for me."
done
OlivineHouseBetaRhydonText:
text "RHYDON: Gugooh!"
done
OlivineHouseBeta_MapEvents:
db 0, 0 ; filler
db 2 ; warp events
warp_event 2, 7, OLIVINE_CITY, 4
warp_event 3, 7, OLIVINE_CITY, 4
db 0 ; coord events
db 2 ; bg events
bg_event 0, 1, BGEVENT_READ, OlivineHouseBetaBookshelf1
bg_event 1, 1, BGEVENT_READ, OlivineHouseBetaBookshelf2
db 2 ; object events
object_event 2, 3, SPRITE_TEACHER, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, OlivineHouseBetaTeacherScript, -1
object_event 6, 4, SPRITE_RHYDON, SPRITEMOVEDATA_WALK_UP_DOWN, 0, 2, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, OlivineHouseBetaRhydonScript, -1
| 23.267857 | 142 | 0.792018 |
81614c23c168a52998ed18f40619b24c1758a46e | 374,842 | rs | Rust | diem-move/diem-framework/experimental/DPN/releases/artifacts/current/transaction_script_builder.rs | PragmaTwice/diem | a290b0859a6152a5ffd6f85773a875f17334adac | [
"Apache-2.0"
] | 16,705 | 2019-06-18T08:46:59.000Z | 2020-12-07T17:25:27.000Z | diem-move/diem-framework/experimental/DPN/releases/artifacts/current/transaction_script_builder.rs | PragmaTwice/diem | a290b0859a6152a5ffd6f85773a875f17334adac | [
"Apache-2.0"
] | 6,316 | 2019-06-18T09:02:03.000Z | 2020-12-07T21:27:46.000Z | diem-move/diem-framework/experimental/DPN/releases/artifacts/current/transaction_script_builder.rs | tnowacki/libra | af68c84afd947e84dc54b3ecaf749968ac6eb428 | [
"Apache-2.0"
] | 2,671 | 2019-06-18T08:47:03.000Z | 2020-12-07T19:35:21.000Z | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
// This file was generated. Do not modify!
//
// To update this code, run: `cargo run --release -p diem-framework`.
//! Conversion library between a structured representation of a Move script call (`ScriptCall`) and the
//! standard BCS-compatible representation used in Diem transactions (`Script`).
//!
//! This code was generated by compiling known Script interfaces ("ABIs") with the tool `transaction-builder-generator`.
#![allow(clippy::unnecessary_wraps)]
#![allow(unused_imports)]
use diem_types::{
account_address::AccountAddress,
transaction::{Script, ScriptFunction, TransactionArgument, TransactionPayload, VecBytes},
};
use move_core_types::{
ident_str,
language_storage::{ModuleId, TypeTag},
};
use std::collections::BTreeMap as Map;
type Bytes = Vec<u8>;
/// Structured representation of a call into a known Move script.
/// ```ignore
/// impl ScriptCall {
/// pub fn encode(self) -> Script { .. }
/// pub fn decode(&Script) -> Option<ScriptCall> { .. }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "fuzzing", derive(proptest_derive::Arbitrary))]
#[cfg_attr(feature = "fuzzing", proptest(no_params))]
pub enum ScriptCall {}
/// Structured representation of a call into a known Move script function.
/// ```ignore
/// impl ScriptFunctionCall {
/// pub fn encode(self) -> TransactionPayload { .. }
/// pub fn decode(&TransactionPayload) -> Option<ScriptFunctionCall> { .. }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "fuzzing", derive(proptest_derive::Arbitrary))]
#[cfg_attr(feature = "fuzzing", proptest(no_params))]
pub enum ScriptFunctionCall {
/// # Summary
/// Adds a zero `Currency` balance to the sending `account`. This will enable `account` to
/// send, receive, and hold `Diem::Diem<Currency>` coins. This transaction can be
/// successfully sent by any account that is allowed to hold balances
/// (e.g., VASP, Designated Dealer).
///
/// # Technical Description
/// After the successful execution of this transaction the sending account will have a
/// `DiemAccount::Balance<Currency>` resource with zero balance published under it. Only
/// accounts that can hold balances can send this transaction, the sending account cannot
/// already have a `DiemAccount::Balance<Currency>` published under it.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being added to the sending account of the transaction. `Currency` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Currency` is not a registered currency on-chain. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EROLE_CANT_STORE_BALANCE` | The sending `account`'s role does not permit balances. |
/// | `Errors::ALREADY_PUBLISHED` | `DiemAccount::EADD_EXISTING_CURRENCY` | A balance for `Currency` is already published under the sending `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `PaymentScripts::peer_to_peer_with_metadata`
AddCurrencyToAccount { currency: TypeTag },
/// # Summary
/// Stores the sending accounts ability to rotate its authentication key with a designated recovery
/// account. Both the sending and recovery accounts need to belong to the same VASP and
/// both be VASP accounts. After this transaction both the sending account and the
/// specified recovery account can rotate the sender account's authentication key.
///
/// # Technical Description
/// Adds the `DiemAccount::KeyRotationCapability` for the sending account
/// (`to_recover_account`) to the `RecoveryAddress::RecoveryAddress` resource under
/// `recovery_address`. After this transaction has been executed successfully the account at
/// `recovery_address` and the `to_recover_account` may rotate the authentication key of
/// `to_recover_account` (the sender of this transaction).
///
/// The sending account of this transaction (`to_recover_account`) must not have previously given away its unique key
/// rotation capability, and must be a VASP account. The account at `recovery_address`
/// must also be a VASP account belonging to the same VASP as the `to_recover_account`.
/// Additionally the account at `recovery_address` must have already initialized itself as
/// a recovery account address using the `AccountAdministrationScripts::create_recovery_address` transaction script.
///
/// The sending account's (`to_recover_account`) key rotation capability is
/// removed in this transaction and stored in the `RecoveryAddress::RecoveryAddress`
/// resource stored under the account at `recovery_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `to_recover_account` | `signer` | The signer of the sending account of this transaction. |
/// | `recovery_address` | `address` | The account address where the `to_recover_account`'s `DiemAccount::KeyRotationCapability` will be stored. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `to_recover_account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::NOT_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | `recovery_address` does not have a `RecoveryAddress` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EINVALID_KEY_ROTATION_DELEGATION` | `to_recover_account` and `recovery_address` do not belong to the same VASP. |
/// | `Errors::LIMIT_EXCEEDED` | ` RecoveryAddress::EMAX_KEYS_REGISTERED` | `RecoveryAddress::MAX_REGISTERED_KEYS` have already been registered with this `recovery_address`. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::create_recovery_address`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
AddRecoveryRotationCapability { recovery_address: AccountAddress },
/// # Summary
/// Adds a validator account to the validator set, and triggers a
/// reconfiguration of the system to admit the account to the validator set for the system. This
/// transaction can only be successfully called by the Diem Root account.
///
/// # Technical Description
/// This script adds the account at `validator_address` to the validator set.
/// This transaction emits a `DiemConfig::NewEpochEvent` event and triggers a
/// reconfiguration. Once the reconfiguration triggered by this script's
/// execution has been performed, the account at the `validator_address` is
/// considered to be a validator in the network.
///
/// This transaction script will fail if the `validator_address` address is already in the validator set
/// or does not have a `ValidatorConfig::ValidatorConfig` resource already published under it.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `validator_name` | `vector<u8>` | ASCII-encoded human name for the validator. Must match the human name in the `ValidatorConfig::ValidatorConfig` for the validator. |
/// | `validator_address` | `address` | The validator account address to be added to the validator set. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | 0 | 0 | The provided `validator_name` does not match the already-recorded human name for the validator. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::EINVALID_PROSPECTIVE_VALIDATOR` | The validator to be added does not have a `ValidatorConfig::ValidatorConfig` resource published under it, or its `config` field is empty. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::EALREADY_A_VALIDATOR` | The `validator_address` account is already a registered validator. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemSystem::EMAX_VALIDATORS` | The validator set is already at its maximum size. The validator could not be added. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
AddValidatorAndReconfigure {
sliding_nonce: u64,
validator_name: Bytes,
validator_address: AccountAddress,
},
/// # Summary
/// Add a VASP domain to parent VASP account. The transaction can only be sent by
/// the Treasury Compliance account.
///
/// # Technical Description
/// Adds a `VASPDomain::VASPDomain` to the `domains` field of the `VASPDomain::VASPDomains` resource published under
/// the account at `address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `address` | `address` | The `address` of the parent VASP account that will have have `domain` added to its domains. |
/// | `domain` | `vector<u8>` | The domain to be added. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAIN_MANAGER` | The `VASPDomain::VASPDomainManager` resource is not yet published under the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAINS_NOT_PUBLISHED` | `address` does not have a `VASPDomain::VASPDomains` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EDOMAIN_ALREADY_EXISTS` | The `domain` already exists in the list of `VASPDomain::VASPDomain`s in the `VASPDomain::VASPDomains` resource published under `address`. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EINVALID_VASP_DOMAIN` | The `domain` is greater in length than `VASPDomain::DOMAIN_LENGTH`. |
AddVaspDomain {
address: AccountAddress,
domain: Bytes,
},
/// # Summary
/// Burns the transaction fees collected in the `CoinType` currency so that the
/// Diem association may reclaim the backing coins off-chain. May only be sent
/// by the Treasury Compliance account.
///
/// # Technical Description
/// Burns the transaction fees collected in `CoinType` so that the
/// association may reclaim the backing coins. Once this transaction has executed
/// successfully all transaction fees that will have been collected in
/// `CoinType` since the last time this script was called with that specific
/// currency. Both `balance` and `preburn` fields in the
/// `TransactionFee::TransactionFee<CoinType>` resource published under the `0xB1E55ED`
/// account address will have a value of 0 after the successful execution of this script.
///
/// # Events
/// The successful execution of this transaction will emit a `Diem::BurnEvent` on the event handle
/// held in the `Diem::CurrencyInfo<CoinType>` resource's `burn_events` published under
/// `0xA550C18`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` being added to the sending account of the transaction. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `TransactionFee::ETRANSACTION_FEE` | `CoinType` is not an accepted transaction fee currency. |
/// | `Errors::INVALID_ARGUMENT` | `Diem::ECOIN` | The collected fees in `CoinType` are zero. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
BurnTxnFees { coin_type: TypeTag },
/// # Summary
/// Burns the coins held in a preburn resource in the preburn queue at the
/// specified preburn address, which are equal to the `amount` specified in the
/// transaction. Finds the first relevant outstanding preburn request with
/// matching amount and removes the contained coins from the system. The sending
/// account must be the Treasury Compliance account.
/// The account that holds the preburn queue resource will normally be a Designated
/// Dealer, but there are no enforced requirements that it be one.
///
/// # Technical Description
/// This transaction permanently destroys all the coins of `Token` type
/// stored in the `Diem::Preburn<Token>` resource published under the
/// `preburn_address` account address.
///
/// This transaction will only succeed if the sending `account` has a
/// `Diem::BurnCapability<Token>`, and a `Diem::Preburn<Token>` resource
/// exists under `preburn_address`, with a non-zero `to_burn` field. After the successful execution
/// of this transaction the `total_value` field in the
/// `Diem::CurrencyInfo<Token>` resource published under `0xA550C18` will be
/// decremented by the value of the `to_burn` field of the preburn resource
/// under `preburn_address` immediately before this transaction, and the
/// `to_burn` field of the preburn resource will have a zero value.
///
/// # Events
/// The successful execution of this transaction will emit a `Diem::BurnEvent` on the event handle
/// held in the `Diem::CurrencyInfo<Token>` resource's `burn_events` published under
/// `0xA550C18`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currency being burned. `Token` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction, must have a burn capability for `Token` published under it. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `preburn_address` | `address` | The address where the coins to-be-burned are currently held. |
/// | `amount` | `u64` | The amount to be burned. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EBURN_CAPABILITY` | The sending `account` does not have a `Diem::BurnCapability<Token>` published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_NOT_FOUND` | The `Diem::PreburnQueue<Token>` resource under `preburn_address` does not contain a preburn request with a value matching `amount`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN_QUEUE` | The account at `preburn_address` does not have a `Diem::PreburnQueue<Token>` resource published under it. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The specified `Token` is not a registered currency on-chain. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_txn_fees`
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
/// * `TreasuryComplianceScripts::preburn`
BurnWithAmount {
token: TypeTag,
sliding_nonce: u64,
preburn_address: AccountAddress,
amount: u64,
},
/// # Summary
/// Cancels and returns the coins held in the preburn area under
/// `preburn_address`, which are equal to the `amount` specified in the transaction. Finds the first preburn
/// resource with the matching amount and returns the funds to the `preburn_address`'s balance.
/// Can only be successfully sent by an account with Treasury Compliance role.
///
/// # Technical Description
/// Cancels and returns all coins held in the `Diem::Preburn<Token>` resource under the `preburn_address` and
/// return the funds to the `preburn_address` account's `DiemAccount::Balance<Token>`.
/// The transaction must be sent by an `account` with a `Diem::BurnCapability<Token>`
/// resource published under it. The account at `preburn_address` must have a
/// `Diem::Preburn<Token>` resource published under it, and its value must be nonzero. The transaction removes
/// the entire balance held in the `Diem::Preburn<Token>` resource, and returns it back to the account's
/// `DiemAccount::Balance<Token>` under `preburn_address`. Due to this, the account at
/// `preburn_address` must already have a balance in the `Token` currency published
/// before this script is called otherwise the transaction will fail.
///
/// # Events
/// The successful execution of this transaction will emit:
/// * A `Diem::CancelBurnEvent` on the event handle held in the `Diem::CurrencyInfo<Token>`
/// resource's `burn_events` published under `0xA550C18`.
/// * A `DiemAccount::ReceivedPaymentEvent` on the `preburn_address`'s
/// `DiemAccount::DiemAccount` `received_events` event handle with both the `payer` and `payee`
/// being `preburn_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currenty that burning is being cancelled for. `Token` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account of this transaction, must have a burn capability for `Token` published under it. |
/// | `preburn_address` | `address` | The address where the coins to-be-burned are currently held. |
/// | `amount` | `u64` | The amount to be cancelled. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EBURN_CAPABILITY` | The sending `account` does not have a `Diem::BurnCapability<Token>` published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_NOT_FOUND` | The `Diem::PreburnQueue<Token>` resource under `preburn_address` does not contain a preburn request with a value matching `amount`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN_QUEUE` | The account at `preburn_address` does not have a `Diem::PreburnQueue<Token>` resource published under it. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The specified `Token` is not a registered currency on-chain. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | The account at `preburn_address` doesn't have a balance resource for `Token`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | The depositing of the funds held in the prebun area would exceed the `account`'s account limits. |
/// | `Errors::INVALID_STATE` | `DualAttestation::EPAYEE_COMPLIANCE_KEY_NOT_SET` | The `account` does not have a compliance key set on it but dual attestion checking was performed. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_txn_fees`
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::preburn`
CancelBurnWithAmount {
token: TypeTag,
preburn_address: AccountAddress,
amount: u64,
},
/// # Summary
/// Creates a Child VASP account with its parent being the sending account of the transaction.
/// The sender of the transaction must be a Parent VASP account.
///
/// # Technical Description
/// Creates a `ChildVASP` account for the sender `parent_vasp` at `child_address` with a balance of
/// `child_initial_balance` in `CoinType` and an initial authentication key of
/// `auth_key_prefix | child_address`. Authentication key prefixes, and how to construct them from an ed25519 public key is described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// If `add_all_currencies` is true, the child address will have a zero balance in all available
/// currencies in the system.
///
/// The new account will be a child account of the transaction sender, which must be a
/// Parent VASP account. The child account will be recorded against the limit of
/// child accounts of the creating Parent VASP account.
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `child_address`,
/// and the `rold_id` field being `Roles::CHILD_VASP_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// Successful execution with a `child_initial_balance` greater than zero will additionaly emit:
/// * A `DiemAccount::SentPaymentEvent` with the `payee` field being `child_address`.
/// This is emitted on the Parent VASP's `DiemAccount::DiemAccount` `sent_events` handle.
/// * A `DiemAccount::ReceivedPaymentEvent` with the `payer` field being the Parent VASP's address.
/// This is emitted on the new Child VASPS's `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` that the child account should be created with. `CoinType` must be an already-registered currency on-chain. |
/// | `parent_vasp` | `signer` | The reference of the sending account. Must be a Parent VASP account. |
/// | `child_address` | `address` | Address of the to-be-created Child VASP account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `add_all_currencies` | `bool` | Whether to publish balance resources for all known currencies when the account is created. |
/// | `child_initial_balance` | `u64` | The initial balance in `CoinType` to give the child account when it's created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | The `auth_key_prefix` was not of length 32. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EPARENT_VASP` | The sending account wasn't a Parent VASP account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `child_address` address is already taken. |
/// | `Errors::LIMIT_EXCEEDED` | `VASP::ETOO_MANY_CHILDREN` | The sending account has reached the maximum number of allowed child accounts. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `CoinType` is not a registered currency on-chain. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED` | The withdrawal capability for the sending account has already been extracted. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | The sending account doesn't have a balance in `CoinType`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | The sending account doesn't have at least `child_initial_balance` of `CoinType` balance. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECANNOT_CREATE_AT_VM_RESERVED` | The `child_address` is the reserved address 0x0. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::add_recovery_rotation_capability`
/// * `AccountAdministrationScripts::create_recovery_address`
CreateChildVaspAccount {
coin_type: TypeTag,
child_address: AccountAddress,
auth_key_prefix: Bytes,
add_all_currencies: bool,
child_initial_balance: u64,
},
/// # Summary
/// Creates a Designated Dealer account with the provided information, and initializes it with
/// default mint tiers. The transaction can only be sent by the Treasury Compliance account.
///
/// # Technical Description
/// Creates an account with the Designated Dealer role at `addr` with authentication key
/// `auth_key_prefix` | `addr` and a 0 balance of type `Currency`. If `add_all_currencies` is true,
/// 0 balances for all available currencies in the system will also be added. This can only be
/// invoked by an account with the TreasuryCompliance role.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// At the time of creation the account is also initialized with default mint tiers of (500_000,
/// 5000_000, 50_000_000, 500_000_000), and preburn areas for each currency that is added to the
/// account.
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `addr`,
/// and the `rold_id` field being `Roles::DESIGNATED_DEALER_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` that the Designated Dealer should be initialized with. `Currency` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `addr` | `address` | Address of the to-be-created Designated Dealer account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the Designated Dealer. |
/// | `add_all_currencies` | `bool` | Whether to publish preburn, balance, and tier info resources for all known (SCS) currencies or just `Currency` when the account is created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Currency` is not a registered currency on-chain. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `addr` address is already taken. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::tiered_mint`
/// * `PaymentScripts::peer_to_peer_with_metadata`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
CreateDesignatedDealer {
currency: TypeTag,
sliding_nonce: u64,
addr: AccountAddress,
auth_key_prefix: Bytes,
human_name: Bytes,
add_all_currencies: bool,
},
/// # Summary
/// Creates a Parent VASP account with the specified human name. Must be called by the Treasury Compliance account.
///
/// # Technical Description
/// Creates an account with the Parent VASP role at `address` with authentication key
/// `auth_key_prefix` | `new_account_address` and a 0 balance of type `CoinType`. If
/// `add_all_currencies` is true, 0 balances for all available currencies in the system will
/// also be added. This can only be invoked by an TreasuryCompliance account.
/// `sliding_nonce` is a unique nonce for operation, see `SlidingNonce` for details.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::PARENT_VASP_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` currency that the Parent VASP account should be initialized with. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Parent VASP account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the Parent VASP. |
/// | `add_all_currencies` | `bool` | Whether to publish balance resources for all known currencies when the account is created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `CoinType` is not a registered currency on-chain. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::add_recovery_rotation_capability`
/// * `AccountAdministrationScripts::create_recovery_address`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
CreateParentVaspAccount {
coin_type: TypeTag,
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Bytes,
human_name: Bytes,
add_all_currencies: bool,
},
/// # Summary
/// Initializes the sending account as a recovery address that may be used by
/// other accounts belonging to the same VASP as `account`.
/// The sending account must be a VASP account, and can be either a child or parent VASP account.
/// Multiple recovery addresses can exist for a single VASP, but accounts in
/// each must be disjoint.
///
/// # Technical Description
/// Publishes a `RecoveryAddress::RecoveryAddress` resource under `account`. It then
/// extracts the `DiemAccount::KeyRotationCapability` for `account` and adds
/// it to the resource. After the successful execution of this transaction
/// other accounts may add their key rotation to this resource so that `account`
/// may be used as a recovery account for those accounts.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::ENOT_A_VASP` | `account` is not a VASP account. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EKEY_ROTATION_DEPENDENCY_CYCLE` | A key rotation recovery cycle would be created by adding `account`'s key rotation capability. |
/// | `Errors::ALREADY_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | A `RecoveryAddress::RecoveryAddress` resource has already been published under `account`. |
///
/// # Related Scripts
/// * `Script::add_recovery_rotation_capability`
/// * `Script::rotate_authentication_key_with_recovery_address`
CreateRecoveryAddress {},
/// # Summary
/// Creates a Validator account. This transaction can only be sent by the Diem
/// Root account.
///
/// # Technical Description
/// Creates an account with a Validator role at `new_account_address`, with authentication key
/// `auth_key_prefix` | `new_account_address`. It publishes a
/// `ValidatorConfig::ValidatorConfig` resource with empty `config`, and
/// `operator_account` fields. The `human_name` field of the
/// `ValidatorConfig::ValidatorConfig` is set to the passed in `human_name`.
/// This script does not add the validator to the validator set or the system,
/// but only creates the account.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::VALIDATOR_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Validator account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the validator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
CreateValidatorAccount {
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Bytes,
human_name: Bytes,
},
/// # Summary
/// Creates a Validator Operator account. This transaction can only be sent by the Diem
/// Root account.
///
/// # Technical Description
/// Creates an account with a Validator Operator role at `new_account_address`, with authentication key
/// `auth_key_prefix` | `new_account_address`. It publishes a
/// `ValidatorOperatorConfig::ValidatorOperatorConfig` resource with the specified `human_name`.
/// This script does not assign the validator operator to any validator accounts but only creates the account.
/// Authentication key prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::VALIDATOR_OPERATOR_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Validator account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the validator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
CreateValidatorOperatorAccount {
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Bytes,
human_name: Bytes,
},
/// # Summary
/// Publishes a `VASPDomain::VASPDomains` resource under a parent VASP account.
/// The sending account must be a parent VASP account.
///
/// # Technical Description
/// Publishes a `VASPDomain::VASPDomains` resource under `account`.
/// The The `VASPDomain::VASPDomains` resource's `domains` field is a vector
/// of VASPDomain, and will be empty on at the end of processing this transaction.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::ALREADY_PUBLISHED` | `VASPDomain::EVASP_DOMAINS` | A `VASPDomain::VASPDomains` resource has already been published under `account`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EPARENT_VASP` | The sending `account` was not a parent VASP account. |
CreateVaspDomains {},
/// # Summary
/// Shifts the window held by the CRSN resource published under `account`
/// by `shift_amount`. This will expire all unused slots in the CRSN at the
/// time of processing that are less than `shift_amount`. The exact
/// semantics are defined in DIP-168.
///
/// # Technical Description
/// This shifts the slots in the published `CRSN::CRSN` resource under
/// `account` by `shift_amount`, and increments the CRSN's `min_nonce` field
/// by `shift_amount` as well. After this, it will shift the window over
/// any set bits. It is important to note that the sequence nonce of the
/// sending transaction must still lie within the range of the window in
/// order for this transaction to be processed successfully.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `shift_amount` | `u64` | The amount to shift the window in the CRSN under `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `CRSN::ENO_CRSN` | A `CRSN::CRSN` resource is not published under `account`. |
ForceExpire { shift_amount: u64 },
/// # Summary
/// Freezes the account at `address`. The sending account of this transaction
/// must be the Treasury Compliance account. The account being frozen cannot be
/// the Diem Root or Treasury Compliance account. After the successful
/// execution of this transaction no transactions may be sent from the frozen
/// account, and the frozen account may not send or receive coins.
///
/// # Technical Description
/// Sets the `AccountFreezing::FreezingBit` to `true` and emits a
/// `AccountFreezing::FreezeAccountEvent`. The transaction sender must be the
/// Treasury Compliance account, but the account at `to_freeze_account` must
/// not be either `0xA550C18` (the Diem Root address), or `0xB1E55ED` (the
/// Treasury Compliance address). Note that this is a per-account property
/// e.g., freezing a Parent VASP will not effect the status any of its child
/// accounts and vice versa.
///
/// # Events
/// Successful execution of this transaction will emit a `AccountFreezing::FreezeAccountEvent` on
/// the `freeze_event_handle` held in the `AccountFreezing::FreezeEventsHolder` resource published
/// under `0xA550C18` with the `frozen_address` being the `to_freeze_account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `to_freeze_account` | `address` | The account address to be frozen. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `AccountFreezing::ECANNOT_FREEZE_TC` | `to_freeze_account` was the Treasury Compliance account (`0xB1E55ED`). |
/// | `Errors::INVALID_ARGUMENT` | `AccountFreezing::ECANNOT_FREEZE_DIEM_ROOT` | `to_freeze_account` was the Diem Root account (`0xA550C18`). |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::unfreeze_account`
FreezeAccount {
sliding_nonce: u64,
to_freeze_account: AccountAddress,
},
/// # Summary
/// Initializes the Diem consensus config that is stored on-chain. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Initializes the `DiemConsensusConfig` on-chain config to empty and allows future updates from DiemRoot via
/// `update_diem_consensus_config`. This doesn't emit a `DiemConfig::NewEpochEvent`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
InitializeDiemConsensusConfig { sliding_nonce: u64 },
/// # Summary
/// Publishes a CRSN resource under `account` and opts the account in to
/// concurrent transaction processing. Upon successful execution of this
/// script, all further transactions sent from this account will be ordered
/// and processed according to DIP-168.
///
/// # Technical Description
/// This publishes a `CRSN::CRSN` resource under `account` with `crsn_size`
/// number of slots. All slots will be initialized to the empty (unused)
/// state, and the CRSN resource's `min_nonce` field will be set to the transaction's
/// sequence number + 1.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `crsn_size` | `u64` | The the number of slots the published CRSN will have. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `CRSN::EHAS_CRSN` | A `CRSN::CRSN` resource was already published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `CRSN::EZERO_SIZE_CRSN` | The `crsn_size` was zero. |
OptInToCrsn { crsn_size: u64 },
/// # Summary
/// Transfers a given number of coins in a specified currency from one account to another by multi-agent transaction.
/// Transfers over a specified amount defined on-chain that are between two different VASPs, or
/// other accounts that have opted-in will be subject to on-chain checks to ensure the receiver has
/// agreed to receive the coins. This transaction can be sent by any account that can hold a
/// balance, and to any account that can hold a balance. Both accounts must hold balances in the
/// currency being transacted.
///
/// # Technical Description
///
/// Transfers `amount` coins of type `Currency` from `payer` to `payee` with (optional) associated
/// `metadata`.
/// Dual attestation is not applied to this script as payee is also a signer of the transaction.
/// Standardized `metadata` BCS format can be found in `diem_types::transaction::metadata::Metadata`.
///
/// # Events
/// Successful execution of this script emits two events:
/// * A `DiemAccount::SentPaymentEvent` on `payer`'s `DiemAccount::DiemAccount` `sent_events` handle; and
/// * A `DiemAccount::ReceivedPaymentEvent` on `payee`'s `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being sent in this transaction. `Currency` must be an already-registered currency on-chain. |
/// | `payer` | `signer` | The signer of the sending account that coins are being transferred from. |
/// | `payee` | `signer` | The signer of the receiving account that the coins are being transferred to. |
/// | `metadata` | `vector<u8>` | Optional metadata about this payment. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `payer` doesn't hold a balance in `Currency`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Currency`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECOIN_DEPOSIT_IS_ZERO` | `amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYEE_DOES_NOT_EXIST` | No account exists at the `payee` address. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | An account exists at `payee`, but it does not accept payments in `Currency`. |
/// | `Errors::INVALID_STATE` | `AccountFreezing::EACCOUNT_FROZEN` | The `payee` account is frozen. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EWITHDRAWAL_EXCEEDS_LIMITS` | `payer` has exceeded its daily withdrawal limits for the backing coins of XDX. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | `payee` has exceeded its daily deposit limits for XDX. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `PaymentScripts::peer_to_peer_with_metadata`
PeerToPeerBySigners {
currency: TypeTag,
amount: u64,
metadata: Bytes,
},
/// # Summary
/// Transfers a given number of coins in a specified currency from one account to another.
/// Transfers over a specified amount defined on-chain that are between two different VASPs, or
/// other accounts that have opted-in will be subject to on-chain checks to ensure the receiver has
/// agreed to receive the coins. This transaction can be sent by any account that can hold a
/// balance, and to any account that can hold a balance. Both accounts must hold balances in the
/// currency being transacted.
///
/// # Technical Description
///
/// Transfers `amount` coins of type `Currency` from `payer` to `payee` with (optional) associated
/// `metadata` and an (optional) `metadata_signature` on the message of the form
/// `metadata` | `Signer::address_of(payer)` | `amount` | `DualAttestation::DOMAIN_SEPARATOR`, that
/// has been signed by the `payee`'s private key associated with the `compliance_public_key` held in
/// the `payee`'s `DualAttestation::Credential`. Both the `Signer::address_of(payer)` and `amount` fields
/// in the `metadata_signature` must be BCS-encoded bytes, and `|` denotes concatenation.
/// The `metadata` and `metadata_signature` parameters are only required if `amount` >=
/// `DualAttestation::get_cur_microdiem_limit` XDX and `payer` and `payee` are distinct VASPs.
/// However, a transaction sender can opt in to dual attestation even when it is not required
/// (e.g., a DesignatedDealer -> VASP payment) by providing a non-empty `metadata_signature`.
/// Standardized `metadata` BCS format can be found in `diem_types::transaction::metadata::Metadata`.
///
/// # Events
/// Successful execution of this script emits two events:
/// * A `DiemAccount::SentPaymentEvent` on `payer`'s `DiemAccount::DiemAccount` `sent_events` handle; and
/// * A `DiemAccount::ReceivedPaymentEvent` on `payee`'s `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being sent in this transaction. `Currency` must be an already-registered currency on-chain. |
/// | `payer` | `signer` | The signer of the sending account that coins are being transferred from. |
/// | `payee` | `address` | The address of the account the coins are being transferred to. |
/// | `metadata` | `vector<u8>` | Optional metadata about this payment. |
/// | `metadata_signature` | `vector<u8>` | Optional signature over `metadata` and payment information. See |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `payer` doesn't hold a balance in `Currency`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Currency`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECOIN_DEPOSIT_IS_ZERO` | `amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYEE_DOES_NOT_EXIST` | No account exists at the `payee` address. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | An account exists at `payee`, but it does not accept payments in `Currency`. |
/// | `Errors::INVALID_STATE` | `AccountFreezing::EACCOUNT_FROZEN` | The `payee` account is frozen. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EMALFORMED_METADATA_SIGNATURE` | `metadata_signature` is not 64 bytes. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EINVALID_METADATA_SIGNATURE` | `metadata_signature` does not verify on the against the `payee'`s `DualAttestation::Credential` `compliance_public_key` public key. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EWITHDRAWAL_EXCEEDS_LIMITS` | `payer` has exceeded its daily withdrawal limits for the backing coins of XDX. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | `payee` has exceeded its daily deposit limits for XDX. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `PaymentScripts::peer_to_peer_by_signers`
PeerToPeerWithMetadata {
currency: TypeTag,
payee: AccountAddress,
amount: u64,
metadata: Bytes,
metadata_signature: Bytes,
},
/// # Summary
/// Moves a specified number of coins in a given currency from the account's
/// balance to its preburn area after which the coins may be burned. This
/// transaction may be sent by any account that holds a balance and preburn area
/// in the specified currency.
///
/// # Technical Description
/// Moves the specified `amount` of coins in `Token` currency from the sending `account`'s
/// `DiemAccount::Balance<Token>` to the `Diem::Preburn<Token>` published under the same
/// `account`. `account` must have both of these resources published under it at the start of this
/// transaction in order for it to execute successfully.
///
/// # Events
/// Successful execution of this script emits two events:
/// * `DiemAccount::SentPaymentEvent ` on `account`'s `DiemAccount::DiemAccount` `sent_events`
/// handle with the `payee` and `payer` fields being `account`'s address; and
/// * A `Diem::PreburnEvent` with `Token`'s currency code on the
/// `Diem::CurrencyInfo<Token`'s `preburn_events` handle for `Token` and with
/// `preburn_address` set to `account`'s address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currency being moved to the preburn area. `Token` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account. |
/// | `amount` | `u64` | The amount in `Token` to be moved to the preburn area. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Token` is not a registered currency on-chain. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED` | The withdrawal capability for `account` has already been extracted. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Token`. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `account` doesn't hold a balance in `Token`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN` | `account` doesn't have a `Diem::Preburn<Token>` resource published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_OCCUPIED` | The `value` field in the `Diem::Preburn<Token>` resource under the sender is non-zero. |
/// | `Errors::NOT_PUBLISHED` | `Roles::EROLE_ID` | The `account` did not have a role assigned to it. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDESIGNATED_DEALER` | The `account` did not have the role of DesignatedDealer. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::burn_txn_fees`
Preburn { token: TypeTag, amount: u64 },
/// # Summary
/// Rotates the authentication key of the sending account to the newly-specified ed25519 public key and
/// publishes a new shared authentication key derived from that public key under the sender's account.
/// Any account can send this transaction.
///
/// # Technical Description
/// Rotates the authentication key of the sending account to the
/// [authentication key derived from `public_key`](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys)
/// and publishes a `SharedEd25519PublicKey::SharedEd25519PublicKey` resource
/// containing the 32-byte ed25519 `public_key` and the `DiemAccount::KeyRotationCapability` for
/// `account` under `account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `public_key` | `vector<u8>` | A valid 32-byte Ed25519 public key for `account`'s authentication key to be rotated to and stored. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability` resource. |
/// | `Errors::ALREADY_PUBLISHED` | `SharedEd25519PublicKey::ESHARED_KEY` | The `SharedEd25519PublicKey::SharedEd25519PublicKey` resource is already published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SharedEd25519PublicKey::EMALFORMED_PUBLIC_KEY` | `public_key` is an invalid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_shared_ed25519_public_key`
PublishSharedEd25519PublicKey { public_key: Bytes },
/// # Summary
/// Updates a validator's configuration. This does not reconfigure the system and will not update
/// the configuration in the validator set that is seen by other validators in the network. Can
/// only be successfully sent by a Validator Operator account that is already registered with a
/// validator.
///
/// # Technical Description
/// This updates the fields with corresponding names held in the `ValidatorConfig::ValidatorConfig`
/// config resource held under `validator_account`. It does not emit a `DiemConfig::NewEpochEvent`
/// so the copy of this config held in the validator set will not be updated, and the changes are
/// only "locally" under the `validator_account` account address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `validator_operator_account` | `signer` | Signer of the sending account. Must be the registered validator operator for the validator at `validator_address`. |
/// | `validator_account` | `address` | The address of the validator's `ValidatorConfig::ValidatorConfig` resource being updated. |
/// | `consensus_pubkey` | `vector<u8>` | New Ed25519 public key to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `validator_network_addresses` | `vector<u8>` | New set of `validator_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `fullnode_network_addresses` | `vector<u8>` | New set of `fullnode_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | `validator_address` does not have a `ValidatorConfig::ValidatorConfig` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_TRANSACTION_SENDER` | `validator_operator_account` is not the registered operator for the validator at `validator_address`. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_CONSENSUS_KEY` | `consensus_pubkey` is not a valid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
RegisterValidatorConfig {
validator_account: AccountAddress,
consensus_pubkey: Bytes,
validator_network_addresses: Bytes,
fullnode_network_addresses: Bytes,
},
/// # Summary
/// This script removes a validator account from the validator set, and triggers a reconfiguration
/// of the system to remove the validator from the system. This transaction can only be
/// successfully called by the Diem Root account.
///
/// # Technical Description
/// This script removes the account at `validator_address` from the validator set. This transaction
/// emits a `DiemConfig::NewEpochEvent` event. Once the reconfiguration triggered by this event
/// has been performed, the account at `validator_address` is no longer considered to be a
/// validator in the network. This transaction will fail if the validator at `validator_address`
/// is not in the validator set.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `validator_name` | `vector<u8>` | ASCII-encoded human name for the validator. Must match the human name in the `ValidatorConfig::ValidatorConfig` for the validator. |
/// | `validator_address` | `address` | The validator account address to be removed from the validator set. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | The sending account is not the Diem Root account or Treasury Compliance account |
/// | 0 | 0 | The provided `validator_name` does not match the already-recorded human name for the validator. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::ENOT_AN_ACTIVE_VALIDATOR` | The validator to be removed is not in the validator set. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
RemoveValidatorAndReconfigure {
sliding_nonce: u64,
validator_name: Bytes,
validator_address: AccountAddress,
},
/// # Summary
/// Remove a VASP domain from parent VASP account. The transaction can only be sent by
/// the Treasury Compliance account.
///
/// # Technical Description
/// Removes a `VASPDomain::VASPDomain` from the `domains` field of the `VASPDomain::VASPDomains` resource published under
/// account with `address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `address` | `address` | The `address` of parent VASP account that will update its domains. |
/// | `domain` | `vector<u8>` | The domain name. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAIN_MANAGER` | The `VASPDomain::VASPDomainManager` resource is not yet published under the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAINS_NOT_PUBLISHED` | `address` does not have a `VASPDomain::VASPDomains` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EINVALID_VASP_DOMAIN` | The `domain` is greater in length than `VASPDomain::DOMAIN_LENGTH`. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EVASP_DOMAIN_NOT_FOUND` | The `domain` does not exist in the list of `VASPDomain::VASPDomain`s in the `VASPDomain::VASPDomains` resource published under `address`. |
RemoveVaspDomain {
address: AccountAddress,
domain: Bytes,
},
/// # Summary
/// Rotates the `account`'s authentication key to the supplied new authentication key. May be sent by any account.
///
/// # Technical Description
/// Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_key`
/// field to `new_key`. `new_key` must be a valid authentication key that
/// corresponds to an ed25519 public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
RotateAuthenticationKey { new_key: Bytes },
/// # Summary
/// Rotates the sender's authentication key to the supplied new authentication key. May be sent by
/// any account that has a sliding nonce resource published under it (usually this is Treasury
/// Compliance or Diem Root accounts).
///
/// # Technical Description
/// Rotates the `account`'s `DiemAccount::DiemAccount` `authentication_key`
/// field to `new_key`. `new_key` must be a valid authentication key that
/// corresponds to an ed25519 public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
RotateAuthenticationKeyWithNonce { sliding_nonce: u64, new_key: Bytes },
/// # Summary
/// Rotates the specified account's authentication key to the supplied new authentication key. May
/// only be sent by the Diem Root account as a write set transaction.
///
/// # Technical Description
/// Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_key` field to `new_key`.
/// `new_key` must be a valid authentication key that corresponds to an ed25519
/// public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of the write set transaction. May only be the Diem Root signer. |
/// | `account` | `signer` | Signer of account specified in the `execute_as` field of the write set transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction for Diem Root. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` in `dr_account` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` in `dr_account` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` in` dr_account` has been previously recorded. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
RotateAuthenticationKeyWithNonceAdmin { sliding_nonce: u64, new_key: Bytes },
/// # Summary
/// Rotates the authentication key of a specified account that is part of a recovery address to a
/// new authentication key. Only used for accounts that are part of a recovery address (see
/// `AccountAdministrationScripts::add_recovery_rotation_capability` for account restrictions).
///
/// # Technical Description
/// Rotates the authentication key of the `to_recover` account to `new_key` using the
/// `DiemAccount::KeyRotationCapability` stored in the `RecoveryAddress::RecoveryAddress` resource
/// published under `recovery_address`. `new_key` must be a valide authentication key as described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
/// This transaction can be sent either by the `to_recover` account, or by the account where the
/// `RecoveryAddress::RecoveryAddress` resource is published that contains `to_recover`'s `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `recovery_address` | `address` | Address where `RecoveryAddress::RecoveryAddress` that holds `to_recover`'s `DiemAccount::KeyRotationCapability` is published. |
/// | `to_recover` | `address` | The address of the account whose authentication key will be updated. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for the account at the `to_recover` address. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | `recovery_address` does not have a `RecoveryAddress::RecoveryAddress` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::ECANNOT_ROTATE_KEY` | The address of `account` is not `recovery_address` or `to_recover`. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EACCOUNT_NOT_RECOVERABLE` | `to_recover`'s `DiemAccount::KeyRotationCapability` is not in the `RecoveryAddress::RecoveryAddress` resource published under `recovery_address`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
RotateAuthenticationKeyWithRecoveryAddress {
recovery_address: AccountAddress,
to_recover: AccountAddress,
new_key: Bytes,
},
/// # Summary
/// Updates the url used for off-chain communication, and the public key used to verify dual
/// attestation on-chain. Transaction can be sent by any account that has dual attestation
/// information published under it. In practice the only such accounts are Designated Dealers and
/// Parent VASPs.
///
/// # Technical Description
/// Updates the `base_url` and `compliance_public_key` fields of the `DualAttestation::Credential`
/// resource published under `account`. The `new_key` must be a valid ed25519 public key.
///
/// # Events
/// Successful execution of this transaction emits two events:
/// * A `DualAttestation::ComplianceKeyRotationEvent` containing the new compliance public key, and
/// the blockchain time at which the key was updated emitted on the `DualAttestation::Credential`
/// `compliance_key_rotation_events` handle published under `account`; and
/// * A `DualAttestation::BaseUrlRotationEvent` containing the new base url to be used for
/// off-chain communication, and the blockchain time at which the url was updated emitted on the
/// `DualAttestation::Credential` `base_url_rotation_events` handle published under `account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `new_url` | `vector<u8>` | ASCII-encoded url to be used for off-chain communication with `account`. |
/// | `new_key` | `vector<u8>` | New ed25519 public key to be used for on-chain dual attestation checking. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DualAttestation::ECREDENTIAL` | A `DualAttestation::Credential` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EINVALID_PUBLIC_KEY` | `new_key` is not a valid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountCreationScripts::create_designated_dealer`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
RotateDualAttestationInfo { new_url: Bytes, new_key: Bytes },
/// # Summary
/// Rotates the authentication key in a `SharedEd25519PublicKey`. This transaction can be sent by
/// any account that has previously published a shared ed25519 public key using
/// `AccountAdministrationScripts::publish_shared_ed25519_public_key`.
///
/// # Technical Description
/// `public_key` must be a valid ed25519 public key. This transaction first rotates the public key stored in `account`'s
/// `SharedEd25519PublicKey::SharedEd25519PublicKey` resource to `public_key`, after which it
/// rotates the `account`'s authentication key to the new authentication key derived from `public_key` as defined
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys)
/// using the `DiemAccount::KeyRotationCapability` stored in `account`'s `SharedEd25519PublicKey::SharedEd25519PublicKey`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `public_key` | `vector<u8>` | 32-byte Ed25519 public key. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SharedEd25519PublicKey::ESHARED_KEY` | A `SharedEd25519PublicKey::SharedEd25519PublicKey` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SharedEd25519PublicKey::EMALFORMED_PUBLIC_KEY` | `public_key` is an invalid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::publish_shared_ed25519_public_key`
RotateSharedEd25519PublicKey { public_key: Bytes },
/// # Summary
/// Updates the gas constants stored on chain and used by the VM for gas
/// metering. This transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the on-chain config holding the `DiemVMConfig` and emits a
/// `DiemConfig::NewEpochEvent` to trigger a reconfiguration of the system.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `global_memory_per_byte_cost` | `u64` | The new cost to read global memory per-byte to be used for gas metering. |
/// | `global_memory_per_byte_write_cost` | `u64` | The new cost to write global memory per-byte to be used for gas metering. |
/// | `min_transaction_gas_units` | `u64` | The new flat minimum amount of gas required for any transaction. |
/// | `large_transaction_cutoff` | `u64` | The new size over which an additional charge will be assessed for each additional byte. |
/// | `intrinsic_gas_per_byte` | `u64` | The new number of units of gas that to be charged per-byte over the new `large_transaction_cutoff`. |
/// | `maximum_number_of_gas_units` | `u64` | The new maximum number of gas units that can be set in a transaction. |
/// | `min_price_per_gas_unit` | `u64` | The new minimum gas price that can be set for a transaction. |
/// | `max_price_per_gas_unit` | `u64` | The new maximum gas price that can be set for a transaction. |
/// | `max_transaction_size_in_bytes` | `u64` | The new maximum size of a transaction that can be processed. |
/// | `gas_unit_scaling_factor` | `u64` | The new scaling factor to use when scaling between external and internal gas units. |
/// | `default_account_size` | `u64` | The new default account size to use when assessing final costs for reads and writes to global storage. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_ARGUMENT` | `DiemVMConfig::EGAS_CONSTANT_INCONSISTENCY` | The provided gas constants are inconsistent. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
SetGasConstants {
sliding_nonce: u64,
global_memory_per_byte_cost: u64,
global_memory_per_byte_write_cost: u64,
min_transaction_gas_units: u64,
large_transaction_cutoff: u64,
intrinsic_gas_per_byte: u64,
maximum_number_of_gas_units: u64,
min_price_per_gas_unit: u64,
max_price_per_gas_unit: u64,
max_transaction_size_in_bytes: u64,
gas_unit_scaling_factor: u64,
default_account_size: u64,
},
/// # Summary
/// Updates a validator's configuration, and triggers a reconfiguration of the system to update the
/// validator set with this new validator configuration. Can only be successfully sent by a
/// Validator Operator account that is already registered with a validator.
///
/// # Technical Description
/// This updates the fields with corresponding names held in the `ValidatorConfig::ValidatorConfig`
/// config resource held under `validator_account`. It then emits a `DiemConfig::NewEpochEvent` to
/// trigger a reconfiguration of the system. This reconfiguration will update the validator set
/// on-chain with the updated `ValidatorConfig::ValidatorConfig`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `validator_operator_account` | `signer` | Signer of the sending account. Must be the registered validator operator for the validator at `validator_address`. |
/// | `validator_account` | `address` | The address of the validator's `ValidatorConfig::ValidatorConfig` resource being updated. |
/// | `consensus_pubkey` | `vector<u8>` | New Ed25519 public key to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `validator_network_addresses` | `vector<u8>` | New set of `validator_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `fullnode_network_addresses` | `vector<u8>` | New set of `fullnode_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | `validator_address` does not have a `ValidatorConfig::ValidatorConfig` resource published under it. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR_OPERATOR` | `validator_operator_account` does not have a Validator Operator role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_TRANSACTION_SENDER` | `validator_operator_account` is not the registered operator for the validator at `validator_address`. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_CONSENSUS_KEY` | `consensus_pubkey` is not a valid ed25519 public key. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::register_validator_config`
SetValidatorConfigAndReconfigure {
validator_account: AccountAddress,
consensus_pubkey: Bytes,
validator_network_addresses: Bytes,
fullnode_network_addresses: Bytes,
},
/// # Summary
/// Sets the validator operator for a validator in the validator's configuration resource "locally"
/// and does not reconfigure the system. Changes from this transaction will not picked up by the
/// system until a reconfiguration of the system is triggered. May only be sent by an account with
/// Validator role.
///
/// # Technical Description
/// Sets the account at `operator_account` address and with the specified `human_name` as an
/// operator for the sending validator account. The account at `operator_account` address must have
/// a Validator Operator role and have a `ValidatorOperatorConfig::ValidatorOperatorConfig`
/// resource published under it. The sending `account` must be a Validator and have a
/// `ValidatorConfig::ValidatorConfig` resource published under it. This script does not emit a
/// `DiemConfig::NewEpochEvent` and no reconfiguration of the system is initiated by this script.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `operator_name` | `vector<u8>` | Validator operator's human name. |
/// | `operator_account` | `address` | Address of the validator operator account to be added as the `account` validator's operator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorOperatorConfig::EVALIDATOR_OPERATOR_CONFIG` | The `ValidatorOperatorConfig::ValidatorOperatorConfig` resource is not published under `operator_account`. |
/// | 0 | 0 | The `human_name` field of the `ValidatorOperatorConfig::ValidatorOperatorConfig` resource under `operator_account` does not match the provided `human_name`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR` | `account` does not have a Validator account role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::ENOT_A_VALIDATOR_OPERATOR` | The account at `operator_account` does not have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource. |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | A `ValidatorConfig::ValidatorConfig` is not published under `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
SetValidatorOperator {
operator_name: Bytes,
operator_account: AccountAddress,
},
/// # Summary
/// Sets the validator operator for a validator in the validator's configuration resource "locally"
/// and does not reconfigure the system. Changes from this transaction will not picked up by the
/// system until a reconfiguration of the system is triggered. May only be sent by the Diem Root
/// account as a write set transaction.
///
/// # Technical Description
/// Sets the account at `operator_account` address and with the specified `human_name` as an
/// operator for the validator `account`. The account at `operator_account` address must have a
/// Validator Operator role and have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource
/// published under it. The account represented by the `account` signer must be a Validator and
/// have a `ValidatorConfig::ValidatorConfig` resource published under it. No reconfiguration of
/// the system is initiated by this script.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | Signer of the sending account of the write set transaction. May only be the Diem Root signer. |
/// | `account` | `signer` | Signer of account specified in the `execute_as` field of the write set transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction for Diem Root. |
/// | `operator_name` | `vector<u8>` | Validator operator's human name. |
/// | `operator_account` | `address` | Address of the validator operator account to be added as the `account` validator's operator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` in `dr_account` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` in `dr_account` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` in` dr_account` has been previously recorded. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | The sending account is not the Diem Root account or Treasury Compliance account |
/// | `Errors::NOT_PUBLISHED` | `ValidatorOperatorConfig::EVALIDATOR_OPERATOR_CONFIG` | The `ValidatorOperatorConfig::ValidatorOperatorConfig` resource is not published under `operator_account`. |
/// | 0 | 0 | The `human_name` field of the `ValidatorOperatorConfig::ValidatorOperatorConfig` resource under `operator_account` does not match the provided `human_name`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR` | `account` does not have a Validator account role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::ENOT_A_VALIDATOR_OPERATOR` | The account at `operator_account` does not have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource. |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | A `ValidatorConfig::ValidatorConfig` is not published under `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
SetValidatorOperatorWithNonceAdmin {
sliding_nonce: u64,
operator_name: Bytes,
operator_account: AccountAddress,
},
/// # Summary
/// Mints a specified number of coins in a currency to a Designated Dealer. The sending account
/// must be the Treasury Compliance account, and coins can only be minted to a Designated Dealer
/// account.
///
/// # Technical Description
/// Mints `mint_amount` of coins in the `CoinType` currency to Designated Dealer account at
/// `designated_dealer_address`. The `tier_index` parameter specifies which tier should be used to
/// check verify the off-chain approval policy, and is based in part on the on-chain tier values
/// for the specific Designated Dealer, and the number of `CoinType` coins that have been minted to
/// the dealer over the past 24 hours. Every Designated Dealer has 4 tiers for each currency that
/// they support. The sending `tc_account` must be the Treasury Compliance account, and the
/// receiver an authorized Designated Dealer account.
///
/// # Events
/// Successful execution of the transaction will emit two events:
/// * A `Diem::MintEvent` with the amount and currency code minted is emitted on the
/// `mint_event_handle` in the stored `Diem::CurrencyInfo<CoinType>` resource stored under
/// `0xA550C18`; and
/// * A `DesignatedDealer::ReceivedMintEvent` with the amount, currency code, and Designated
/// Dealer's address is emitted on the `mint_event_handle` in the stored `DesignatedDealer::Dealer`
/// resource published under the `designated_dealer_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` being minted. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `designated_dealer_address` | `address` | The address of the Designated Dealer account being minted to. |
/// | `mint_amount` | `u64` | The number of coins to be minted. |
/// | `tier_index` | `u64` | [Deprecated] The mint tier index to use for the Designated Dealer account. Will be ignored |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `DesignatedDealer::EINVALID_MINT_AMOUNT` | `mint_amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DesignatedDealer::EDEALER` | `DesignatedDealer::Dealer` or `DesignatedDealer::TierInfo<CoinType>` resource does not exist at `designated_dealer_address`. |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EMINT_CAPABILITY` | `tc_account` does not have a `Diem::MintCapability<CoinType>` resource published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EMINTING_NOT_ALLOWED` | Minting is not currently allowed for `CoinType` coins. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | The depositing of the funds would exceed the `account`'s account limits. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_designated_dealer`
/// * `PaymentScripts::peer_to_peer_with_metadata`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
TieredMint {
coin_type: TypeTag,
sliding_nonce: u64,
designated_dealer_address: AccountAddress,
mint_amount: u64,
tier_index: u64,
},
/// # Summary
/// Unfreezes the account at `address`. The sending account of this transaction must be the
/// Treasury Compliance account. After the successful execution of this transaction transactions
/// may be sent from the previously frozen account, and coins may be sent and received.
///
/// # Technical Description
/// Sets the `AccountFreezing::FreezingBit` to `false` and emits a
/// `AccountFreezing::UnFreezeAccountEvent`. The transaction sender must be the Treasury Compliance
/// account. Note that this is a per-account property so unfreezing a Parent VASP will not effect
/// the status any of its child accounts and vice versa.
///
/// # Events
/// Successful execution of this script will emit a `AccountFreezing::UnFreezeAccountEvent` with
/// the `unfrozen_address` set the `to_unfreeze_account`'s address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `to_unfreeze_account` | `address` | The account address to be frozen. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::freeze_account`
UnfreezeAccount {
sliding_nonce: u64,
to_unfreeze_account: AccountAddress,
},
/// # Summary
/// Updates the Diem consensus config that is stored on-chain and is used by the Consensus. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the `DiemConsensusConfig` on-chain config and emits a `DiemConfig::NewEpochEvent` to trigger
/// a reconfiguration of the system.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `config` | `vector<u8>` | The serialized bytes of consensus config. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
UpdateDiemConsensusConfig { sliding_nonce: u64, config: Bytes },
/// # Summary
/// Updates the Diem major version that is stored on-chain and is used by the VM. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the `DiemVersion` on-chain config and emits a `DiemConfig::NewEpochEvent` to trigger
/// a reconfiguration of the system. The `major` version that is passed in must be strictly greater
/// than the current major version held on-chain. The VM reads this information and can use it to
/// preserve backwards compatibility with previous major versions of the VM.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `major` | `u64` | The `major` version of the VM to be used from this transaction on. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
/// | `Errors::INVALID_ARGUMENT` | `DiemVersion::EINVALID_MAJOR_VERSION_NUMBER` | `major` is less-than or equal to the current major version stored on-chain. |
UpdateDiemVersion { sliding_nonce: u64, major: u64 },
/// # Summary
/// Update the dual attestation limit on-chain. Defined in terms of micro-XDX. The transaction can
/// only be sent by the Treasury Compliance account. After this transaction all inter-VASP
/// payments over this limit must be checked for dual attestation.
///
/// # Technical Description
/// Updates the `micro_xdx_limit` field of the `DualAttestation::Limit` resource published under
/// `0xA550C18`. The amount is set in micro-XDX.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_micro_xdx_limit` | `u64` | The new dual attestation limit to be used on-chain. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_exchange_rate`
/// * `TreasuryComplianceScripts::update_minting_ability`
UpdateDualAttestationLimit {
sliding_nonce: u64,
new_micro_xdx_limit: u64,
},
/// # Summary
/// Update the rough on-chain exchange rate between a specified currency and XDX (as a conversion
/// to micro-XDX). The transaction can only be sent by the Treasury Compliance account. After this
/// transaction the updated exchange rate will be used for normalization of gas prices, and for
/// dual attestation checking.
///
/// # Technical Description
/// Updates the on-chain exchange rate from the given `Currency` to micro-XDX. The exchange rate
/// is given by `new_exchange_rate_numerator/new_exchange_rate_denominator`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` whose exchange rate is being updated. `Currency` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for the transaction. |
/// | `new_exchange_rate_numerator` | `u64` | The numerator for the new to micro-XDX exchange rate for `Currency`. |
/// | `new_exchange_rate_denominator` | `u64` | The denominator for the new to micro-XDX exchange rate for `Currency`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `FixedPoint32::EDENOMINATOR` | `new_exchange_rate_denominator` is zero. |
/// | `Errors::INVALID_ARGUMENT` | `FixedPoint32::ERATIO_OUT_OF_RANGE` | The quotient is unrepresentable as a `FixedPoint32`. |
/// | `Errors::LIMIT_EXCEEDED` | `FixedPoint32::ERATIO_OUT_OF_RANGE` | The quotient is unrepresentable as a `FixedPoint32`. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_dual_attestation_limit`
/// * `TreasuryComplianceScripts::update_minting_ability`
UpdateExchangeRate {
currency: TypeTag,
sliding_nonce: u64,
new_exchange_rate_numerator: u64,
new_exchange_rate_denominator: u64,
},
/// # Summary
/// Script to allow or disallow minting of new coins in a specified currency. This transaction can
/// only be sent by the Treasury Compliance account. Turning minting off for a currency will have
/// no effect on coins already in circulation, and coins may still be removed from the system.
///
/// # Technical Description
/// This transaction sets the `can_mint` field of the `Diem::CurrencyInfo<Currency>` resource
/// published under `0xA550C18` to the value of `allow_minting`. Minting of coins if allowed if
/// this field is set to `true` and minting of new coins in `Currency` is disallowed otherwise.
/// This transaction needs to be sent by the Treasury Compliance account.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` whose minting ability is being updated. `Currency` must be an already-registered currency on-chain. |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `allow_minting` | `bool` | Whether to allow minting of new coins in `Currency`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | `Currency` is not a registered currency on-chain. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_dual_attestation_limit`
/// * `TreasuryComplianceScripts::update_exchange_rate`
UpdateMintingAbility {
currency: TypeTag,
allow_minting: bool,
},
}
impl ScriptFunctionCall {
/// Build a Diem `TransactionPayload` from a structured object `ScriptFunctionCall`.
pub fn encode(self) -> TransactionPayload {
use ScriptFunctionCall::*;
match self {
AddCurrencyToAccount { currency } => {
encode_add_currency_to_account_script_function(currency)
}
AddRecoveryRotationCapability { recovery_address } => {
encode_add_recovery_rotation_capability_script_function(recovery_address)
}
AddValidatorAndReconfigure {
sliding_nonce,
validator_name,
validator_address,
} => encode_add_validator_and_reconfigure_script_function(
sliding_nonce,
validator_name,
validator_address,
),
AddVaspDomain { address, domain } => {
encode_add_vasp_domain_script_function(address, domain)
}
BurnTxnFees { coin_type } => encode_burn_txn_fees_script_function(coin_type),
BurnWithAmount {
token,
sliding_nonce,
preburn_address,
amount,
} => encode_burn_with_amount_script_function(
token,
sliding_nonce,
preburn_address,
amount,
),
CancelBurnWithAmount {
token,
preburn_address,
amount,
} => encode_cancel_burn_with_amount_script_function(token, preburn_address, amount),
CreateChildVaspAccount {
coin_type,
child_address,
auth_key_prefix,
add_all_currencies,
child_initial_balance,
} => encode_create_child_vasp_account_script_function(
coin_type,
child_address,
auth_key_prefix,
add_all_currencies,
child_initial_balance,
),
CreateDesignatedDealer {
currency,
sliding_nonce,
addr,
auth_key_prefix,
human_name,
add_all_currencies,
} => encode_create_designated_dealer_script_function(
currency,
sliding_nonce,
addr,
auth_key_prefix,
human_name,
add_all_currencies,
),
CreateParentVaspAccount {
coin_type,
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
add_all_currencies,
} => encode_create_parent_vasp_account_script_function(
coin_type,
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
add_all_currencies,
),
CreateRecoveryAddress {} => encode_create_recovery_address_script_function(),
CreateValidatorAccount {
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
} => encode_create_validator_account_script_function(
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
),
CreateValidatorOperatorAccount {
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
} => encode_create_validator_operator_account_script_function(
sliding_nonce,
new_account_address,
auth_key_prefix,
human_name,
),
CreateVaspDomains {} => encode_create_vasp_domains_script_function(),
ForceExpire { shift_amount } => encode_force_expire_script_function(shift_amount),
FreezeAccount {
sliding_nonce,
to_freeze_account,
} => encode_freeze_account_script_function(sliding_nonce, to_freeze_account),
InitializeDiemConsensusConfig { sliding_nonce } => {
encode_initialize_diem_consensus_config_script_function(sliding_nonce)
}
OptInToCrsn { crsn_size } => encode_opt_in_to_crsn_script_function(crsn_size),
PeerToPeerBySigners {
currency,
amount,
metadata,
} => encode_peer_to_peer_by_signers_script_function(currency, amount, metadata),
PeerToPeerWithMetadata {
currency,
payee,
amount,
metadata,
metadata_signature,
} => encode_peer_to_peer_with_metadata_script_function(
currency,
payee,
amount,
metadata,
metadata_signature,
),
Preburn { token, amount } => encode_preburn_script_function(token, amount),
PublishSharedEd25519PublicKey { public_key } => {
encode_publish_shared_ed25519_public_key_script_function(public_key)
}
RegisterValidatorConfig {
validator_account,
consensus_pubkey,
validator_network_addresses,
fullnode_network_addresses,
} => encode_register_validator_config_script_function(
validator_account,
consensus_pubkey,
validator_network_addresses,
fullnode_network_addresses,
),
RemoveValidatorAndReconfigure {
sliding_nonce,
validator_name,
validator_address,
} => encode_remove_validator_and_reconfigure_script_function(
sliding_nonce,
validator_name,
validator_address,
),
RemoveVaspDomain { address, domain } => {
encode_remove_vasp_domain_script_function(address, domain)
}
RotateAuthenticationKey { new_key } => {
encode_rotate_authentication_key_script_function(new_key)
}
RotateAuthenticationKeyWithNonce {
sliding_nonce,
new_key,
} => {
encode_rotate_authentication_key_with_nonce_script_function(sliding_nonce, new_key)
}
RotateAuthenticationKeyWithNonceAdmin {
sliding_nonce,
new_key,
} => encode_rotate_authentication_key_with_nonce_admin_script_function(
sliding_nonce,
new_key,
),
RotateAuthenticationKeyWithRecoveryAddress {
recovery_address,
to_recover,
new_key,
} => encode_rotate_authentication_key_with_recovery_address_script_function(
recovery_address,
to_recover,
new_key,
),
RotateDualAttestationInfo { new_url, new_key } => {
encode_rotate_dual_attestation_info_script_function(new_url, new_key)
}
RotateSharedEd25519PublicKey { public_key } => {
encode_rotate_shared_ed25519_public_key_script_function(public_key)
}
SetGasConstants {
sliding_nonce,
global_memory_per_byte_cost,
global_memory_per_byte_write_cost,
min_transaction_gas_units,
large_transaction_cutoff,
intrinsic_gas_per_byte,
maximum_number_of_gas_units,
min_price_per_gas_unit,
max_price_per_gas_unit,
max_transaction_size_in_bytes,
gas_unit_scaling_factor,
default_account_size,
} => encode_set_gas_constants_script_function(
sliding_nonce,
global_memory_per_byte_cost,
global_memory_per_byte_write_cost,
min_transaction_gas_units,
large_transaction_cutoff,
intrinsic_gas_per_byte,
maximum_number_of_gas_units,
min_price_per_gas_unit,
max_price_per_gas_unit,
max_transaction_size_in_bytes,
gas_unit_scaling_factor,
default_account_size,
),
SetValidatorConfigAndReconfigure {
validator_account,
consensus_pubkey,
validator_network_addresses,
fullnode_network_addresses,
} => encode_set_validator_config_and_reconfigure_script_function(
validator_account,
consensus_pubkey,
validator_network_addresses,
fullnode_network_addresses,
),
SetValidatorOperator {
operator_name,
operator_account,
} => encode_set_validator_operator_script_function(operator_name, operator_account),
SetValidatorOperatorWithNonceAdmin {
sliding_nonce,
operator_name,
operator_account,
} => encode_set_validator_operator_with_nonce_admin_script_function(
sliding_nonce,
operator_name,
operator_account,
),
TieredMint {
coin_type,
sliding_nonce,
designated_dealer_address,
mint_amount,
tier_index,
} => encode_tiered_mint_script_function(
coin_type,
sliding_nonce,
designated_dealer_address,
mint_amount,
tier_index,
),
UnfreezeAccount {
sliding_nonce,
to_unfreeze_account,
} => encode_unfreeze_account_script_function(sliding_nonce, to_unfreeze_account),
UpdateDiemConsensusConfig {
sliding_nonce,
config,
} => encode_update_diem_consensus_config_script_function(sliding_nonce, config),
UpdateDiemVersion {
sliding_nonce,
major,
} => encode_update_diem_version_script_function(sliding_nonce, major),
UpdateDualAttestationLimit {
sliding_nonce,
new_micro_xdx_limit,
} => encode_update_dual_attestation_limit_script_function(
sliding_nonce,
new_micro_xdx_limit,
),
UpdateExchangeRate {
currency,
sliding_nonce,
new_exchange_rate_numerator,
new_exchange_rate_denominator,
} => encode_update_exchange_rate_script_function(
currency,
sliding_nonce,
new_exchange_rate_numerator,
new_exchange_rate_denominator,
),
UpdateMintingAbility {
currency,
allow_minting,
} => encode_update_minting_ability_script_function(currency, allow_minting),
}
}
/// Try to recognize a Diem `TransactionPayload` and convert it into a structured object `ScriptFunctionCall`.
pub fn decode(payload: &TransactionPayload) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
match SCRIPT_FUNCTION_DECODER_MAP.get(&format!(
"{}{}",
script.module().name(),
script.function()
)) {
Some(decoder) => decoder(payload),
None => None,
}
} else {
None
}
}
}
/// # Summary
/// Adds a zero `Currency` balance to the sending `account`. This will enable `account` to
/// send, receive, and hold `Diem::Diem<Currency>` coins. This transaction can be
/// successfully sent by any account that is allowed to hold balances
/// (e.g., VASP, Designated Dealer).
///
/// # Technical Description
/// After the successful execution of this transaction the sending account will have a
/// `DiemAccount::Balance<Currency>` resource with zero balance published under it. Only
/// accounts that can hold balances can send this transaction, the sending account cannot
/// already have a `DiemAccount::Balance<Currency>` published under it.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being added to the sending account of the transaction. `Currency` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Currency` is not a registered currency on-chain. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EROLE_CANT_STORE_BALANCE` | The sending `account`'s role does not permit balances. |
/// | `Errors::ALREADY_PUBLISHED` | `DiemAccount::EADD_EXISTING_CURRENCY` | A balance for `Currency` is already published under the sending `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `PaymentScripts::peer_to_peer_with_metadata`
pub fn encode_add_currency_to_account_script_function(currency: TypeTag) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("add_currency_to_account").to_owned(),
vec![currency],
vec![],
))
}
/// # Summary
/// Stores the sending accounts ability to rotate its authentication key with a designated recovery
/// account. Both the sending and recovery accounts need to belong to the same VASP and
/// both be VASP accounts. After this transaction both the sending account and the
/// specified recovery account can rotate the sender account's authentication key.
///
/// # Technical Description
/// Adds the `DiemAccount::KeyRotationCapability` for the sending account
/// (`to_recover_account`) to the `RecoveryAddress::RecoveryAddress` resource under
/// `recovery_address`. After this transaction has been executed successfully the account at
/// `recovery_address` and the `to_recover_account` may rotate the authentication key of
/// `to_recover_account` (the sender of this transaction).
///
/// The sending account of this transaction (`to_recover_account`) must not have previously given away its unique key
/// rotation capability, and must be a VASP account. The account at `recovery_address`
/// must also be a VASP account belonging to the same VASP as the `to_recover_account`.
/// Additionally the account at `recovery_address` must have already initialized itself as
/// a recovery account address using the `AccountAdministrationScripts::create_recovery_address` transaction script.
///
/// The sending account's (`to_recover_account`) key rotation capability is
/// removed in this transaction and stored in the `RecoveryAddress::RecoveryAddress`
/// resource stored under the account at `recovery_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `to_recover_account` | `signer` | The signer of the sending account of this transaction. |
/// | `recovery_address` | `address` | The account address where the `to_recover_account`'s `DiemAccount::KeyRotationCapability` will be stored. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `to_recover_account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::NOT_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | `recovery_address` does not have a `RecoveryAddress` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EINVALID_KEY_ROTATION_DELEGATION` | `to_recover_account` and `recovery_address` do not belong to the same VASP. |
/// | `Errors::LIMIT_EXCEEDED` | ` RecoveryAddress::EMAX_KEYS_REGISTERED` | `RecoveryAddress::MAX_REGISTERED_KEYS` have already been registered with this `recovery_address`. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::create_recovery_address`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
pub fn encode_add_recovery_rotation_capability_script_function(
recovery_address: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("add_recovery_rotation_capability").to_owned(),
vec![],
vec![bcs::to_bytes(&recovery_address).unwrap()],
))
}
/// # Summary
/// Adds a validator account to the validator set, and triggers a
/// reconfiguration of the system to admit the account to the validator set for the system. This
/// transaction can only be successfully called by the Diem Root account.
///
/// # Technical Description
/// This script adds the account at `validator_address` to the validator set.
/// This transaction emits a `DiemConfig::NewEpochEvent` event and triggers a
/// reconfiguration. Once the reconfiguration triggered by this script's
/// execution has been performed, the account at the `validator_address` is
/// considered to be a validator in the network.
///
/// This transaction script will fail if the `validator_address` address is already in the validator set
/// or does not have a `ValidatorConfig::ValidatorConfig` resource already published under it.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `validator_name` | `vector<u8>` | ASCII-encoded human name for the validator. Must match the human name in the `ValidatorConfig::ValidatorConfig` for the validator. |
/// | `validator_address` | `address` | The validator account address to be added to the validator set. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | 0 | 0 | The provided `validator_name` does not match the already-recorded human name for the validator. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::EINVALID_PROSPECTIVE_VALIDATOR` | The validator to be added does not have a `ValidatorConfig::ValidatorConfig` resource published under it, or its `config` field is empty. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::EALREADY_A_VALIDATOR` | The `validator_address` account is already a registered validator. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemSystem::EMAX_VALIDATORS` | The validator set is already at its maximum size. The validator could not be added. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_add_validator_and_reconfigure_script_function(
sliding_nonce: u64,
validator_name: Vec<u8>,
validator_address: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("add_validator_and_reconfigure").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&validator_name).unwrap(),
bcs::to_bytes(&validator_address).unwrap(),
],
))
}
/// # Summary
/// Add a VASP domain to parent VASP account. The transaction can only be sent by
/// the Treasury Compliance account.
///
/// # Technical Description
/// Adds a `VASPDomain::VASPDomain` to the `domains` field of the `VASPDomain::VASPDomains` resource published under
/// the account at `address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `address` | `address` | The `address` of the parent VASP account that will have have `domain` added to its domains. |
/// | `domain` | `vector<u8>` | The domain to be added. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAIN_MANAGER` | The `VASPDomain::VASPDomainManager` resource is not yet published under the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAINS_NOT_PUBLISHED` | `address` does not have a `VASPDomain::VASPDomains` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EDOMAIN_ALREADY_EXISTS` | The `domain` already exists in the list of `VASPDomain::VASPDomain`s in the `VASPDomain::VASPDomains` resource published under `address`. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EINVALID_VASP_DOMAIN` | The `domain` is greater in length than `VASPDomain::DOMAIN_LENGTH`. |
pub fn encode_add_vasp_domain_script_function(
address: AccountAddress,
domain: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("add_vasp_domain").to_owned(),
vec![],
vec![
bcs::to_bytes(&address).unwrap(),
bcs::to_bytes(&domain).unwrap(),
],
))
}
/// # Summary
/// Burns the transaction fees collected in the `CoinType` currency so that the
/// Diem association may reclaim the backing coins off-chain. May only be sent
/// by the Treasury Compliance account.
///
/// # Technical Description
/// Burns the transaction fees collected in `CoinType` so that the
/// association may reclaim the backing coins. Once this transaction has executed
/// successfully all transaction fees that will have been collected in
/// `CoinType` since the last time this script was called with that specific
/// currency. Both `balance` and `preburn` fields in the
/// `TransactionFee::TransactionFee<CoinType>` resource published under the `0xB1E55ED`
/// account address will have a value of 0 after the successful execution of this script.
///
/// # Events
/// The successful execution of this transaction will emit a `Diem::BurnEvent` on the event handle
/// held in the `Diem::CurrencyInfo<CoinType>` resource's `burn_events` published under
/// `0xA550C18`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` being added to the sending account of the transaction. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `TransactionFee::ETRANSACTION_FEE` | `CoinType` is not an accepted transaction fee currency. |
/// | `Errors::INVALID_ARGUMENT` | `Diem::ECOIN` | The collected fees in `CoinType` are zero. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
pub fn encode_burn_txn_fees_script_function(coin_type: TypeTag) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("burn_txn_fees").to_owned(),
vec![coin_type],
vec![],
))
}
/// # Summary
/// Burns the coins held in a preburn resource in the preburn queue at the
/// specified preburn address, which are equal to the `amount` specified in the
/// transaction. Finds the first relevant outstanding preburn request with
/// matching amount and removes the contained coins from the system. The sending
/// account must be the Treasury Compliance account.
/// The account that holds the preburn queue resource will normally be a Designated
/// Dealer, but there are no enforced requirements that it be one.
///
/// # Technical Description
/// This transaction permanently destroys all the coins of `Token` type
/// stored in the `Diem::Preburn<Token>` resource published under the
/// `preburn_address` account address.
///
/// This transaction will only succeed if the sending `account` has a
/// `Diem::BurnCapability<Token>`, and a `Diem::Preburn<Token>` resource
/// exists under `preburn_address`, with a non-zero `to_burn` field. After the successful execution
/// of this transaction the `total_value` field in the
/// `Diem::CurrencyInfo<Token>` resource published under `0xA550C18` will be
/// decremented by the value of the `to_burn` field of the preburn resource
/// under `preburn_address` immediately before this transaction, and the
/// `to_burn` field of the preburn resource will have a zero value.
///
/// # Events
/// The successful execution of this transaction will emit a `Diem::BurnEvent` on the event handle
/// held in the `Diem::CurrencyInfo<Token>` resource's `burn_events` published under
/// `0xA550C18`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currency being burned. `Token` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction, must have a burn capability for `Token` published under it. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `preburn_address` | `address` | The address where the coins to-be-burned are currently held. |
/// | `amount` | `u64` | The amount to be burned. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EBURN_CAPABILITY` | The sending `account` does not have a `Diem::BurnCapability<Token>` published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_NOT_FOUND` | The `Diem::PreburnQueue<Token>` resource under `preburn_address` does not contain a preburn request with a value matching `amount`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN_QUEUE` | The account at `preburn_address` does not have a `Diem::PreburnQueue<Token>` resource published under it. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The specified `Token` is not a registered currency on-chain. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_txn_fees`
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
/// * `TreasuryComplianceScripts::preburn`
pub fn encode_burn_with_amount_script_function(
token: TypeTag,
sliding_nonce: u64,
preburn_address: AccountAddress,
amount: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("burn_with_amount").to_owned(),
vec![token],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&preburn_address).unwrap(),
bcs::to_bytes(&amount).unwrap(),
],
))
}
/// # Summary
/// Cancels and returns the coins held in the preburn area under
/// `preburn_address`, which are equal to the `amount` specified in the transaction. Finds the first preburn
/// resource with the matching amount and returns the funds to the `preburn_address`'s balance.
/// Can only be successfully sent by an account with Treasury Compliance role.
///
/// # Technical Description
/// Cancels and returns all coins held in the `Diem::Preburn<Token>` resource under the `preburn_address` and
/// return the funds to the `preburn_address` account's `DiemAccount::Balance<Token>`.
/// The transaction must be sent by an `account` with a `Diem::BurnCapability<Token>`
/// resource published under it. The account at `preburn_address` must have a
/// `Diem::Preburn<Token>` resource published under it, and its value must be nonzero. The transaction removes
/// the entire balance held in the `Diem::Preburn<Token>` resource, and returns it back to the account's
/// `DiemAccount::Balance<Token>` under `preburn_address`. Due to this, the account at
/// `preburn_address` must already have a balance in the `Token` currency published
/// before this script is called otherwise the transaction will fail.
///
/// # Events
/// The successful execution of this transaction will emit:
/// * A `Diem::CancelBurnEvent` on the event handle held in the `Diem::CurrencyInfo<Token>`
/// resource's `burn_events` published under `0xA550C18`.
/// * A `DiemAccount::ReceivedPaymentEvent` on the `preburn_address`'s
/// `DiemAccount::DiemAccount` `received_events` event handle with both the `payer` and `payee`
/// being `preburn_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currenty that burning is being cancelled for. `Token` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account of this transaction, must have a burn capability for `Token` published under it. |
/// | `preburn_address` | `address` | The address where the coins to-be-burned are currently held. |
/// | `amount` | `u64` | The amount to be cancelled. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EBURN_CAPABILITY` | The sending `account` does not have a `Diem::BurnCapability<Token>` published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_NOT_FOUND` | The `Diem::PreburnQueue<Token>` resource under `preburn_address` does not contain a preburn request with a value matching `amount`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN_QUEUE` | The account at `preburn_address` does not have a `Diem::PreburnQueue<Token>` resource published under it. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The specified `Token` is not a registered currency on-chain. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | The account at `preburn_address` doesn't have a balance resource for `Token`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | The depositing of the funds held in the prebun area would exceed the `account`'s account limits. |
/// | `Errors::INVALID_STATE` | `DualAttestation::EPAYEE_COMPLIANCE_KEY_NOT_SET` | The `account` does not have a compliance key set on it but dual attestion checking was performed. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::burn_txn_fees`
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::preburn`
pub fn encode_cancel_burn_with_amount_script_function(
token: TypeTag,
preburn_address: AccountAddress,
amount: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("cancel_burn_with_amount").to_owned(),
vec![token],
vec![
bcs::to_bytes(&preburn_address).unwrap(),
bcs::to_bytes(&amount).unwrap(),
],
))
}
/// # Summary
/// Creates a Child VASP account with its parent being the sending account of the transaction.
/// The sender of the transaction must be a Parent VASP account.
///
/// # Technical Description
/// Creates a `ChildVASP` account for the sender `parent_vasp` at `child_address` with a balance of
/// `child_initial_balance` in `CoinType` and an initial authentication key of
/// `auth_key_prefix | child_address`. Authentication key prefixes, and how to construct them from an ed25519 public key is described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// If `add_all_currencies` is true, the child address will have a zero balance in all available
/// currencies in the system.
///
/// The new account will be a child account of the transaction sender, which must be a
/// Parent VASP account. The child account will be recorded against the limit of
/// child accounts of the creating Parent VASP account.
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `child_address`,
/// and the `rold_id` field being `Roles::CHILD_VASP_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// Successful execution with a `child_initial_balance` greater than zero will additionaly emit:
/// * A `DiemAccount::SentPaymentEvent` with the `payee` field being `child_address`.
/// This is emitted on the Parent VASP's `DiemAccount::DiemAccount` `sent_events` handle.
/// * A `DiemAccount::ReceivedPaymentEvent` with the `payer` field being the Parent VASP's address.
/// This is emitted on the new Child VASPS's `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` that the child account should be created with. `CoinType` must be an already-registered currency on-chain. |
/// | `parent_vasp` | `signer` | The reference of the sending account. Must be a Parent VASP account. |
/// | `child_address` | `address` | Address of the to-be-created Child VASP account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `add_all_currencies` | `bool` | Whether to publish balance resources for all known currencies when the account is created. |
/// | `child_initial_balance` | `u64` | The initial balance in `CoinType` to give the child account when it's created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | The `auth_key_prefix` was not of length 32. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EPARENT_VASP` | The sending account wasn't a Parent VASP account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `child_address` address is already taken. |
/// | `Errors::LIMIT_EXCEEDED` | `VASP::ETOO_MANY_CHILDREN` | The sending account has reached the maximum number of allowed child accounts. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `CoinType` is not a registered currency on-chain. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED` | The withdrawal capability for the sending account has already been extracted. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | The sending account doesn't have a balance in `CoinType`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | The sending account doesn't have at least `child_initial_balance` of `CoinType` balance. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECANNOT_CREATE_AT_VM_RESERVED` | The `child_address` is the reserved address 0x0. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::add_recovery_rotation_capability`
/// * `AccountAdministrationScripts::create_recovery_address`
pub fn encode_create_child_vasp_account_script_function(
coin_type: TypeTag,
child_address: AccountAddress,
auth_key_prefix: Vec<u8>,
add_all_currencies: bool,
child_initial_balance: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountCreationScripts").to_owned(),
),
ident_str!("create_child_vasp_account").to_owned(),
vec![coin_type],
vec![
bcs::to_bytes(&child_address).unwrap(),
bcs::to_bytes(&auth_key_prefix).unwrap(),
bcs::to_bytes(&add_all_currencies).unwrap(),
bcs::to_bytes(&child_initial_balance).unwrap(),
],
))
}
/// # Summary
/// Creates a Designated Dealer account with the provided information, and initializes it with
/// default mint tiers. The transaction can only be sent by the Treasury Compliance account.
///
/// # Technical Description
/// Creates an account with the Designated Dealer role at `addr` with authentication key
/// `auth_key_prefix` | `addr` and a 0 balance of type `Currency`. If `add_all_currencies` is true,
/// 0 balances for all available currencies in the system will also be added. This can only be
/// invoked by an account with the TreasuryCompliance role.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// At the time of creation the account is also initialized with default mint tiers of (500_000,
/// 5000_000, 50_000_000, 500_000_000), and preburn areas for each currency that is added to the
/// account.
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `addr`,
/// and the `rold_id` field being `Roles::DESIGNATED_DEALER_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` that the Designated Dealer should be initialized with. `Currency` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `addr` | `address` | Address of the to-be-created Designated Dealer account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the Designated Dealer. |
/// | `add_all_currencies` | `bool` | Whether to publish preburn, balance, and tier info resources for all known (SCS) currencies or just `Currency` when the account is created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Currency` is not a registered currency on-chain. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `addr` address is already taken. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::tiered_mint`
/// * `PaymentScripts::peer_to_peer_with_metadata`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
pub fn encode_create_designated_dealer_script_function(
currency: TypeTag,
sliding_nonce: u64,
addr: AccountAddress,
auth_key_prefix: Vec<u8>,
human_name: Vec<u8>,
add_all_currencies: bool,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountCreationScripts").to_owned(),
),
ident_str!("create_designated_dealer").to_owned(),
vec![currency],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&addr).unwrap(),
bcs::to_bytes(&auth_key_prefix).unwrap(),
bcs::to_bytes(&human_name).unwrap(),
bcs::to_bytes(&add_all_currencies).unwrap(),
],
))
}
/// # Summary
/// Creates a Parent VASP account with the specified human name. Must be called by the Treasury Compliance account.
///
/// # Technical Description
/// Creates an account with the Parent VASP role at `address` with authentication key
/// `auth_key_prefix` | `new_account_address` and a 0 balance of type `CoinType`. If
/// `add_all_currencies` is true, 0 balances for all available currencies in the system will
/// also be added. This can only be invoked by an TreasuryCompliance account.
/// `sliding_nonce` is a unique nonce for operation, see `SlidingNonce` for details.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::PARENT_VASP_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` currency that the Parent VASP account should be initialized with. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Parent VASP account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the Parent VASP. |
/// | `add_all_currencies` | `bool` | Whether to publish balance resources for all known currencies when the account is created. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `CoinType` is not a registered currency on-chain. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::add_recovery_rotation_capability`
/// * `AccountAdministrationScripts::create_recovery_address`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
pub fn encode_create_parent_vasp_account_script_function(
coin_type: TypeTag,
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Vec<u8>,
human_name: Vec<u8>,
add_all_currencies: bool,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountCreationScripts").to_owned(),
),
ident_str!("create_parent_vasp_account").to_owned(),
vec![coin_type],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_account_address).unwrap(),
bcs::to_bytes(&auth_key_prefix).unwrap(),
bcs::to_bytes(&human_name).unwrap(),
bcs::to_bytes(&add_all_currencies).unwrap(),
],
))
}
/// # Summary
/// Initializes the sending account as a recovery address that may be used by
/// other accounts belonging to the same VASP as `account`.
/// The sending account must be a VASP account, and can be either a child or parent VASP account.
/// Multiple recovery addresses can exist for a single VASP, but accounts in
/// each must be disjoint.
///
/// # Technical Description
/// Publishes a `RecoveryAddress::RecoveryAddress` resource under `account`. It then
/// extracts the `DiemAccount::KeyRotationCapability` for `account` and adds
/// it to the resource. After the successful execution of this transaction
/// other accounts may add their key rotation to this resource so that `account`
/// may be used as a recovery account for those accounts.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::ENOT_A_VASP` | `account` is not a VASP account. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EKEY_ROTATION_DEPENDENCY_CYCLE` | A key rotation recovery cycle would be created by adding `account`'s key rotation capability. |
/// | `Errors::ALREADY_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | A `RecoveryAddress::RecoveryAddress` resource has already been published under `account`. |
///
/// # Related Scripts
/// * `Script::add_recovery_rotation_capability`
/// * `Script::rotate_authentication_key_with_recovery_address`
pub fn encode_create_recovery_address_script_function() -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("create_recovery_address").to_owned(),
vec![],
vec![],
))
}
/// # Summary
/// Creates a Validator account. This transaction can only be sent by the Diem
/// Root account.
///
/// # Technical Description
/// Creates an account with a Validator role at `new_account_address`, with authentication key
/// `auth_key_prefix` | `new_account_address`. It publishes a
/// `ValidatorConfig::ValidatorConfig` resource with empty `config`, and
/// `operator_account` fields. The `human_name` field of the
/// `ValidatorConfig::ValidatorConfig` is set to the passed in `human_name`.
/// This script does not add the validator to the validator set or the system,
/// but only creates the account.
/// Authentication keys, prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::VALIDATOR_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Validator account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the validator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_create_validator_account_script_function(
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Vec<u8>,
human_name: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountCreationScripts").to_owned(),
),
ident_str!("create_validator_account").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_account_address).unwrap(),
bcs::to_bytes(&auth_key_prefix).unwrap(),
bcs::to_bytes(&human_name).unwrap(),
],
))
}
/// # Summary
/// Creates a Validator Operator account. This transaction can only be sent by the Diem
/// Root account.
///
/// # Technical Description
/// Creates an account with a Validator Operator role at `new_account_address`, with authentication key
/// `auth_key_prefix` | `new_account_address`. It publishes a
/// `ValidatorOperatorConfig::ValidatorOperatorConfig` resource with the specified `human_name`.
/// This script does not assign the validator operator to any validator accounts but only creates the account.
/// Authentication key prefixes, and how to construct them from an ed25519 public key are described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
///
/// # Events
/// Successful execution will emit:
/// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`,
/// and the `rold_id` field being `Roles::VALIDATOR_OPERATOR_ROLE_ID`. This is emitted on the
/// `DiemAccount::AccountOperationsCapability` `creation_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_account_address` | `address` | Address of the to-be-created Validator account. |
/// | `auth_key_prefix` | `vector<u8>` | The authentication key prefix that will be used initially for the newly created account. |
/// | `human_name` | `vector<u8>` | ASCII-encoded human name for the validator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::ALREADY_PUBLISHED` | `Roles::EROLE_ID` | The `new_account_address` address is already taken. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_create_validator_operator_account_script_function(
sliding_nonce: u64,
new_account_address: AccountAddress,
auth_key_prefix: Vec<u8>,
human_name: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountCreationScripts").to_owned(),
),
ident_str!("create_validator_operator_account").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_account_address).unwrap(),
bcs::to_bytes(&auth_key_prefix).unwrap(),
bcs::to_bytes(&human_name).unwrap(),
],
))
}
/// # Summary
/// Publishes a `VASPDomain::VASPDomains` resource under a parent VASP account.
/// The sending account must be a parent VASP account.
///
/// # Technical Description
/// Publishes a `VASPDomain::VASPDomains` resource under `account`.
/// The The `VASPDomain::VASPDomains` resource's `domains` field is a vector
/// of VASPDomain, and will be empty on at the end of processing this transaction.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::ALREADY_PUBLISHED` | `VASPDomain::EVASP_DOMAINS` | A `VASPDomain::VASPDomains` resource has already been published under `account`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EPARENT_VASP` | The sending `account` was not a parent VASP account. |
pub fn encode_create_vasp_domains_script_function() -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("create_vasp_domains").to_owned(),
vec![],
vec![],
))
}
/// # Summary
/// Shifts the window held by the CRSN resource published under `account`
/// by `shift_amount`. This will expire all unused slots in the CRSN at the
/// time of processing that are less than `shift_amount`. The exact
/// semantics are defined in DIP-168.
///
/// # Technical Description
/// This shifts the slots in the published `CRSN::CRSN` resource under
/// `account` by `shift_amount`, and increments the CRSN's `min_nonce` field
/// by `shift_amount` as well. After this, it will shift the window over
/// any set bits. It is important to note that the sequence nonce of the
/// sending transaction must still lie within the range of the window in
/// order for this transaction to be processed successfully.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `shift_amount` | `u64` | The amount to shift the window in the CRSN under `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `CRSN::ENO_CRSN` | A `CRSN::CRSN` resource is not published under `account`. |
pub fn encode_force_expire_script_function(shift_amount: u64) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("force_expire").to_owned(),
vec![],
vec![bcs::to_bytes(&shift_amount).unwrap()],
))
}
/// # Summary
/// Freezes the account at `address`. The sending account of this transaction
/// must be the Treasury Compliance account. The account being frozen cannot be
/// the Diem Root or Treasury Compliance account. After the successful
/// execution of this transaction no transactions may be sent from the frozen
/// account, and the frozen account may not send or receive coins.
///
/// # Technical Description
/// Sets the `AccountFreezing::FreezingBit` to `true` and emits a
/// `AccountFreezing::FreezeAccountEvent`. The transaction sender must be the
/// Treasury Compliance account, but the account at `to_freeze_account` must
/// not be either `0xA550C18` (the Diem Root address), or `0xB1E55ED` (the
/// Treasury Compliance address). Note that this is a per-account property
/// e.g., freezing a Parent VASP will not effect the status any of its child
/// accounts and vice versa.
///
/// # Events
/// Successful execution of this transaction will emit a `AccountFreezing::FreezeAccountEvent` on
/// the `freeze_event_handle` held in the `AccountFreezing::FreezeEventsHolder` resource published
/// under `0xA550C18` with the `frozen_address` being the `to_freeze_account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `to_freeze_account` | `address` | The account address to be frozen. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `AccountFreezing::ECANNOT_FREEZE_TC` | `to_freeze_account` was the Treasury Compliance account (`0xB1E55ED`). |
/// | `Errors::INVALID_ARGUMENT` | `AccountFreezing::ECANNOT_FREEZE_DIEM_ROOT` | `to_freeze_account` was the Diem Root account (`0xA550C18`). |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::unfreeze_account`
pub fn encode_freeze_account_script_function(
sliding_nonce: u64,
to_freeze_account: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("freeze_account").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&to_freeze_account).unwrap(),
],
))
}
/// # Summary
/// Initializes the Diem consensus config that is stored on-chain. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Initializes the `DiemConsensusConfig` on-chain config to empty and allows future updates from DiemRoot via
/// `update_diem_consensus_config`. This doesn't emit a `DiemConfig::NewEpochEvent`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
pub fn encode_initialize_diem_consensus_config_script_function(
sliding_nonce: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("SystemAdministrationScripts").to_owned(),
),
ident_str!("initialize_diem_consensus_config").to_owned(),
vec![],
vec![bcs::to_bytes(&sliding_nonce).unwrap()],
))
}
/// # Summary
/// Publishes a CRSN resource under `account` and opts the account in to
/// concurrent transaction processing. Upon successful execution of this
/// script, all further transactions sent from this account will be ordered
/// and processed according to DIP-168.
///
/// # Technical Description
/// This publishes a `CRSN::CRSN` resource under `account` with `crsn_size`
/// number of slots. All slots will be initialized to the empty (unused)
/// state, and the CRSN resource's `min_nonce` field will be set to the transaction's
/// sequence number + 1.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `crsn_size` | `u64` | The the number of slots the published CRSN will have. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `CRSN::EHAS_CRSN` | A `CRSN::CRSN` resource was already published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `CRSN::EZERO_SIZE_CRSN` | The `crsn_size` was zero. |
pub fn encode_opt_in_to_crsn_script_function(crsn_size: u64) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("opt_in_to_crsn").to_owned(),
vec![],
vec![bcs::to_bytes(&crsn_size).unwrap()],
))
}
/// # Summary
/// Transfers a given number of coins in a specified currency from one account to another by multi-agent transaction.
/// Transfers over a specified amount defined on-chain that are between two different VASPs, or
/// other accounts that have opted-in will be subject to on-chain checks to ensure the receiver has
/// agreed to receive the coins. This transaction can be sent by any account that can hold a
/// balance, and to any account that can hold a balance. Both accounts must hold balances in the
/// currency being transacted.
///
/// # Technical Description
///
/// Transfers `amount` coins of type `Currency` from `payer` to `payee` with (optional) associated
/// `metadata`.
/// Dual attestation is not applied to this script as payee is also a signer of the transaction.
/// Standardized `metadata` BCS format can be found in `diem_types::transaction::metadata::Metadata`.
///
/// # Events
/// Successful execution of this script emits two events:
/// * A `DiemAccount::SentPaymentEvent` on `payer`'s `DiemAccount::DiemAccount` `sent_events` handle; and
/// * A `DiemAccount::ReceivedPaymentEvent` on `payee`'s `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being sent in this transaction. `Currency` must be an already-registered currency on-chain. |
/// | `payer` | `signer` | The signer of the sending account that coins are being transferred from. |
/// | `payee` | `signer` | The signer of the receiving account that the coins are being transferred to. |
/// | `metadata` | `vector<u8>` | Optional metadata about this payment. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `payer` doesn't hold a balance in `Currency`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Currency`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECOIN_DEPOSIT_IS_ZERO` | `amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYEE_DOES_NOT_EXIST` | No account exists at the `payee` address. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | An account exists at `payee`, but it does not accept payments in `Currency`. |
/// | `Errors::INVALID_STATE` | `AccountFreezing::EACCOUNT_FROZEN` | The `payee` account is frozen. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EWITHDRAWAL_EXCEEDS_LIMITS` | `payer` has exceeded its daily withdrawal limits for the backing coins of XDX. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | `payee` has exceeded its daily deposit limits for XDX. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `PaymentScripts::peer_to_peer_with_metadata`
pub fn encode_peer_to_peer_by_signers_script_function(
currency: TypeTag,
amount: u64,
metadata: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("PaymentScripts").to_owned(),
),
ident_str!("peer_to_peer_by_signers").to_owned(),
vec![currency],
vec![
bcs::to_bytes(&amount).unwrap(),
bcs::to_bytes(&metadata).unwrap(),
],
))
}
/// # Summary
/// Transfers a given number of coins in a specified currency from one account to another.
/// Transfers over a specified amount defined on-chain that are between two different VASPs, or
/// other accounts that have opted-in will be subject to on-chain checks to ensure the receiver has
/// agreed to receive the coins. This transaction can be sent by any account that can hold a
/// balance, and to any account that can hold a balance. Both accounts must hold balances in the
/// currency being transacted.
///
/// # Technical Description
///
/// Transfers `amount` coins of type `Currency` from `payer` to `payee` with (optional) associated
/// `metadata` and an (optional) `metadata_signature` on the message of the form
/// `metadata` | `Signer::address_of(payer)` | `amount` | `DualAttestation::DOMAIN_SEPARATOR`, that
/// has been signed by the `payee`'s private key associated with the `compliance_public_key` held in
/// the `payee`'s `DualAttestation::Credential`. Both the `Signer::address_of(payer)` and `amount` fields
/// in the `metadata_signature` must be BCS-encoded bytes, and `|` denotes concatenation.
/// The `metadata` and `metadata_signature` parameters are only required if `amount` >=
/// `DualAttestation::get_cur_microdiem_limit` XDX and `payer` and `payee` are distinct VASPs.
/// However, a transaction sender can opt in to dual attestation even when it is not required
/// (e.g., a DesignatedDealer -> VASP payment) by providing a non-empty `metadata_signature`.
/// Standardized `metadata` BCS format can be found in `diem_types::transaction::metadata::Metadata`.
///
/// # Events
/// Successful execution of this script emits two events:
/// * A `DiemAccount::SentPaymentEvent` on `payer`'s `DiemAccount::DiemAccount` `sent_events` handle; and
/// * A `DiemAccount::ReceivedPaymentEvent` on `payee`'s `DiemAccount::DiemAccount` `received_events` handle.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` being sent in this transaction. `Currency` must be an already-registered currency on-chain. |
/// | `payer` | `signer` | The signer of the sending account that coins are being transferred from. |
/// | `payee` | `address` | The address of the account the coins are being transferred to. |
/// | `metadata` | `vector<u8>` | Optional metadata about this payment. |
/// | `metadata_signature` | `vector<u8>` | Optional signature over `metadata` and payment information. See |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `payer` doesn't hold a balance in `Currency`. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Currency`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::ECOIN_DEPOSIT_IS_ZERO` | `amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYEE_DOES_NOT_EXIST` | No account exists at the `payee` address. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EPAYEE_CANT_ACCEPT_CURRENCY_TYPE` | An account exists at `payee`, but it does not accept payments in `Currency`. |
/// | `Errors::INVALID_STATE` | `AccountFreezing::EACCOUNT_FROZEN` | The `payee` account is frozen. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EMALFORMED_METADATA_SIGNATURE` | `metadata_signature` is not 64 bytes. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EINVALID_METADATA_SIGNATURE` | `metadata_signature` does not verify on the against the `payee'`s `DualAttestation::Credential` `compliance_public_key` public key. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EWITHDRAWAL_EXCEEDS_LIMITS` | `payer` has exceeded its daily withdrawal limits for the backing coins of XDX. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | `payee` has exceeded its daily deposit limits for XDX. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_child_vasp_account`
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountAdministrationScripts::add_currency_to_account`
/// * `PaymentScripts::peer_to_peer_by_signers`
pub fn encode_peer_to_peer_with_metadata_script_function(
currency: TypeTag,
payee: AccountAddress,
amount: u64,
metadata: Vec<u8>,
metadata_signature: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("PaymentScripts").to_owned(),
),
ident_str!("peer_to_peer_with_metadata").to_owned(),
vec![currency],
vec![
bcs::to_bytes(&payee).unwrap(),
bcs::to_bytes(&amount).unwrap(),
bcs::to_bytes(&metadata).unwrap(),
bcs::to_bytes(&metadata_signature).unwrap(),
],
))
}
/// # Summary
/// Moves a specified number of coins in a given currency from the account's
/// balance to its preburn area after which the coins may be burned. This
/// transaction may be sent by any account that holds a balance and preburn area
/// in the specified currency.
///
/// # Technical Description
/// Moves the specified `amount` of coins in `Token` currency from the sending `account`'s
/// `DiemAccount::Balance<Token>` to the `Diem::Preburn<Token>` published under the same
/// `account`. `account` must have both of these resources published under it at the start of this
/// transaction in order for it to execute successfully.
///
/// # Events
/// Successful execution of this script emits two events:
/// * `DiemAccount::SentPaymentEvent ` on `account`'s `DiemAccount::DiemAccount` `sent_events`
/// handle with the `payee` and `payer` fields being `account`'s address; and
/// * A `Diem::PreburnEvent` with `Token`'s currency code on the
/// `Diem::CurrencyInfo<Token`'s `preburn_events` handle for `Token` and with
/// `preburn_address` set to `account`'s address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Token` | Type | The Move type for the `Token` currency being moved to the preburn area. `Token` must be an already-registered currency on-chain. |
/// | `account` | `signer` | The signer of the sending account. |
/// | `amount` | `u64` | The amount in `Token` to be moved to the preburn area. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | The `Token` is not a registered currency on-chain. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EWITHDRAWAL_CAPABILITY_ALREADY_EXTRACTED` | The withdrawal capability for `account` has already been extracted. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EINSUFFICIENT_BALANCE` | `amount` is greater than `payer`'s balance in `Token`. |
/// | `Errors::NOT_PUBLISHED` | `DiemAccount::EPAYER_DOESNT_HOLD_CURRENCY` | `account` doesn't hold a balance in `Token`. |
/// | `Errors::NOT_PUBLISHED` | `Diem::EPREBURN` | `account` doesn't have a `Diem::Preburn<Token>` resource published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EPREBURN_OCCUPIED` | The `value` field in the `Diem::Preburn<Token>` resource under the sender is non-zero. |
/// | `Errors::NOT_PUBLISHED` | `Roles::EROLE_ID` | The `account` did not have a role assigned to it. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDESIGNATED_DEALER` | The `account` did not have the role of DesignatedDealer. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::cancel_burn_with_amount`
/// * `TreasuryComplianceScripts::burn_with_amount`
/// * `TreasuryComplianceScripts::burn_txn_fees`
pub fn encode_preburn_script_function(token: TypeTag, amount: u64) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("preburn").to_owned(),
vec![token],
vec![bcs::to_bytes(&amount).unwrap()],
))
}
/// # Summary
/// Rotates the authentication key of the sending account to the newly-specified ed25519 public key and
/// publishes a new shared authentication key derived from that public key under the sender's account.
/// Any account can send this transaction.
///
/// # Technical Description
/// Rotates the authentication key of the sending account to the
/// [authentication key derived from `public_key`](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys)
/// and publishes a `SharedEd25519PublicKey::SharedEd25519PublicKey` resource
/// containing the 32-byte ed25519 `public_key` and the `DiemAccount::KeyRotationCapability` for
/// `account` under `account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `public_key` | `vector<u8>` | A valid 32-byte Ed25519 public key for `account`'s authentication key to be rotated to and stored. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability` resource. |
/// | `Errors::ALREADY_PUBLISHED` | `SharedEd25519PublicKey::ESHARED_KEY` | The `SharedEd25519PublicKey::SharedEd25519PublicKey` resource is already published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SharedEd25519PublicKey::EMALFORMED_PUBLIC_KEY` | `public_key` is an invalid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_shared_ed25519_public_key`
pub fn encode_publish_shared_ed25519_public_key_script_function(
public_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("publish_shared_ed25519_public_key").to_owned(),
vec![],
vec![bcs::to_bytes(&public_key).unwrap()],
))
}
/// # Summary
/// Updates a validator's configuration. This does not reconfigure the system and will not update
/// the configuration in the validator set that is seen by other validators in the network. Can
/// only be successfully sent by a Validator Operator account that is already registered with a
/// validator.
///
/// # Technical Description
/// This updates the fields with corresponding names held in the `ValidatorConfig::ValidatorConfig`
/// config resource held under `validator_account`. It does not emit a `DiemConfig::NewEpochEvent`
/// so the copy of this config held in the validator set will not be updated, and the changes are
/// only "locally" under the `validator_account` account address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `validator_operator_account` | `signer` | Signer of the sending account. Must be the registered validator operator for the validator at `validator_address`. |
/// | `validator_account` | `address` | The address of the validator's `ValidatorConfig::ValidatorConfig` resource being updated. |
/// | `consensus_pubkey` | `vector<u8>` | New Ed25519 public key to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `validator_network_addresses` | `vector<u8>` | New set of `validator_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `fullnode_network_addresses` | `vector<u8>` | New set of `fullnode_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | `validator_address` does not have a `ValidatorConfig::ValidatorConfig` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_TRANSACTION_SENDER` | `validator_operator_account` is not the registered operator for the validator at `validator_address`. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_CONSENSUS_KEY` | `consensus_pubkey` is not a valid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_register_validator_config_script_function(
validator_account: AccountAddress,
consensus_pubkey: Vec<u8>,
validator_network_addresses: Vec<u8>,
fullnode_network_addresses: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("register_validator_config").to_owned(),
vec![],
vec![
bcs::to_bytes(&validator_account).unwrap(),
bcs::to_bytes(&consensus_pubkey).unwrap(),
bcs::to_bytes(&validator_network_addresses).unwrap(),
bcs::to_bytes(&fullnode_network_addresses).unwrap(),
],
))
}
/// # Summary
/// This script removes a validator account from the validator set, and triggers a reconfiguration
/// of the system to remove the validator from the system. This transaction can only be
/// successfully called by the Diem Root account.
///
/// # Technical Description
/// This script removes the account at `validator_address` from the validator set. This transaction
/// emits a `DiemConfig::NewEpochEvent` event. Once the reconfiguration triggered by this event
/// has been performed, the account at `validator_address` is no longer considered to be a
/// validator in the network. This transaction will fail if the validator at `validator_address`
/// is not in the validator set.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of this transaction. Must be the Diem Root signer. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `validator_name` | `vector<u8>` | ASCII-encoded human name for the validator. Must match the human name in the `ValidatorConfig::ValidatorConfig` for the validator. |
/// | `validator_address` | `address` | The validator account address to be removed from the validator set. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | The sending account is not the Diem Root account or Treasury Compliance account |
/// | 0 | 0 | The provided `validator_name` does not match the already-recorded human name for the validator. |
/// | `Errors::INVALID_ARGUMENT` | `DiemSystem::ENOT_AN_ACTIVE_VALIDATOR` | The validator to be removed is not in the validator set. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EDIEM_ROOT` | The sending account is not the Diem Root account. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_remove_validator_and_reconfigure_script_function(
sliding_nonce: u64,
validator_name: Vec<u8>,
validator_address: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("remove_validator_and_reconfigure").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&validator_name).unwrap(),
bcs::to_bytes(&validator_address).unwrap(),
],
))
}
/// # Summary
/// Remove a VASP domain from parent VASP account. The transaction can only be sent by
/// the Treasury Compliance account.
///
/// # Technical Description
/// Removes a `VASPDomain::VASPDomain` from the `domains` field of the `VASPDomain::VASPDomains` resource published under
/// account with `address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `address` | `address` | The `address` of parent VASP account that will update its domains. |
/// | `domain` | `vector<u8>` | The domain name. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAIN_MANAGER` | The `VASPDomain::VASPDomainManager` resource is not yet published under the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `VASPDomain::EVASP_DOMAINS_NOT_PUBLISHED` | `address` does not have a `VASPDomain::VASPDomains` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EINVALID_VASP_DOMAIN` | The `domain` is greater in length than `VASPDomain::DOMAIN_LENGTH`. |
/// | `Errors::INVALID_ARGUMENT` | `VASPDomain::EVASP_DOMAIN_NOT_FOUND` | The `domain` does not exist in the list of `VASPDomain::VASPDomain`s in the `VASPDomain::VASPDomains` resource published under `address`. |
pub fn encode_remove_vasp_domain_script_function(
address: AccountAddress,
domain: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("remove_vasp_domain").to_owned(),
vec![],
vec![
bcs::to_bytes(&address).unwrap(),
bcs::to_bytes(&domain).unwrap(),
],
))
}
/// # Summary
/// Rotates the `account`'s authentication key to the supplied new authentication key. May be sent by any account.
///
/// # Technical Description
/// Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_key`
/// field to `new_key`. `new_key` must be a valid authentication key that
/// corresponds to an ed25519 public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
pub fn encode_rotate_authentication_key_script_function(new_key: Vec<u8>) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_authentication_key").to_owned(),
vec![],
vec![bcs::to_bytes(&new_key).unwrap()],
))
}
/// # Summary
/// Rotates the sender's authentication key to the supplied new authentication key. May be sent by
/// any account that has a sliding nonce resource published under it (usually this is Treasury
/// Compliance or Diem Root accounts).
///
/// # Technical Description
/// Rotates the `account`'s `DiemAccount::DiemAccount` `authentication_key`
/// field to `new_key`. `new_key` must be a valid authentication key that
/// corresponds to an ed25519 public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
pub fn encode_rotate_authentication_key_with_nonce_script_function(
sliding_nonce: u64,
new_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_authentication_key_with_nonce").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_key).unwrap(),
],
))
}
/// # Summary
/// Rotates the specified account's authentication key to the supplied new authentication key. May
/// only be sent by the Diem Root account as a write set transaction.
///
/// # Technical Description
/// Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_key` field to `new_key`.
/// `new_key` must be a valid authentication key that corresponds to an ed25519
/// public key as described [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys),
/// and `account` must not have previously delegated its `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | The signer of the sending account of the write set transaction. May only be the Diem Root signer. |
/// | `account` | `signer` | Signer of account specified in the `execute_as` field of the write set transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction for Diem Root. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for `account`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` in `dr_account` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` in `dr_account` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` in` dr_account` has been previously recorded. |
/// | `Errors::INVALID_STATE` | `DiemAccount::EKEY_ROTATION_CAPABILITY_ALREADY_EXTRACTED` | `account` has already delegated/extracted its `DiemAccount::KeyRotationCapability`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_recovery_address`
pub fn encode_rotate_authentication_key_with_nonce_admin_script_function(
sliding_nonce: u64,
new_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_authentication_key_with_nonce_admin").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_key).unwrap(),
],
))
}
/// # Summary
/// Rotates the authentication key of a specified account that is part of a recovery address to a
/// new authentication key. Only used for accounts that are part of a recovery address (see
/// `AccountAdministrationScripts::add_recovery_rotation_capability` for account restrictions).
///
/// # Technical Description
/// Rotates the authentication key of the `to_recover` account to `new_key` using the
/// `DiemAccount::KeyRotationCapability` stored in the `RecoveryAddress::RecoveryAddress` resource
/// published under `recovery_address`. `new_key` must be a valide authentication key as described
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys).
/// This transaction can be sent either by the `to_recover` account, or by the account where the
/// `RecoveryAddress::RecoveryAddress` resource is published that contains `to_recover`'s `DiemAccount::KeyRotationCapability`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `recovery_address` | `address` | Address where `RecoveryAddress::RecoveryAddress` that holds `to_recover`'s `DiemAccount::KeyRotationCapability` is published. |
/// | `to_recover` | `address` | The address of the account whose authentication key will be updated. |
/// | `new_key` | `vector<u8>` | New authentication key to be used for the account at the `to_recover` address. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `RecoveryAddress::ERECOVERY_ADDRESS` | `recovery_address` does not have a `RecoveryAddress::RecoveryAddress` resource published under it. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::ECANNOT_ROTATE_KEY` | The address of `account` is not `recovery_address` or `to_recover`. |
/// | `Errors::INVALID_ARGUMENT` | `RecoveryAddress::EACCOUNT_NOT_RECOVERABLE` | `to_recover`'s `DiemAccount::KeyRotationCapability` is not in the `RecoveryAddress::RecoveryAddress` resource published under `recovery_address`. |
/// | `Errors::INVALID_ARGUMENT` | `DiemAccount::EMALFORMED_AUTHENTICATION_KEY` | `new_key` was an invalid length. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::rotate_authentication_key`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce`
/// * `AccountAdministrationScripts::rotate_authentication_key_with_nonce_admin`
pub fn encode_rotate_authentication_key_with_recovery_address_script_function(
recovery_address: AccountAddress,
to_recover: AccountAddress,
new_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_authentication_key_with_recovery_address").to_owned(),
vec![],
vec![
bcs::to_bytes(&recovery_address).unwrap(),
bcs::to_bytes(&to_recover).unwrap(),
bcs::to_bytes(&new_key).unwrap(),
],
))
}
/// # Summary
/// Updates the url used for off-chain communication, and the public key used to verify dual
/// attestation on-chain. Transaction can be sent by any account that has dual attestation
/// information published under it. In practice the only such accounts are Designated Dealers and
/// Parent VASPs.
///
/// # Technical Description
/// Updates the `base_url` and `compliance_public_key` fields of the `DualAttestation::Credential`
/// resource published under `account`. The `new_key` must be a valid ed25519 public key.
///
/// # Events
/// Successful execution of this transaction emits two events:
/// * A `DualAttestation::ComplianceKeyRotationEvent` containing the new compliance public key, and
/// the blockchain time at which the key was updated emitted on the `DualAttestation::Credential`
/// `compliance_key_rotation_events` handle published under `account`; and
/// * A `DualAttestation::BaseUrlRotationEvent` containing the new base url to be used for
/// off-chain communication, and the blockchain time at which the url was updated emitted on the
/// `DualAttestation::Credential` `base_url_rotation_events` handle published under `account`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account of the transaction. |
/// | `new_url` | `vector<u8>` | ASCII-encoded url to be used for off-chain communication with `account`. |
/// | `new_key` | `vector<u8>` | New ed25519 public key to be used for on-chain dual attestation checking. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `DualAttestation::ECREDENTIAL` | A `DualAttestation::Credential` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `DualAttestation::EINVALID_PUBLIC_KEY` | `new_key` is not a valid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_parent_vasp_account`
/// * `AccountCreationScripts::create_designated_dealer`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
pub fn encode_rotate_dual_attestation_info_script_function(
new_url: Vec<u8>,
new_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_dual_attestation_info").to_owned(),
vec![],
vec![
bcs::to_bytes(&new_url).unwrap(),
bcs::to_bytes(&new_key).unwrap(),
],
))
}
/// # Summary
/// Rotates the authentication key in a `SharedEd25519PublicKey`. This transaction can be sent by
/// any account that has previously published a shared ed25519 public key using
/// `AccountAdministrationScripts::publish_shared_ed25519_public_key`.
///
/// # Technical Description
/// `public_key` must be a valid ed25519 public key. This transaction first rotates the public key stored in `account`'s
/// `SharedEd25519PublicKey::SharedEd25519PublicKey` resource to `public_key`, after which it
/// rotates the `account`'s authentication key to the new authentication key derived from `public_key` as defined
/// [here](https://developers.diem.com/docs/core/accounts/#addresses-authentication-keys-and-cryptographic-keys)
/// using the `DiemAccount::KeyRotationCapability` stored in `account`'s `SharedEd25519PublicKey::SharedEd25519PublicKey`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `public_key` | `vector<u8>` | 32-byte Ed25519 public key. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SharedEd25519PublicKey::ESHARED_KEY` | A `SharedEd25519PublicKey::SharedEd25519PublicKey` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SharedEd25519PublicKey::EMALFORMED_PUBLIC_KEY` | `public_key` is an invalid ed25519 public key. |
///
/// # Related Scripts
/// * `AccountAdministrationScripts::publish_shared_ed25519_public_key`
pub fn encode_rotate_shared_ed25519_public_key_script_function(
public_key: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("AccountAdministrationScripts").to_owned(),
),
ident_str!("rotate_shared_ed25519_public_key").to_owned(),
vec![],
vec![bcs::to_bytes(&public_key).unwrap()],
))
}
/// # Summary
/// Updates the gas constants stored on chain and used by the VM for gas
/// metering. This transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the on-chain config holding the `DiemVMConfig` and emits a
/// `DiemConfig::NewEpochEvent` to trigger a reconfiguration of the system.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `global_memory_per_byte_cost` | `u64` | The new cost to read global memory per-byte to be used for gas metering. |
/// | `global_memory_per_byte_write_cost` | `u64` | The new cost to write global memory per-byte to be used for gas metering. |
/// | `min_transaction_gas_units` | `u64` | The new flat minimum amount of gas required for any transaction. |
/// | `large_transaction_cutoff` | `u64` | The new size over which an additional charge will be assessed for each additional byte. |
/// | `intrinsic_gas_per_byte` | `u64` | The new number of units of gas that to be charged per-byte over the new `large_transaction_cutoff`. |
/// | `maximum_number_of_gas_units` | `u64` | The new maximum number of gas units that can be set in a transaction. |
/// | `min_price_per_gas_unit` | `u64` | The new minimum gas price that can be set for a transaction. |
/// | `max_price_per_gas_unit` | `u64` | The new maximum gas price that can be set for a transaction. |
/// | `max_transaction_size_in_bytes` | `u64` | The new maximum size of a transaction that can be processed. |
/// | `gas_unit_scaling_factor` | `u64` | The new scaling factor to use when scaling between external and internal gas units. |
/// | `default_account_size` | `u64` | The new default account size to use when assessing final costs for reads and writes to global storage. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::INVALID_ARGUMENT` | `DiemVMConfig::EGAS_CONSTANT_INCONSISTENCY` | The provided gas constants are inconsistent. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
pub fn encode_set_gas_constants_script_function(
sliding_nonce: u64,
global_memory_per_byte_cost: u64,
global_memory_per_byte_write_cost: u64,
min_transaction_gas_units: u64,
large_transaction_cutoff: u64,
intrinsic_gas_per_byte: u64,
maximum_number_of_gas_units: u64,
min_price_per_gas_unit: u64,
max_price_per_gas_unit: u64,
max_transaction_size_in_bytes: u64,
gas_unit_scaling_factor: u64,
default_account_size: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("SystemAdministrationScripts").to_owned(),
),
ident_str!("set_gas_constants").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&global_memory_per_byte_cost).unwrap(),
bcs::to_bytes(&global_memory_per_byte_write_cost).unwrap(),
bcs::to_bytes(&min_transaction_gas_units).unwrap(),
bcs::to_bytes(&large_transaction_cutoff).unwrap(),
bcs::to_bytes(&intrinsic_gas_per_byte).unwrap(),
bcs::to_bytes(&maximum_number_of_gas_units).unwrap(),
bcs::to_bytes(&min_price_per_gas_unit).unwrap(),
bcs::to_bytes(&max_price_per_gas_unit).unwrap(),
bcs::to_bytes(&max_transaction_size_in_bytes).unwrap(),
bcs::to_bytes(&gas_unit_scaling_factor).unwrap(),
bcs::to_bytes(&default_account_size).unwrap(),
],
))
}
/// # Summary
/// Updates a validator's configuration, and triggers a reconfiguration of the system to update the
/// validator set with this new validator configuration. Can only be successfully sent by a
/// Validator Operator account that is already registered with a validator.
///
/// # Technical Description
/// This updates the fields with corresponding names held in the `ValidatorConfig::ValidatorConfig`
/// config resource held under `validator_account`. It then emits a `DiemConfig::NewEpochEvent` to
/// trigger a reconfiguration of the system. This reconfiguration will update the validator set
/// on-chain with the updated `ValidatorConfig::ValidatorConfig`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `validator_operator_account` | `signer` | Signer of the sending account. Must be the registered validator operator for the validator at `validator_address`. |
/// | `validator_account` | `address` | The address of the validator's `ValidatorConfig::ValidatorConfig` resource being updated. |
/// | `consensus_pubkey` | `vector<u8>` | New Ed25519 public key to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `validator_network_addresses` | `vector<u8>` | New set of `validator_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
/// | `fullnode_network_addresses` | `vector<u8>` | New set of `fullnode_network_addresses` to be used in the updated `ValidatorConfig::ValidatorConfig`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | `validator_address` does not have a `ValidatorConfig::ValidatorConfig` resource published under it. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR_OPERATOR` | `validator_operator_account` does not have a Validator Operator role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_TRANSACTION_SENDER` | `validator_operator_account` is not the registered operator for the validator at `validator_address`. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::EINVALID_CONSENSUS_KEY` | `consensus_pubkey` is not a valid ed25519 public key. |
/// | `Errors::INVALID_STATE` | `DiemConfig::EINVALID_BLOCK_TIME` | An invalid time value was encountered in reconfiguration. Unlikely to occur. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::register_validator_config`
pub fn encode_set_validator_config_and_reconfigure_script_function(
validator_account: AccountAddress,
consensus_pubkey: Vec<u8>,
validator_network_addresses: Vec<u8>,
fullnode_network_addresses: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("set_validator_config_and_reconfigure").to_owned(),
vec![],
vec![
bcs::to_bytes(&validator_account).unwrap(),
bcs::to_bytes(&consensus_pubkey).unwrap(),
bcs::to_bytes(&validator_network_addresses).unwrap(),
bcs::to_bytes(&fullnode_network_addresses).unwrap(),
],
))
}
/// # Summary
/// Sets the validator operator for a validator in the validator's configuration resource "locally"
/// and does not reconfigure the system. Changes from this transaction will not picked up by the
/// system until a reconfiguration of the system is triggered. May only be sent by an account with
/// Validator role.
///
/// # Technical Description
/// Sets the account at `operator_account` address and with the specified `human_name` as an
/// operator for the sending validator account. The account at `operator_account` address must have
/// a Validator Operator role and have a `ValidatorOperatorConfig::ValidatorOperatorConfig`
/// resource published under it. The sending `account` must be a Validator and have a
/// `ValidatorConfig::ValidatorConfig` resource published under it. This script does not emit a
/// `DiemConfig::NewEpochEvent` and no reconfiguration of the system is initiated by this script.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | The signer of the sending account of the transaction. |
/// | `operator_name` | `vector<u8>` | Validator operator's human name. |
/// | `operator_account` | `address` | Address of the validator operator account to be added as the `account` validator's operator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `ValidatorOperatorConfig::EVALIDATOR_OPERATOR_CONFIG` | The `ValidatorOperatorConfig::ValidatorOperatorConfig` resource is not published under `operator_account`. |
/// | 0 | 0 | The `human_name` field of the `ValidatorOperatorConfig::ValidatorOperatorConfig` resource under `operator_account` does not match the provided `human_name`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR` | `account` does not have a Validator account role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::ENOT_A_VALIDATOR_OPERATOR` | The account at `operator_account` does not have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource. |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | A `ValidatorConfig::ValidatorConfig` is not published under `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator_with_nonce_admin`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_set_validator_operator_script_function(
operator_name: Vec<u8>,
operator_account: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("set_validator_operator").to_owned(),
vec![],
vec![
bcs::to_bytes(&operator_name).unwrap(),
bcs::to_bytes(&operator_account).unwrap(),
],
))
}
/// # Summary
/// Sets the validator operator for a validator in the validator's configuration resource "locally"
/// and does not reconfigure the system. Changes from this transaction will not picked up by the
/// system until a reconfiguration of the system is triggered. May only be sent by the Diem Root
/// account as a write set transaction.
///
/// # Technical Description
/// Sets the account at `operator_account` address and with the specified `human_name` as an
/// operator for the validator `account`. The account at `operator_account` address must have a
/// Validator Operator role and have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource
/// published under it. The account represented by the `account` signer must be a Validator and
/// have a `ValidatorConfig::ValidatorConfig` resource published under it. No reconfiguration of
/// the system is initiated by this script.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `dr_account` | `signer` | Signer of the sending account of the write set transaction. May only be the Diem Root signer. |
/// | `account` | `signer` | Signer of account specified in the `execute_as` field of the write set transaction. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction for Diem Root. |
/// | `operator_name` | `vector<u8>` | Validator operator's human name. |
/// | `operator_account` | `address` | Address of the validator operator account to be added as the `account` validator's operator. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `dr_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` in `dr_account` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` in `dr_account` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` in` dr_account` has been previously recorded. |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | The sending account is not the Diem Root account or Treasury Compliance account |
/// | `Errors::NOT_PUBLISHED` | `ValidatorOperatorConfig::EVALIDATOR_OPERATOR_CONFIG` | The `ValidatorOperatorConfig::ValidatorOperatorConfig` resource is not published under `operator_account`. |
/// | 0 | 0 | The `human_name` field of the `ValidatorOperatorConfig::ValidatorOperatorConfig` resource under `operator_account` does not match the provided `human_name`. |
/// | `Errors::REQUIRES_ROLE` | `Roles::EVALIDATOR` | `account` does not have a Validator account role. |
/// | `Errors::INVALID_ARGUMENT` | `ValidatorConfig::ENOT_A_VALIDATOR_OPERATOR` | The account at `operator_account` does not have a `ValidatorOperatorConfig::ValidatorOperatorConfig` resource. |
/// | `Errors::NOT_PUBLISHED` | `ValidatorConfig::EVALIDATOR_CONFIG` | A `ValidatorConfig::ValidatorConfig` is not published under `account`. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_validator_account`
/// * `AccountCreationScripts::create_validator_operator_account`
/// * `ValidatorAdministrationScripts::register_validator_config`
/// * `ValidatorAdministrationScripts::remove_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::add_validator_and_reconfigure`
/// * `ValidatorAdministrationScripts::set_validator_operator`
/// * `ValidatorAdministrationScripts::set_validator_config_and_reconfigure`
pub fn encode_set_validator_operator_with_nonce_admin_script_function(
sliding_nonce: u64,
operator_name: Vec<u8>,
operator_account: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("ValidatorAdministrationScripts").to_owned(),
),
ident_str!("set_validator_operator_with_nonce_admin").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&operator_name).unwrap(),
bcs::to_bytes(&operator_account).unwrap(),
],
))
}
/// # Summary
/// Mints a specified number of coins in a currency to a Designated Dealer. The sending account
/// must be the Treasury Compliance account, and coins can only be minted to a Designated Dealer
/// account.
///
/// # Technical Description
/// Mints `mint_amount` of coins in the `CoinType` currency to Designated Dealer account at
/// `designated_dealer_address`. The `tier_index` parameter specifies which tier should be used to
/// check verify the off-chain approval policy, and is based in part on the on-chain tier values
/// for the specific Designated Dealer, and the number of `CoinType` coins that have been minted to
/// the dealer over the past 24 hours. Every Designated Dealer has 4 tiers for each currency that
/// they support. The sending `tc_account` must be the Treasury Compliance account, and the
/// receiver an authorized Designated Dealer account.
///
/// # Events
/// Successful execution of the transaction will emit two events:
/// * A `Diem::MintEvent` with the amount and currency code minted is emitted on the
/// `mint_event_handle` in the stored `Diem::CurrencyInfo<CoinType>` resource stored under
/// `0xA550C18`; and
/// * A `DesignatedDealer::ReceivedMintEvent` with the amount, currency code, and Designated
/// Dealer's address is emitted on the `mint_event_handle` in the stored `DesignatedDealer::Dealer`
/// resource published under the `designated_dealer_address`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `CoinType` | Type | The Move type for the `CoinType` being minted. `CoinType` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `designated_dealer_address` | `address` | The address of the Designated Dealer account being minted to. |
/// | `mint_amount` | `u64` | The number of coins to be minted. |
/// | `tier_index` | `u64` | [Deprecated] The mint tier index to use for the Designated Dealer account. Will be ignored |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `DesignatedDealer::EINVALID_MINT_AMOUNT` | `mint_amount` is zero. |
/// | `Errors::NOT_PUBLISHED` | `DesignatedDealer::EDEALER` | `DesignatedDealer::Dealer` or `DesignatedDealer::TierInfo<CoinType>` resource does not exist at `designated_dealer_address`. |
/// | `Errors::REQUIRES_CAPABILITY` | `Diem::EMINT_CAPABILITY` | `tc_account` does not have a `Diem::MintCapability<CoinType>` resource published under it. |
/// | `Errors::INVALID_STATE` | `Diem::EMINTING_NOT_ALLOWED` | Minting is not currently allowed for `CoinType` coins. |
/// | `Errors::LIMIT_EXCEEDED` | `DiemAccount::EDEPOSIT_EXCEEDS_LIMITS` | The depositing of the funds would exceed the `account`'s account limits. |
///
/// # Related Scripts
/// * `AccountCreationScripts::create_designated_dealer`
/// * `PaymentScripts::peer_to_peer_with_metadata`
/// * `AccountAdministrationScripts::rotate_dual_attestation_info`
pub fn encode_tiered_mint_script_function(
coin_type: TypeTag,
sliding_nonce: u64,
designated_dealer_address: AccountAddress,
mint_amount: u64,
tier_index: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("tiered_mint").to_owned(),
vec![coin_type],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&designated_dealer_address).unwrap(),
bcs::to_bytes(&mint_amount).unwrap(),
bcs::to_bytes(&tier_index).unwrap(),
],
))
}
/// # Summary
/// Unfreezes the account at `address`. The sending account of this transaction must be the
/// Treasury Compliance account. After the successful execution of this transaction transactions
/// may be sent from the previously frozen account, and coins may be sent and received.
///
/// # Technical Description
/// Sets the `AccountFreezing::FreezingBit` to `false` and emits a
/// `AccountFreezing::UnFreezeAccountEvent`. The transaction sender must be the Treasury Compliance
/// account. Note that this is a per-account property so unfreezing a Parent VASP will not effect
/// the status any of its child accounts and vice versa.
///
/// # Events
/// Successful execution of this script will emit a `AccountFreezing::UnFreezeAccountEvent` with
/// the `unfrozen_address` set the `to_unfreeze_account`'s address.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `to_unfreeze_account` | `address` | The account address to be frozen. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | The sending account is not the Treasury Compliance account. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::freeze_account`
pub fn encode_unfreeze_account_script_function(
sliding_nonce: u64,
to_unfreeze_account: AccountAddress,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("unfreeze_account").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&to_unfreeze_account).unwrap(),
],
))
}
/// # Summary
/// Updates the Diem consensus config that is stored on-chain and is used by the Consensus. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the `DiemConsensusConfig` on-chain config and emits a `DiemConfig::NewEpochEvent` to trigger
/// a reconfiguration of the system.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `config` | `vector<u8>` | The serialized bytes of consensus config. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
pub fn encode_update_diem_consensus_config_script_function(
sliding_nonce: u64,
config: Vec<u8>,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("SystemAdministrationScripts").to_owned(),
),
ident_str!("update_diem_consensus_config").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&config).unwrap(),
],
))
}
/// # Summary
/// Updates the Diem major version that is stored on-chain and is used by the VM. This
/// transaction can only be sent from the Diem Root account.
///
/// # Technical Description
/// Updates the `DiemVersion` on-chain config and emits a `DiemConfig::NewEpochEvent` to trigger
/// a reconfiguration of the system. The `major` version that is passed in must be strictly greater
/// than the current major version held on-chain. The VM reads this information and can use it to
/// preserve backwards compatibility with previous major versions of the VM.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `major` | `u64` | The `major` version of the VM to be used from this transaction on. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::EDIEM_ROOT` | `account` is not the Diem Root account. |
/// | `Errors::INVALID_ARGUMENT` | `DiemVersion::EINVALID_MAJOR_VERSION_NUMBER` | `major` is less-than or equal to the current major version stored on-chain. |
pub fn encode_update_diem_version_script_function(
sliding_nonce: u64,
major: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("SystemAdministrationScripts").to_owned(),
),
ident_str!("update_diem_version").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&major).unwrap(),
],
))
}
/// # Summary
/// Update the dual attestation limit on-chain. Defined in terms of micro-XDX. The transaction can
/// only be sent by the Treasury Compliance account. After this transaction all inter-VASP
/// payments over this limit must be checked for dual attestation.
///
/// # Technical Description
/// Updates the `micro_xdx_limit` field of the `DualAttestation::Limit` resource published under
/// `0xA550C18`. The amount is set in micro-XDX.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for this transaction. |
/// | `new_micro_xdx_limit` | `u64` | The new dual attestation limit to be used on-chain. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_exchange_rate`
/// * `TreasuryComplianceScripts::update_minting_ability`
pub fn encode_update_dual_attestation_limit_script_function(
sliding_nonce: u64,
new_micro_xdx_limit: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("update_dual_attestation_limit").to_owned(),
vec![],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_micro_xdx_limit).unwrap(),
],
))
}
/// # Summary
/// Update the rough on-chain exchange rate between a specified currency and XDX (as a conversion
/// to micro-XDX). The transaction can only be sent by the Treasury Compliance account. After this
/// transaction the updated exchange rate will be used for normalization of gas prices, and for
/// dual attestation checking.
///
/// # Technical Description
/// Updates the on-chain exchange rate from the given `Currency` to micro-XDX. The exchange rate
/// is given by `new_exchange_rate_numerator/new_exchange_rate_denominator`.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` whose exchange rate is being updated. `Currency` must be an already-registered currency on-chain. |
/// | `tc_account` | `signer` | The signer of the sending account of this transaction. Must be the Treasury Compliance account. |
/// | `sliding_nonce` | `u64` | The `sliding_nonce` (see: `SlidingNonce`) to be used for the transaction. |
/// | `new_exchange_rate_numerator` | `u64` | The numerator for the new to micro-XDX exchange rate for `Currency`. |
/// | `new_exchange_rate_denominator` | `u64` | The denominator for the new to micro-XDX exchange rate for `Currency`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::NOT_PUBLISHED` | `SlidingNonce::ESLIDING_NONCE` | A `SlidingNonce` resource is not published under `tc_account`. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_OLD` | The `sliding_nonce` is too old and it's impossible to determine if it's duplicated or not. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_TOO_NEW` | The `sliding_nonce` is too far in the future. |
/// | `Errors::INVALID_ARGUMENT` | `SlidingNonce::ENONCE_ALREADY_RECORDED` | The `sliding_nonce` has been previously recorded. |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::REQUIRES_ROLE` | `Roles::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::INVALID_ARGUMENT` | `FixedPoint32::EDENOMINATOR` | `new_exchange_rate_denominator` is zero. |
/// | `Errors::INVALID_ARGUMENT` | `FixedPoint32::ERATIO_OUT_OF_RANGE` | The quotient is unrepresentable as a `FixedPoint32`. |
/// | `Errors::LIMIT_EXCEEDED` | `FixedPoint32::ERATIO_OUT_OF_RANGE` | The quotient is unrepresentable as a `FixedPoint32`. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_dual_attestation_limit`
/// * `TreasuryComplianceScripts::update_minting_ability`
pub fn encode_update_exchange_rate_script_function(
currency: TypeTag,
sliding_nonce: u64,
new_exchange_rate_numerator: u64,
new_exchange_rate_denominator: u64,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("update_exchange_rate").to_owned(),
vec![currency],
vec![
bcs::to_bytes(&sliding_nonce).unwrap(),
bcs::to_bytes(&new_exchange_rate_numerator).unwrap(),
bcs::to_bytes(&new_exchange_rate_denominator).unwrap(),
],
))
}
/// # Summary
/// Script to allow or disallow minting of new coins in a specified currency. This transaction can
/// only be sent by the Treasury Compliance account. Turning minting off for a currency will have
/// no effect on coins already in circulation, and coins may still be removed from the system.
///
/// # Technical Description
/// This transaction sets the `can_mint` field of the `Diem::CurrencyInfo<Currency>` resource
/// published under `0xA550C18` to the value of `allow_minting`. Minting of coins if allowed if
/// this field is set to `true` and minting of new coins in `Currency` is disallowed otherwise.
/// This transaction needs to be sent by the Treasury Compliance account.
///
/// # Parameters
/// | Name | Type | Description |
/// | ------ | ------ | ------------- |
/// | `Currency` | Type | The Move type for the `Currency` whose minting ability is being updated. `Currency` must be an already-registered currency on-chain. |
/// | `account` | `signer` | Signer of the sending account. Must be the Diem Root account. |
/// | `allow_minting` | `bool` | Whether to allow minting of new coins in `Currency`. |
///
/// # Common Abort Conditions
/// | Error Category | Error Reason | Description |
/// | ---------------- | -------------- | ------------- |
/// | `Errors::REQUIRES_ADDRESS` | `CoreAddresses::ETREASURY_COMPLIANCE` | `tc_account` is not the Treasury Compliance account. |
/// | `Errors::NOT_PUBLISHED` | `Diem::ECURRENCY_INFO` | `Currency` is not a registered currency on-chain. |
///
/// # Related Scripts
/// * `TreasuryComplianceScripts::update_dual_attestation_limit`
/// * `TreasuryComplianceScripts::update_exchange_rate`
pub fn encode_update_minting_ability_script_function(
currency: TypeTag,
allow_minting: bool,
) -> TransactionPayload {
TransactionPayload::ScriptFunction(ScriptFunction::new(
ModuleId::new(
AccountAddress::new([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
ident_str!("TreasuryComplianceScripts").to_owned(),
),
ident_str!("update_minting_ability").to_owned(),
vec![currency],
vec![bcs::to_bytes(&allow_minting).unwrap()],
))
}
fn decode_add_currency_to_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::AddCurrencyToAccount {
currency: script.ty_args().get(0)?.clone(),
})
} else {
None
}
}
fn decode_add_recovery_rotation_capability_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::AddRecoveryRotationCapability {
recovery_address: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_add_validator_and_reconfigure_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::AddValidatorAndReconfigure {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
validator_name: bcs::from_bytes(script.args().get(1)?).ok()?,
validator_address: bcs::from_bytes(script.args().get(2)?).ok()?,
})
} else {
None
}
}
fn decode_add_vasp_domain_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::AddVaspDomain {
address: bcs::from_bytes(script.args().get(0)?).ok()?,
domain: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_burn_txn_fees_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::BurnTxnFees {
coin_type: script.ty_args().get(0)?.clone(),
})
} else {
None
}
}
fn decode_burn_with_amount_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::BurnWithAmount {
token: script.ty_args().get(0)?.clone(),
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
preburn_address: bcs::from_bytes(script.args().get(1)?).ok()?,
amount: bcs::from_bytes(script.args().get(2)?).ok()?,
})
} else {
None
}
}
fn decode_cancel_burn_with_amount_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CancelBurnWithAmount {
token: script.ty_args().get(0)?.clone(),
preburn_address: bcs::from_bytes(script.args().get(0)?).ok()?,
amount: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_create_child_vasp_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CreateChildVaspAccount {
coin_type: script.ty_args().get(0)?.clone(),
child_address: bcs::from_bytes(script.args().get(0)?).ok()?,
auth_key_prefix: bcs::from_bytes(script.args().get(1)?).ok()?,
add_all_currencies: bcs::from_bytes(script.args().get(2)?).ok()?,
child_initial_balance: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_create_designated_dealer_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CreateDesignatedDealer {
currency: script.ty_args().get(0)?.clone(),
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
addr: bcs::from_bytes(script.args().get(1)?).ok()?,
auth_key_prefix: bcs::from_bytes(script.args().get(2)?).ok()?,
human_name: bcs::from_bytes(script.args().get(3)?).ok()?,
add_all_currencies: bcs::from_bytes(script.args().get(4)?).ok()?,
})
} else {
None
}
}
fn decode_create_parent_vasp_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CreateParentVaspAccount {
coin_type: script.ty_args().get(0)?.clone(),
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_account_address: bcs::from_bytes(script.args().get(1)?).ok()?,
auth_key_prefix: bcs::from_bytes(script.args().get(2)?).ok()?,
human_name: bcs::from_bytes(script.args().get(3)?).ok()?,
add_all_currencies: bcs::from_bytes(script.args().get(4)?).ok()?,
})
} else {
None
}
}
fn decode_create_recovery_address_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(_script) = payload {
Some(ScriptFunctionCall::CreateRecoveryAddress {})
} else {
None
}
}
fn decode_create_validator_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CreateValidatorAccount {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_account_address: bcs::from_bytes(script.args().get(1)?).ok()?,
auth_key_prefix: bcs::from_bytes(script.args().get(2)?).ok()?,
human_name: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_create_validator_operator_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::CreateValidatorOperatorAccount {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_account_address: bcs::from_bytes(script.args().get(1)?).ok()?,
auth_key_prefix: bcs::from_bytes(script.args().get(2)?).ok()?,
human_name: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_create_vasp_domains_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(_script) = payload {
Some(ScriptFunctionCall::CreateVaspDomains {})
} else {
None
}
}
fn decode_force_expire_script_function(payload: &TransactionPayload) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::ForceExpire {
shift_amount: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_freeze_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::FreezeAccount {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
to_freeze_account: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_initialize_diem_consensus_config_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::InitializeDiemConsensusConfig {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_opt_in_to_crsn_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::OptInToCrsn {
crsn_size: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_peer_to_peer_by_signers_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::PeerToPeerBySigners {
currency: script.ty_args().get(0)?.clone(),
amount: bcs::from_bytes(script.args().get(0)?).ok()?,
metadata: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_peer_to_peer_with_metadata_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::PeerToPeerWithMetadata {
currency: script.ty_args().get(0)?.clone(),
payee: bcs::from_bytes(script.args().get(0)?).ok()?,
amount: bcs::from_bytes(script.args().get(1)?).ok()?,
metadata: bcs::from_bytes(script.args().get(2)?).ok()?,
metadata_signature: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_preburn_script_function(payload: &TransactionPayload) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::Preburn {
token: script.ty_args().get(0)?.clone(),
amount: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_publish_shared_ed25519_public_key_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::PublishSharedEd25519PublicKey {
public_key: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_register_validator_config_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RegisterValidatorConfig {
validator_account: bcs::from_bytes(script.args().get(0)?).ok()?,
consensus_pubkey: bcs::from_bytes(script.args().get(1)?).ok()?,
validator_network_addresses: bcs::from_bytes(script.args().get(2)?).ok()?,
fullnode_network_addresses: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_remove_validator_and_reconfigure_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RemoveValidatorAndReconfigure {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
validator_name: bcs::from_bytes(script.args().get(1)?).ok()?,
validator_address: bcs::from_bytes(script.args().get(2)?).ok()?,
})
} else {
None
}
}
fn decode_remove_vasp_domain_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RemoveVaspDomain {
address: bcs::from_bytes(script.args().get(0)?).ok()?,
domain: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_rotate_authentication_key_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RotateAuthenticationKey {
new_key: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_rotate_authentication_key_with_nonce_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RotateAuthenticationKeyWithNonce {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_key: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_rotate_authentication_key_with_nonce_admin_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RotateAuthenticationKeyWithNonceAdmin {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_key: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_rotate_authentication_key_with_recovery_address_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(
ScriptFunctionCall::RotateAuthenticationKeyWithRecoveryAddress {
recovery_address: bcs::from_bytes(script.args().get(0)?).ok()?,
to_recover: bcs::from_bytes(script.args().get(1)?).ok()?,
new_key: bcs::from_bytes(script.args().get(2)?).ok()?,
},
)
} else {
None
}
}
fn decode_rotate_dual_attestation_info_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RotateDualAttestationInfo {
new_url: bcs::from_bytes(script.args().get(0)?).ok()?,
new_key: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_rotate_shared_ed25519_public_key_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::RotateSharedEd25519PublicKey {
public_key: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
fn decode_set_gas_constants_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::SetGasConstants {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
global_memory_per_byte_cost: bcs::from_bytes(script.args().get(1)?).ok()?,
global_memory_per_byte_write_cost: bcs::from_bytes(script.args().get(2)?).ok()?,
min_transaction_gas_units: bcs::from_bytes(script.args().get(3)?).ok()?,
large_transaction_cutoff: bcs::from_bytes(script.args().get(4)?).ok()?,
intrinsic_gas_per_byte: bcs::from_bytes(script.args().get(5)?).ok()?,
maximum_number_of_gas_units: bcs::from_bytes(script.args().get(6)?).ok()?,
min_price_per_gas_unit: bcs::from_bytes(script.args().get(7)?).ok()?,
max_price_per_gas_unit: bcs::from_bytes(script.args().get(8)?).ok()?,
max_transaction_size_in_bytes: bcs::from_bytes(script.args().get(9)?).ok()?,
gas_unit_scaling_factor: bcs::from_bytes(script.args().get(10)?).ok()?,
default_account_size: bcs::from_bytes(script.args().get(11)?).ok()?,
})
} else {
None
}
}
fn decode_set_validator_config_and_reconfigure_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::SetValidatorConfigAndReconfigure {
validator_account: bcs::from_bytes(script.args().get(0)?).ok()?,
consensus_pubkey: bcs::from_bytes(script.args().get(1)?).ok()?,
validator_network_addresses: bcs::from_bytes(script.args().get(2)?).ok()?,
fullnode_network_addresses: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_set_validator_operator_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::SetValidatorOperator {
operator_name: bcs::from_bytes(script.args().get(0)?).ok()?,
operator_account: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_set_validator_operator_with_nonce_admin_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::SetValidatorOperatorWithNonceAdmin {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
operator_name: bcs::from_bytes(script.args().get(1)?).ok()?,
operator_account: bcs::from_bytes(script.args().get(2)?).ok()?,
})
} else {
None
}
}
fn decode_tiered_mint_script_function(payload: &TransactionPayload) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::TieredMint {
coin_type: script.ty_args().get(0)?.clone(),
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
designated_dealer_address: bcs::from_bytes(script.args().get(1)?).ok()?,
mint_amount: bcs::from_bytes(script.args().get(2)?).ok()?,
tier_index: bcs::from_bytes(script.args().get(3)?).ok()?,
})
} else {
None
}
}
fn decode_unfreeze_account_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UnfreezeAccount {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
to_unfreeze_account: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_update_diem_consensus_config_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UpdateDiemConsensusConfig {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
config: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_update_diem_version_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UpdateDiemVersion {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
major: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_update_dual_attestation_limit_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UpdateDualAttestationLimit {
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_micro_xdx_limit: bcs::from_bytes(script.args().get(1)?).ok()?,
})
} else {
None
}
}
fn decode_update_exchange_rate_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UpdateExchangeRate {
currency: script.ty_args().get(0)?.clone(),
sliding_nonce: bcs::from_bytes(script.args().get(0)?).ok()?,
new_exchange_rate_numerator: bcs::from_bytes(script.args().get(1)?).ok()?,
new_exchange_rate_denominator: bcs::from_bytes(script.args().get(2)?).ok()?,
})
} else {
None
}
}
fn decode_update_minting_ability_script_function(
payload: &TransactionPayload,
) -> Option<ScriptFunctionCall> {
if let TransactionPayload::ScriptFunction(script) = payload {
Some(ScriptFunctionCall::UpdateMintingAbility {
currency: script.ty_args().get(0)?.clone(),
allow_minting: bcs::from_bytes(script.args().get(0)?).ok()?,
})
} else {
None
}
}
type ScriptFunctionDecoderMap = std::collections::HashMap<
String,
Box<
dyn Fn(&TransactionPayload) -> Option<ScriptFunctionCall>
+ std::marker::Sync
+ std::marker::Send,
>,
>;
static SCRIPT_FUNCTION_DECODER_MAP: once_cell::sync::Lazy<ScriptFunctionDecoderMap> =
once_cell::sync::Lazy::new(|| {
let mut map: ScriptFunctionDecoderMap = std::collections::HashMap::new();
map.insert(
"AccountAdministrationScriptsadd_currency_to_account".to_string(),
Box::new(decode_add_currency_to_account_script_function),
);
map.insert(
"AccountAdministrationScriptsadd_recovery_rotation_capability".to_string(),
Box::new(decode_add_recovery_rotation_capability_script_function),
);
map.insert(
"ValidatorAdministrationScriptsadd_validator_and_reconfigure".to_string(),
Box::new(decode_add_validator_and_reconfigure_script_function),
);
map.insert(
"TreasuryComplianceScriptsadd_vasp_domain".to_string(),
Box::new(decode_add_vasp_domain_script_function),
);
map.insert(
"TreasuryComplianceScriptsburn_txn_fees".to_string(),
Box::new(decode_burn_txn_fees_script_function),
);
map.insert(
"TreasuryComplianceScriptsburn_with_amount".to_string(),
Box::new(decode_burn_with_amount_script_function),
);
map.insert(
"TreasuryComplianceScriptscancel_burn_with_amount".to_string(),
Box::new(decode_cancel_burn_with_amount_script_function),
);
map.insert(
"AccountCreationScriptscreate_child_vasp_account".to_string(),
Box::new(decode_create_child_vasp_account_script_function),
);
map.insert(
"AccountCreationScriptscreate_designated_dealer".to_string(),
Box::new(decode_create_designated_dealer_script_function),
);
map.insert(
"AccountCreationScriptscreate_parent_vasp_account".to_string(),
Box::new(decode_create_parent_vasp_account_script_function),
);
map.insert(
"AccountAdministrationScriptscreate_recovery_address".to_string(),
Box::new(decode_create_recovery_address_script_function),
);
map.insert(
"AccountCreationScriptscreate_validator_account".to_string(),
Box::new(decode_create_validator_account_script_function),
);
map.insert(
"AccountCreationScriptscreate_validator_operator_account".to_string(),
Box::new(decode_create_validator_operator_account_script_function),
);
map.insert(
"AccountAdministrationScriptscreate_vasp_domains".to_string(),
Box::new(decode_create_vasp_domains_script_function),
);
map.insert(
"AccountAdministrationScriptsforce_expire".to_string(),
Box::new(decode_force_expire_script_function),
);
map.insert(
"TreasuryComplianceScriptsfreeze_account".to_string(),
Box::new(decode_freeze_account_script_function),
);
map.insert(
"SystemAdministrationScriptsinitialize_diem_consensus_config".to_string(),
Box::new(decode_initialize_diem_consensus_config_script_function),
);
map.insert(
"AccountAdministrationScriptsopt_in_to_crsn".to_string(),
Box::new(decode_opt_in_to_crsn_script_function),
);
map.insert(
"PaymentScriptspeer_to_peer_by_signers".to_string(),
Box::new(decode_peer_to_peer_by_signers_script_function),
);
map.insert(
"PaymentScriptspeer_to_peer_with_metadata".to_string(),
Box::new(decode_peer_to_peer_with_metadata_script_function),
);
map.insert(
"TreasuryComplianceScriptspreburn".to_string(),
Box::new(decode_preburn_script_function),
);
map.insert(
"AccountAdministrationScriptspublish_shared_ed25519_public_key".to_string(),
Box::new(decode_publish_shared_ed25519_public_key_script_function),
);
map.insert(
"ValidatorAdministrationScriptsregister_validator_config".to_string(),
Box::new(decode_register_validator_config_script_function),
);
map.insert(
"ValidatorAdministrationScriptsremove_validator_and_reconfigure".to_string(),
Box::new(decode_remove_validator_and_reconfigure_script_function),
);
map.insert(
"TreasuryComplianceScriptsremove_vasp_domain".to_string(),
Box::new(decode_remove_vasp_domain_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_authentication_key".to_string(),
Box::new(decode_rotate_authentication_key_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_authentication_key_with_nonce".to_string(),
Box::new(decode_rotate_authentication_key_with_nonce_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_authentication_key_with_nonce_admin".to_string(),
Box::new(decode_rotate_authentication_key_with_nonce_admin_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_authentication_key_with_recovery_address"
.to_string(),
Box::new(decode_rotate_authentication_key_with_recovery_address_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_dual_attestation_info".to_string(),
Box::new(decode_rotate_dual_attestation_info_script_function),
);
map.insert(
"AccountAdministrationScriptsrotate_shared_ed25519_public_key".to_string(),
Box::new(decode_rotate_shared_ed25519_public_key_script_function),
);
map.insert(
"SystemAdministrationScriptsset_gas_constants".to_string(),
Box::new(decode_set_gas_constants_script_function),
);
map.insert(
"ValidatorAdministrationScriptsset_validator_config_and_reconfigure".to_string(),
Box::new(decode_set_validator_config_and_reconfigure_script_function),
);
map.insert(
"ValidatorAdministrationScriptsset_validator_operator".to_string(),
Box::new(decode_set_validator_operator_script_function),
);
map.insert(
"ValidatorAdministrationScriptsset_validator_operator_with_nonce_admin".to_string(),
Box::new(decode_set_validator_operator_with_nonce_admin_script_function),
);
map.insert(
"TreasuryComplianceScriptstiered_mint".to_string(),
Box::new(decode_tiered_mint_script_function),
);
map.insert(
"TreasuryComplianceScriptsunfreeze_account".to_string(),
Box::new(decode_unfreeze_account_script_function),
);
map.insert(
"SystemAdministrationScriptsupdate_diem_consensus_config".to_string(),
Box::new(decode_update_diem_consensus_config_script_function),
);
map.insert(
"SystemAdministrationScriptsupdate_diem_version".to_string(),
Box::new(decode_update_diem_version_script_function),
);
map.insert(
"TreasuryComplianceScriptsupdate_dual_attestation_limit".to_string(),
Box::new(decode_update_dual_attestation_limit_script_function),
);
map.insert(
"TreasuryComplianceScriptsupdate_exchange_rate".to_string(),
Box::new(decode_update_exchange_rate_script_function),
);
map.insert(
"TreasuryComplianceScriptsupdate_minting_ability".to_string(),
Box::new(decode_update_minting_ability_script_function),
);
map
});
| 73.04014 | 253 | 0.532315 |
519220ee9bd58508fe9f26b1b7a4f878bbd781a8 | 2,682 | ps1 | PowerShell | src/Gui/Windows.Forms.ps1 | peetrike/Examples | e134bc212a8dd73a1d81cae3a1197e5af98ab08b | [
"MIT"
] | null | null | null | src/Gui/Windows.Forms.ps1 | peetrike/Examples | e134bc212a8dd73a1d81cae3a1197e5af98ab08b | [
"MIT"
] | null | null | null | src/Gui/Windows.Forms.ps1 | peetrike/Examples | e134bc212a8dd73a1d81cae3a1197e5af98ab08b | [
"MIT"
] | null | null | null | $message = 'Should we do something?'
$title = 'A message'
#region Load Assembly if necessary
try {
$null = [Windows.Forms.MessageBoxButtons]::OK
} catch {
Add-Type -AssemblyName System.Windows.Forms
}
#endregion
#region MessageBox
# https://docs.microsoft.com/dotnet/api/system.windows.forms.messagebox.show
$result = [Windows.Forms.MessageBox]::Show($message)
$result = [Windows.Forms.MessageBox]::Show($message, $title)
# https://docs.microsoft.com/dotnet/api/system.windows.forms.messageboxbuttons
[Enum]::GetValues([Windows.Forms.MessageBoxButtons])
[Windows.Forms.MessageBoxButtons]'YesNoCancel'
[Windows.Forms.MessageBoxButtons]::OK
$ButtonOption = [Windows.Forms.MessageBoxButtons]::YesNoCancel
$result = [Windows.Forms.MessageBox]::Show(
$message,
$title,
$ButtonOption
)
# https://docs.microsoft.com/dotnet/api/system.windows.forms.messageboxicon
[Enum]::GetValues([Windows.Forms.MessageBoxIcon])
[Windows.Forms.MessageBoxIcon]'hand'
$IconOption = [Windows.Forms.MessageBoxIcon]::Warning
$result = [Windows.Forms.MessageBox]::Show(
$message,
$title,
$ButtonOption,
$IconOption
)
# https://docs.microsoft.com/dotnet/api/system.windows.forms.messageboxdefaultbutton
[Enum]::GetValues([Windows.Forms.MessageBoxDefaultButton])
[Windows.Forms.MessageBoxDefaultButton]'button3'
$DefaultButton = [Windows.Forms.MessageBoxDefaultButton]::Button3
$result = [Windows.Forms.MessageBox]::Show(
$message,
$title,
$ButtonOption,
$IconOption,
$DefaultButton
)
#endregion
#region Notification balloon (toast message in Windows 10)
try {
$null = [Drawing.Icon]
} catch {
Add-Type -AssemblyName System.Drawing
}
# https://docs.microsoft.com/dotnet/api/System.Windows.Forms.NotifyIcon
$NotifyIcon = New-Object System.Windows.Forms.NotifyIcon
# https://docs.microsoft.com/dotnet/api/system.drawing.icon
# $NotifyIcon.Icon = [Drawing.Icon]::new('C:\Program Files\PowerShell\7\assets\Powershell_black.ico')
# https://docs.microsoft.com/dotnet/api/system.drawing.systemicons
$NotifyIcon.Icon = [Drawing.SystemIcons]::Question
$NotifyIcon.Text = 'A notification from script'
# This makes system tray icon visible
$NotifyIcon.Visible = $True
# https://docs.microsoft.com/dotnet/api/system.windows.forms.tooltipicon
# $NotifyIcon.BalloonTipIcon = [Windows.Forms.ToolTipIcon]::Info
# $NotifyIcon.BalloonTipIcon = 'Info'
$NotifyIcon.BalloonTipText = $message
$NotifyIcon.BalloonTipTitle = $title
# when giving too small time for balloon tip, Windows applies system default timing
$NotifyIcon.ShowBalloonTip(0)
Start-Sleep -Seconds 10
# remove the icon from system tray
$NotifyIcon.Visible = $false
#endregion
| 29.472527 | 101 | 0.757271 |
776cf9a846f716f7a3cbcec5eb8e481827df7bfa | 33 | html | HTML | src/app/candidates/edit-candidate/edit-candidate.component.html | AJEETX/saimex | 80a261d6cbc84eba05d89aaa2ff5132f7a877607 | [
"Apache-2.0"
] | 1 | 2020-03-20T12:17:20.000Z | 2020-03-20T12:17:20.000Z | src/app/candidates/edit-candidate/edit-candidate.component.html | AJEETX/saimex | 80a261d6cbc84eba05d89aaa2ff5132f7a877607 | [
"Apache-2.0"
] | 5 | 2021-03-10T11:13:29.000Z | 2022-03-02T07:46:31.000Z | src/app/candidates/edit-candidate/edit-candidate.component.html | AJEETX/saimex | 80a261d6cbc84eba05d89aaa2ff5132f7a877607 | [
"Apache-2.0"
] | null | null | null | <p>
edit-candidate works!
</p>
| 8.25 | 23 | 0.606061 |
28961fd7e74e5a2a75ceb2afc44e7413a72b9b23 | 10,236 | sql | SQL | src/EA.Iws.Database/scripts/Update/0001-Release1/Sprint07/20150515-093436-Flatten-DB.sql | DEFRA/prsd-iws | 00622f1ec2db33516d365143e260843bbceb63c9 | [
"Unlicense"
] | 1 | 2019-05-17T06:08:08.000Z | 2019-05-17T06:08:08.000Z | src/EA.Iws.Database/scripts/Update/0001-Release1/Sprint07/20150515-093436-Flatten-DB.sql | DEFRA/prsd-iws | 00622f1ec2db33516d365143e260843bbceb63c9 | [
"Unlicense"
] | 46 | 2017-01-24T17:10:09.000Z | 2022-01-24T16:38:50.000Z | src/EA.Iws.Database/scripts/Update/0001-Release1/Sprint07/20150515-093436-Flatten-DB.sql | DEFRA/prsd-iws | 00622f1ec2db33516d365143e260843bbceb63c9 | [
"Unlicense"
] | 2 | 2017-12-13T19:37:51.000Z | 2021-04-10T21:34:43.000Z | GO
PRINT N'Dropping FK_AspNetUsers_Organisation...';
GO
ALTER TABLE [Identity].[AspNetUsers] DROP CONSTRAINT [FK_AspNetUsers_Organisation];
GO
PRINT N'Dropping FK_Organisation_Country...';
GO
ALTER TABLE [Business].[Organisation] DROP CONSTRAINT [FK_Organisation_Country];
GO
PRINT N'Dropping FK_Producer_Contact...';
GO
ALTER TABLE [Business].[Producer] DROP CONSTRAINT [FK_Producer_Contact];
GO
PRINT N'Dropping FK_Producer_Address...';
GO
ALTER TABLE [Business].[Producer] DROP CONSTRAINT [FK_Producer_Address];
GO
PRINT N'Dropping FK_NotificationProducer_Producer...';
GO
ALTER TABLE [Business].[NotificationProducer] DROP CONSTRAINT [FK_NotificationProducer_Producer];
GO
PRINT N'Dropping FK_Notification_Exporter...';
GO
ALTER TABLE [Notification].[Notification] DROP CONSTRAINT [FK_Notification_Exporter];
GO
PRINT N'Dropping FK_Exporter_Address...';
GO
ALTER TABLE [Notification].[Exporter] DROP CONSTRAINT [FK_Exporter_Address];
GO
PRINT N'Dropping FK_Exporter_Contact...';
GO
ALTER TABLE [Notification].[Exporter] DROP CONSTRAINT [FK_Exporter_Contact];
GO
PRINT N'Starting rebuilding table [Business].[Organisation]...';
GO
BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [Business].[tmp_ms_xx_Organisation] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (2048) NOT NULL,
[Type] NVARCHAR (64) NOT NULL,
[RowVersion] ROWVERSION NOT NULL,
[RegistrationNumber] NVARCHAR (64) NULL,
[AditionalRegistrationNumber] NVARCHAR (64) NULL,
[Building] NVARCHAR (1024) NULL,
[Address1] NVARCHAR (1024) NULL,
[TownOrCity] NVARCHAR (1024) NULL,
[Address2] NVARCHAR (1024) NULL,
[PostalCode] NVARCHAR (64) NULL,
[Country] NVARCHAR (1024) NULL,
[FirstName] NVARCHAR (150) NULL,
[LastName] NVARCHAR (150) NULL,
[Telephone] NVARCHAR (150) NULL,
[Fax] NVARCHAR (150) NULL,
[Email] NVARCHAR (150) NULL,
CONSTRAINT [tmp_ms_xx_constraint_PK_Organisation_Id] PRIMARY KEY CLUSTERED ([Id] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [Business].[Organisation])
BEGIN
INSERT INTO [Business].[tmp_ms_xx_Organisation] ([Id], [Name], [Type], [RegistrationNumber], [AditionalRegistrationNumber], [Building], [Address1], [TownOrCity], [Address2], [PostalCode], [Country], [FirstName], [LastName], [Telephone], [Fax], [Email])
SELECT o.[Id],
o.[Name],
o.[Type],
o.[RegistrationNumber],
o.[AditionalRegistrationNumber],
a.[Building],
a.[Address1],
a.[TownOrCity],
a.[Address2],
a.[PostalCode],
c.[Name],
o.[FirstName],
o.[LastName],
o.[Telephone],
o.[Fax],
o.[Email]
FROM [Business].[Organisation] o
INNER JOIN [Business].[Address] a on o.AddressId = a.Id
INNER JOIN [Lookup].[Country] c on a.CountryId = c.Id
ORDER BY o.[Id] ASC;
END
DROP TABLE [Business].[Organisation];
EXECUTE sp_rename N'[Business].[tmp_ms_xx_Organisation]', N'Organisation';
EXECUTE sp_rename N'[Business].[tmp_ms_xx_constraint_PK_Organisation_Id]', N'PK_Organisation_Id', N'OBJECT';
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
GO
PRINT N'Starting rebuilding table [Business].[Producer]...';
GO
BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [Business].[tmp_ms_xx_Producer] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[IsSiteOfExport] BIT NOT NULL,
[Type] NVARCHAR (64) NOT NULL,
[RegistrationNumber] NVARCHAR (64) NULL,
[AdditionalRegistrationNumber] NVARCHAR (64) NULL,
[Building] NVARCHAR (1024) NULL,
[Address1] NVARCHAR (1024) NULL,
[TownOrCity] NVARCHAR (1024) NULL,
[Address2] NVARCHAR (1024) NULL,
[PostalCode] NVARCHAR (64) NULL,
[Country] NVARCHAR (1024) NULL,
[FirstName] NVARCHAR (150) NULL,
[LastName] NVARCHAR (150) NULL,
[Telephone] NVARCHAR (150) NULL,
[Fax] NVARCHAR (150) NULL,
[Email] NVARCHAR (150) NULL,
[RowVersion] ROWVERSION NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [Business].[Producer])
BEGIN
INSERT INTO [Business].[tmp_ms_xx_Producer] ([Id], [Name], [IsSiteOfExport], [Type], [RegistrationNumber], [AdditionalRegistrationNumber], [Building], [Address1], [TownOrCity], [Address2], [PostalCode], [Country], [FirstName], [LastName], [Telephone], [Fax], [Email])
SELECT p.[Id],
p.[Name],
p.[IsSiteOfExport],
p.[Type],
p.[RegistrationNumber],
p.[AdditionalRegistrationNumber],
a.[Building],
a.[Address1],
a.[TownOrCity],
a.[Address2],
a.[PostalCode],
c.[Name],
co.[FirstName],
co.[LastName],
co.[Telephone],
co.[Fax],
co.[Email]
FROM [Business].[Producer] p
INNER JOIN [Business].[Address] a on p.AddressId = a.Id
INNER JOIN [Lookup].[Country] c on a.CountryId = c.Id
INNER JOIN [Business].[Contact] co on p.ContactId = co.Id
ORDER BY p.[Id] ASC;
END
DROP TABLE [Business].[Producer];
EXECUTE sp_rename N'[Business].[tmp_ms_xx_Producer]', N'Producer';
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
GO
PRINT N'Starting rebuilding table [Notification].[Exporter]...';
GO
BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [Notification].[tmp_ms_xx_Exporter] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (20) NOT NULL,
[Type] NVARCHAR (64) NOT NULL,
[RegistrationNumber] NVARCHAR (64) NULL,
[AdditionalRegistrationNumber] NVARCHAR (64) NULL,
[Building] NVARCHAR (1024) NULL,
[Address1] NVARCHAR (1024) NULL,
[TownOrCity] NVARCHAR (1024) NULL,
[Address2] NVARCHAR (1024) NULL,
[PostalCode] NVARCHAR (64) NULL,
[Country] NVARCHAR (1024) NULL,
[FirstName] NVARCHAR (150) NULL,
[LastName] NVARCHAR (150) NULL,
[Telephone] NVARCHAR (150) NULL,
[Fax] NVARCHAR (150) NULL,
[Email] NVARCHAR (150) NULL,
[RowVersion] ROWVERSION NOT NULL,
CONSTRAINT [tmp_ms_xx_constraint_PK_Exporter] PRIMARY KEY CLUSTERED ([Id] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [Notification].[Exporter])
BEGIN
INSERT INTO [Notification].[tmp_ms_xx_Exporter] ([Id], [Name], [Type], [RegistrationNumber], [AdditionalRegistrationNumber], [Building], [Address1], [TownOrCity], [Address2], [PostalCode], [Country], [FirstName], [LastName], [Telephone], [Fax], [Email])
SELECT e.[Id],
e.[Name],
e.[Type],
e.[RegistrationNumber],
e.[AdditionalRegistrationNumber],
a.[Building],
a.[Address1],
a.[TownOrCity],
a.[Address2],
a.[PostalCode],
c.[Name],
co.[FirstName],
co.[LastName],
co.[Telephone],
co.[Fax],
co.[Email]
FROM [Notification].[Exporter] e
INNER JOIN [Business].[Address] a on e.AddressId = a.Id
INNER JOIN [Lookup].[Country] c on a.CountryId = c.Id
INNER JOIN [Business].[Contact] co on e.ContactId = co.Id
ORDER BY [Id] ASC;
END
DROP TABLE [Notification].[Exporter];
EXECUTE sp_rename N'[Notification].[tmp_ms_xx_Exporter]', N'Exporter';
EXECUTE sp_rename N'[Notification].[tmp_ms_xx_constraint_PK_Exporter]', N'PK_Exporter', N'OBJECT';
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
GO
PRINT N'Creating FK_AspNetUsers_Organisation...';
GO
ALTER TABLE [Identity].[AspNetUsers] WITH NOCHECK
ADD CONSTRAINT [FK_AspNetUsers_Organisation] FOREIGN KEY ([OrganisationId]) REFERENCES [Business].[Organisation] ([Id]);
GO
PRINT N'Creating FK_NotificationProducer_Producer...';
GO
ALTER TABLE [Business].[NotificationProducer] WITH NOCHECK
ADD CONSTRAINT [FK_NotificationProducer_Producer] FOREIGN KEY ([ProducerId]) REFERENCES [Business].[Producer] ([Id]);
GO
PRINT N'Creating FK_Notification_Exporter...';
GO
ALTER TABLE [Notification].[Notification] WITH NOCHECK
ADD CONSTRAINT [FK_Notification_Exporter] FOREIGN KEY ([ExporterId]) REFERENCES [Notification].[Exporter] ([Id]);
GO
PRINT N'Checking existing data against newly created constraints';
GO
GO
ALTER TABLE [Identity].[AspNetUsers] WITH CHECK CHECK CONSTRAINT [FK_AspNetUsers_Organisation];
ALTER TABLE [Business].[NotificationProducer] WITH CHECK CHECK CONSTRAINT [FK_NotificationProducer_Producer];
ALTER TABLE [Notification].[Notification] WITH CHECK CHECK CONSTRAINT [FK_Notification_Exporter];
GO
PRINT N'Update complete.';
GO | 31.690402 | 275 | 0.578644 |
af8949b0d061d8d1c93490881a01e83f0edb4cce | 252 | rb | Ruby | menu/def.rb | rgbkrk/xiki | 47f86a4d069d42e65b3bdae3aef3aba002dd16cf | [
"MIT"
] | 3 | 2015-08-14T15:28:08.000Z | 2020-05-31T17:42:19.000Z | menu/def.rb | rgbkrk/xiki | 47f86a4d069d42e65b3bdae3aef3aba002dd16cf | [
"MIT"
] | null | null | null | menu/def.rb | rgbkrk/xiki | 47f86a4d069d42e65b3bdae3aef3aba002dd16cf | [
"MIT"
] | null | null | null | class Def
def self.menu *args
options = yield
options[:no_slash] = 1
Line.delete
txt = %`
def self.
"hi"
end
`.unindent
View.insert txt.gsub(/^/, ' '), :dont_move=>1
Move.to_end
""
end
end
| 12.6 | 50 | 0.503968 |
030fccea023eb5751a7aa2b788fe1808a3cadbff | 1,333 | lua | Lua | script-beta/vm/eachDef.lua | AliDeym/lua-language-server | f22c28c498db95fd0cf90395c96cd392b4650619 | [
"MIT"
] | null | null | null | script-beta/vm/eachDef.lua | AliDeym/lua-language-server | f22c28c498db95fd0cf90395c96cd392b4650619 | [
"MIT"
] | null | null | null | script-beta/vm/eachDef.lua | AliDeym/lua-language-server | f22c28c498db95fd0cf90395c96cd392b4650619 | [
"MIT"
] | null | null | null | local vm = require 'vm.vm'
local guide = require 'parser.guide'
local files = require 'files'
local util = require 'utility'
local await = require 'await'
local m = {}
function m.searchLibrary(source, results)
if not source then
return
end
local lib = vm.getLibrary(source)
if not lib then
return
end
vm.mergeResults(results, { lib })
end
function m.eachDef(source, results)
results = results or {}
local lock = vm.lock('eachDef', source)
if not lock then
return results
end
await.delay()
local clock = os.clock()
local myResults, count = guide.requestDefinition(source, vm.interface)
if DEVELOP and os.clock() - clock > 0.1 then
log.warn('requestDefinition', count, os.clock() - clock, guide.getRoot(source).uri, util.dump(source, { deep = 1 }))
end
vm.mergeResults(results, myResults)
m.searchLibrary(source, results)
m.searchLibrary(guide.getObjectValue(source), results)
lock()
return results
end
function vm.getDefs(source)
local cache = vm.getCache('eachDef')[source] or m.eachDef(source)
vm.getCache('eachDef')[source] = cache
return cache
end
function vm.eachDef(source, callback)
local results = vm.getDefs(source)
for i = 1, #results do
callback(results[i])
end
end
| 24.236364 | 124 | 0.663166 |
b304853e5a7093a317717b3ef062cfcba0bcb934 | 3,533 | ps1 | PowerShell | BitbucketServerAutomation/Functions/Move-BBServerRepository.ps1 | pshdo/BitbucketServerAutomation | fd6b4ca6257bce381d63e6ec3c41b15bd28579e2 | [
"Apache-2.0"
] | 7 | 2017-06-22T01:57:31.000Z | 2020-07-01T22:08:21.000Z | BitbucketServerAutomation/Functions/Move-BBServerRepository.ps1 | pshdo/BitbucketServerAutomation | fd6b4ca6257bce381d63e6ec3c41b15bd28579e2 | [
"Apache-2.0"
] | 5 | 2017-08-23T17:02:32.000Z | 2019-01-30T15:15:05.000Z | BitbucketServerAutomation/Functions/Move-BBServerRepository.ps1 | webmd-health-services/BitbucketServerAutomation | fd6b4ca6257bce381d63e6ec3c41b15bd28579e2 | [
"Apache-2.0"
] | 6 | 2017-07-20T21:00:58.000Z | 2021-04-07T16:26:25.000Z | # Copyright 2016 - 2018 WebMD Health Services
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
function Move-BBServerRepository
{
<#
.SYNOPSIS
Move a repository in Bitbucket Server from one project to another.
.DESCRIPTION
The `Move-BBServerRepository` moves a repository in Bitbucket Server.
Use the `New-BBServerConnection` function to create a connection object to pass to the `Connection` parameter.
.EXAMPLE
Move-BBServerRepository -Connection $conn -ProjectKey 'BBSA' -RepoName 'fubarsnafu' -TargetProjectKey 'BBSA_NEW'
Demonstrates how to move the repository 'fubarsnafu' from the 'BBSA' project to the 'BBSA_NEW'
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[object]
# The connection information that describe what Bitbucket Server instance to connect to, what credentials to use, etc. Use the `New-BBServerConnection` function to create a connection object.
$Connection,
[Parameter(Mandatory=$true)]
[string]
# The key/ID that identifies the project where the repository currently resides. This is *not* the project name.
$ProjectKey,
[Parameter(Mandatory=$true)]
[object]
# The name of a specific repository to move to the new project.
$RepoName,
[Parameter(Mandatory=$true)]
# The key/ID that identifies the target project where the repository will be moved. This is *not* the project name.
$TargetProjectKey
)
Set-StrictMode -Version 'Latest'
Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState
$resourcePath = ('projects/{0}/repos/{1}' -f $ProjectKey, $RepoName)
$getProjects = Get-BBServerProject -Connection $Connection
$currentProject = $getProjects | Where-Object { $_.key -eq $ProjectKey }
if( !$currentProject )
{
Write-Error -Message ('A project with key/ID ''{0}'' does not exist. Specified repository cannot be moved.' -f $ProjectKey)
return
}
$targetProject = $getProjects | Where-Object { $_.key -eq $TargetProjectKey }
if( !$targetProject )
{
Write-Error -Message ('A project with key/ID ''{0}'' does not exist. Specified repository cannot be moved.' -f $TargetProjectKey)
return
}
$currentRepo = Get-BBServerRepository -Connection $Connection -ProjectKey $ProjectKey | Where-Object { $_.name -eq $RepoName }
if( !$currentRepo )
{
Write-Error -Message ('A repository with name ''{0}'' does not exist in the project ''{1}''. Specified respository cannot be moved.' -f $RepoName, $ProjectKey)
return
}
$repoProjectConfig = @{ project = @{ key = $TargetProjectKey } }
$setRepoProject = Invoke-BBServerRestMethod -Connection $Connection -Method 'PUT' -ApiName 'api' -ResourcePath $resourcePath -InputObject $repoProjectConfig
return $setRepoProject
}
| 41.081395 | 200 | 0.673932 |
5cab2db3a934525a626220736dc0ba2815807c94 | 660 | swift | Swift | Project_Section_07/MyPlayground.playground/Contents.swift | KasRoid/The_Complete_iOS_App_Development_Bootcamp | 06b6e3bab1cab10f03b3eed4c269bdd9528763da | [
"MIT"
] | null | null | null | Project_Section_07/MyPlayground.playground/Contents.swift | KasRoid/The_Complete_iOS_App_Development_Bootcamp | 06b6e3bab1cab10f03b3eed4c269bdd9528763da | [
"MIT"
] | null | null | null | Project_Section_07/MyPlayground.playground/Contents.swift | KasRoid/The_Complete_iOS_App_Development_Bootcamp | 06b6e3bab1cab10f03b3eed4c269bdd9528763da | [
"MIT"
] | null | null | null | import UIKit
func greeting() {
for _ in 1...4 {
print("Hello")
}
}
greeting()
3//Don't change this code:
func calculator() {
let a = Int(readLine()!)! //First input
let b = Int(readLine()!)! //Second input
add(n1: a, n2: b)
subtract(n1: a, n2: b)
multiply(n1: a, n2: b)
divide(n1: a, n2: b)
}
//Write your code below this line to make the above function calls work.
func add(n1: Int, n2: Int) {
print(n1 + n2)
}
func subtract(n1: Int, n2: Int) {
print(n1 - n2)
}
func multiply(n1: Int, n2: Int) {
print(n1 * n2)
}
func divide(n1: Int, n2: Int) {
print(Double(Double(n1) / Double(n2)))
}
calculator()
| 15.348837 | 72 | 0.581818 |
905bb86ee8702bccbec9cc4b4546e2dbe38564f4 | 3,539 | py | Python | jsoncsv/dumptool.py | loftwah/jsoncsv | eec6a1e38d3d7430268c1a7962b200ffcb2b15ae | [
"Apache-2.0"
] | 74 | 2016-07-28T01:47:22.000Z | 2022-03-09T02:49:37.000Z | jsoncsv/dumptool.py | loftwah/jsoncsv | eec6a1e38d3d7430268c1a7962b200ffcb2b15ae | [
"Apache-2.0"
] | 31 | 2017-07-11T09:24:48.000Z | 2021-07-30T03:59:54.000Z | jsoncsv/dumptool.py | loftwah/jsoncsv | eec6a1e38d3d7430268c1a7962b200ffcb2b15ae | [
"Apache-2.0"
] | 20 | 2016-10-30T10:58:38.000Z | 2022-01-11T02:11:00.000Z | # coding=utf-8
# author@alingse
# 2015.10.09
import json
import unicodecsv as csv
import xlwt
class Dump(object):
def __init__(self, fin, fout, **kwargs):
self.fin = fin
self.fout = fout
self.initialize(**kwargs)
def initialize(self, **kwargs):
pass
def prepare(self):
pass
def dump_file(self, obj):
raise NotImplementedError
def on_finish(self):
pass
def dump(self):
self.prepare()
self.dump_file()
self.on_finish()
class ReadHeadersMixin(object):
@staticmethod
def load_headers(fin, read_row=None, sort_type=None):
headers = set()
datas = []
# read
if not read_row or read_row < 1:
read_row = -1
for line in fin:
obj = json.loads(line)
headers.update(obj.keys())
datas.append(obj)
read_row -= 1
if not read_row:
break
# TODO: add some sort_type here
headers = sorted(list(headers))
return (list(headers), datas)
class DumpExcel(Dump, ReadHeadersMixin):
def initialize(self, **kwargs):
super(DumpExcel, self).initialize(**kwargs)
self._read_row = kwargs.get('read_row')
self._sort_type = kwargs.get('sort_type')
def prepare(self):
headers, datas = self.load_headers(self.fin, self._read_row,
self._sort_type)
self._headers = headers
self._datas = datas
def write_headers(self):
raise NotImplementedError
def write_obj(self):
raise NotImplementedError
def dump_file(self):
self.write_headers()
for obj in self._datas:
self.write_obj(obj)
for line in self.fin:
obj = json.loads(line)
self.write_obj(obj)
class DumpCSV(DumpExcel):
def initialize(self, **kwargs):
super(DumpCSV, self).initialize(**kwargs)
self.csv_writer = None
def write_headers(self):
self.csv_writer = csv.DictWriter(self.fout, self._headers)
self.csv_writer.writeheader()
def write_obj(self, obj):
patched_obj = {
key: self.patch_value(value)
for key, value in obj.items()
}
self.csv_writer.writerow(patched_obj)
def patch_value(self, value):
if value in (None, {}, []):
return ""
return value
class DumpXLS(DumpExcel):
def initialize(self, **kwargs):
super(DumpXLS, self).initialize(**kwargs)
self.sheet = kwargs.get('sheet', 'Sheet1')
self.wb = xlwt.Workbook(encoding='utf-8')
self.ws = self.wb.add_sheet(self.sheet)
self.row = 0
self.cloumn = 0
def write_headers(self):
for head in self._headers:
self.ws.write(self.row, self.cloumn, head)
self.cloumn += 1
self.row += 1
def write_obj(self, obj):
self.cloumn = 0
for head in self._headers:
value = obj.get(head)
# patch
if value in ({},):
value = "{}"
self.ws.write(self.row, self.cloumn, value)
self.cloumn += 1
self.row += 1
def on_finish(self):
self.wb.save(self.fout)
def dump_excel(fin, fout, klass, **kwargs):
if not isinstance(klass, type) or not issubclass(klass, DumpExcel):
raise ValueError("unknow dumpexcel type")
dump = klass(fin, fout, **kwargs)
dump.dump()
| 23.751678 | 71 | 0.567674 |
052408f612dd8c2a1904147694948cdcf062d76b | 767 | rb | Ruby | lib/rock_paper_scissors_not_lizard_spock/throw.rb | SeanLuckett/rock_paper_scissors_not_lizard_spock | 40010318aa0b4e9036bd95c417cea6c5d226f0b6 | [
"MIT"
] | null | null | null | lib/rock_paper_scissors_not_lizard_spock/throw.rb | SeanLuckett/rock_paper_scissors_not_lizard_spock | 40010318aa0b4e9036bd95c417cea6c5d226f0b6 | [
"MIT"
] | null | null | null | lib/rock_paper_scissors_not_lizard_spock/throw.rb | SeanLuckett/rock_paper_scissors_not_lizard_spock | 40010318aa0b4e9036bd95c417cea6c5d226f0b6 | [
"MIT"
] | null | null | null | module RockPaperScissorsNotLizardSpock
class Throw
LEGAL_THROWS = %w(rock paper scissors).freeze
THROW_RULES = {
rock: { beats: 'scissors', ties: 'rock' },
paper: { beats: 'rock', ties: 'paper' },
scissors: { beats: 'paper', ties: 'scissors' }
}.freeze
attr_reader :choice
def self.random_throw
LEGAL_THROWS.sample
end
def initialize(player_throw)
@choice = player_throw
end
def beats?(other_throw)
return false if tied?(other_throw)
THROW_RULES.dig(@choice.to_sym, :beats) == other_throw.choice
end
def legal?
LEGAL_THROWS.include? @choice
end
def tied?(other_throw)
THROW_RULES.dig(@choice.to_sym, :ties) == other_throw.choice
end
end
end | 23.242424 | 67 | 0.637549 |
fd74d1c6ba019dcee5b68181abb507b64d86b1a7 | 1,175 | c | C | server/test/suites/server/pointer_return.c | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | server/test/suites/server/pointer_return.c | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | server/test/suites/server/pointer_return.c | PolyProgrammist/UTBotCpp | 4886622f21c92e3b73daa553008e541be9d82f21 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved.
*/
#include "pointer_return.h"
#include <stdlib.h>
long long* returns_pointer_with_min(long long a, long long b) {
static long long return_val;
if (a < b) {
return_val = a;
} else {
return_val = b;
}
return (&return_val);
}
unsigned int* returns_pointer_with_max(unsigned int a, unsigned int b) {
unsigned int *return_val = (unsigned int*)malloc(sizeof(unsigned int));
if (a > b) {
*return_val = a;
} else {
*return_val = b;
}
return return_val;
}
int* five_square_numbers(int from) {
static int sq[5];
for (int i = 0; i < 10; i++) {
sq[i] = from * from;
from++;
}
return sq;
}
struct MinMax* returns_struct_with_min_max(int a, int b) {
struct MinMax *min_max = (struct MinMax*)malloc(sizeof(struct MinMax));
if (a < b) {
min_max->a = a;
min_max->b = b;
} else {
min_max->b = a;
min_max->a = b;
}
return min_max;
}
void * return_array_like_void_ptr() {
void * ptr = malloc(10);
((char*)ptr)[0] = 0;
return ptr;
}
| 19.915254 | 78 | 0.571915 |
eadf52e5ab70ee51895a96ae60d4f0fa6796e2bb | 2,922 | sql | SQL | search/add_if_in.sql | progserega/osm_local_geoportal | 84948efa9796d5c67a152c2d8d2bb305f4cb9abf | [
"BSD-2-Clause"
] | 22 | 2017-10-12T08:51:49.000Z | 2021-11-09T11:29:53.000Z | search/add_if_in.sql | progserega/osm_local_geoportal | 84948efa9796d5c67a152c2d8d2bb305f4cb9abf | [
"BSD-2-Clause"
] | 10 | 2018-04-20T07:44:05.000Z | 2020-05-05T18:55:52.000Z | search/add_if_in.sql | progserega/osm_local_geoportal | 84948efa9796d5c67a152c2d8d2bb305f4cb9abf | [
"BSD-2-Clause"
] | 9 | 2017-11-16T14:36:01.000Z | 2021-09-28T14:36:53.000Z | -- update region in all
UPDATE search_osm AS search1 SET region=search2.region
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.region is not null OR search2.region<>'')
AND (search1.region is null OR search1.region='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='')
-- AND (search1.district is not null OR search1.district <> '')
;
-- update district in all
UPDATE search_osm AS search1 SET district=search2.district
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.district is not null OR search2.district<>'')
AND (search1.district is null OR search1.district='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='');
-- update city in all
UPDATE search_osm AS search1 SET city=search2.city
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.city is not null OR search2.city<>'')
AND (search1.city is null OR search1.city='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='');
-- update village in all
UPDATE search_osm AS search1 SET city=search2.village
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.village is not null OR search2.village<>'')
AND (search1.village is null OR search1.village='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='');
-- update street in all
UPDATE search_osm AS search1 SET city=search2.street
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.street is not null OR search2.street<>'')
AND (search1.street is null OR search1.street='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='');
-- update housenumber in all
UPDATE search_osm AS search1 SET city=search2.housenumber
FROM search_osm AS search2
WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
AND (search2.housenumber is not null OR search2.housenumber<>'')
AND (search1.housenumber is null OR search1.housenumber='')
AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='');
-- update region in city
--UPDATE search_osm AS search1 SET region=search2.region
--FROM search_osm AS search2
--WHERE ((search2.geom && search1.geom) AND ST_Covers(search2.geom, search1.geom))
-- AND (search2.region is not null OR search2.region<>'')
-- AND (search1.region is null OR search1.region='')
-- AND (search1.member_role = 'outer' OR search1.member_role is null OR search1.member_role='')
-- AND (search1.city is not null OR search1.city <> '');
| 47.901639 | 97 | 0.749487 |
58622b914a43f4bd17d9463c2cf2892887bb5803 | 343 | swift | Swift | Xit/Utils/CombineExtensions.swift | ferben/Xit | fd8cde70b5a3207a6fa97d6ea7736229ff609012 | [
"Apache-2.0"
] | 761 | 2015-01-06T13:12:57.000Z | 2022-03-31T21:12:09.000Z | Xit/Utils/CombineExtensions.swift | ferben/Xit | fd8cde70b5a3207a6fa97d6ea7736229ff609012 | [
"Apache-2.0"
] | 358 | 2016-03-18T02:22:46.000Z | 2022-03-01T20:35:46.000Z | Xit/Utils/CombineExtensions.swift | ferben/Xit | fd8cde70b5a3207a6fa97d6ea7736229ff609012 | [
"Apache-2.0"
] | 33 | 2016-08-19T12:06:30.000Z | 2022-02-12T19:17:01.000Z | import Foundation
import Combine
extension Publisher where Self.Failure == Never
{
/// Convenience function for `receive(on: DispatchQueue.main).sink()`
public func sinkOnMainQueue(receiveValue: @escaping ((Self.Output) -> Void))
-> AnyCancellable
{
receive(on: DispatchQueue.main)
.sink(receiveValue: receiveValue)
}
}
| 24.5 | 78 | 0.720117 |
16f89d0e92c2edc4afa0f7c46374e3145e6ac062 | 87,019 | asm | Assembly | Opus/asm/disptbn2.asm | Computer-history-Museum/MS-Word-for-Windows-v1.1 | 549a2a32e930694df7b91e3273b886d735fa9151 | [
"MIT"
] | 2 | 2018-01-22T14:38:52.000Z | 2019-02-25T02:16:30.000Z | Microsoft DOS/Word 1.1a CHM Distribution/Opus/asm/disptbn2.asm | mindcont/Open-Source | 416917cbe3d4469cc036d05e7c858b05b8081ded | [
"CC0-1.0"
] | null | null | null | Microsoft DOS/Word 1.1a CHM Distribution/Opus/asm/disptbn2.asm | mindcont/Open-Source | 416917cbe3d4469cc036d05e7c858b05b8081ded | [
"CC0-1.0"
] | 1 | 2021-06-25T17:34:43.000Z | 2021-06-25T17:34:43.000Z | include w2.inc
include noxport.inc
include consts.inc
include structs.inc
createSeg disptbl_PCODE,disptbn2,byte,public,CODE
; DEBUGGING DECLARATIONS
ifdef DEBUG
midDisptbn2 equ 31 ; module ID, for native asserts
NatPause equ 1
endif
ifdef NatPause
PAUSE MACRO
int 3
ENDM
else
PAUSE MACRO
ENDM
endif
; EXTERNAL FUNCTIONS
externFP <CacheTc>
externFP <ClearRclInParentDr>
externFP <CpFirstTap>
externFP <CpFirstTap1>
externFP <CpMacDocEdit>
externFP <CpMacPlc>
externFP <CpMin>
externFP <CpPlc>
externFP <DlkFromVfli>
externFP <DrawEndMark>
externFP <DrawTableRevBar>
externFP <DrawStyNameFromWwDL>
externFP <DrcToRc>
externFP <DrclToRcw>
externFP <FEmptyRc>
externFP <FillRect>
externFP <FInCa>
externFP <FInitHplcedl>
externFP <FInsertInPl>
externFP <FMatchAbs>
externFP <FrameTable>
externFP <FreeDrs>
externFP <FreeEdl>
externFP <FreeEdls>
externFP <FreePpv>
externFP <FreeHpl>
externFP <FreeHq>
externFP <FShowOutline>
externFP <GetPlc>
externFP <HplInit2>
externFP <IMacPlc>
externFP <N_PdodMother>
externFP <NMultDiv>
externFP <PatBltRc>
externFP <PutCpPlc>
externFP <PutIMacPlc>
externFP <PutPlc>
externFP <N_PwwdWw>
externFP <RcwPgvTableClip>
externFP <ScrollDrDown>
externFP <FSectRc>
externFP <XwFromXl>
externFP <XwFromXp>
externFP <YwFromYl>
externFP <YwFromYp>
externFP <SetErrorMatProc>
ifdef DEBUG
externFP <AssertProcForNative>
externFP <DypHeightTc>
externFP <PutPlcLastDebugProc>
externFP <S_CachePara>
externFP <S_DisplayFli>
externFP <S_FInTableDocCp>
externFP <S_FormatDrLine>
externFP <S_FreePdrf>
externFP <S_FUpdateDr>
externFP <S_ItcGetTcxCache>
externFP <S_PdrFetch>
externFP <S_PdrFetchAndFree>
externFP <S_PdrFreeAndFetch>
externFP <S_WidthHeightFromBrc>
externFP <S_FUpdTableDr>
else ; !DEBUG
externFP <N_CachePara>
externFP <N_DisplayFli>
externFP <N_FInTableDocCp>
externFP <N_FormatDrLine>
externFP <N_FreePdrf>
externFP <N_FUpdateDr>
externFP <N_ItcGetTcxCache>
externFP <N_PdrFetch>
externFP <N_PdrFetchAndFree>
externFP <N_PdrFreeAndFetch>
externFP <N_WidthHeightFromBrc>
externFP <PutPlcLastProc>
endif ; DEBUG
sBegin data
;
; /* E X T E R N A L S */
;
externW caTap
externW dxpPenBrc
externW dypPenBrc
externW hbrPenBrc
externW vfmtss
externW vfli
externW vfti
externW vhbrGray
externW vihpldrMac
externW vmerr
externW vpapFetch
externW vrghpldr
externW vsci
externW vtapFetch
externW vtcc
sEnd data
; CODE SEGMENT _DISPTBN2
sBegin disptbn2
assumes cs,disptbn2
assumes ds,dgroup
assumes ss,dgroup
; /*
; /* F U P D A T E T A B L E
; /*
; /* Description: Given the cp beginning a table row, format and display
; /* that table row. Returns fTrue iff the format was successful, with
; /* cp and ypTop correctly advanced. If format fails, cp and ypTop
; /* are left with their original values.
; /**/
; NATIVE FUpdateTable ( ww, doc, hpldr, idr, pcp, pypTop, hplcedl, dlNew, dlOld, dlMac,
; ypFirstShow, ypLimWw, ypLimDr, rcwInval, fScrollOK )
; int ww, doc, idr, dlNew, dlOld, dlMac;
; int ypFirstShow, ypLimWw, ypLimDr, fScrollOK;
; struct PLCEDL **hplcedl;
; struct PLDR **hpldr;
; CP *pcp;
; int *pypTop;
; struct RC rcwInval;
; {
;
; NATIVE NOTE, USE OF REGISTERS: Whenever there is a dr currently fetched,
; or recently FetchedAndFree'd, the pdr is kept in SI. After the early
; set-up code (see LUpdateTable), DI is used to store &drfFetch. This
; is used in scattered places through the code and should not be disturbed
; carelessly. The little helper routines also assume these uses.
;
; %%Function:FUpdateTable %%Owner:tomsax
cProc N_FUpdateTable,<PUBLIC,FAR>,<si,di>
ParmW ww
ParmW doc
ParmW hpldr
ParmW idr
ParmW pcp
ParmW pypTop
ParmW hplcedl
ParmW dlNew
ParmW dlOld
ParmW dlMac
ParmW ypFirstShow
ParmW ypLimWw
ParmW ypLimDr
ParmW rcwInvalYwBottomRc
ParmW rcwInvalXwRightRc
ParmW rcwInvalYwTopRc
ParmW rcwInvalXwLeftRc
ParmW fScrollOK
; int idrTable, idrMacTable, itcMac;
LocalW <idrTable,idrMacTable>
LocalW itcMac
; int dylOld, dylNew, dylDr, dylDrOld;
LocalW dylOld
LocalW dylNew
LocalW dylDrOld
; native note dylDr kept in register when need
; int dylAbove, dylBelow, dylLimPldr, dylLimDr;
LocalW dylAbove
LocalW dylBelow
LocalW dylLimPldr
LocalW dylLimDr
; int dylBottomFrameDirty = 0;
LocalW dylBottomFrameDirty
; int dyaRowHeight, ypTop, ylT; native note: ylT registerized
LocalW <dyaRowHeight, ypTop>
; Mac(int cbBmbSav);
; int dlLast, dlMacOld, lrk;
LocalW dlLast
LocalW dlMacOld
LocalB lrk ; byte-size makes life easier
; BOOL fIncr, fTtpDr, fReusePldr, fFrameLines, fOverflowDrs;
LocalB fIncr
LocalB fTtpDr
LocalB fReusePldr
LocalB fFrameLines
LocalB fOverflowDrs
; BOOL fSomeDrDirty, fLastDlDirty, fLastRow, fFirstRow, fAbsHgtRow;
LocalB fSomeDrDirty
LocalB fLastDlDirty
LocalB fLastRow
LocalB fFirstRow
LocalB fAbsHgtRow
; BOOL fOutline, fPageView, fDrawBottom;
LocalB fOutline
LocalB fPageView
LocalB fDrawBottom
; Win(BOOL fRMark;)
LocalB fRMark
; CP cp = *pcp;
LocalD cp
; struct WWD *pwwd; ; native note: registerized
LocalW pdrTable
; struct DR *pdrT, *pdrTable; ; native note: registerized
; struct PLDR **hpldrTable, *ppldrTable;
LocalW hpldrTable
; LocalW ppldrTable -- registerized
; struct RC rcwTableInval;
LocalV rcwTableInval,cbRcMin
; struct CA caTapCur;
LocalV caTapCur,cbCaMin
; struct EDL edl, edlLast, edlNext;
LocalV edl,cbEdlMin
LocalV edlLast,cbEdlMin
LocalV edlNext,cbEdlMin
; struct DRF drfT,drfFetch;
LocalV drfFetch,cbDrfMin
LocalV drfT,cbDrfMin
; struct TCX tcx;
LocalV tcx,cbTcxMin
; struct PAP papT;
LocalV papT,cbPapMin
; this trick works on the assumption that *pypTop is not altered
; until the end of the routine.
cBegin
;PAUSE
; ypTop = *pypTop; assume & assert *pypTop doesn't change until the end.
mov bx,[pypTop]
mov ax,[bx]
mov [ypTop],ax
; dylBottomFrameDirty = Win(fRMark =) 0;
;PAUSE
xor ax,ax
mov [dylBottomFrameDirty],ax
mov [fRMark],al
; cp = *pcp;
mov si,pcp
mov ax,[si+2]
mov [SEG_cp],ax
mov ax,[si]
mov [OFF_cp],ax
; pwwd = PwwdWw(ww);
call LN_PwwdWw
; fOutline = pwwd->fOutline;
; ax = pwwd
xchg ax,di ; move to a more convenient register
mov al,[di.fOutlineWwd]
and al,maskFOutlineWwd
mov [fOutline],al
; fPageView = pwwd->fPageView;
mov al,[di.fPageViewWwd]
and al,maskFPageViewWwd
mov [fPageView],al
; CacheTc(ww,doc,cp,fFalse,fFalse); /* Call this before CpFirstTap for efficiency */
push [ww]
push [doc]
push [SEG_cp]
push [OFF_cp]
xor ax,ax
push ax
push ax
cCall CacheTc,<>
; CpFirstTap1(doc, cp, fOutline);
;PAUSE
push [doc]
push [SEG_cp]
push [OFF_cp]
mov al,[fOutline]
cbw
push ax
cCall CpFirstTap1,<>
; Assert(cp == caTap.cpFirst);
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[OFF_cp]
mov dx,[SEG_cp]
sub ax,[caTap.LO_cpFirstCa]
sbb dx,[caTap.HI_cpFirstCa]
or ax,dx
je UT001
mov ax,midDisptbn2
mov bx,303
cCall AssertProcForNative,<ax,bx>
UT001:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; caTapCur = caTap;
mov si,dataoffset [caTap]
lea di,[caTapCur]
push ds
pop es
errnz <cbCaMin-10>
movsw
movsw
movsw
movsw
movsw
; itcMac = vtapFetch.itcMac;
mov ax,[vtapFetch.itcMacTap]
mov [itcMac],ax
; fAbsHgtRow = (dyaRowHeight = vtapFetch.dyaRowHeight) < 0;
;PAUSE
mov cx,[vtapFetch.dyaRowHeightTap]
mov [dyaRowHeight],cx
xor ax,ax ; assume correct value is zero
or cx,cx
jge UT010
errnz <fTrue-1>
;PAUSE
inc ax
UT010:
mov [fAbsHgtRow],al
; Assert ( FInCa(doc,cp,&caTapCur) );
ifdef DEBUG
push ax
push bx
push cx
push dx
push [doc]
push [SEG_cp]
push [OFF_cp]
lea ax,[caTapCur]
push ax
cCall FInCa,<>
or ax,ax
jnz UT020
mov ax,midDisptbn2
mov bx,169
cCall AssertProcForNative,<ax,bx>
UT020:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; pdrT = PdrFetchAndFree(hpldr, idr, &drfT);
; native note: this doesn't count as setting up di yet,
; we'll need di for some other things first...
lea di,[drfT]
push [hpldr]
push [idr]
push di
ifdef DEBUG
cCall S_PdrFetchAndFree,<>
else
cCall N_PdrFetchAndFree,<>
endif
xchg ax,si
; lrk = pdrT->lrk;
; si = pdrT
mov al,[si.lrkDr]
mov [lrk],al
; DrclToRcw(hpldr,&pdrT->drcl,&rcwTableInval);
; si = pdrT
push [hpldr]
errnz <drclDr>
push si
lea ax,[rcwTableInval]
push ax
cCall DrclToRcw,<>
; /* check to see if we need to force a first row or last row condition */
; fFirstRow = fLastRow = fFalse; /* assume no override */
; si = pdrT
xor ax,ax
mov [fFirstRow],al
mov [fLastRow],al
; if (fPageView)
; ax = 0, si = pdrT
cmp [fPageView],al
jnz UT025
jmp LChkOutline
; {
; if (pdrT->fForceFirstRow)
; {
UT025:
;PAUSE
test [si.fForceFirstRowDr],maskfForceFirstRowDr
jz UT060
; if (caTap.cpFirst == pdrT->cpFirst || dlNew == 0)
; fFirstRow = fTrue;
;PAUSE
; ax = 0, si = pdrT
cmp [dlNew],ax
jz UT050
;PAUSE
mov cx,[caTap.LO_cpFirstCa]
cmp cx,[si.LO_cpFirstDr]
jnz UT040
;PAUSE
mov cx,[caTap.HI_cpFirstCa]
cmp cx,[si.HI_cpFirstDr]
jz UT050
; else
; {
UT040:
; Assert(dlNew > 0);
; dlLast = dlNew - 1;
; GetPlc(hplcedl,dlLast,&edlLast);
;PAUSE
lea ax,[edlLast]
mov cx,[dlNew]
ifdef DEBUG
push ax
push bx
push cx
push dx
or cx,cx
jg UT005
mov ax,midDisptbn2
mov bx,1001
cCall AssertProcForNative,<ax,bx>
UT005:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
dec cx
mov [dlLast],cx
call LN_GetPlcParent
; if (caTapCur.cpFirst != CpPlc(hplcedl,dlLast) + edlLast.dcp)
; fFirstRow = fTrue;
push [hplcedl]
push [dlLast]
cCall CpPlc,<>
add ax,[edlLast.LO_dcpEdl]
adc dx,[edlLast.HI_dcpEdl]
sub ax,[caTapCur.LO_cpFirstCa] ; sub to re-zero ax
sbb dx,[caTapCur.HI_cpFirstCa]
or ax,dx
je UT060
UT050:
;PAUSE
mov [fFirstRow],fTrue
xor ax,ax
; }
; }
UT060:
; if (pdrT->cpLim != cpNil && pdrT->cpLim <= caTap.cpLim)
; {
; ax = 0, si = pdrT
errnz <LO_cpNil+1>
errnz <HI_cpNil+1>
mov cx,[si.LO_cpLimDr]
and cx,[si.HI_cpLimDr]
inc cx
jz UT062 ; to the else clause
mov ax,[caTap.LO_cpLimCa]
mov dx,[caTap.HI_cpLimCa]
sub ax,[si.LO_cpLimDr]
sbb dx,[si.HI_cpLimDr]
js UT062 ; to the else clause
; if (pdrT->idrFlow == idrNil)
; fLastRow = fTrue;
;PAUSE
cmp [si.idrFlowDr],0
js UT065 ; set fLastRow = fTrue, or fall through for else
; else
; {
; /* use the pdrTable and drfFetch momentarily... */
; pdrTable = PdrFetchAndFree(hpldr, pdrT->idrFlow, &drfFetch);
; native note: this doesn't count as setting up di yet,
; we'll need di for some other things first...
;PAUSE
lea di,[drfFetch]
push [hpldr]
push [si.idrFlowDr]
push di
ifdef DEBUG
cCall S_PdrFetchAndFree,<>
else
cCall N_PdrFetchAndFree,<>
endif
xchg ax,bx
; Assert(pdrT->doc == pdrTable->doc);
ifdef DEBUG
;Did this DEBUG stuff with a call so as not to mess up short jumps.
call UT2130
endif ; DEBUG
; fLastRow = pdrT->xl != pdrTable->xl;
mov cx,[si.xlDr]
cmp cx,[bx.xlDr]
jne UT065 ; set fLastRow = fTrue, or fall through for else
;PAUSE
jmp short UT070
; }
; }
; else
; {
; if (FInTableDocCp(doc,caTapCur.cpLim))
UT062:
;PAUSE
push [doc]
push [caTapCur.HI_cpLimCa]
push [caTapCur.LO_cpLimCa]
ifdef DEBUG
cCall S_FInTableDocCp,<>
else
cCall N_FInTableDocCp,<>
endif
or ax,ax
jz UT070
; {
; CachePara(doc, caTapCur.cpLim);
;PAUSE
push [doc]
push [caTapCur.HI_cpLimCa]
push [caTapCur.LO_cpLimCa]
ifdef DEBUG
cCall S_CachePara,<>
else
cCall N_CachePara,<>
endif
; papT = vpapFetch;
push si ; save pdrT
mov si,dataoffset [vpapFetch]
lea di,[papT]
push ds
pop es
errnz <cbPapMin and 1>
mov cx,cbPapMin SHR 1
rep movsw
pop si ; restore pdrT
; CachePara(doc, cp);
push [doc]
push [SEG_cp]
push [OFF_cp]
ifdef DEBUG
cCall S_CachePara,<>
else
cCall N_CachePara,<>
endif
; if (!FMatchAbs(caPara.doc, &papT, &vpapFetch))
push [doc]
lea ax,[papT]
push ax
mov ax,dataoffset [vpapFetch]
push ax
cCall FMatchAbs,<>
or ax,ax
jnz UT070
; fLastRow = fTrue;
;PAUSE
UT065:
;PAUSE
mov [fLastRow],fTrue
; }
; }
UT070:
; }
; native note: end of if fPageView clause
; else if (pwwd->fOutline)
; native note: use fOutline instead
; REVIEW - C should also use fOutline
LChkOutline:
; si = pdrT
cmp [fOutline],0
jz LChkOverride
; {
; if (!FShowOutline(doc, CpMax(caTap.cpFirst - 1, cp0)))
; fFirstRow = fTrue;
;PAUSE
mov ax,[caTap.LO_cpFirstCa]
mov dx,[caTap.HI_cpFirstCa]
sub ax,1
sbb dx,0
jns UT075
xor ax,ax
cwd
UT075:
push [doc]
push dx ; SEG
push ax ; OFF
cCall FShowOutline,<>
or ax,ax
jnz UT080
;PAUSE
mov [fFirstRow],fTrue
UT080:
; if (!FShowOutline(doc, CpMin(caTap.cpLim, CpMacDocEdit(doc))))
; fLastRow = fTrue;
push [doc]
cCall CpMacDocEdit,<>
push dx ; SEG
push ax ; OFF
push [caTap.HI_cpLimCa]
push [caTap.LO_cpLimCa]
cCall CpMin,<>
push [doc]
push dx ; SEG
push ax ; OFF
cCall FShowOutline,<>
or ax,ax
jnz UT085
;PAUSE
mov [fLastRow],fTrue
UT085:
; }
LChkOverride:
; /* Rebuild the cache if we need to override. */
; if ((fFirstRow && !vtcc.fFirstRow) || (fLastRow && !vtcc.fLastRow))
; CacheTc(ww,doc,cp,fFirstRow,fLastRow);
; si = pdrT
xor ax,ax ; a zero register will be handy
cmp [fFirstRow],al
jz UT090
test [vtcc.fFirstRowTcc],maskFFirstRowTcc
jz UT100
UT090:
cmp [fLastRow],al
jz UT110
test [vtcc.fLastRowTcc],maskFLastRowTcc
jnz UT110
UT100:
;PAUSE
; ax = 0
push [ww]
push [doc]
push [SEG_cp]
push [OFF_cp]
mov al,[fFirstRow]
push ax
mov al,[fLastRow]
push ax
cCall CacheTc,<>
UT110:
; fFirstRow = vtcc.fFirstRow;
; fLastRow = vtcc.fLastRow;
errnz <fFirstRowTcc-fLastRowTcc>
mov al,[vtcc.fFirstRowTcc]
push ax
and al,maskFFirstRowTcc
mov [fFirstRow],al
pop ax
and al,maskFLastRowTcc
mov [fLastRow],al
; dylAbove = vtcc.dylAbove;
;PAUSE
mov ax,[vtcc.dylAboveTcc]
mov [dylAbove],ax
; dylBelow = vtcc.dylBelow;
mov ax,[vtcc.dylBelowTcc]
mov [dylBelow],ax
; /* NOTE: The height available for an non-incremental update is extended
; /* past the bottom of the bounding DR so that the bottom border
; /* or frame line will not be shown if the row over flows.
; /**/
; si = pdrT
; fFrameLines = FDrawTableDrsWw(ww);
; dylLimPldr = pdrT->dyl - *pypTop + dylBelow;
;PAUSE
mov ax,[si.dylDr]
sub ax,[ypTop]
add ax,[dylBelow]
mov [dylLimPldr],ax
; native note - do fFrameLines here so that we can jump
; over the next block without retesting it
; #define FDrawTableDrsWw(ww) \
; (PwwdWw(ww)->grpfvisi.fDrawTableDrs || PwwdWw(ww)->grpfvisi.fvisiShowAll)
call LN_PwwdWw
xchg ax,bx
xor ax,ax
mov [fFrameLines],al ; assume fFalse
test [bx.grpfvisiWwd],maskfDrawTableDrsGrpfvisi or maskfvisiShowAllGrpfvisi
jz UT130
mov [fFrameLines],fTrue ; assumption failed
; fall through to next block with fFrameLines already tested true
; if (dylBelow == 0 && fFrameLines && !fPageView)
; dylLimPldr += DyFromBrc(brcNone,fTrue/*fFrameLines*/);
; si = pdrT, ax = 0
cmp [dylBelow],ax
jnz UT130
cmp [fPageView],al
jnz UT130
; #define DyFromBrc(brc, fFrameLines) DxyFromBrc(brc, fFrameLines, fFalse)
; #define DxyFromBrc(brc, fFrameLines, fWidth) \
; WidthHeightFromBrc(brc, fFrameLines | (fWidth << 1))
errnz <brcNone>
; si = pdrT, ax = 0
push ax
inc ax ; fFrameLines | (fWidth << 1) == 1
push ax
ifdef DEBUG
cCall S_WidthHeightFromBrc,<>
else
cCall N_WidthHeightFromBrc,<>
endif
add [dylLimPldr],ax
xor ax,ax
UT130:
; if (fAbsHgtRow)
; dylLimPldr = min(dylLimPldr,DypFromDya(-dyaRowHeight) + dylBelow);
; si = pdrT, ax = 0
;PAUSE
cmp [fAbsHgtRow],al
jz UT135 ; do screwy jump to set up ax for next block
mov ax,[dyaRowHeight]
neg ax
call LN_DypFromDya
add ax,[dylBelow]
cmp ax,[dylLimPldr]
jle UT140
UT135:
mov ax,[dylLimPldr]
UT140:
mov [dylLimPldr],ax
UT150:
; dylLimDr = dylLimPldr - dylAbove - dylBelow;
; si = pdrT, ax = dylLimPldr
sub ax,[dylAbove]
sub ax,[dylBelow]
mov [dylLimDr],ax
; /* Check for incremental update */
; Break3(); /* Mac only thing */
; if (dlOld == dlNew && dlOld < dlMac && cp == CpPlc(hplcedl,dlNew))
mov ax,[dlOld]
cmp ax,[dlNew]
jne LChkFreeEdl
;PAUSE
cmp ax,[dlMac]
jge LChkFreeEdl
push [hplcedl]
push ax ; since dlNew == dlOld
cCall CpPlc,<>
;PAUSE
sub ax,[OFF_cp]
sbb dx,[SEG_cp]
or ax,dx
jne LChkFreeEdl
; {
; /* we are about to either use dlOld, or trash it. The next
; /* potentially useful dl is therefore dlOld+1
; /**/
; GetPlc ( hplcedl, dlNew, &edl );
;PAUSE
lea ax,[edl]
mov cx,[dlNew]
call LN_GetPlcParent
; if ( edl.ypTop == *pypTop && edl.hpldr != hNil )
mov ax,[ypTop]
sub ax,[edl.ypTopEdl]
jne UT175
; ax = 0
errnz <hNil>
cmp [edl.hpldrEdl],ax
jz UT175
; {
; hpldrTable = edl.hpldr;
mov ax,[edl.hpldrEdl]
mov [hpldrTable],ax
; Assert ( !edl.fDirty );
; Assert((*hpldrTable)->idrMac == itcMac + 1);
ifdef DEBUG
push ax
push bx
push cx
push dx
push di
test [edl.fDirtyEdl],maskFDirtyEdl
jz UT160
mov ax,midDisptbn2
mov bx,507
cCall AssertProcForNative,<ax,bx>
UT160:
mov di,[hpldrTable]
mov di,[di]
mov ax,[di.idrMacPldr]
sub ax,[itcMac]
dec ax
jz UT170
mov ax,midDisptbn2
mov bx,517
cCall AssertProcForNative,<ax,bx>
UT170:
pop di
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; fIncr = fTrue;
mov [fIncr],fTrue
; ++dlOld;
inc [dlOld]
; goto LUpdateTable;
jmp LUpdateTable
; }
UT175:
; }
LChkFreeEdl:
; if (dlNew == dlOld && dlOld < dlMac) /* existing edl is useless, free it */
mov ax,[dlOld]
cmp ax,[dlNew]
jne LClearFIncr
cmp ax,[dlMac]
jge LClearFIncr
; FreeEdl(hplcedl, dlOld++);
;PAUSE
push [hplcedl]
push ax
inc ax
mov [dlOld],ax
cCall FreeEdl,<>
; Break3(); native note: Mac only
; fIncr = fReusePldr = fFalse;
LClearFIncr:
xor ax,ax
mov [fIncr],al
mov [fReusePldr],al
; /* new table row; init edl */
; if (vihpldrMac > 0)
mov cx,[vihpldrMac]
jcxz LHpldrInit
; {
; hpldrTable = vrghpldr[--vihpldrMac];
; vrghpldr[vihpldrMac] = hNil; /* we're gonna use or lose it */
;PAUSE
dec cx
mov [vihpldrMac],cx
sal cx,1
mov di,cx
mov bx,[vrghpldr.di]
mov [vrghpldr.di],hNil
mov [hpldrTable],bx
; ppldrTable = *hpldrTable;
mov di,[bx]
; if (ppldrTable->idrMax != itcMac+1 || !ppldrTable->fExternal)
mov ax,[di.idrMaxPldr]
sub ax,[itcMac]
dec ax
jnz LFreeHpldr
; ax = 0
cmp [di.fExternalPldr],ax
jnz LReusePldr
LFreeHpldr:
; {
; /* If ppldrTable->idrMac == 0, LcbGrowZone freed up all of
; /* the far memory associated with this hpldr. We now need to
; /* free only the near memory. */
; if (ppldrTable->idrMax > 0)
; bx = hpldrTable, di = ppldrTable
;PAUSE
mov cx,[di.idrMaxPldr] ; technically an uns
jcxz LFreeHpldr2
; {
; FreeDrs(hpldrTable, 0);
; if ((*hpldrTable)->fExternal)
; FreeHq((*hpldrTable)->hqpldre);
push bx
xor ax,ax
push ax
cCall FreeDrs,<>
mov cx,[di.fExternalPldr]
jcxz LFreeHpldr2
push [di.HI_hqpldrePldr]
push [di.LO_hqpldrePldr]
cCall FreeHq,<>
LFreeHpldr2:
; }
; FreeH(hpldrTable);
; #define FreeH(h) FreePpv(sbDds,(h))
mov ax,sbDds
push ax
push [hpldrTable]
cCall FreePpv,<>
; hpldrTable = hNil;
mov [hpldrTable],hNil
jmp short LHpldrInit
; }
; else
; {
; Assert(ppldrTable->brgdr == offset(PLDR, rgdr));
LReusePldr:
; bx = hpldrTable, di = ppldrTable
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [di.brgdrPldr],rgdrPldr
je UT180
mov ax,midDisptbn2
mov bx,632
cCall AssertProcForNative,<ax,bx>
UT180:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; fReusePldr = fTrue;
mov [fReusePldr],fTrue
jmp short LChkHpldr
; }
; }
; if (!fReusePldr)
; native note: we jump directly into the right clause from above
; {
; hpldrTable = HplInit2(sizeof(struct DR),offset(PLDR, rgdr), itcMac+1, fTrue);
LHpldrInit:
mov ax,cbDrMin
push ax
mov ax,rgdrPldr
push ax
mov ax,[itcMac]
inc ax
push ax
mov ax,fTrue
push ax
cCall HplInit2,<>
mov [hpldrTable],ax
xchg ax,bx
; Assert(hpldrTable == hNil || (*hpldrTable)->idrMac == 0);
ifdef DEBUG
push ax
push bx
push cx
push dx
mov bx,[hpldrTable]
or bx,bx
jz UT190
mov bx,[bx]
cmp [bx.idrMacPldr],0
jz UT190
mov ax,midDisptbn2
mov bx,716
cCall AssertProcForNative,<ax,bx>
UT190:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; }
LChkHpldr:
; bx = hpldrTable
; edl.hpldr = hpldrTable;
mov [edl.hpldrEdl],bx
; if (hpldrTable == hNil || vmerr.fMemFail)
or bx,bx
jz UT200
cmp [vmerr.fMemFailMerr],0
jz UT210
; {
; SetErrorMat(matDisp);
UT200:
mov ax,matDisp
push ax
cCall SetErrorMatProc,<>
; return fFalse; /* operation failed */
xor ax,ax
jmp LExitUT
; }
; bx = hpldrTable
; edl.ypTop = *pypTop;
UT210:
mov ax,[ypTop]
mov [edl.ypTopEdl],ax
; native note: the order of these next instructions has been altered
; from the C version for efficiency...
;
; /* this allows us to clobber (probably useless) dl's below */
; Assert(FInCa(doc,cp,&vtcc.ca) && vtcc.itc == 0);
ifdef DEBUG
push ax
push bx
push cx
push dx
push [doc]
push [SEG_cp]
push [OFF_cp]
mov ax,dataoffset [vtcc.caTcc]
push ax
cCall FInCa,<>
or ax,ax
jz UT220
cmp [vtcc.itcTcc],0
jz UT230
UT220:
mov ax,midDisptbn2
mov bx,908
cCall AssertProcForNative,<ax,bx>
UT230:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; dylDrOld = dylLimDr;
mov ax,[dylLimDr]
mov [dylDrOld],ax
; edl.dyp = dylLimPldr;
mov ax,[dylLimPldr]
mov [edl.dypEdl],ax
; edl.dcpDepend = 1;
; edl.dlk = dlkNil;
; REVIEW is this right?
errnz <dcpDependEdl+1-(dlkEdl)>
mov [edl.grpfEdl],00001h
; edl.xpLeft = vtcc.xpCellLeft;
mov ax,[vtcc.xpCellLeftTcc]
mov [edl.xpLeftEdl],ax
; ppldrTable = *hpldrTable;
; set-up for fast moves..
mov di,[bx]
add di,hpldrBackPldr
push ds
pop es
; ppldrTable->hpldrBack = hpldr;
mov ax,[hpldr]
stosw
; ppldrTable->idrBack = idr;
errnz <hpldrBackPldr+2-idrBackPldr>
mov ax,[idr]
stosw
; ppldrTable->ptOrigin.xp = 0;
errnz <idrBackPldr+2-ptOriginPldr>
errnz <xwPt>
xor ax,ax
stosw
; ppldrTable->ptOrigin.yp = edl.ypTop;
mov ax,[edl.ypTopEdl]
stosw
; ppldrTable->dyl = edl.dyp;
errnz <ptOriginPldr+ypPt+2-(dylPldr)>
mov ax,[edl.dypEdl]
stosw
; PutCpPlc ( hplcedl, dlNew, cp );
; PutPlc ( hplcedl, dlNew, &edl );
; bx = hpldrTable
; push arguments for PutCpPlc call
push [hplcedl]
push [dlNew]
push [SEG_cp]
push [OFF_cp]
cCall PutCpPlc,<>
call LN_PutPlc
; Break3();
LUpdateTable:
; native note: set up register variable, this is
; assumed by the remainder of the routine (and the
; little helper routines)
;PAUSE
lea di,[drfFetch]
; fSomeDrDirty = fFalse; /* for second pass */
; CpFirstTap1( doc, cp, fOutline );
; idrMacTable = fIncr ? itcMac + 1 : 0;
xor ax,ax
mov [fSomeDrDirty],al
cmp [fIncr],al
jz UT300
;PAUSE
mov ax,[itcMac]
inc ax
UT300:
mov [idrMacTable],ax
;PAUSE
push [doc]
push [SEG_cp]
push [OFF_cp]
mov al,[fOutline]
cbw
push ax
cCall CpFirstTap1,<>
; dylNew = DypFromDya(abs(vtapFetch.dyaRowHeight)) - dylAbove - dylBelow;
mov ax,[vtapFetch.dyaRowHeightTap]
or ax,ax
jns UT310
;PAUSE
neg ax
UT310:
call LN_DypFromDya
sub ax,[dylAbove]
sub ax,[dylBelow]
mov [dylNew],ax
; dylOld = (*hpldrTable)->dyl;
mov bx,[hpldrTable]
mov bx,[bx]
mov ax,[bx.dylPldr]
mov [dylOld],ax
; for ( idrTable = fTtpDr = 0; !fTtpDr; ++idrTable )
; {
xor ax,ax
mov [idrTable],ax
mov [fTtpDr],al
LIdrLoopTest:
cmp fTtpDr,0
jz UT320
jmp LIdrLoopEnd
; fTtpDr = idrTable == itcMac;
UT320:
mov ax,[idrTable]
cmp ax,[itcMac]
jne UT330
mov [fTtpDr],fTrue
UT330:
; Assert ( FInCa(doc,cp,&caTapCur) );
ifdef DEBUG
push ax
push bx
push cx
push dx
push [doc]
push [SEG_cp]
push [OFF_cp]
lea ax,[caTapCur]
push ax
cCall FInCa,<>
or ax,ax
jnz UT340
mov ax,midDisptbn2
mov bx,828
cCall AssertProcForNative,<ax,bx>
UT340:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; ax = idrTable
; if ( idrTable >= idrMacTable )
; ax = idrTable
sub ax,[idrMacTable] ; sub for zero register on branch
jge LNewDr
; native note: we'll do the else clause here...
; else
; pdrTable = PdrFetch(hpldrTable,idrTable,&drfFetch);
;PAUSE
call LN_PdrFetchTable
jmp LValidateDr
; native note: we now return you to our regularly scheduled if statement
; native note: assert idrTable == idrMacTable, hence ax == 0
LNewDr:
ifdef DEBUG
push ax
push bx
push cx
push dx
xor ax,ax
jz UT350
mov ax,midDisptbn2
mov bx,849
cCall AssertProcForNative,<ax,bx>
UT350:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; { /* this is a new cell in the table */
; if (fReusePldr)
; ax = 0
cmp fReusePldr,al
jz UT370 ; native note: branch expects ax = 0
; {
; pdrTable = PdrFetch(hpldrTable, idrTable, &drfFetch);
;PAUSE
call LN_PdrFetchTable
; Assert(drfFetch.pdrfUsed == 0);
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [drfFetch.pdrfUsedDrf],0
jz UT360
mov ax,midDisptbn2
mov bx,860
cCall AssertProcForNative,<ax,bx>
UT360:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; PutIMacPlc(drfFetch.dr.hplcedl, 0);
push [drfFetch.drDrf.hplcedlDr]
xor ax,ax
push ax
cCall PutIMacPlc,<>
jmp short UT380
; }
; else
; {
UT370:
; SetWords ( &drfFetch, 0, sizeof(struct DRF) / sizeof(int) );
; ax = 0, di = &drfFetch
errnz <cbDrfMin and 1>
mov cx,cbDrfMin SHR 1
push di ; save register variable
push ds
pop es
rep stosw
pop di
; }
; /* NOTE We are assuming that the 'xl' coordiates in the table frame (PLDR)
; /* are the same as the 'xp' coordinates of the bounding DR.
; /**/
; ItcGetTcxCache(ww, doc, cp, &vtapFetch, idrTable/*itc*/, &tcx);
UT380:
;PAUSE
push [ww]
push [doc]
push [SEG_cp]
push [OFF_cp]
mov ax,dataoffset [vtapFetch]
push ax
push [idrTable]
lea ax,[tcx]
push ax
ifdef DEBUG
cCall S_ItcGetTcxCache
else
cCall N_ItcGetTcxCache
endif
; native note: the following block of code has been rearranged from
; the C version of efficiency...
;
push di ; save register variable
push ds
pop es
lea di,[drfFetch.drDrf.xlDr]
; drfFetch.dr.xl = tcx.xpDrLeft;
mov ax,[tcx.xpDrLeftTcx]
stosw
; drfFetch.dr.yl = fTtpDr ? max(dyFrameLine,dylAbove) : dylAbove;
errnz <xlDr+2-ylDr>
mov ax,[dylAbove] ; right more often than not
cmp [fTtpDr],0
jz UT390
;PAUSE
mov ax,[dylAbove]
; #define dyFrameLine dypBorderFti
; #define dypBorderFti vfti.dypBorder
cmp ax,[vfti.dypBorderFti]
jge UT390
mov ax,[vfti.dypBorderFti]
UT390:
stosw
; drfFetch.dr.dxl = tcx.xpDrRight - drfFetch.dr.xl;
errnz <ylDr+2-dxlDr>
mov ax,[tcx.xpDrRightTcx]
sub ax,[drfFetch.drDrf.xlDr]
stosw
; drfFetch.dr.dyl = edl.dyp - drfFetch.dr.yl - dylBelow;
;PAUSE
errnz <dxlDr+2-dylDr>
mov ax,[edl.dypEdl]
sub ax,[drfFetch.drDrf.ylDr]
sub ax,[dylBelow]
stosw
; drfFetch.dr.cpLim = cpNil;
; drfFetch.dr.doc = doc;
errnz <dylDr+2+4-cpLimDr>
errnz <LO_cpNil+1>
errnz <HI_cpNil+1>
add di,4
mov ax,-1
stosw
stosw
errnz <cpLimDr+4-docDr>
mov ax,[doc]
stosw
; drfFetch.dr.fDirty = fTrue;
; drfFetch.dr.fCpBad = fTrue;
; drfFetch.dr.fInTable = fTrue;
; drfFetch.dr.fForceWidth = fTrue;
; this next one is silly since it is already set to zero...
; drfFetch.dr.fBottomTableFrame = fFalse; /* we'll set this correctly later */
errnz <docDr+2-dcpDependDr>
errnz <dcpDependDr+1-fDirtyDr>
errnz <fDirtyDr-fCpBadDr>
errnz <fDirtyDr-fInTableDr>
errnz <fDirtyDr-fForceWidthDr>
; native note: this stores 0 in dr.dcpDepend, which has
; no net effect (it's already zero by the SetWords)
;PAUSE
errnz <maskFDirtyDr-00001h>
errnz <maskFCpBadDr-00002h>
errnz <maskFInTableDr-00020h>
errnz <maskFForceWidthDr-00080h>
;mov ax,(maskFDirtyDr or maskFCpBadDr or fInTableDr or fForceWidthDr) SHL 8
mov ax,0A300h
stosw ; how's that for C to 8086 compression?
;
; drfFetch.dr.dxpOutLeft = tcx.dxpOutLeft;
errnz <dcpDependDr+6-(dxpOutLeftDr)>
add di,4 ; advance di
mov ax,[tcx.dxpOutLeftTcx]
stosw
; drfFetch.dr.dxpOutRight = tcx.dxpOutRight;
errnz <dxpOutLeftDr+2-dxpOutRightDr>
mov ax,[tcx.dxpOutRightTcx]
stosw
; drfFetch.dr.idrFlow = idrNil;
errnz <dxpOutRightDr+2-idrFlowDr>
errnz <idrNil+1>
mov ax,-1
stosw
; drfFetch.dr.lrk = lrk;
; ax = -1
errnz <idrFlowDr+2-ccolM1Dr>
errnz <ccolM1Dr+1-lrkDr>
inc ax ; now it's zero
mov ah,[lrk]
stosw ; also stores 0 in ccolM1, again no net change
; drfFetch.dr.fCantGrow = fPageView || fAbsHgtRow;
errnz <lrkDr+1-fCantGrowDr>
mov al,[fPageView]
or al,[fAbsHgtRow]
jz UT400
;PAUSE
or bptr [di],maskFCantGrowDr
UT400:
;PAUSE
pop di ; restore register variable
; if (!fReusePldr)
cmp [fReusePldr],0
jnz UT430
; {
; if (!FInsertInPl ( hpldrTable, idrTable, &drfFetch.dr )
push [hpldrTable]
push [idrTable]
lea ax,[drfFetch.drDrf]
push ax
cCall FInsertInPl,<>
or ax,ax
jz LAbortUT ; if we branch, ax is zero as required
; || !FInitHplcedl(1, cpMax, hpldrTable, idrTable))
; native note: hold on to your hats, this next bit is trickey
errnz <LO_cpMax-0FFFFh>
errnz <HI_cpMax-07FFFh>
mov ax,1
push ax
neg ax
cwd
shr dx,1
push dx ; SEG
push ax ; OFF
push [hpldrTable]
push [idrTable]
cCall FInitHplcedl,<>
or ax,ax
jnz UT420
; {
; native note: as usual, the order of the following has been changed
; to save a few bytes...
LAbortUT: ; NOTE ax must be zero when jumping to this label!!!
;PAUSE
; ax = 0
; edl.hpldr = hNil;
errnz <hNil>
mov [edl.hpldrEdl],ax
; FreeDrs(hpldrTable, 0);
push [hpldrTable]
push ax
cCall FreeDrs,<>
; FreeHpl(hpldrTable);
push [hpldrTable]
cCall FreeHpl,<>
; PutPlc(hplcedl, dlNew, &edl);
call LN_PutPlc
; return fFalse; /* operation failed */
xor ax,ax
jmp LExitUT
; }
; pdrTable = PdrFetch(hpldrTable,idrTable,&drfFetch);
UT420:
call LN_PdrFetchTable
; }
UT430:
; ++idrMacTable;
inc [idrMacTable]
; Assert (fReusePldr || (*hpldrTable)->idrMac == idrMacTable );
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [fReusePldr],0
jnz UT440
mov bx,[hpldrTable]
mov bx,[bx]
mov ax,[bx.idrMacPldr]
cmp ax,[idrMacTable]
je UT440
mov ax,midDisptbn2
mov bx,1097
cCall AssertProcForNative,<ax,bx>
UT440:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; }
; native note: else clause done above
LValidateDr:
; si = pdrTable
; if (pdrTable->fCpBad || pdrTable->cpFirst != cp)
; native note: this next block is somewhat verbose,
; to leave [cp] in ax,dx
mov ax,[OFF_cp]
mov dx,[SEG_cp]
test [si.fCpBadDr],maskFCpBadDr
jnz UT500
;PAUSE
cmp ax,[si.LO_cpFirstDr]
jnz UT500
cmp dx,[si.HI_cpFirstDr]
jz UT510
; {
; pdrTable->cpFirst = cp;
UT500:
; si = pdrTable, ax,dx = cp
mov [si.HI_cpFirstDr],dx
mov [si.LO_cpFirstDr],ax
; pdrTable->fCpBad = fFalse;
and [si.fCpBadDr],not maskFCpBadDr
; pdrTable->fDirty = fTrue;
or [si.fDirtyDr],maskFDirtyDr
; }
; if (pdrTable->yl != (ylT = fTtpDr ? max(dylAbove,dyFrameLine) : dylAbove))
UT510:
mov ax,[dylAbove]
cmp [fTtpDr],0
jz UT520
; #define dyFrameLine dypBorderFti
; #define dypBorderFti vfti.dypBorder
;PAUSE
cmp ax,[vfti.dypBorderFti]
jge UT520
mov ax,[vfti.dypBorderFti]
UT520:
sub ax,[si.ylDr] ; sub for zero register on branch
je UT530
; {
; pdrTable->yl = ylT;
; ax = ylT - pdrTable->ylDr
;PAUSE
add [si.ylDr],ax
; FreeEdls(pdrTable->hplcedl,0,IMacPlc(pdrTable->hplcedl));
; PutIMacPlc(pdrTable->hplcedl,0);
mov bx,[si.hplcedlDr]
xor cx,cx ; zero register
push bx ; arguments for
push cx ; PutIMacPlc call
push bx ; some arguments for
push cx ; FreeEdls call
call LN_IMacPlcTable
push ax ; last argument for FreeEdls - IMacPlc result
cCall FreeEdls,<>
cCall PutIMacPlc,<>
; pdrTable->fDirty = fTrue;
or [si.fDirtyDr],maskFDirtyDr
jmp short LChkFTtpDr
; }
; else if (pdrTable->fBottomTableFrame != fLastRow || pdrTable->fDirty)
UT530:
; ax = 0
test [si.fBottomTableFrameDr],maskFBottomTableFrameDr
jz UT540
inc ax
UT540:
cmp [fLastRow],0
jz UT550
xor ax,1
UT550:
or ax,ax
jnz UT560
;PAUSE
test [si.fDirtyDr],maskFDirtyDr
jz LChkFTtpDr
; {
; if ((dlLast = IMacPlc(pdrTable->hplcedl) - 1) >= 0)
UT560:
call LN_IMacPlcTable
dec ax
mov [dlLast],ax
jl UT570
; {
; GetPlc(pdrTable->hplcedl,dlLast,&edlLast);
;PAUSE
xchg ax,cx
call LN_GetPlcTable
; edlLast.fDirty = fTrue;
or [edlLast.fDirtyEdl],maskFDirtyEdl
; PutPlcLast(pdrTable->hplcedl,dlLast,&edlLast);
; #ifdef DEBUG
; # define PutPlcLast(h, i, pch) PutPlcLastDebugProc(h, i, pch)
; #else
; # define PutPlcLast(h, i, pch) PutPlcLastProc()
; #endif
; }
ifdef DEBUG
push [si.hplcedlDr]
push [dlLast]
lea ax,[edlLast]
push ax
cCall PutPlcLastDebugProc,<>
else ; !DEBUG
call LN_PutPlcLast
endif ; DEBUG
UT570:
; pdrTable->fDirty = fTrue;
or [si.fDirtyDr],maskFDirtyDr
; }
; if (fTtpDr)
LChkFTtpDr:
cmp [fTtpDr],0
jz UT620
; {
; if (fAbsHgtRow)
;PAUSE
cmp [fAbsHgtRow],0
jz UT590
; dylNew = DypFromDya(abs(vtapFetch.dyaRowHeight)) + dylBelow;
;PAUSE
mov ax,[vtapFetch.dyaRowHeightTap]
; native note: Assert(vtapFetch.dyaRowHeight < 0);
ifdef DEBUG
push ax
push bx
push cx
push dx
or ax,ax
js UT580
mov ax,midDisptbn2
mov bx,1482
cCall AssertProcForNative,<ax,bx>
UT580:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
neg ax
call LN_DypFromDya
add ax,[dylBelow]
jmp short UT600
; else
; dylNew += dylAbove + dylBelow;
UT590:
;PAUSE
mov ax,[dylNew]
add ax,[dylAbove]
add ax,[dylBelow]
UT600:
mov [dylNew],ax ; leave dylNew in ax for next block...
; pdrTable->dyl = min(pdrTable->dyl, dylNew - pdrTable->yl - dylBelow);
; ax = dylNew
sub ax,[si.ylDr]
sub ax,[dylBelow]
cmp ax,[si.dylDr]
jge UT610
mov [si.dylDr],ax
UT610:
; }
UT620:
; Assert ( pdrTable->cpFirst == cp );
;PAUSE
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[OFF_cp]
cmp ax,[si.LO_cpFirstDr]
jne UT630
mov ax,[SEG_cp]
cmp ax,[si.HI_cpFirstDr]
je UT640
UT630:
mov ax,midDisptbn2
mov bx,1284
cCall AssertProcForNative,<ax,bx>
UT640:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; if (pdrTable->fDirty)
test [si.fDirtyDr],maskFDirtyDr
jnz UT650
jmp LSetDylNew
; {
; /* set DR to full row height */
; if (fIncr)
UT650:
cmp [fIncr],0
jz LSetFBottom
; {
; /* we're betting that the row height doesn't change.
; /* record some info to check our bet and take corrective
; /* measures if we lose.
; /**/
; dlMacOld = IMacPlc(pdrTable->hplcedl);
;PAUSE
call LN_IMacPlcTable
mov [dlMacOld],ax
; dylDrOld = pdrTable->dyl;
mov ax,[si.dylDr]
mov [dylDrOld],ax
; pdrTable->fCantGrow = pdrTable->dyl >= dylLimDr && (fPageView || fAbsHgtRow);
call LN_SetFCantGrow
; pdrTable->dyl = edl.dyp - pdrTable->yl - dylBelow;
mov ax,[edl.dypEdl]
sub ax,[si.ylDr]
sub ax,[dylBelow]
mov [si.dylDr],ax
; }
; /* enable drawing the bottom table frame */
; pdrTable->fBottomTableFrame = fLastRow;
LSetFBottom:
and [si.fBottomTableFrameDr],not maskFBottomTableFrameDr ; assume fFalse
cmp [fLastRow],0
jz UT660
or [si.fBottomTableFrameDr],maskFBottomTableFrameDr ; assumption failed
UT660:
; /* write any changes we have made, native code will need them */
; pdrTable = PdrFreeAndFetch(hpldrTable,idrTable,&drfFetch);
push [hpldrTable]
push [idrTable]
push di
ifdef DEBUG
cCall S_PdrFreeAndFetch,<>
else
cCall N_PdrFreeAndFetch,<>
endif
xchg ax,si
; if (!FUpdTableDr(ww,hpldrTable,idrTable))
; if (!FUpdateDr(ww,hpldrTable,idrTable,rcwInval,fFalse,udmodTable,cpNil))
; {
; LFreeAndAbort:
; FreePdrf(&drfFetch);
; goto LAbort;
; }
; NOTE: the local routine also does the assert with DypHeightTc
;PAUSE
xor ax,ax ; flag to helper routine
mov cx,[idrTable]
errnz <xwLeftRc>
lea bx,[rcwInvalXwLeftRc]
call LN_FUpdateOneDr
jnz UT670
LFreeAndAbortUT:
call LN_FreePdrf
xor ax,ax
jmp LAbortUT ; note ax is zero, as required for the jump
UT670:
; /* check for height change */
; pdrTable->fCantGrow = pdrTable->dyl >= dylLimDr && (fPageView || fAbsHgtRow);
call LN_SetFCantGrow
; if (pdrTable->dyl != dylDrOld)
mov ax,[dylDrOld]
cmp ax,[si.dylDr]
je LSetFSomeDirty
; {
; if (fIncr && fLastRow && dylDrOld == dylOld - dylAbove - dylBelow
; && IMacPlc(pdrTable->hplcedl) >= dlMacOld)
; ax = [dylDrOld]
cmp [fIncr],0
jz LSetFSomeDirty
;PAUSE
cmp [fLastRow],0
jz LSetFSomeDirty
sub ax,[dylOld]
add ax,[dylAbove]
add ax,[dylBelow]
jnz LSetFSomeDirty
call LN_IMacPlcTable
cmp ax,[dlMacOld]
jl LSetFSomeDirty
; {
; /* we probably have a dl that has a frame line in the
; /* middle of a DR.
; /**/
; pdrTable->fDirty = fTrue;
;PAUSE
or [si.fDirtyDr],maskFDirtyDr
; GetPlc(pdrTable->hplcedl,dlMacOld-1,&edlLast);
mov cx,[dlMacOld]
dec cx
call LN_GetPlcTable
; edlLast.fDirty = fTrue;
or [edlLast.fDirtyEdl],maskFDirtyEdl
; PutPlcLast(pdrTable->hplcedl,dlMacOld-1,&edlLast);
; #ifdef DEBUG
; # define PutPlcLast(h, i, pch) PutPlcLastDebugProc(h, i, pch)
; #else
; # define PutPlcLast(h, i, pch) PutPlcLastProc()
; #endif
; }
ifdef DEBUG
push [si.hplcedlDr]
mov ax,[dlMacOld]
dec ax
push ax
lea ax,[edlLast]
push ax
cCall PutPlcLastDebugProc,<>
else ; !DEBUG
call LN_PutPlcLast
endif ; DEBUG
; }
; }
; fSomeDrDirty |= pdrTable->fDirty && !fTtpDr;
LSetFSomeDirty:
test [si.fDirtyDr],maskFDirtyDr
jz LSetDylNew
;PAUSE
cmp [fTtpDr],0
jnz LSetDylNew
mov [fSomeDrDirty],fTrue
; }
; if (!fTtpDr)
LSetDylNew:
cmp [fTtpDr],0
jnz UT690
; dylNew = max(dylNew, pdrTable->dyl);
;PAUSE
mov ax,[si.dylDr]
cmp ax,[dylNew]
jle UT690
mov [dylNew],ax
UT690:
; Win(fRMark |= pdrTable->fRMark;)
;PAUSE
test [si.fRMarkDr],maskFRMarkDr
je UT695
mov [fRMark],fTrue
UT695:
; /* advance the cp */
; cp = CpMacPlc ( pdrTable->hplcedl );
push [si.hplcedlDr]
cCall CpMacPlc,<>
mov [OFF_cp],ax
mov [SEG_cp],dx
; FreePdrf(&drfFetch);
call LN_FreePdrf
; } /* end of for idrTable loop */
inc [idrTable]
jmp LIdrLoopTest
LIdrLoopEnd:
; idrMacTable = (*hpldrTable)->idrMac = itcMac + 1;
mov bx,[hpldrTable]
mov bx,[bx]
mov cx,[itcMac]
inc cx
mov [bx.idrMacPldr],cx
; /* adjust the TTP DR to the correct height, don't want it to dangle
; /* below the PLDR/outer EDL
; /**/
; pdrTable = PdrFetch(hpldrTable, itcMac, &drfFetch);
; cx = itcMac + 1
dec cx
call LN_PdrFetch
; if (pdrTable->yl + pdrTable->dyl + dylBelow > dylNew)
mov ax,[dylNew]
sub ax,[si.ylDr]
sub ax,[dylBelow]
cmp ax,[si.dylDr]
jge LFreeDrMac
; {
; pdrTable->dyl = dylNew - pdrTable->yl - dylBelow;
; ax = dylNew - pdrTable->yl - dylBelow
mov [si.dylDr],ax
; Assert(IMacPlc(pdrTable->hplcedl) == 1);
ifdef DEBUG
push ax
push bx
push cx
push dx
push [si.hplcedlDr]
cCall IMacPlc,<>
dec ax
jz UT700
mov ax,midDisptbn2
mov bx,1559
cCall AssertProcForNative,<ax,bx>
UT700:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; if (dylOld >= dylNew)
mov ax,[dylOld]
cmp ax,[dylNew]
jl LFreeDrMac
; {
; GetPlc(pdrTable->hplcedl, 0, &edlLast);
xor cx,cx
call LN_GetPlcTable
; edlLast.fDirty = fFalse;
and [edlLast.fDirtyEdl],not maskFDirtyEdl
; PutPlcLast(pdrTable->hplcedl, 0, &edlLast);
; #ifdef DEBUG
; # define PutPlcLast(h, i, pch) PutPlcLastDebugProc(h, i, pch)
; #else
; # define PutPlcLast(h, i, pch) PutPlcLastProc()
; #endif
; }
ifdef DEBUG
push [si.hplcedlDr]
xor ax,ax
push ax
lea ax,[edlLast]
push ax
cCall PutPlcLastDebugProc,<>
else ; !DEBUG
call LN_PutPlcLast
endif ; DEBUG
; pdrTable->fDirty = fFalse;
and [si.fDirtyDr],not maskFDirtyDr
; }
; }
LFreeDrMac:
; FreePdrf(&drfFetch);
call LN_FreePdrf
; Assert ( cp == caTap.cpLim );
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[OFF_cp]
mov dx,[SEG_cp]
cmp ax,[caTap.LO_cpLimCa]
jnz UT710
cmp dx,[caTap.HI_cpLimCa]
jz UT720
UT710:
mov ax,midDisptbn2
mov bx,1622
cCall AssertProcForNative,<ax,bx>
UT720:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; /* At this point, we have scanned the row of the table,
; /* found the fTtp para, and updated the cell's DR's up
; /* to the height of the old EDL. We know
; /* the number of cells/DRs in the row of the table. We now
; /* adjust the height of the mother EDL to the correct row height.
; /**/
; if (fAbsHgtRow)
cmp [fAbsHgtRow],0
jz LUpdateHeight
; {
; dylNew -= dylAbove + dylBelow;
; native note: we'll keep this transient value of dylNew in registers
;PAUSE
mov si,[dylNew]
sub si,[dylAbove]
sub si,[dylBelow]
; for ( idrTable = itcMac; idrTable--; FreePdrf(&drfFetch))
; di = &drfFetch, si = dylNew
mov cx,[itcMac]
LLoop2Body:
dec cx
push cx ; save idrTable
; {
; /* this depends on the theory that we never need a second
; /* pass for an absolute height row
; /**/
; pdrTable = PdrFetch(hpldrTable, idrTable, &drfFetch);
; si = dylNew, di = &drfFetch, cx = idrTable
call LN_PdrFetch
; now, ax = dylNew, si = pdrTable, di = &drfFetch
; if (pdrTable->dyl >= dylNew)
cmp ax,[si.dylDr]
jg UT725
; {
; pdrTable->fCantGrow = fTrue;
;PAUSE
or [si.fCantGrowDr],maskFCantGrowDr
; pdrTable->dyl = dylNew;
mov [si.dylDr],ax
jmp short LLoop2Next
; }
; else
UT725:
; pdrTable->fCantGrow = fFalse;
and [si.fCantGrowDr],not maskFCantGrowDr
; pdrTable->fDirty = fFalse;
and [si.fDirtyDr],not maskFDirtyDr
; }
LLoop2Next:
xchg ax,si ; save dylNew
call LN_FreePdrf
pop cx ; restore itcTable
jcxz LLoop2Exit
jmp short LLoop2Body
LLoop2Exit:
; dylNew += dylAbove + dylBelow;
; native note: didn't store the transient value in [dylNew], so no
; need to restore it...
; }
LUpdateHeight:
; /* update hpldr and edl to correct height now for second scan,
; old height still in dylOld */
; (*hpldrTable)->dyl = edl.dyp = dylNew;
mov ax,[dylNew]
mov [edl.dypEdl],ax
mov bx,[hpldrTable]
mov bx,[bx]
mov [bx.dylPldr],ax
; if (dylNew == dylOld || (!fSomeDrDirty && !fLastRow))
; ax = dylNew
cmp ax,[dylOld]
je UT730
mov al,[fSomeDrDirty]
or al,[fLastRow]
jnz UT735
UT730:
; goto LFinishTable;
;PAUSE
jmp LFinishTable
UT735:
; if (fOverflowDrs = (fPageView && dylNew > dylLimPldr - dylBelow))
;PAUSE
xor cx,cx ; clear high byte
mov cl,[fPageView]
mov ax,[dylNew]
sub ax,[dylLimPldr]
add ax,[dylBelow]
jg UT740
xor cx,cx
UT740:
mov [fOverflowDrs],cl
jcxz LChkLastRow
; {
; pdrT = PdrFetchAndFree(hpldr,idr,&drfFetch);
; di = &drfFetch
;PAUSE
push [hpldr]
push [idr]
push di
ifdef DEBUG
cCall S_PdrFetchAndFree,<>
else
cCall N_PdrFetchAndFree,<>
endif
xchg ax,si
; if ((dylNew < pdrT->dyl || pdrT->lrk == lrkAbs) && !pdrT->fCantGrow)
mov ax,[dylNew]
cmp ax,[si.dylDr]
jl UT745
cmp [si.lrkDr],lrkAbs
jne UT750
UT745:
test [si.fCantGrowDr],maskFCantGrowDr
jnz UT750
; /* force a repagination next time through */
; {
; /* to avoid infinite loops, we won't repeat if the
; DRs are brand new */
; pwwd = PwwdWw(ww);
;PAUSE
call LN_PwwdWw
xchg ax,bx
; pwwd->fDrDirty |= !pwwd->fNewDrs;
test [bx.fNewDrsWwd],maskfNewDrsWwd
jnz UT750
or [bx.fDrDirtyWwd],maskfDrDirtyWwd
UT750:
; }
; for ( idrTable = itcMac; idrTable--; FreePdrf(&drfFetch))
mov si,[dylLimDr]
mov cx,[itcMac]
LLoop3Body:
dec cx
push cx ; save idrTable
; {
; pdrTable = PdrFetch(hpldrTable, idrTable, &drfFetch);
; cx = idrTable, si = dylLimDr, di = &drfFetch
call LN_PdrFetch
; REVIEW - do I need to specify the stack segment?
pop cx ; recover idrTable
push cx ; save it back again
; if (pdrTable->dyl > dylLimDr)
; cx = idrTable, ax = dylLimDr, si = pdrTable, di = &drfFetch
cmp ax,[si.dylDr]
jge UT760
; pdrTable->dyl = dylLimDr;
mov [si.dylDr],ax
UT760:
pop cx
push cx
xchg ax,si ; save dylLimDr in si
call LN_FreePdrf
pop cx ; restore idrTable
jcxz UT770
jmp short LLoop3Body
UT770:
; }
; /* doctor dylNew and fix earlier mistake */
; dylNew = dylLimPldr;
mov ax,[dylLimPldr]
mov [dylNew],ax
; (*hpldrTable)->dyl = edl.dyp = dylNew;
; ax = dylNew
mov [edl.dypEdl],ax
mov bx,[hpldrTable]
mov bx,[bx]
mov [bx.dylPldr],ax
; }
LChkLastRow:
; if (fLastRow && fFrameLines)
cmp [fLastRow],0
jz UT800
cmp [fFrameLines],0
jnz UT810
UT800:
;PAUSE
jmp LSecondPass
UT810:
; {
; /* Here we decide what cells have to be drawn because of the bottom frame
; /* line. State: All cells are updated to the original height of the edl,
; /* the last EDL of every cell that was drawn in the first update pass
; /* has been set dirty (even if the fDirty bit for the DR is not set)
; /* and does not have a bottom frame line.
; /**/
; pwwd = PwwdWw(ww);
; fDrawBottom = dylBelow == 0 && YwFromYl(hpldrTable,dylNew) <= pwwd->rcwDisp.ywBottom;
xor cx,cx
cmp [dylBelow],cx
jnz UT820
call LN_PwwdWw
xchg ax,si ; save in less volatile register
push [hpldrTable]
push [dylNew]
cCall YwFromYl,<>
xor cx,cx
cmp ax,[si.rcwDispWwd.ywBottomRc]
jg UT820
errnz <fTrue-1>
inc cl
UT820:
mov [fDrawBottom],cl
; Mac(cbBmbSav = vcbBmb);
ifdef MAC
move.w vcbBmb,cbBmbSav ; mem-to-mem moves, what a concept!!
endif
; fLastDlDirty = fFalse;
mov [fLastDlDirty],fFalse
; for ( idrTable = 0; idrTable < itcMac/*skip TTP*/; FreePdrf(&drfFetch),++idrTable )
; native note: run the loop in the other direction...
;PAUSE
mov si,[dylOld]
mov cx,[itcMac]
LLoop4Body:
;PAUSE
dec cx ; decrement idrTable
push cx ; save idrTable
; {
; pdrTable = PdrFetch(hpldrTable, idrTable, &drfFetch);
; cx = idrTable, si = dylOld
call LN_PdrFetch
; if (pdrTable->fDirty)
; now ax = dylOld, si = pdrTable, di = &drfFetch
push ax ; save dylOld for easy restore
test [si.fDirtyDr],maskFDirtyDr
jz UT840
; {
; /* If the DR is dirty, there is little chance of a frame line
; /* problem. The test below catches the possible cases.
; /**/
; if (pdrTable->yl + pdrTable->dyl >= dylOld && dylOld < dylNew)
; ax = dylOld, si = pdrTable, di = &drfFetch
;PAUSE
mov cx,[si.ylDr]
add cx,[si.dylDr]
cmp cx,ax
jl UT830
cmp ax,[dylNew]
jge UT830
; dylBottomFrameDirty = 1;
mov [dylBottomFrameDirty],1
; continue;
UT830:
;PAUSE
jmp short LLoop4Cont
; }
UT840:
; dylDr = pdrTable->yl + pdrTable->dyl;
; GetPlc ( pdrTable->hplcedl, dlLast = IMacPlc(pdrTable->hplcedl) - 1, &edlLast );
call LN_IMacPlcTable
dec ax
mov [dlLast],ax
xchg ax,cx
call LN_GetPlcTable
mov ax,[si.ylDr]
add ax,[si.dylDr]
mov cx,ax
pop ax ; restore dylOld
push ax ; re-save it
; /* does the last dl of the cell lack a needed bottom frame ? */
; if ( (dylDr == dylNew && dylNew < dylOld && fDrawBottom)
; ax = dylOld, cx = dylDr, si = pdrTable, di = &drfFetch
cmp cx,[dylNew]
jne UT850
cmp cx,ax ; native note by first condition, cx = dylDr = dylNew
jge UT850
cmp [fDrawBottom],0
jnz UT860
; /* OR does the last dl have an unneeded bottom frame? */
; || (dylDr == dylOld && dylOld < dylNew ) )
UT850:
; ax = dylOld, cx = dylDr, si = pdrTable, di = &drfFetch
;PAUSE
cmp ax,cx
jne UT870
cmp ax,[dylNew]
jge UT870
;PAUSE
UT860:
; {
; /* verbose for native compiler bug */
; fLastDlDirty = fTrue;
;PAUSE
mov [fLastDlDirty],fTrue
; edlLast.fDirty = fTrue;
or [edlLast.fDirtyEdl],maskFDirtyEdl
; pdrTable->fDirty = fTrue;
or [si.fDirtyDr],maskFDirtyDr
; PutPlcLast ( pdrTable->hplcedl, dlLast, &edlLast );
ifdef DEBUG
push [si.hplcedlDr]
push [dlLast]
lea ax,[edlLast]
push ax
cCall PutPlcLastDebugProc,<>
else ; !DEBUG
call LN_PutPlcLast
endif ; DEBUG
UT870:
; }
LLoop4Cont:
; now di = &drfFetch; dylOld and idrTable stored on stack
call LN_FreePdrf
pop si ; recover dylOld
pop cx ; recover idrTable
jcxz UT900
jmp short LLoop4Body
UT900:
; } /* end of for pdrTable loop */
; /* If we are doing the second update scan only to redraw the last
; /* rows with the bottom border, then have DisplayFli use an
; /* off-screen buffer to avoid flickering.
; /**/
; if ( fLastDlDirty && !fSomeDrDirty )
; {
; Mac(vcbBmb = vcbBmbPerm);
; fSomeDrDirty = fTrue;
; }
; native note: because we don't have to play games with an offscreen
; buffer, the net effect of the above for !MAC is
; fSomeDrDirty |= fLastDlDirty;
mov al,[fLastDlDirty]
or [fSomeDrDirty],al
; }
LSecondPass:
; /* If some DRs were not fully updated, finish updating them */
; if (fSomeDrDirty)
cmp [fSomeDrDirty],0
jnz UT905
;PAUSE
jmp LFinishTable
; {
; Break3(); some dopey mac thing
; /* If there's a potentially useful dl that's about to get
; /* blitzed, move it down some.
; /**/
; if (dylNew > dylOld && dlOld < dlMac && dlNew < dlOld && fScrollOK)
UT905:
mov ax,[dylNew]
cmp ax,[dylOld]
jle LSetRcwInval
;PAUSE
mov ax,[dlOld]
cmp ax,[dlMac]
jge LSetRcwInval
cmp ax,[dlNew]
jle LSetRcwInval
cmp [fScrollOK],0
jz LSetRcwInval
; {
; GetPlc ( hplcedl, dlOld, &edlNext );
; ax = dlOld
xchg ax,cx
lea ax,[edlNext]
call LN_GetPlcParent
; if (edlNext.ypTop < *pypTop + dylNew)
mov ax,[ypTop]
add ax,[dylNew]
cmp ax,[edlNext.ypTopEdl]
jle UT910
; ScrollDrDown ( ww, hpldr, idr, hplcedl, dlOld,
; dlOld, edlNext.ypTop, *pypTop + dylNew,
; ypFirstShow, ypLimWw, ypLimDr);
; ax = *pypTop + dylNew
push [ww]
push [hpldr]
push [idr]
push [hplcedl]
push [dlOld]
push [dlOld]
push [edlNext.ypTopEdl]
push ax
push [ypFirstShow]
push [ypLimWw]
push [ypLimDr]
cCall ScrollDrDown,<>
UT910:
; dlMac = IMacPlc ( hplcedl );
mov ax,[hplcedl]
call LN_IMacPlc
mov [dlMac],ax
; }
;
; rcwTableInval.ywTop += *pypTop + min(dylNew,dylOld) - dylBottomFrameDirty;
LSetRcwInval:
mov ax,[dylNew]
cmp ax,[dylOld]
jle UT920
mov ax,[dylOld]
UT920:
add ax,[ypTop]
sub ax,[dylBottomFrameDirty];
add [rcwTableInval.ywTopRc],ax
; rcwTableInval.ywBottom += *pypTop + max(dylNew,dylOld);
mov ax,[dylNew]
cmp ax,[dylOld]
jge UT930
mov ax,[dylOld]
UT930:
add ax,[ypTop]
add [rcwTableInval.ywBottomRc],ax
;
; DrawEndmark ( ww, hpldr, idr, *pypTop + edl.dyp, *pypTop + dylNew, emkBlank );
push [ww]
push [hpldr]
push [idr]
mov ax,[ypTop]
add ax,[edl.dypEdl]
push ax
mov ax,[ypTop]
add ax,[dylNew]
push ax
errnz <emkBlank>
xor ax,ax
push ax
cCall DrawEndMark,<>
;
; for ( idrTable = 0; idrTable < idrMacTable; ++idrTable )
; native note: try the backwards loop and see how it looks...
;PAUSE
mov cx,[idrMacTable]
LLoop5Body:
dec cx
push cx ; save idrTable
; {
; pdrTable = PdrFetch(hpldrTable,idrTable,&drfFetch);
; cx = idrTable
call LN_PdrFetch
; if ( pdrTable->fDirty )
test [si.fDirtyDr],maskFDirtyDr
jz LLoop5Cont
; {
; /* Since we have already filled in the PLCEDL for the DR,
; /* the chance of this failing seems pretty small. It won't
; /* hurt to check, however.
; /**/
; if (fIncr || !FUpdTableDr(ww,hpldrTable,idrTable))
; if (!FUpdateDr(ww,hpldrTable,idrTable,rcwTableInval,fFalse,udmodTable,cpNil))
; goto LFreeAndAbort;
; NOTE: the local routine also does the assert with DypHeightTc
mov al,[fIncr] ; flag to helper routine
pop cx ; recover idrTable
push cx ; re-save idrTable
lea bx,[rcwTableInval]
;PAUSE
call LN_FUpdateOneDr
jnz UT950
;PAUSE
pop cx
jmp LFreeAndAbortUT
UT950:
; if (fOverflowDrs && pdrTable->dyl > dylLimDr)
;PAUSE
cmp [fOverflowDrs],0
jz UT960
;PAUSE
mov ax,[dylLimDr]
cmp ax,[si.dylDr]
jge UT960
; pdrTable->dyl = dylLimDr;
mov [si.dylDr],ax
UT960:
; }
LLoop5Cont:
; Win(fRMark |= pdrTable->fRMark;)
;PAUSE
test [si.fRMarkDr],maskFRMarkDr
je UT965
mov [fRMark],fTrue
UT965:
; FreePdrf(&drfFetch);
; di = &drfFetch
call LN_FreePdrf
pop cx
jcxz UT970
jmp short LLoop5Body
; }
UT970: ; ick! Mac stuff
; if ( fLastRow )
; Mac(vcbBmb = cbBmbSav);
; } /* end of if fSomeDrDirty */
LFinishTable:
; /* Now, clear out bits in edl not already drawn and draw cell
; /* borders.
; /**/
; Assert(edl.dyp == dylNew);
;PAUSE
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[edl.dypEdl]
cmp ax,[dylNew]
je UT980
mov ax,midDisptbn2
mov bx,2324
cCall AssertProcForNative,<ax,bx>
UT980:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; FrameTable(ww,doc,caTapCur.cpFirst,hpldrTable, dylNew, fFirstRow, fLastRow );
push [ww]
push [doc]
push [caTapCur.HI_cpFirstCa]
push [caTapCur.LO_cpFirstCa]
push [hpldrTable]
lea ax,[edl]
push ax
xor ax,ax
mov al,[fFirstRow]
push ax
mov al,[fLastRow]
push ax
cCall FrameTable,<>
; /* update edl and pldrT to reflect what we have done */
; edl.fDirty = edl.fTableDirty = fFalse;
errnz <fDirtyEdl-fTableDirtyEdl>
and [edl.fDirtyEdl],not (maskFDirtyEdl or maskFTableDirtyEdl)
; edl.dcp = cp - CpPlc(hplcedl,dlNew);
push [hplcedl]
push [dlNew]
cCall CpPlc,<>
mov bx,[OFF_cp]
mov cx,[SEG_cp]
sub bx,ax
sbb cx,dx
; now, <bx,cx> = cp - CpPlc()
mov [edl.LO_dcpEdl],bx
mov [edl.HI_dcpEdl],cx
;
; /* because of the way borders and frame lines are drawn,
; /* a table row always depends on the next character
; /**/
; edl.dcpDepend = 1;
mov [edl.dcpDependEdl],1
;
; PutPlc ( hplcedl, dlNew, &edl );
call LN_PutPlc
ifdef WIN
ifndef BOGUS
; if (fRMark)
; DrawTableRevBar(ww, idr, dlNew);
;PAUSE
cmp [fRMark],0
jz UT990
push [ww]
push [idr]
push [dlNew]
cCall DrawTableRevBar,<>
UT990:
else ; BOGUS
; if (vfRevBar)
mov cx,[vfRevBar]
jcxz UT1190
; {
; int xwRevBar;
;
; if (!(pwwd = PwwdWw(ww))->fPageView)
;#define dxwSelBarSci vsci.dxwSelBar
;PAUSE
push di ; save &drfFetch
mov di,[vsci.dxwSelBarSci] ; store value is safe register
sar di,1 ; for use later
call LN_PwwdWw
xchg ax,si
test [si.fPageViewWwd],maskfPageViewWwd
jnz UT1100
; xwRevBar = pwwd->xwSelBar + dxwSelBarSci / 2;
; si = pwwd, di = [dxwSelBarSci]/2
mov ax,[si.xwSelBarWwd]
jmp short UT1180
; else
; {
; switch (PdodMother(doc)->dop.irmBar)
UT1100:
; si = pwwd, di = [dxwSelBarSci]/2
push [doc]
cCall N_PdodMother,<>
xchg ax,bx
mov al,[bx.dopDod.irmBarDop]
errnz <irmBarLeft-1>
dec al
je UT1130
errnz <irmBarRight-irmBarLeft-1>
dec al
je UT1140
; #ifdef DEBUG
; default:
; Assert(fFalse);
; /* fall through */
; #endif
ifdef DEBUG
push ax
push bx
push cx
push dx
dec al
je UT1110
mov ax,midDisptbn2
mov bx,2423
cCall AssertProcForNative,<ax,bx>
UT1110:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; {
; case irmBarOutside:
; if (vfmtss.pgn & 1)
; goto LRight;
test [vfmtss.pgnFmtss],1
jnz UT1140
; /* fall through */
; case irmBarLeft:
UT1130:
; xwRevBar = XwFromXp( hpldrTable, 0, edl.xpLeft )
; - (dxwSelBarSci / 2);
; si = pwwd, di = [dxwSelBarSci]/2
neg di ; so that it will get subtracted
db 0A8h ;turns next "stc" into "test al,immediate"
;also clears the carry flag
; break;
; case irmBarRight:
; LRight:
; xwRevBar = XwFromXp( hpldrTable, 0, edl.xpLeft + edl.dxp)
; + (dxwSelBarSci / 2);
UT1140:
stc
mov ax,[edl.xpLeftEdl]
jnc UT1150
add ax,[edl.dxpEdl]
UT1150:
push [hpldrTable]
xor cx,cx
push cx
push ax
cCall XwFromXp,<>
; break;
; }
; }
; DrawRevBar( PwwdWw(ww)->hdc, xwRevBar,
; YwFromYl(hpldrTable,0), dylNew);
UT1180:
; ax + di = xwRevBar, si = pwwd
add ax,di
; si = pwwd, ax = xwRevBar
push [si.hdcWwd] ; some arguments
push ax ; for DrawRevBar
push [hpldrTable]
xor ax,ax
push ax
cCall YwFromYl,<>
push ax
push [dylNew]
cCall DrawRevBar,<>
pop di ; restore &drfFetch
UT1190:
; }
endif ; BOGUS
; /* draw the style name area and border for a table row */
; if (PwwdWw(ww)->xwSelBar)
call LN_PwwdWw
xchg ax,si
mov cx,[si.xwSelBarWwd]
jcxz UT1200
; {
; DrawStyNameFromWwDl(ww, hpldr, idr, dlNew);
;PAUSE
push [ww]
push [hpldr]
push [idr]
push [dlNew]
cCall DrawStyNameFromWwDl,<>
; }
UT1200:
endif ; WIN
; /* advance the caller's cp and ypTop */
; *pcp = cp;
mov bx,[pcp]
mov ax,[OFF_cp]
mov [bx],ax
mov ax,[SEG_cp]
mov [bx+2],ax
; *pypTop += dylNew;
; Assert(*pypTop == ypTop);
ifdef DEBUG
push ax
push bx
push cx
push dx
mov bx,[pypTop]
mov ax,[bx]
cmp ax,[ypTop]
jz UT1210
mov ax,midDisptbn2
mov bx,2213
cCall AssertProcForNative,<ax,bx>
UT1210:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
mov bx,[pypTop]
mov ax,[dylNew]
add [bx],ax
; return fTrue; /* it worked! */
mov ax,fTrue
; }
LExitUT:
cEnd
; NATIVE NOTE: these are short cut routines used by FUpdateTable to
; reduce size of common calling seqeuences.
; upon entry: ax = dya
; upon exit: ax = dyp, + the usual registers trashed
; #define DypFromDya(dya) NMultDiv((dya), vfti.dypInch, czaInch)
LN_DypFromDya:
;PAUSE
push ax
push [vfti.dypInchFti]
mov ax,czaInch
push ax
cCall NMultDiv,<>
ret
; upon entry: di = pdrf
; upon exit: the usual things munged
LN_FreePdrf:
push di
ifdef DEBUG
cCall S_FreePdrf,<>
else
cCall N_FreePdrf,<>
endif
ret
; LN_GetPlcTable = GetPlc(((DR*)si)->hplcedl, cx, &edlLast);
; LN_GetPlcParent = GetPlc(hplcedl, cx, ax);
LN_GetPlcTable:
lea ax,[edlLast]
push [si.hplcedlDr]
jmp short UT2000
LN_GetPlcParent:
push [hplcedl]
UT2000:
push cx
push ax
cCall GetPlc,<>
ret
; upon entry: si = pdrTable
; upon exit: ax = IMacPlc(pdrTable->hplcedl);
; plus the usual things munged
LN_IMacPlcTable:
mov ax,[si.hplcedlDr]
; upon entry: ax = hplcedl
; upon exit: ax = IMacPlc(pdrTable->hplcedl);
; plus the usual things munged
LN_IMacPlc:
push ax
cCall IMacPlc,<>
ret
; call this one for PdrFetch(hpldrTable, idrTable, &drfFetch);
; upon entry: di = &drfFetch
; upon exit: ax = old si value, si = pdr NOTE RETURN VALUE IN SI!!!!
; plus the usual things munged
LN_PdrFetchTable:
mov cx,[idrTable]
; call this one for PdrFetch(hpldrTable, ax, &drfFetch);
; upon entry: cx = idr, di = &drfFetch
; upon exit: ax = old si value, si = pdr NOTE RETURN VALUE IN SI!!!!
; plus the usual things munged
LN_PdrFetch:
push [hpldrTable]
push cx
push di
ifdef DEBUG
cCall S_PdrFetch,<>
else
cCall N_PdrFetch,<>
endif
xchg ax,si
ret
; does PutPlc(hplcedl, dlNew, &edl)
LN_PutPlc:
push [hplcedl]
push [dlNew]
lea ax,[edl]
push ax
cCall PutPlc,<>
ret
ifndef DEBUG
LN_PutPlcLast:
cCall PutPlcLastProc,<>
ret
endif ; not DEBUG
LN_PwwdWw:
push [ww]
cCall N_PwwdWw,<>
ret
LN_SetFCantGrow:
; pdrTable->fCantGrow = pdrTable->dyl >= dylLimDr && (fPageView || fAbsHgtRow);
; si = pdrTable
and [si.fCantGrowDr],not maskFCantGrowDr ; assume fFalse
mov ax,[si.dylDr]
cmp ax,[dylLimDr]
jl UT2050
;PAUSE
mov al,[fPageView]
or al,[fAbsHgtRow]
jz UT2050
;PAUSE
or [si.fCantGrowDr],maskFCantGrowDr ; assumption failed, fix it
UT2050:
ret
LN_FUpdateOneDr:
; this is equivalent to:
; if ((al != 0) || !FUpdTableDr(ww, hpldrTable, cx=idrTable))
; if (!FUpdateDr(ww,hpldrTable,cx,*(RC*)bx,fFalse,udmodTable,cpNil))
; return fFalse;
; return fTrue;
;
; upon entry: ax = fTrue iff FUpdTableDr should be SKIPPED
; upon exit: ax = fTrue iff things worked, AND condition codes set accordingly
;
; if ((al != 0) || !FUpdTableDr(ww,hpldrTable,idrTable))
or al,al
jnz UT2100
push bx ; save prc
push cx ; save idrTable
push [ww]
push [hpldrTable]
push cx
ifdef DEBUG
cCall S_FUpdTableDr,<>
else
call LN_FUpdTableDr
endif
pop cx ; recover idrTable
pop bx ; recover prcwInval
or ax,ax
jnz UT2110
; if (!FUpdateDr(ww,hpldrTable,idrTable,rcwTableInval,fFalse,udmodTable,cpNil))
UT2100:
;PAUSE
push [ww]
push [hpldrTable]
push cx
errnz <cbRcMin-8>
push [bx+6]
push [bx+4]
push [bx+2]
push [bx]
xor ax,ax
push ax
errnz <udmodTable-2>
inc ax
inc ax
push ax
errnz <LO_CpNil+1>
errnz <HI_CpNil+1>
mov ax,LO_CpNil
push ax
push ax
ifdef DEBUG
cCall S_FUpdateDr,<>
else
cCall N_FUpdateDr,<>
endif ; DEBUG
UT2110:
ifdef ENABLE
; /* FUTURE: this is bogus for windows, since DypHeightTc returns the height
; /* in printer units, not screen units. Further, it is questionable to call
; /* DypHeightTc without setting up vlm and vflm.
; /*
; /* Enable this next line to check that FUpdate table yields the same height
; /* as does DypHeightTc using the FormatLine and PHE's, slows down redrawing.
; /**/
ifdef DEBUG
; CacheTc(ww, doc, pdrTable->cpFirst, fFirstRow, fLastRow);
;PAUSE
push ax
push bx
push cx
push dx
push [ww]
push [doc]
push [si.HI_cpFirstDr]
push [si.LO_cpFirstDr]
xor ax,ax
mov al,[fFirstRow]
push ax
mov al,[fLastRow]
push ax
cCall CacheTc,<>
; Assert ( DypHeightTc(ww,doc,pdrTable->cpFirst) == pdrTable->dyl );
push [ww]
push [doc]
push [si.HI_cpFirstDr]
push [si.LO_cpFirstDr]
cCall DypHeightTc,<>
cmp ax,[si.dylDr]
je UT2120
mov ax,midDisptbn2
mov bx,2391
cCall AssertProcForNative,<ax,bx>
UT2120:
pop dx
pop cx
pop bx
pop ax
endif
endif
or ax,ax
ret
;Did this DEBUG stuff with a call so as not to mess up short jumps.
; Assert(pdrT->doc == pdrTable->doc);
ifdef DEBUG
UT2130:
push ax
push bx
push cx
push dx
mov cx,[si.docDr]
cmp cx,[bx.docDr]
jz UT2140
mov ax,midDisptbn2
mov bx,2869
cCall AssertProcForNative,<ax,bx>
UT2140:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
; /* F U P D A T E T A B L E D R
; /*
; /* Description: Attempt to handle the most common table dr update
; /* in record time by simply calling FormatLine and DisplayFli.
; /* If simple checks show we have updated the entire DR, return
; /* fTrue, else record the EDL we wrote and return fFalse so that
; /* FUpdateDr() gets called to finish the job.
; /**/
; %%Function:FUpdTableDr %%Owner:tomsax
; NATIVE FUpdTableDr(ww, hpldr, idr)
; int ww;
; struct PLDR **hpldr;
; int idr;
; {
; int dlMac;
; BOOL fSuccess, fOverflow; native note: fOverflow not necessary
; struct PLC **hplcedl; native note: won't be using this one
; struct DR *pdr; native note: register variable
; struct WWD *pwwd;
; struct EDL edl;
; struct DRF drf;
;
; register usage:
; si = pdr
;
ifdef DEBUG
cProc N_FUpdTableDr,<PUBLIC,FAR>,<si,di>
else
cProc LN_FUpdTableDr,<PUBLIC,NEAR>,<si,di>
endif
ParmW ww
ParmW hpldr
ParmW idr
LocalW dlMac
LocalW rgf ; first byte is fSuccess, second is fOverflow
LocalW pwwd
LocalV edl,cbEdlMin
LocalV drf,cbDrfMin
cBegin
; pdr = PdrFetch(hpldr, idr, &drf);
;PAUSE
push [hpldr]
push [idr]
lea bx,[drf]
push bx
ifdef DEBUG
cCall S_PdrFetch,<>
else
cCall N_PdrFetch,<>
endif
xchg ax,si
; fSuccess = fFalse;
; native note: di is used as a zero register
xor di,di
; native note: fOverflow also initialized to zero
errnz <fFalse>
mov [rgf],di
; hplcedl = pdr->hplcedl; ; native note, forget this...
; Assert(hplcedl != hNil && (*hplcedl)->iMax > 1);
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [si.hplcedlDr],hNil
jz UTD010
mov bx,[si.hplcedlDr]
mov bx,[bx]
cmp [bx.iMaxPlc],1
jg UTD020
UTD010:
mov ax,midDisptbn2
mov bx,2809
cCall AssertProcForNative,<ax,bx>
UTD020:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; if ((dlMac = IMacPlc(hplcedl)) > 0)
; di = 0
mov bx,[si.hplcedlDr]
mov bx,[bx]
cmp [bx.iMacPlcSTR],di
jle UTD040
; {
; GetPlc(hplcedl, 0, &edl);
;PAUSE
; di = 0
push [si.hplcedlDr]
push di ; 0
lea ax,[edl]
push ax
cCall GetPlc,<>
; Assert(edl.hpldr == hNil); /* no need to FreeEdl */
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [edl.hpldrEdl],hNil
je UTD030
mov ax,midDisptbn2
mov bx,2839
cCall AssertProcForNative,<ax,bx>
UTD030:
pop dx
pop cx
pop bx
pop ax
endif ; DEBUG
; if (!edl.fDirty)
; goto LRet;
test [edl.fDirtyEdl],maskFDirtyEdl
jnz UTD040
;PAUSE
UTDTemp:
jmp LExitUTD
; }
UTD040:
; FormatLineDr(ww, pdr->cpFirst, pdr);
; di = 0
push [ww]
push [si.HI_cpFirstDr]
push [si.LO_cpFirstDr]
push si
ifdef DEBUG
cCall S_FormatDrLine,<>
else
cCall N_FormatDrLine,<>
endif
; /* cache can be blown by FormatLine */
; CpFirstTap(pdr->doc, pdr->cpFirst);
; di = 0
push [si.docDr]
push [si.HI_cpFirstDr]
push [si.LO_cpFirstDr]
cCall CpFirstTap,<>
; pwwd = PwwdWw(ww); /* verbose for native compiler bug */
; fOverflow = vfli.dypLine > pdr->dyl;
; native note: not a problem here! wait till we need it to compute it
; same for fOverflow
; if (fSuccess = vfli.fSplatBreak
; fSuccess set to false above...
; di = 0
test [vfli.fSplatBreakFli],maskFSplatBreakFli
jz UTDTemp
; && vfli.chBreak == chTable
;PAUSE
cmp [vfli.chBreakFli],chTable
jne UTDTemp
; && (!fOverflow
;PAUSE
mov cx,[vfli.dypLineFli]
cmp cx,[si.dylDr]
jle UTD060
errnz <maskFDirtyDr-1>
inc bptr [rgf+1] ; sleazy bit trick, fill in the bit we want
; || idr == vtapFetch.itcMac
;PAUSE
mov ax,[idr]
cmp ax,[vtapFetch.itcMacTap]
je UTD060
; || YwFromYp(hpldr,idr,pdr->dyl) >= pwwd->rcwDisp.ywBottom))
;PAUSE
; di = 0
push [ww]
cCall N_PwwdWw,<>
push ax ; we'll want this in a second here...
push [hpldr]
push [idr]
push [si.dylDr]
cCall YwFromYp,<>
pop bx ; recover pwwd from above
cmp ax,[bx.rcwDispWwd.ywBottomRc]
jl LExitUTD
;PAUSE
UTD060:
errnz <fTrue-1>
inc bptr [rgf] ; fSuccess = fTrue ** we win!!!
; {
; DisplayFli(ww, hpldr, idr, 0, vfli.dypLine);
; di = 0
push [ww]
push [hpldr]
push [idr]
push di
push [vfli.dypLineFli]
ifdef DEBUG
cCall S_DisplayFli,<>
else
cCall N_DisplayFli,<>
endif
; pdr->dyl = vfli.dypLine;
mov ax,[vfli.dypLineFli]
mov [si.dylDr],ax
; pdr->fDirty = fOverflow;
and [si.fDirtyDr],not maskFDirtyDr
mov al,bptr [rgf+1]
or [si.fDirtyDr],al
; pdr->fRMark = vfli.fRMark;
;PAUSE
and [si.fRMarkDr],not maskFRMarkDr
test [vfli.fRMarkFli],maskFRMarkFli
je UTD070
or [si.fRMarkDr],maskFRMarkDr
UTD070:
; DlkFromVfli(hplcedl, 0);
; PutCpPlc(hplcedl, 1, vfli.cpMac);
; PutIMacPlc(hplcedl, 1);
;PAUSE
; di = 0
mov bx,[si.hplcedlDr] ; arguments
push bx
inc di ; == 1
push di ; PutIMacPlc
push bx ; arguments for
push di ; PutCpPlc
push [vfli.HI_cpMacFli]
push [vfli.LO_cpMacFli]
push bx
dec di
push di
cCall DlkFromVfli,<>
cCall PutCpPlc,<>
cCall PutIMacPlc,<>
; }
; LRet:
LExitUTD:
; FreePdrf(&drf);
lea ax,[drf]
push ax
ifdef DEBUG
cCall S_FreePdrf,<>
else
cCall N_FreePdrf,<>
endif
; return fSuccess;
mov al,bptr [rgf]
cbw
; }
cEnd
; /* F R A M E E A S Y T A B L E
; /* Description: Under certain (common) circumstances, it is possible
; /* to draw the table borders without going through all of the hoops
; /* to correctly join borders at corners. This routines handles those
; /* cases.
; /*
; /* Also uses info in caTap, vtapFetch and vtcc (itc = 0 cached).
; /**/
; int ww;
; struct PLDR **hpldr;
; struct DR *pdrParent;
; int dyl;
; BOOL fFrameLines, fDrFrameLines, fFirstRow, fLastRow;
; HANDNATIVE C_FrameEasyTable(ww, doc, cp, hpldr, prclDrawn, pdrParent, dyl, fFrameLines, fDrFrameLines, fFirstRow, fLastRow)
; %%Function:FrameEasyTable %%Owner:tomsax
cProc N_FrameEasyTable,<PUBLIC,FAR>,<si,di>
ParmW <ww, doc>
ParmD cp
ParmW <hpldr, prclDrawn, pdrParent, dyl>
ParmW <fFrameLines, fDrFrameLines, fFirstRow, fLastRow>
; {
; int dxwBrcLeft, dxwBrcRight, dxwBrcInside, dywBrcTop, dywBrcBottom;
LocalW <dxwBrcLeft,dxwBrcRight,dxwBrcInside,dywBrcTop,dywBrcBottom>
; int dxLToW, dyLToW;
LocalW <dxLToW, dyLToW>
; int xwLeft, xwRight, dylDrRow, dylDrRowM1, ywTop;
; native note: dylDrRowM1 used only in Mac version
LocalW <xwLeft, xwRight, dylDrRow, ywTop>
; int itc, itcNext, itcMac;
LocalW <itc, itcNext, itcMac>
; int brcCur;
LocalW brcCur
; BOOL fRestorePen, fBottomFrameLine;
LocalW <fRestorePen, fBottomFrameLine>
; struct DR *pdr; ; native note: registerized
; struct RC rclErase, rcw;
LocalV rclErase,cbRcMin
LocalV rcw,cbRcMin
; struct TCX tcx;
LocalV tcx,cbTcxMin
; struct DRF drf;
LocalV drf,cbDrfMin
; #ifdef WIN
; HDC hdc = PwwdWw(ww)->hdc;
LocalW hdc
; struct RC rcDraw, rcwClip;
LocalV rcDraw,cbRcMin
LocalV rcwClip,cbRcMin
; int xwT, ywT; ; native note: registerized
; struct WWD *pwwd = PwwdWw(ww); ; native note: registerized
cBegin
;PAUSE
; native note: do auto initializations...
call LN_PwwdWwFET
mov ax,[bx.hdcWwd]
mov [hdc],ax
;
; if (pwwd->fPageView)
; bx = pwwd
lea di,[rcwClip]
test [bx.fPageViewWwd],maskFPageViewWwd
jz FET010
; RcwPgvTableClip(ww, (*hpldr)->hpldrBack, (*hpldr)->idrBack, &rcwClip);
;PAUSE
; di = &rcwClip
push [ww]
mov bx,[hpldr]
mov bx,[bx]
push [bx.hpldrBackPldr]
push [bx.idrBackPldr]
push di
cCall RcwPgvTableClip,<>
jmp short FET020
; else
; rcwClip = pwwd->rcwDisp;
FET010:
; bx = pwwd, di = &rcwClip
lea si,[bx.rcwDispWwd]
push ds
pop es
errnz <cbRcMin-8>
movsw
movsw
movsw
movsw
FET020:
; #endif
;
; Assert(FInCa(doc, cp, &vtcc.ca));
; Assert(vtcc.itc == 0);
; Assert(dyl > 0);
;PAUSE
ifdef DEBUG
push ax
push bx
push cx
push dx
push [doc]
push [SEG_cp]
push [OFF_cp]
mov ax,dataoffset [vtcc.caTcc]
push ax
cCall FInCa,<>
or ax,ax
mov bx,3088 ; assert line number
jz FET030
cmp [vtcc.itcTcc],0
mov bx,3092 ; assert line number
jnz FET030
mov ax,[dyl]
or ax,ax
jg FET035
mov bx,3097 ; assert line number
FET030:
mov ax,midDisptbn2
cCall AssertProcForNative,<ax,bx>
FET035:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; native note: we clear fRestorePen here so we don't have it clear
; it every time through the loops.
xor ax,ax
mov [fRestorePen],ax
; dxLToW = XwFromXl(hpldr, 0);
; dyLToW = YwFromYl(hpldr, 0);
; ax = 0
push [hpldr] ; arguments
push ax ; for YwFromYl
push [hpldr] ; arguments
push ax ; for XwFromXl
cCall XwFromXl,<>
mov [dxLToW],ax
cCall YwFromYl,<>
mov [dyLToW],ax
;
; LN_DxFromIbrc Does:
; DxFromBrc(*(int*)(si + rgbrcEasyTcc + bx), fFrameLines)
lea si,[vtcc]
; dxwBrcLeft = DxFromBrc(vtcc.rgbrcEasy[ibrcLeft],fTrue/*fFrameLines*/);
mov bx,ibrcLeft SHL 1
call LN_DxFromIbrc
mov [dxwBrcLeft],ax
; dxwBrcRight = DxFromBrc(vtcc.rgbrcEasy[ibrcRight],fTrue/*fFrameLines*/);
mov bx,ibrcRight SHL 1
call LN_DxFromIbrc
mov [dxwBrcRight],ax
; dxwBrcInside = DxFromBrc(vtcc.rgbrcEasy[ibrcInside],fTrue/*fFrameLines*/);
mov bx,ibrcInside SHL 1
call LN_DxFromIbrc
mov [dxwBrcInside],ax
; dywBrcTop = vtcc.dylAbove;
; dywBrcBottom = vtcc.dylBelow;
; si = &vtcc
mov ax,[si.dylAboveTcc]
mov [dywBrcTop],ax
mov cx,[si.dylBelowTcc]
mov [dywBrcBottom],cx
; leave si = &vtcc, ax = dywBrcTop, cx = dywBrcBottom
;
; Assert(dywBrcTop == DyFromBrc(vtcc.rgbrcEasy[ibrcTop],fFalse/*fFrameLines*/));
; Assert(dywBrcBottom == (fLastRow ? DyFromBrc(vtcc.rgbrcEasy[ibrcBottom],fFalse/*fFrameLines*/) : 0));
; #define DyFromBrc(brc, fFrameLines) DxyFromBrc(brc, fFrameLines, fFalse)
; #define DxyFromBrc(brc, fFrameLines, fWidth) \
; WidthHeightFromBrc(brc, fFrameLines | (fWidth << 1))
ifdef DEBUG
; si = &vtcc, ax = dywBrcTop, cx = dywBrcBottom
push ax
push bx
push cx
push dx
mov bx,ibrcTop SHL 1
push [bx.si.rgbrcEasyTcc]
xor ax,ax
push ax
ifdef DEBUG
cCall S_WidthHeightFromBrc,<>
else
cCall N_WidthHeightFromBrc,<>
endif
cmp ax,[dywBrcTop]
mov bx,3158 ; assert line number
jne FET040
mov cx,[fLastRow]
jcxz FET050
;PAUSE
mov bx,ibrcBottom SHL 1
push [bx.si.rgbrcEasyTcc]
xor ax,ax
push ax
ifdef DEBUG
cCall S_WidthHeightFromBrc,<>
else
cCall N_WidthHeightFromBrc,<>
endif
cmp ax,[dywBrcBottom]
mov bx,3171 ; assert line number
je FET050
FET040:
mov ax,midDisptbn2
cCall AssertProcForNative,<ax,bx>
FET050:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
;
; ywTop = dyLToW + dywBrcTop;
; si = &vtcc, ax = dywBrcTop, cx = dywBrcBottom
mov dx,ax
add dx,[dyLToW]
mov [ywTop],dx
; dylDrRow = dyl - dywBrcTop - dywBrcBottom;
add cx,ax
mov ax,[dyl]
sub ax,cx
mov [dylDrRow],ax
; dylDrRowM1 = dylDrRow - 1; naitve note: needed only in Mac version
; itcMac = vtapFetch.itcMac;
mov ax,[vtapFetch.itcMacTap]
mov [itcMac],ax
; /* erase bits to the left of the PLDR */
lea di,[rclErase]
push ds
pop es
; rclErase.xlLeft = - pdrParent->dxpOutLeft;
errnz <xlLeftRc>
mov bx,[pdrParent]
mov ax,[bx.dxpOutLeftDr]
neg ax
stosw
; rclErase.ylTop = 0;
errnz <ylTopRc-2-xlLeftRc>
xor ax,ax
stosw
; rclErase.xlRight = vtcc.xpDrLeft - vtcc.dxpOutLeft - dxwBrcLeft;
errnz <xlRightRc-2-ylTopRc>
mov ax,[si.xpDrLeftTcc]
sub ax,[si.dxpOutLeftTcc]
sub ax,[dxwBrcLeft]
stosw
xchg ax,cx ; stash for later
; rclErase.ylBottom = dyl;
errnz <ylBottomRc-2-xlRightRc>
mov ax,[dyl]
stosw
; xwLeft = rclErase.xlRight + dxLToW; /* will be handy later */
; si = &vtcc, cx = rclErase.xlRight
add cx,[dxLToW]
mov [xwLeft],cx
; if (!FEmptyRc(&rclErase))
; ClearRclInParentDr(ww,hpldr,rclErase,&rcwClip);
call LN_ClearRclIfNotMT
; PenNormal();
; #define PenNormal() /* some bogus Mac thing... */
; /* the left border */
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcLeft], fFalse/*fHoriz*/, fFrameLines);
;PAUSE
mov bx,ibrcLeft SHL 1
call LN_SetPenBrcV
; #ifdef MAC
; MoveTo(xwLeft, ywTop);
; Line(0, dylDrRowM1);
; #else /* WIN */
; PrcSet(&rcDraw, xwLeft, ywTop,
; xwLeft + dxpPenBrc, ywTop + dylDrRow);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
mov ax,[xwLeft]
push ax
mov cx,[ywTop]
push cx
add ax,[dxpPenBrc]
push ax
add cx,[dylDrRow]
push cx
call LN_SetSectAndFillRect
; #endif
; /* the inside borders */
; itc = 0;
; itcNext = ItcGetTcxCache ( ww, doc, cp, &vtapFetch, itc, &tcx);
xor cx,cx
call LN_ItcGetTcxCache
; /* pre-compute loop invariant */
; fBottomFrameLine = fLastRow && fFrameLines && dywBrcBottom == 0;
mov cx,[fLastRow]
jcxz FET055
;PAUSE
mov cx,[fFrameLines]
jcxz FET055
; cx = 0
xor cx,cx
cmp [dywBrcBottom],cx
jnz FET055
errnz <fTrue-1>
;PAUSE
inc cx
FET055:
mov [fBottomFrameLine],cx
;
;
; if (itcNext >= itcMac)
mov cx,[itcNext]
cmp cx,[itcMac]
jl FET060
; {
; /* BEWARE the case of a single cell row, we have to hack things
; /* up a bit to avoid trying to draw a between border.
; /**/
; if (brcCur != brcNone)
;PAUSE
errnz <brcNone>
mov cx,[brcCur]
jcxz FET080
; SetPenForBrc(ww, brcCur = brcNone, fFalse/*fHoriz*/, fFrameLines);
call LN_SetPenBrcVNone
jmp short FET080
; }
; else if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[ibrcInside])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcInside], fFalse/*fHoriz*/, fFrameLines);
FET060:
;PAUSE
mov bx,ibrcInside SHL 1
call LN_ChkSetPenBrcV
FET080:
; for ( ; ; )
; {
LInsideLoop:
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [fRestorePen],0
je FET085
mov ax,midDisptbn2
mov bx,3414 ; assert line number
cCall AssertProcForNative,<ax,bx>
FET085:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
;PAUSE
; pdr = PdrFetchAndFree(hpldr, itc, &drf);
push [hpldr]
push [itc]
lea ax,[drf]
push ax
ifdef DEBUG
cCall S_PdrFetchAndFree,<>
else
cCall N_PdrFetchAndFree,<>
endif ; DEBUG
xchg ax,si
; if (pdr->dyl < dylDrRow)
; si = pdr
mov ax,[dylDrRow]
cmp ax,[si.dylDr]
jg FET087
jmp FET120
FET087:
; {
; DrclToRcw(hpldr, &pdr->drcl, &rcw);
;PAUSE
; si = pdr
lea di,[rcw]
push [hpldr]
errnz <drclDr>
push si
push di
cCall DrclToRcw,<>
; native note: these next four lines rearranged for efficiency...
; si = pdr, di = &rcw
push ds
pop es
; rcw.xwLeft -= pdr->dxpOutLeft;
errnz <xwLeftRc>
mov ax,[di]
sub ax,[si.dxpOutLeftDr]
stosw
; rcw.ywTop += pdr->dyl;
errnz <ywTopRc-2-xwLeftRc>
mov ax,[di]
add ax,[si.dylDr]
stosw
; rcw.xwRight += pdr->dxpOutRight;
errnz <xwRightRc-2-ywTopRc>
mov ax,[di]
add ax,[si.dxpOutRightDr]
stosw
; rcw.ywBottom += dylDrRow - pdr->dyl;
errnz <ywBottomRc-2-xwRightRc>
mov ax,[di]
add ax,[dylDrRow]
sub ax,[si.dylDr]
stosw
; #ifdef WIN
; SectRc(&rcw, &rcwClip, &rcw);
sub di,cbRcMin
push di
lea ax,[rcwClip]
push ax
push di
; #define SectRc(prc1,prc2,prcDest) FSectRc(prc1,prc2,prcDest)
cCall FSectRc,<>
; #endif
; if (fBottomFrameLine)
mov cx,[fBottomFrameLine]
jcxz FET110
; {
; --rcw.ywBottom;
; si = pdr, di = &rcw
dec [di.ywBottomRc]
; if (fRestorePen = brcCur != brcNone)
; native note: fRestorePen was cleared above,
; so we only have to clear it if we set it
mov cx,[brcCur]
jcxz FET090
;PAUSE
; SetPenForBrc(ww, brcCur = brcNone, fFalse/*fHoriz*/, fFrameLines);
call LN_SetPenBrcVNone
inc [fRestorePen]
FET090:
; #ifdef MAC
; MoveTo(rcw.xwLeft,rcw.ywBottom);
; LineTo(rcw.xwRight-1,rcw.ywBottom);
; #else /* WIN */
; FillRect(hdc, (LPRECT)PrcSet(&rcDraw,
; rcw.xwLeft, rcw.ywBottom,
; rcw.xwRight, rcw.ywBottom + dypPenBrc),
; hbrPenBrc);
; si = pdr, di = &rcw
push [rcw.xwLeftRc]
mov ax,[rcw.ywBottomRc]
push ax
push [rcw.xwRightRc]
add ax,[dypPenBrc]
push ax
call LN_SetAndFillRect
; #endif
; if (fRestorePen)
; si = pdr, di = &rcw
mov cx,[fRestorePen]
jcxz FET100
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcInside], fFalse/*fHoriz*/, fFrameLines);
;PAUSE
mov bx,ibrcInside SHL 1
call LN_SetPenBrcV
dec [fRestorePen] ; clear fRestorePen
; native note: Assert(fRestorePen == fFalse);
FET100:
; if (rcw.ywTop >= rcw.ywBottom)
; goto LCheckItc;
; si = pdr, di = &rcw
mov ax,[rcw.ywTopRc]
cmp ax,[rcw.ywBottomRc]
jge LCheckItc
FET110:
; }
; EraseRc(ww, &rcw);
; si = pdr, di = &rcw
; #define EraseRc(ww, _prc) \
; PatBltRc(PwwdWw(ww)->hdc, (_prc), vsci.ropErase)
call LN_PwwdWwFET
push [bx.hdcWwd]
push di
push [vsci.HI_ropEraseSci]
push [vsci.LO_ropEraseSci]
cCall PatBltRc,<>
FET120:
; }
LCheckItc:
; if (itcNext == itcMac)
; break;
mov ax,[itcNext]
cmp ax,[itcMac]
je FET130
; #ifdef MAC
; MoveTo(tcx.xpDrRight + tcx.dxpOutRight + dxLToW, ywTop);
; Line(0, dylDrRowM1);
; #else /* WIN */
; xwT = tcx.xpDrRight + tcx.dxpOutRight + dxLToW;
mov cx,[tcx.xpDrRightTcx]
add cx,[tcx.dxpOutRightTcx]
add cx,[dxLToW]
; PrcSet(&rcDraw, xwT, ywTop,
; xwT + dxpPenBrc, ywTop + dylDrRow);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
push cx
mov ax,[ywTop]
push ax
add cx,[dxpPenBrc]
push cx
add ax,[dylDrRow]
push ax
call LN_SetSectAndFillRect
; #endif
; itc = itcNext;
; itcNext = ItcGetTcxCache ( ww, doc, cp, &vtapFetch, itc, &tcx);
mov cx,[itcNext]
call LN_ItcGetTcxCache
jmp LInsideLoop
; }
FET130:
; LTopBorder:
; Assert(itcNext == itcMac);
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[itcNext]
cmp ax,[itcMac]
je FET140
mov ax,midDisptbn2
mov bx,3414 ; assert line number
cCall AssertProcForNative,<ax,bx>
FET140:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; xwRight = tcx.xpDrRight + tcx.dxpOutRight + dxLToW;
mov ax,[tcx.xpDrRightTcx]
add ax,[tcx.dxpOutRightTcx]
add ax,[dxLToW]
mov [xwRight],ax
; /* top */
; if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[ibrcTop])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcTop], fTrue/*fHoriz*/, fFrameLines);
errnz <ibrcTop>
xor bx,bx
call LN_ChkSetPenBrcH
; if (dywBrcTop > 0)
mov cx,[dywBrcTop]
jcxz FET150
; {
; #ifdef MAC
; MoveTo(xwLeft, dyLToW);
; LineTo(xwRight + dxwBrcRight - 1, dyLToW);
; #else /* WIN */
; PrcSet(&rcDraw, xwLeft, dyLToW,
; xwRight + dxwBrcRight, dyLToW + dypPenBrc);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
push [xwLeft]
mov ax,[dyLToW]
push ax
mov cx,[xwRight]
add cx,[dxwBrcRight]
push cx
add ax,[dypPenBrc]
push ax
call LN_SetSectAndFillRect
; #endif
; }
FET150:
; /* right */
; if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[ibrcRight])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcRight], fFalse/*fHoriz*/, fFrameLines);
mov bx,ibrcRight SHL 1
call LN_ChkSetPenBrcV
; #ifdef MAC
; MoveTo(xwRight, ywTop);
; Line(0, dylDrRowM1);
; #else /* WIN */
; PrcSet(&rcDraw, xwRight, ywTop,
; xwRight + dxwBrcRight, ywTop + dylDrRow);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
mov ax,[xwRight]
push ax
mov cx,[ywTop]
push cx
add ax,[dxwBrcRight]
push ax
add cx,[dylDrRow]
push cx
call LN_SetSectAndFillRect
; #endif
; /* bottom */
; if (dywBrcBottom > 0)
mov cx,[dywBrcBottom]
jcxz FET165
; {
; Assert(fLastRow);
;PAUSE
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [fLastRow],0
jnz FET160
mov ax,midDisptbn2
mov bx,3568 ; assert line number
cCall AssertProcForNative,<ax,bx>
FET160:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[ibrcBottom])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcBottom], fTrue/*fHoriz*/, fFrameLines);
mov bx,ibrcBottom SHL 1
call LN_ChkSetPenBrcH
; #ifdef MAC
; MoveTo(xwLeft, dyLToW + dyl - dywBrcBottom);
; Line(xwRight + dxwBrcRight - xwLeft - 1, 0);
; #else /* WIN */
; ywT = dyLToW + dyl - dywBrcBottom;
mov cx,[dyLToW]
add cx,[dyl]
sub cx,[dywBrcBottom]
; PrcSet(&rcDraw, xwLeft, ywT,
; xwRight + dxwBrcRight, ywT + dypPenBrc);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
push [xwLeft]
push cx
mov ax,[xwRight]
add ax,[dxwBrcRight]
push ax
add cx,[dypPenBrc]
push cx
call LN_SetSectAndFillRect
; #endif
; }
FET165:
; /* clear any space above or below the fTtp DR */
; pdr = PdrFetchAndFree(hpldr, itcMac, &drf);
push [hpldr]
push [itcMac]
lea ax,[drf]
push ax
ifdef DEBUG
cCall S_PdrFetchAndFree,<>
else
cCall N_PdrFetchAndFree,<>
endif
xchg ax,si
; DrcToRc(&pdr->drcl, &rclErase);
lea di,[rclErase]
errnz <drclDr>
push si
push di
cCall DrcToRc,<>
; native note: the following lines have been rearranged
; for more hard core native trickery...
; di = &rclErase
push ds
pop es
; rclErase.xlLeft -= pdr->dxpOutLeft;
errnz <xlLeftRc>
mov ax,[di]
sub ax,[si.dxpOutLeftDr]
stosw
; if (fFrameLines && rclErase.ylTop == 0)
; rclErase.ylTop = dyFrameLine;
errnz <ylDr-2-xlDr>
mov ax,[di]
mov cx,[fFrameLines]
jcxz FET170
or ax,ax
jnz FET170
; #define dyFrameLine dypBorderFti
; #define dypBorderFti vfti.dypBorder
mov ax,[vfti.dypBorderFti]
FET170:
stosw
xchg ax,cx ; save rclErase.ylTop
; rclErase.xlRight += pdr->dxpOutRight;
errnz <xlRightRc-2-ylDr>
mov ax,[di]
add ax,[si.dxpOutRightDr]
stosw
; if (rclErase.ylTop > 0)
; cx = rclErase.ylTop
jcxz FET180
; {
; rclErase.ylBottom = rclErase.ylTop;
mov ax,[rclErase.ylTopRc]
mov [rclErase.ylBottomRc],ax
; rclErase.ylTop = 0;
sub [rclErase.ylTopRc],ax
; ClearRclInParentDr(ww,hpldr,rclErase,&rcwClip);
call LN_ClearRcl
; rclErase.ylBottom += pdr->drcl.dyl;
mov ax,[si.drclDr.dylDrc]
add [rclErase.ylBottomRc],ax
; }
FET180:
; if (rclErase.ylBottom < dyl)
mov cx,[dyl]
cmp cx,[rclErase.ylBottomRc]
jle FET190
; {
; rclErase.ylTop = rclErase.ylBottom;
;PAUSE
; cx = dyl
mov ax,[rclErase.ylBottomRc]
mov [rclErase.ylTopRc],ax
; rclErase.ylBottom = dyl;
; cx = dyl
mov [rclErase.ylBottomRc],cx
; ClearRclInParentDr(ww,hpldr,rclErase,&rcwClip);
call LN_ClearRcl
; }
FET190:
;PAUSE
mov di,[prclDrawn]
push ds
pop es
; prclDrawn->xlLeft = xwLeft - dxLToW;
mov ax,[xwLeft]
sub ax,[dxLToW]
stosw
; prclDrawn->ylTop = 0;
xor ax,ax
stosw
; prclDrawn->xlRight = rclErase.xlRight;
mov ax,[rclErase.xlRightRc]
stosw
; prclDrawn->ylBottom = dywBrcTop;
mov ax,[dywBrcTop]
stosw
; /* erase bits to the right of the PLDR */
; native note: more rearranging...
lea di,[rclErase]
push ds
pop es
; rclErase.xlLeft = rclErase.xlRight;
errnz <xlLeftRc>
mov ax,[di.xlRightRc-(xlLeftRc)]
stosw
; rclErase.ylTop = 0;
errnz <ylTopRc-2-xlLeftRc>
xor ax,ax
stosw
; rclErase.xlRight = pdrParent->dxl + pdrParent->dxpOutRight;
errnz <xlRightRc-2-ylTopRc>
mov bx,pdrParent
mov ax,[bx.dxlDr]
add ax,[bx.dxpOutRightDr]
stosw
; rclErase.ylBottom = dyl;
errnz <ylBottomRc-2-xlRightRc>
mov ax,[dyl]
stosw
; if (!FEmptyRc(&rclErase))
; ClearRclInParentDr(ww,hpldr,rclErase,&rcwClip);
call LN_ClearRclIfNotMT
; }
cEnd
; Some utility routines for FrameEasyTable...
; LN_ClearRclIfNotMT Does:
; if (!FEmptyRc(&rclErase))
; ClearRclInParentDr(ww,hpldr,rclErase,&rcwClip);
LN_ClearRclIfNotMT:
;PAUSE
lea ax,[rclErase]
push ax
cCall FEmptyRc,<>
or ax,ax
jnz FED1000
LN_ClearRcl:
;PAUSE
push [ww]
push [hpldr]
push [rclErase.ylBottomRc]
push [rclErase.xlRightRc]
push [rclErase.YwTopRc]
push [rclErase.xwLeftRc]
lea ax,[rcwClip]
push ax
cCall ClearRclInParentDr,<>
FED1000:
ret
; LN_DxFromIbrc Does:
; DxFromBrc(*(int*)(si + rgbrcEasyTcc + bx), fTrue/*fFrameLines*/)
; Upon Entry: bx = ibrc, di = &vtcc.rgbrcEasy
; Upon Exit: ax = DxFromBrc(vtcc.rgbrcEasy[ibrcInside],fTrue/*fFrameLines*/);
LN_DxFromIbrc:
; #define DxFromBrc(brc, fFrameLines) DxyFromBrc(brc, fFrameLines, fTrue)
; #define DxyFromBrc(brc, fFrameLines, fWidth) \
; WidthHeightFromBrc(brc, fFrameLines | (fWidth << 1))
push [bx.si.rgbrcEasyTcc]
mov ax,3
push ax
ifdef DEBUG
cCall S_WidthHeightFromBrc,<>
else
cCall N_WidthHeightFromBrc,<>
endif
ret
; %%Function:ItcGetTcxCache %%Owner:tomsax
; LN_ItcGetTcxCache does three things:
; itc = cx;
; ax = ItcGetTcxCache ( ww, doc, cp, &vtapFetch, itc, &tcx);
; itcNext = ax
LN_ItcGetTcxCache:
;PAUSE
mov [itc],cx
push [ww]
push [doc]
push [SEG_cp]
push [OFF_cp]
mov ax,dataoffset [vtapFetch]
push ax
push cx
lea ax,[tcx]
push ax
ifdef DEBUG
cCall S_ItcGetTcxCache
else
cCall N_ItcGetTcxCache
endif
mov [itcNext],ax
ret
; Upon entry: who cares, apart from FrameEasyTable's stack frame...
; Upon exit: bx = PwwdWw([ww]), + the usual registers trashed...
LN_PwwdWwFET:
;PAUSE
push [ww]
cCall N_PwwdWw,<>
xchg ax,bx
ret
; PrcSet(&rcDraw, xwLeft, ywTop,
; xwLeft + dxpPenBrc, ywTop + dylDrRow);
; SectRc(&rcDraw, &rcwClip, &rcDraw);
; FillRect(hdc, (LPRECT)&rcDraw, hbrPenBrc);
LN_SetSectAndFillRect:
;PAUSE
db 0A8h ;turns next "stc" into "test al,immediate"
;also clears the carry flag
LN_SetAndFillRect:
stc
;PAUSE
; native note: blt from the stack into rcwDraw.
pop bx ; save the return address
mov dx,di ; save current di
push ds
pop es
std ; blt backwards
errnz <xwLeftRc>
errnz <ywTopRc-2-xwLeftRc>
errnz <xwRightRc-2-ywTopRc>
errnz <ywBottomRc-2-xwRightRc>
errnz <ywBottomRc+2-cbRcMin>
lea di,[rcDraw.ywBottomRc]
pop ax
stosw
pop ax
stosw
pop ax
stosw
pop ax
stosw
cld ; clear the direction flag
push bx ; restore the return address
push dx ; save original di value
lea di,[di+2] ; doesn't affect condition flags
jc FET1100 ; use that bit set above
push di
lea ax,[rcwClip]
push ax
push di
; #define SectRc(prc1,prc2,prcDest) FSectRc(prc1,prc2,prcDest)
cCall FSectRc,<>
FET1100:
; bx = &rcDraw
push [hdc]
push ds
push di
push [hbrPenBrc]
cCall FillRect,<>
pop di ; restore original di
ret
; %%Function:SetPenForBrc %%Owner:tomsax
; NATIVE SetPenForBrc(ww, brc, fHoriz, fFrameLines)
; int ww;
; int brc;
; BOOL fHoriz, fFrameLines;
; {
; extern HBRUSH vhbrGray;
; Upon Entry: bx = ibrc*2 (ignored by SetPenBrcVNone)
;LN_ChkSetPenBrcH Does:
; if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[bx/2/*ibrc*/])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcInside], fTrue/*fHoriz*/, fFrameLines);
;LN_ChkSetPenBrcV Does:
; if (brcCur != brcNone || brcCur != vtcc.rgbrcEasy[bx/2/*ibrc*/])
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ibrcInside], fFalse/*fHoriz*/, fFrameLines);
;LN_SetPenBrcV Does:
; SetPenForBrc(ww, brcCur = vtcc.rgbrcEasy[ax/2], fFalse/*fHoriz*/, fFrameLines)
;LN_SetPenBrcVNone Does:
; SetPenForBrc(ww, brcCur = brcNone, fFalse/*fHoriz*/, fFrameLines)
LN_ChkSetPenBrcH:
;PAUSE
db 0B8h ;this combines with the next opcode
; to become B8C031 = mov ax,c031
LN_ChkSetPenBrcV:
xor ax,ax ; don't alter this opcode, see note above
;PAUSE
; si = &vtcc, bx = ibrcInside * 2
mov cx,[bx.vtcc.rgbrcEasyTcc]
cmp cx,[brcCur]
jne FET1200
errnz <brcNone>
jcxz FET1250 ; jump to rts
jmp short FET1200
LN_SetPenBrcV:
xor ax,ax
;PAUSE
mov cx,[bx.vtcc.rgbrcEasyTcc]
db 03Dh ; this combines with the next opcode
; to become 3D33C9 = cmp ax,C933
LN_SetPenBrcVNone:
errnz <brcNone>
xor cx,cx ; don't alter this opcode, see note above
; NOTE: fHoriz doesn't get used if brc==brcNone,
; therefore it is OK to leave it uninitialized...
;PAUSE
FET1200:
; cx = brc, ax = fHoriz (not restricted to 0,1 values)
; brcCur = whatever was passed for the new brc;
mov [brcCur],cx
; switch (brc)
; {
jcxz LBrcNone
cmp cx,brcDotted
je LBrcDotted
; default:
; Assert(fFalse);
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp cx,brcSingle
je FET1210
cmp cx,brcHairline
je FET1210
cmp cx,brcThick
je FET1210
mov ax,midDisptbn2
mov bx,3881 ; assert line number
cCall AssertProcForNative,<ax,bx>
FET1210:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; case brcSingle:
; case brcHairline:
; case brcThick:
; hbrPenBrc = vsci.hbrText;
mov bx,[vsci.hbrTextSci]
jmp short FET1220
; break;
; case brcNone:
LBrcNone:
; if (!fFrameLines)
; {
; hbrPenBrc = vsci.hbrBkgrnd;
; break;
; }
mov bx,[vsci.hbrBkgrndSci]
cmp [fFrameLines],0
jz FET1220
; /* else fall through */
; case brcDotted:
; hbrPenBrc = vhbrGray;
LBrcDotted:
mov bx,[vhbrGray]
; break;
; }
FET1220:
mov [hbrPenBrc],bx
; cx = brc, ax = fHoriz (not restricted to 0,1 values)
; dxpPenBrc = dxpBorderFti;
mov dx,[vsci.dxpBorderSci]
mov [dxpPenBrc],dx
; dypPenBrc = dypBorderFti;
mov dx,[vsci.dypBorderSci]
mov [dypPenBrc],dx
; cx = brc, ax = fHoriz (not restricted to 0,1 values)
; if (brc == brcThick)
cmp cx,brcThick
jne FET1250
; {
; if (fHoriz)
;PAUSE
xchg ax,cx
jcxz FET1240
; dypPenBrc = 2 * dypBorderFti;
sal [dypPenBrc],1
jmp short FET1250
; else
FET1240:
; dxpPenBrc = 2 * dxpBorderFti;
sal [dxpPenBrc],1
; }
FET1250:
ret
; }
sEnd fetchtbn
end
| 20.763302 | 125 | 0.701399 |
9481f8c69706816485e9b79d2ec5596d32818faa | 1,105 | rs | Rust | src/natives.rs | bramvdbogaerde/interpeter-experiments | be2abedc679255395a99e85b1df9d94aa8711f20 | [
"MIT"
] | null | null | null | src/natives.rs | bramvdbogaerde/interpeter-experiments | be2abedc679255395a99e85b1df9d94aa8711f20 | [
"MIT"
] | null | null | null | src/natives.rs | bramvdbogaerde/interpeter-experiments | be2abedc679255395a99e85b1df9d94aa8711f20 | [
"MIT"
] | null | null | null | use crate::values::{Val, Exp};
pub fn minus(operands: Vec<Exp>) -> Exp {
let op1 = operands[0].borrow();
let op2 = operands[1].borrow();
match (&*op1, &*op2) {
(Val::Number(x), Val::Number(y)) => Val::wrap(Val::Number(x-y)),
_ => panic!("unsupported operands"),
}
}
pub fn plus(operands: Vec<Exp>) -> Exp {
let op1 = operands[0].borrow();
let op2 = operands[1].borrow();
match (&*op1, &*op2) {
(Val::Number(x), Val::Number(y)) => Val::wrap(Val::Number(x+y)),
_ => panic!("unsupported operands"),
}
}
pub fn times(operands: Vec<Exp>) -> Exp {
let op1 = operands[0].borrow();
let op2 = operands[1].borrow();
match (&*op1, &*op2) {
(Val::Number(x), Val::Number(y)) => Val::wrap(Val::Number(x*y)),
_ => panic!("unsupported operands"),
}
}
pub fn equals(operands: Vec<Exp>) -> Exp {
let op1 = operands[0].borrow();
let op2 = operands[1].borrow();
match (&*op1, &*op2) {
(Val::Number(x), Val::Number(y)) => Val::wrap(Val::Bool(x == y)),
_ => panic!("unsupported operands"),
}
}
| 28.333333 | 73 | 0.533937 |
e7f30077f490cc616f7f71217c5e89c086968e6a | 1,807 | py | Python | www/purple_admin/urls.py | SubminO/vas | 3096df12e637fc614d18cb3eef43c18be0775e5c | [
"Apache-2.0"
] | null | null | null | www/purple_admin/urls.py | SubminO/vas | 3096df12e637fc614d18cb3eef43c18be0775e5c | [
"Apache-2.0"
] | null | null | null | www/purple_admin/urls.py | SubminO/vas | 3096df12e637fc614d18cb3eef43c18be0775e5c | [
"Apache-2.0"
] | null | null | null | from django.urls import path
from purple_admin import views
urlpatterns = [
path('', views.cabinet, name='admin_panel_cabinet'),
# Адмника Наименований маршрутов
path('route_list', views.cabinet_list, {'type': 'route'}, name='admin_panel_route_list'),
path('route_add', views.cabinet_add, {'type': 'route'}, name='admin_panel_route_add'),
path('route_edit/<int:pk>/', views.cabinet_edit, {'type': 'route'}, name='admin_panel_route_edit'),
path('route_delete/<int:pk>/', views.cabinet_delete, {'type': 'route'}, name='admin_panel_route_delete'),
# Адмника наименований остановок
path('route_platform_list', views.cabinet_list, {'type': 'route_platform'}, name='admin_panel_route_platform_list'),
path('route_platform_add', views.cabinet_add, {'type': 'route_platform'}, name='admin_panel_route_platform_add'),
path('route_platform_edit/<int:pk>/', views.cabinet_edit, {'type': 'route_platform'},
name='admin_panel_route_platform_edit'),
path('route_platform_delete/<int:pk>/', views.cabinet_delete, {'type': 'route_platform'},
name='admin_panel_route_platform_delete'),
path('route_relation_add_ajax', views.cabinet_add, {'type': 'route_platform_type'},
name='admin_panel_route_platform_type_relation_ajax_add'),
# Админка ТС
path('ts_list', views.cabinet_list, {'type': 'ts'}, name='admin_panel_ts_list'),
path('ts_add', views.cabinet_add, {'type': 'ts'}, name='admin_panel_ts_add'),
path('ts_edit/<int:pk>/', views.cabinet_edit, {'type': 'ts'}, name='admin_panel_ts_edit'),
path('ts_delete/<int:pk>/', views.cabinet_delete, {'type': 'ts'}, name='admin_panel_ts_delete'),
# Адмника Создания маршрута на карте
path('map_route_editor_add', views.mapped_route_add, name='admin_panel_mapped_route_add'),
]
| 62.310345 | 120 | 0.716657 |
2e517cd8ec1e685e672274d2a93ff61a5389b4e3 | 1,974 | ps1 | PowerShell | src/modules/Server/private/Get-VfpVMSwitchPort.ps1 | microsoft/SdnDiagnostics | 3689d64cbb8ce3b524ef4b573568bd642470b941 | [
"MIT"
] | 4 | 2021-09-24T01:38:29.000Z | 2022-02-08T17:39:19.000Z | src/modules/Server/private/Get-VfpVMSwitchPort.ps1 | microsoft/SdnDiagnostics | 3689d64cbb8ce3b524ef4b573568bd642470b941 | [
"MIT"
] | 14 | 2021-09-23T09:20:08.000Z | 2022-03-15T02:16:04.000Z | src/modules/Server/private/Get-VfpVMSwitchPort.ps1 | microsoft/SdnDiagnostics | 3689d64cbb8ce3b524ef4b573568bd642470b941 | [
"MIT"
] | null | null | null | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
function Get-VfpVMSwitchPort {
<#
.SYNOPSIS
Returns a list of ports from within VFP.
#>
try {
$arrayList = [System.Collections.ArrayList]::new()
$vfpResults = vfpctrl /list-vmswitch-port
if ($null -eq $vfpResults) {
$msg = "Unable to retrieve vmswitch ports from vfpctrl`n{0}" -f $_
throw New-Object System.NullReferenceException($msg)
}
foreach ($line in $vfpResults) {
# lines in the VFP output that contain : contain properties and values
# need to split these based on count of ":" to build key and values
if ($line.Contains(":")) {
$results = $line.Split(":").Trim().Replace(" ", "")
if ($results.Count -eq 3) {
$key = "$($results[0])-$($results[1])"
$value = $results[2]
}
elseif ($results.Count -eq 2) {
$key = $results[0]
$value = $results[1]
}
# all ports begin with this property and value so need to create a new psobject when we see these keys
if ($key -eq "Portname") {
$port = New-Object -TypeName PSObject
}
# add the line values to the object
$port | Add-Member -MemberType NoteProperty -Name $key -Value $value
}
# all the ports are seperated with a blank line
# use this as our end of properties to add the current obj to the array list
if ([string]::IsNullOrEmpty($line)) {
if ($port) {
[void]$arrayList.Add($port)
}
}
}
return $arrayList
}
catch {
"{0}`n{1}" -f $_.Exception, $_.ScriptStackTrace | Trace-Output -Level:Error
}
}
| 34.631579 | 118 | 0.502533 |
513f81b86b9d735e6ea6120325f8f329794cdaf7 | 663 | lua | Lua | moonpie/test_helpers/file_assertions.lua | tredfern/moonpie | b7b6542007a4acd6ca01c7d36957b10774ba242b | [
"MIT"
] | 5 | 2019-04-16T09:55:57.000Z | 2021-01-31T21:50:47.000Z | moonpie/test_helpers/file_assertions.lua | tredfern/moonpie | b7b6542007a4acd6ca01c7d36957b10774ba242b | [
"MIT"
] | 7 | 2021-04-26T12:14:05.000Z | 2022-02-15T13:26:13.000Z | moonpie/test_helpers/file_assertions.lua | tredfern/moonpie | b7b6542007a4acd6ca01c7d36957b10774ba242b | [
"MIT"
] | null | null | null | -- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local assert = require("luassert")
local say = require("say")
local function file_exists(state, arguments)
local path = arguments[1]
local f = io.open(path, "r")
local result = f ~= nil
if f then f:close() end
return result
end
say:set("assertion.file_exists.positive", "File %s does not exist.")
say:set("assertion.file_exists.negative", "File %s exists and should not.")
assert:register("assertion", "file_exists", file_exists, "assertion.file_exists.positive", "assertion.file_exists.negative") | 31.571429 | 124 | 0.707391 |
a131cb3802f353ad5a8b47564b2296ffacb13130 | 5,492 | go | Go | app/interface/main/creative/service/account/account.go | 78182648/blibli-go | 7c717cc07073ff3397397fd3c01aa93234b142e3 | [
"MIT"
] | 22 | 2019-04-27T06:44:41.000Z | 2022-02-04T16:54:14.000Z | app/interface/main/creative/service/account/account.go | YouthAge/blibli-go | 7c717cc07073ff3397397fd3c01aa93234b142e3 | [
"MIT"
] | null | null | null | app/interface/main/creative/service/account/account.go | YouthAge/blibli-go | 7c717cc07073ff3397397fd3c01aa93234b142e3 | [
"MIT"
] | 34 | 2019-05-07T08:22:27.000Z | 2022-03-25T08:14:56.000Z | package account
import (
"context"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/sync/errgroup"
"time"
accmdl "go-common/app/interface/main/creative/model/account"
account "go-common/app/service/main/account/model"
"go-common/library/ecode"
xtime "go-common/library/time"
"sync"
)
const creatorMID = 37090048
// MyInfo get use level.
func (s *Service) MyInfo(c context.Context, mid int64, ip string, now time.Time) (m *accmdl.MyInfo, err error) {
var (
idCkCode = 0
res *account.Profile
)
// init myinfo
m = &accmdl.MyInfo{
Mid: mid,
Level: 1,
Activated: true,
Deftime: xtime.Time(now.Add(time.Duration(14400) * time.Second).Unix()),
DeftimeEnd: xtime.Time(now.Add(time.Duration(15*24) * time.Hour).Unix()),
DeftimeMsg: ecode.String(ecode.VideoupDelayTimeErr.Error()).Message(),
IdentifyInfo: &accmdl.IdentifyInfo{
Code: idCkCode,
Msg: accmdl.IdentifyEnum[idCkCode],
},
UploadSize: map[string]bool{
"4-8": false,
"8-16": false,
},
DmSubtitle: true,
}
if res, err = s.acc.Profile(c, mid, ip); err != nil {
log.Error("s.acc.Profile (%d) error(%v)", mid, err)
return
}
if res == nil {
err = ecode.NothingFound
return
}
if res.Silence == 1 {
m.Banned = true
}
if res.EmailStatus == 1 || res.TelStatus == 1 {
m.Activated = true
}
m.Name = res.Name
m.Face = res.Face
m.Level = int(res.Level)
if _, ok := s.exemptIDCheckUps[mid]; ok {
log.Info("s.exemptIDCheckUps (%d) info(%v)", mid, s.exemptIDCheckUps)
idCkCode = 0
} else {
idCkCode, _ = s.acc.IdentifyInfo(c, mid, 0, ip)
}
m.IdentifyInfo.Code = idCkCode
m.IdentifyInfo.Msg = accmdl.IdentifyEnum[idCkCode] // NOTE: exist check
m = s.ignoreLevelUpAndActivated(m, mid, s.exemptZeroLevelAndAnswerUps)
if _, ok := s.uploadTopSizeUps[mid]; ok {
m.UploadSize["4-8"] = true
m.UploadSize["8-16"] = true
}
return
}
// type为12的白名单人员,免账号激活,免账号升级到1级
func (s *Service) ignoreLevelUpAndActivated(m *accmdl.MyInfo, mid int64, exemptZeroLevelAndAnswerUps map[int64]int64) *accmdl.MyInfo {
if len(exemptZeroLevelAndAnswerUps) > 0 {
_, ok := exemptZeroLevelAndAnswerUps[mid]
if ok && (m.Level < 1 || !m.Activated) {
m.Activated = true
m.Level = 1
}
}
return m
}
// UpInfo get video article pic blink up infos.
func (s *Service) UpInfo(c context.Context, mid int64, ip string) (v *accmdl.UpInfo, err error) {
cache := true
if v, err = s.acc.UpInfoCache(c, mid); err != nil {
s.pCacheMiss.Incr("upinfo_cache")
err = nil
cache = false
} else if v != nil {
s.pCacheHit.Incr("upinfo_cache")
return
}
s.pCacheMiss.Incr("upinfo_cache")
var (
g = &errgroup.Group{}
ctx = context.TODO()
)
v = &accmdl.UpInfo{
Archive: accmdl.NotUp,
Article: accmdl.NotUp,
Pic: accmdl.NotUp,
Blink: accmdl.NotUp,
}
g.Go(func() error {
blikCnt, _ := s.acc.Blink(ctx, mid, ip)
if blikCnt > 0 {
v.Blink = accmdl.IsUp
}
return nil
})
g.Go(func() error {
picCnt, _ := s.acc.Pic(c, mid, ip)
if picCnt > 0 {
v.Pic = accmdl.IsUp
}
return nil
})
g.Go(func() error {
arcCnt, _ := s.archive.UpCount(c, mid)
if arcCnt > 0 {
v.Archive = accmdl.IsUp
}
return nil
})
g.Go(func() error {
isAuthor, _ := s.article.IsAuthor(c, mid, ip)
if isAuthor {
v.Article = accmdl.IsUp
}
return nil
})
g.Wait()
if cache {
s.addCache(func() {
s.acc.AddUpInfoCache(context.Background(), mid, v)
})
}
return
}
// RecFollows 推荐关注
func (s *Service) RecFollows(c context.Context, mid int64) (fs []*accmdl.Friend, err error) {
var (
fsMids = []int64{creatorMID}
shouldFollowMids = []int64{}
infos = make(map[int64]*account.Info)
)
ip := metadata.String(c, metadata.RemoteIP)
if shouldFollowMids, err = s.acc.ShouldFollow(c, mid, fsMids, ip); err != nil {
log.Error("s.acc.ShouldFollow mid(%d)|ip(%s)|error(%v)", mid, ip, err)
return
}
if len(shouldFollowMids) > 0 {
if infos, err = s.acc.Infos(c, shouldFollowMids, ip); err != nil {
log.Error("s.acc.Infos mid(%d)|ip(%s)|shouldFollowMids(%+v)|error(%v)", mid, ip, shouldFollowMids, err)
return
}
for mid, info := range infos {
f := &accmdl.Friend{
Mid: mid,
Sign: info.Sign,
Face: info.Face,
Name: info.Name,
}
if mid == creatorMID {
f.Comment = "关注创作中心,获取更多创作情报"
f.ShouldFollow = 0
}
fs = append(fs, f)
}
}
return
}
// Infos 获取多个UP主的信息
func (s *Service) Infos(c context.Context, mids []int64, ip string) (res map[int64]*account.Info, err error) {
return s.acc.Infos(c, mids, ip)
}
// Relations 批量获取mid与其它用户的关系
func (s *Service) Relations(c context.Context, mid int64, fids []int64, ip string) (res map[int64]int, err error) {
return s.acc.Relations(c, mid, fids, ip)
}
// FRelations 获取用户与mid的关系(Relations的反向)
func (s *Service) FRelations(c context.Context, mid int64, fids []int64, ip string) (res map[int64]int, err error) {
var (
g errgroup.Group
sm sync.RWMutex
)
res = make(map[int64]int)
for _, v := range fids {
g.Go(func() error {
var r map[int64]int
if r, err = s.acc.Relations(c, v, []int64{mid}, ip); err != nil {
return err
}
sm.Lock()
res[v] = r[mid]
sm.Unlock()
return nil
})
}
if err = g.Wait(); err != nil {
log.Error("s.FRelations(%d,%v) error(%v)", mid, fids, err)
}
return
}
// Cards 批量获取用户的Card
func (s *Service) Cards(c context.Context, mids []int64, ip string) (cards map[int64]*account.Card, err error) {
return s.acc.Cards(c, mids, ip)
}
| 24.963636 | 134 | 0.64421 |
a99cc57a9f360a17b475e2fde6c486ae600c4535 | 4,752 | html | HTML | 64x64x64.html | AntonioNoack/Aarch64MatmulVM | fc01c5be7727ade825c59bae24625b88bb6e8ff0 | [
"Apache-2.0"
] | null | null | null | 64x64x64.html | AntonioNoack/Aarch64MatmulVM | fc01c5be7727ade825c59bae24625b88bb6e8ff0 | [
"Apache-2.0"
] | null | null | null | 64x64x64.html | AntonioNoack/Aarch64MatmulVM | fc01c5be7727ade825c59bae24625b88bb6e8ff0 | [
"Apache-2.0"
] | null | null | null | <html><head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="highlightjs/nnfx-light.css">
</head><body>
<div id="delay" class="hidden">0.1</div>
<div id="mkn" class="hidden">64,64,64</div>
<div id="code" class="hidden">
.text
.align 4
.type gemm_asm_sve_64_64_64, %function
.global gemm_asm_sve_64_64_64
gemm_asm_sve_64_64_64:
// geschrieben für SVE2 mit 512 Bits = 16 Floats je Vektor
// rette die Register, die wir nutzen, die gerettet werden müssen
// wir verwenden nur x0-x4, da müssen wir also nichts retten
// dank Umbenennung ist es nicht mehr notwendig, die Vektorregister zu retten
// stp d8, d9, [sp, #-16]!
// stp d10, d11, [sp, #-16]!
// stp d12, d13, [sp, #-16]!
// stp d14, d15, [sp, #-16]!
// setze p0 überall auf 1
ptrue p0.s
// gehe über alle 4er-Spalten-Gruppen von C
mov x4, #16
loop_n:
// lade die ersten vier Spalten von C
ldr z0, [x2]
add x2,x2,#16*4
ldr z1, [x2]
add x2,x2,#16*4
ldr z2, [x2]
add x2,x2,#16*4
ldr z3, [x2]
add x2,x2,#16*4
ldr z4, [x2]
add x2,x2,#16*4
ldr z5, [x2]
add x2,x2,#16*4
ldr z6, [x2]
add x2,x2,#16*4
ldr z7, [x2]
add x2,x2,#16*4
ldr z24, [x2]
add x2,x2,#16*4
ldr z25, [x2]
add x2,x2,#16*4
ldr z26, [x2]
add x2,x2,#16*4
ldr z27, [x2]
add x2,x2,#16*4
ldr z28, [x2]
add x2,x2,#16*4
ldr z29, [x2]
add x2,x2,#16*4
ldr z30, [x2]
add x2,x2,#16*4
ldr z31, [x2]
// setze C fürs Schreiben zurück
sub x2,x2,#(15*16*4)
// gehe über alle Spalten von A
mov x3, #64
loop_k:
// broadcast, speichert den Wert aus B in alle Positionen im Vektor
ld1rw {z16.s}, p0/z, [x1]
add x1,x1,#64*4
ld1rw {z17.s}, p0/z, [x1]
add x1,x1,#64*4
ld1rw {z18.s}, p0/z, [x1]
add x1,x1,#64*4
ld1rw {z19.s}, p0/z, [x1]
// setze B zurück nach links und eins weiter nach unten
sub x1,x1,#(3*64-1)*4
// lade ganze Spalte von A
ldr z20, [x0]
add x0,x0,#16*4
ldr z21, [x0]
add x0,x0,#16*4
ldr z22, [x0]
add x0,x0,#16*4
ldr z23, [x0]
add x0,x0,#16*4
// rechnen
fmla z0.s, p0/m, z20.s, z16.s
fmla z1.s, p0/m, z21.s, z16.s
fmla z2.s, p0/m, z22.s, z16.s
fmla z3.s, p0/m, z23.s, z16.s
fmla z4.s, p0/m, z20.s, z17.s
fmla z5.s, p0/m, z21.s, z17.s
fmla z6.s, p0/m, z22.s, z17.s
fmla z7.s, p0/m, z23.s, z17.s
fmla z24.s, p0/m, z20.s, z18.s
fmla z25.s, p0/m, z21.s, z18.s
fmla z26.s, p0/m, z22.s, z18.s
fmla z27.s, p0/m, z23.s, z18.s
fmla z28.s, p0/m, z20.s, z19.s
fmla z29.s, p0/m, z21.s, z19.s
fmla z30.s, p0/m, z22.s, z19.s
fmla z31.s, p0/m, z23.s, z19.s
sub x3,x3,#1
cbnz x3, loop_k
// speichere C
str z0, [x2]
add x2,x2,#16*4
str z1, [x2]
add x2,x2,#16*4
str z2, [x2]
add x2,x2,#16*4
str z3, [x2]
add x2,x2,#16*4
str z4, [x2]
add x2,x2,#16*4
str z5, [x2]
add x2,x2,#16*4
str z6, [x2]
add x2,x2,#16*4
str z7, [x2]
add x2,x2,#16*4
str z24, [x2]
add x2,x2,#16*4
str z25, [x2]
add x2,x2,#16*4
str z26, [x2]
add x2,x2,#16*4
str z27, [x2]
add x2,x2,#16*4
str z28, [x2]
add x2,x2,#16*4
str z29, [x2]
add x2,x2,#16*4
str z30, [x2]
add x2,x2,#16*4
str z31, [x2]
add x2,x2,#16*4
// A ist komplett bearbeitet wurden, also setze es zurück
sub x0,x0,#64*64*4
// B wäre jetzt in der nächsten Spalte, aber wir bearbeiten immer vier, also fehlen noch drei Spalten
add x1,x1,#64*3*4
// C ist schon korrekt
sub x4,x4,#1
cbnz x4, loop_n
// restore all used registers
// dank Umbenennung nicht mehr notwendig
// ldp d14, d15, [sp], #16
// ldp d12, d13, [sp], #16
// ldp d10, d11, [sp], #16
// ldp d8, d9, [sp], #16
ret
.size gemm_asm_sve_64_64_64, (. - gemm_asm_sve_64_64_64)
</div>
<h1>AARCH64, 16 x 12 x 4 Matrix-Multiplication</h1>
<h2>Running Code:</h2>
<button id="cont" onclick="if(redrawDelay>=1e6){ redrawDelay=redrawDelay0; step(); cont.innerText='Stop' } else { redrawDelay=1e9; cont.innerText='Continue' }">Stop</button>
<button onclick="redrawDelay=1e9;step();cont.innerText='Continue'">Step</button>
<button onclick="restart();redraw()">Restart</button>
<button onclick="zoomIn()">Zoom +</button>
<button onclick="zoomOut()">Zoom -</button>
<button onclick="runFaster()">Speed +</button>
<button onclick="runSlower()">Speed -</button>
<br>
<canvas id="canvas"></canvas>
<h2>Source Code:</h2>
<!--<textarea id="codeText" rows="100" cols="160"></textarea>-->
<pre><code><p id="codeText"></p></code></pre>
<script src="highlightjs/highlight.min.js"></script>
<script src="virtualMachine.js"></script>
<script src="task.js"></script>
<script src="drawing.js"></script>
<script src="start.js"></script>
</body></html> | 23.879397 | 174 | 0.602062 |
2aa7e8056893aef61c611e11f2882e85755ccbb8 | 197 | sql | SQL | demo-orm-mybatis-simple/src/main/resources/script/dml.sql | stewart-tian/spring-boot-series-demo | 488d450fecf4df76667124cfe9ab92a96317395d | [
"Apache-2.0"
] | 2 | 2020-12-08T12:21:24.000Z | 2021-01-06T11:48:16.000Z | demo-orm-mybatis-simple/src/main/resources/script/dml.sql | stewart-tian/spring-boot-series-demo | 488d450fecf4df76667124cfe9ab92a96317395d | [
"Apache-2.0"
] | null | null | null | demo-orm-mybatis-simple/src/main/resources/script/dml.sql | stewart-tian/spring-boot-series-demo | 488d450fecf4df76667124cfe9ab92a96317395d | [
"Apache-2.0"
] | null | null | null | insert into orm_demo (`info`,`resume`) value ("Demo信息一","信息简述一");
insert into orm_demo (`info`,`resume`) value ("Demo信息二","信息简述二");
insert into orm_demo (`info`,`resume`) value ("Demo信息三","信息简述三"); | 65.666667 | 65 | 0.685279 |