file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
51-remove-pdfinfo-property.spec.js | import testingDB from 'api/utils/testing_db';
import { testingEnvironment } from 'api/utils/testingEnvironment';
import migration from '../index.js';
import fixtures from './fixtures.js';
describe('migration remove-pdfinfo-property', () => {
beforeEach(async () => {
spyOn(process.stdout, 'write');
await testingEnvironment.setUp(fixtures);
});
afterAll(async () => {
await testingEnvironment.tearDown();
});
it('should have a delta number', () => {
expect(migration.delta).toBe(51);
});
describe('unset pdfInfo property', () => {
beforeEach(async () => {
await migration.up(testingDB.mongodb);
});
it('should remove pdfInfo property from entities and keep the rest of properties', async () => {
const entities = await testingDB.mongodb
.collection('entities')
.find({})
.toArray(); | { title: 'entity2' },
{
title: 'entity3',
published: true,
},
]);
});
it('should remove pdfInfo property from files and keep the rest of properties', async () => {
const filesWithoutPdfInfo = fixtures.files.map(file => {
const { pdfInfo, ...fileWithoutPdfInfo } = file;
return fileWithoutPdfInfo;
});
const files = await testingDB.mongodb
.collection('files')
.find({})
.toArray();
expect(files).toEqual(filesWithoutPdfInfo);
});
});
}); |
expect(entities).toMatchObject([
{ title: 'entity1', metadata: { text: [{ value: 'test' }] } }, |
keycloak-multitenant.service.ts | import { Inject, Injectable } from '@nestjs/common';
import KeycloakConnect from 'keycloak-connect';
import { KEYCLOAK_CONNECT_OPTIONS } from '../constants';
import { KeycloakConnectOptions } from '../interface/keycloak-connect-options.interface';
/**
* Stores all keycloak instances when multi tenant option is defined.
*/
@Injectable()
export class | {
private instances: Map<string, KeycloakConnect.Keycloak> = new Map();
constructor(
@Inject(KEYCLOAK_CONNECT_OPTIONS)
private keycloakOpts: KeycloakConnectOptions,
) {}
/**
* Retrieves a keycloak instance based on the realm provided.
* @param realm the realm to retrieve from
* @returns the multi tenant keycloak instance
*/
get(realm: string): KeycloakConnect.Keycloak {
if (this.instances.has(realm)) {
return this.instances.get(realm);
} else {
// TODO: Repeating code from provider, will need to rework this in 2.0
// Override realm
const keycloakOpts: any = Object.assign(this.keycloakOpts, { realm });
// Override secret
const creds = keycloakOpts.credentials;
if (
creds !== undefined &&
creds.realmSecretMap !== undefined &&
creds.realmSecretMap.has(realm)
) {
keycloakOpts.secret = keycloakOpts.credentials.realmSecretMap[realm];
} // else it it will default to global secret
const keycloak: any = new KeycloakConnect({}, keycloakOpts);
// The most important part
keycloak.accessDenied = (req: any, res: any, next: any) => {
req.resourceDenied = true;
next();
};
this.instances.set(realm, keycloak);
return keycloak;
}
}
}
| KeycloakMultiTenantService |
user_test.go | // Copyright (c) 2020 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package database
import (
"database/sql"
"reflect"
"strconv"
"testing"
"github.com/go-vela/types/library"
)
func | (t *testing.T) {
// setup types
var u *User
want := &User{
ID: sql.NullInt64{Int64: 0, Valid: false},
Name: sql.NullString{String: "", Valid: false},
Token: sql.NullString{String: "", Valid: false},
Hash: sql.NullString{String: "", Valid: false},
Active: sql.NullBool{Bool: false, Valid: false},
Admin: sql.NullBool{Bool: false, Valid: false},
}
// setup tests
tests := []struct {
user *User
want *User
}{
{
user: testUser(),
want: testUser(),
},
{
user: u,
want: nil,
},
{
user: new(User),
want: want,
},
}
// run tests
for _, test := range tests {
got := test.user.Nullify()
if !reflect.DeepEqual(got, test.want) {
t.Errorf("Nullify is %v, want %v", got, test.want)
}
}
}
func TestDatabase_User_ToLibrary(t *testing.T) {
// setup types
want := new(library.User)
want.SetID(1)
want.SetName("octocat")
want.SetToken("superSecretToken")
want.SetHash("superSecretHash")
want.SetFavorites([]string{"github/octocat"})
want.SetActive(true)
want.SetAdmin(false)
// run test
got := testUser().ToLibrary()
if !reflect.DeepEqual(got, want) {
t.Errorf("ToLibrary is %v, want %v", got, want)
}
}
func TestDatabase_User_Validate(t *testing.T) {
// setup tests
tests := []struct {
failure bool
user *User
}{
{
failure: false,
user: testUser(),
},
{ // no name set for user
failure: true,
user: &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Token: sql.NullString{String: "superSecretToken", Valid: true},
Hash: sql.NullString{String: "superSecretHash", Valid: true},
},
},
{ // no token set for user
failure: true,
user: &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Name: sql.NullString{String: "octocat", Valid: true},
Hash: sql.NullString{String: "superSecretHash", Valid: true},
},
},
{ // no hash set for user
failure: true,
user: &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Name: sql.NullString{String: "octocat", Valid: true},
Token: sql.NullString{String: "superSecretToken", Valid: true},
},
},
{ // invalid name set for user
failure: true,
user: &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Name: sql.NullString{String: "!@#$%^&*()", Valid: true},
Token: sql.NullString{String: "superSecretToken", Valid: true},
Hash: sql.NullString{String: "superSecretHash", Valid: true},
},
},
{ // invalid favorites set for user
failure: true,
user: &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Name: sql.NullString{String: "octocat", Valid: true},
Token: sql.NullString{String: "superSecretToken", Valid: true},
Hash: sql.NullString{String: "superSecretHash", Valid: true},
Favorites: exceededFavorites(),
},
},
}
// run tests
for _, test := range tests {
err := test.user.Validate()
if test.failure {
if err == nil {
t.Errorf("Validate should have returned err")
}
continue
}
if err != nil {
t.Errorf("Validate returned err: %v", err)
}
}
}
func TestDatabase_UserFromLibrary(t *testing.T) {
// setup types
u := new(library.User)
u.SetID(1)
u.SetName("octocat")
u.SetToken("superSecretToken")
u.SetHash("superSecretHash")
u.SetFavorites([]string{"github/octocat"})
u.SetActive(true)
u.SetAdmin(false)
want := testUser()
// run test
got := UserFromLibrary(u)
if !reflect.DeepEqual(got, want) {
t.Errorf("UserFromLibrary is %v, want %v", got, want)
}
}
// testUser is a test helper function to create a User
// type with all fields set to a fake value.
func testUser() *User {
return &User{
ID: sql.NullInt64{Int64: 1, Valid: true},
Name: sql.NullString{String: "octocat", Valid: true},
Token: sql.NullString{String: "superSecretToken", Valid: true},
Hash: sql.NullString{String: "superSecretHash", Valid: true},
Favorites: []string{"github/octocat"},
Active: sql.NullBool{Bool: true, Valid: true},
Admin: sql.NullBool{Bool: false, Valid: true},
}
}
// exceededFavorites returns a list of valid favorites that exceed the maximum size
func exceededFavorites() []string {
// initialize empty favorites
favorites := []string{}
// add enough favorites to exceed the character limit
for i := 0; i < 500; i++ {
// construct favorite
// use i to adhere to unique favorites
favorite := "github/octocat-" + strconv.Itoa(i)
favorites = append(favorites, favorite)
}
return favorites
}
| TestDatabase_User_Nullify |
hamlist.component.ts | import { Component, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-hamlist',
templateUrl: './hamlist.component.html',
styleUrls: ['./hamlist.component.css'],
animations: [
trigger('changeTrigger', [
state('out', style({
transform: 'translate3d(150%,0,0)'
})),
state('in', style({
transform: 'translate3d(70%,0,0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
])
]
})
export class | {
@Input() currentState;
}
| HamlistComponent |
id.go | package utils
import (
"crypto/sha1"
"fmt"
"os"
"github.com/jxskiss/base62"
"github.com/lithammer/shortuuid/v3"
)
const (
RoomPrefix = "RM_"
NodePrefix = "ND_"
ParticipantPrefix = "PA_"
TrackPrefix = "TR_"
APIKeyPrefix = "API"
RecordingPrefix = "RR_"
RPCPrefix = "RPC"
)
func NewGuid(prefix string) string {
return prefix + shortuuid.New()[:12]
}
// Creates a hashed ID from a unique string
func HashedID(id string) string {
h := sha1.New()
h.Write([]byte(id))
val := h.Sum(nil)
return base62.EncodeToString(val)
}
func LocalNodeID() (string, error) {
hostname, err := os.Hostname()
if err != nil |
return fmt.Sprintf("%s%s", NodePrefix, HashedID(hostname)[:8]), nil
}
| {
return "", err
} |
dataset.rs | use std::ffi::CString;
use std::path::Path;
use std::ptr::null_mut;
use libc::c_int;
use vector::Layer;
use vector::driver::_register_drivers;
use gdal_major_object::MajorObject;
use metadata::Metadata;
use gdal_sys::{self, GDALMajorObjectH, OGRDataSourceH, OGRLayerH, OGRwkbGeometryType};
use utils::_last_null_pointer_err;
use errors::*;
/// Vector dataset
///
/// ```
/// use std::path::Path;
/// use gdal::vector::Dataset;
///
/// let mut dataset = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap();
/// println!("Dataset has {} layers", dataset.count());
/// ```
pub struct Dataset {
c_dataset: OGRDataSourceH,
layers: Vec<Layer>,
}
impl MajorObject for Dataset {
unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
self.c_dataset
}
}
impl Metadata for Dataset {}
impl Dataset {
pub unsafe fn _with_c_dataset(c_dataset: OGRDataSourceH) -> Dataset {
Dataset{c_dataset, layers: vec!()}
}
/// Open the dataset at `path`.
pub fn open(path: &Path) -> Result<Dataset> {
_register_drivers();
let filename = path.to_string_lossy();
let c_filename = CString::new(filename.as_ref())?;
let c_dataset = unsafe { gdal_sys::OGROpen(c_filename.as_ptr(), 0, null_mut()) };
if c_dataset.is_null() {
Err(_last_null_pointer_err("OGROpen"))?;
};
Ok(Dataset{c_dataset, layers: vec!()})
}
/// Get number of layers.
pub fn count(&self) -> isize {
(unsafe { gdal_sys::OGR_DS_GetLayerCount(self.c_dataset) }) as isize
}
fn _child_layer(&mut self, c_layer: OGRLayerH) -> &Layer {
let layer = unsafe { Layer::_with_c_layer(c_layer) };
self.layers.push(layer);
self.layers.last().unwrap()
}
/// Get layer number `idx`.
pub fn layer(&mut self, idx: isize) -> Result<&Layer> |
/// Get layer with `name`.
pub fn layer_by_name(&mut self, name: &str) -> Result<&Layer> {
let c_name = CString::new(name)?;
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayerByName(self.c_dataset, c_name.as_ptr()) };
if c_layer.is_null() {
Err(_last_null_pointer_err("OGR_DS_GetLayerByName"))?;
}
Ok(self._child_layer(c_layer))
}
/// Create a new layer with a blank definition.
pub fn create_layer(&mut self) -> Result<&mut Layer> {
let c_name = CString::new("")?;
let c_layer = unsafe { gdal_sys::OGR_DS_CreateLayer(
self.c_dataset,
c_name.as_ptr(),
null_mut(),
OGRwkbGeometryType::wkbUnknown,
null_mut(),
) };
if c_layer.is_null() {
Err(_last_null_pointer_err("OGR_DS_CreateLayer"))?;
};
self._child_layer(c_layer);
Ok(self.layers.last_mut().unwrap()) // TODO: is this safe?
}
}
impl Drop for Dataset {
fn drop(&mut self) {
unsafe { gdal_sys::OGR_DS_Destroy(self.c_dataset); }
}
}
| {
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayer(self.c_dataset, idx as c_int) };
if c_layer.is_null() {
Err(_last_null_pointer_err("OGR_DS_GetLayer"))?;
}
Ok(self._child_layer(c_layer))
} |
settings-image-settings.tsx | import { view } from "react-easy-state";
import { state } from "../../../../../state";
import { Button, SpacedItems, Section } from "./styled";
export const SettingsImageSettings = view(() => {
if (state.settings.cleanVersion) return null;
return (
<>
{state.image.imageSourceWithFallback === "LOCAL" && (
<Section title="Image settings">
<SpacedItems horizontal>
<Button onClick={() => state.image.shiftImageLocalIndex(-1)}>Previous</Button>
<Button onClick={state.image.setImageLocalRandom}>Random</Button>
<Button onClick={() => state.image.shiftImageLocalIndex(1)}>Next</Button>
</SpacedItems>
</Section>
)} | </>
);
}); |
|
jws.go | package acme
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"fmt"
"net/http"
"sync"
"gopkg.in/square/go-jose.v1"
)
type jws struct {
directoryURL string
privKey crypto.PrivateKey
nonces []string
sync.Mutex
}
func keyAsJWK(key interface{}) *jose.JsonWebKey {
switch k := key.(type) {
case *ecdsa.PublicKey:
return &jose.JsonWebKey{Key: k, Algorithm: "EC"}
case *rsa.PublicKey:
return &jose.JsonWebKey{Key: k, Algorithm: "RSA"}
default:
return nil
}
}
// Posts a JWS signed message to the specified URL
func (j *jws) post(url string, content []byte) (*http.Response, error) {
signedContent, err := j.signContent(content)
if err != nil {
return nil, err
}
resp, err := httpPost(url, "application/jose+json", bytes.NewBuffer([]byte(signedContent.FullSerialize())))
if err != nil {
return nil, err
}
j.getNonceFromResponse(resp)
return resp, err
}
func (j *jws) signContent(content []byte) (*jose.JsonWebSignature, error) {
var alg jose.SignatureAlgorithm
switch k := j.privKey.(type) {
case *rsa.PrivateKey:
alg = jose.RS256
case *ecdsa.PrivateKey:
if k.Curve == elliptic.P256() {
alg = jose.ES256
} else if k.Curve == elliptic.P384() {
alg = jose.ES384
}
}
signer, err := jose.NewSigner(alg, j.privKey)
if err != nil {
return nil, err
}
signer.SetNonceSource(j)
signed, err := signer.Sign(content)
if err != nil {
return nil, err
} | func (j *jws) getNonceFromResponse(resp *http.Response) error {
j.Lock()
defer j.Unlock()
nonce := resp.Header.Get("Replay-Nonce")
if nonce == "" {
return fmt.Errorf("Server did not respond with a proper nonce header.")
}
j.nonces = append(j.nonces, nonce)
return nil
}
func (j *jws) getNonce() error {
resp, err := httpHead(j.directoryURL)
if err != nil {
return err
}
return j.getNonceFromResponse(resp)
}
func (j *jws) Nonce() (string, error) {
nonce := ""
if len(j.nonces) == 0 {
err := j.getNonce()
if err != nil {
return nonce, err
}
}
if len(j.nonces) == 0 {
return "", fmt.Errorf("Can't get nonce")
}
j.Lock()
defer j.Unlock()
nonce, j.nonces = j.nonces[len(j.nonces)-1], j.nonces[:len(j.nonces)-1]
return nonce, nil
} | return signed, nil
}
|
t01_inline.rs | //! Tests auto-converted from "sass-spec/spec/non_conformant/parser/interpolate/11_escaped_literal/01_inline.hrx"
#[allow(unused)]
fn runner() -> crate::TestRunner {
super::runner()
}
#[test]
fn test() | {
assert_eq!(
runner().ok(".result {\
\n output: l\\\\ite\\ral;\
\n output: #{l\\\\ite\\ral};\
\n output: \"[#{l\\\\ite\\ral}]\";\
\n output: \"#{l\\\\ite\\ral}\";\
\n output: \'#{l\\\\ite\\ral}\';\
\n output: \"[\'#{l\\\\ite\\ral}\']\";\
\n}\n"),
".result {\
\n output: l\\\\iteral;\
\n output: l\\\\iteral;\
\n output: \"[l\\\\\\\\iteral]\";\
\n output: \"l\\\\\\\\iteral\";\
\n output: \"l\\\\\\\\iteral\";\
\n output: \"[\'l\\\\\\\\iteral\']\";\
\n}\n"
);
} |
|
middlewares.py | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from typing import Iterable
from scrapy import signals
from .items import TransportInfo, SeatInfo
from .settings import MOCKED_DATA_PATH
class TicketerSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class TicketerDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None |
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class MockedSpiderMiddleware(object):
def process_spider_output(self, response, result: Iterable[TransportInfo], spider):
with open(MOCKED_DATA_PATH, 'w') as fout:
fout.write(response.body)
for i in result:
yield i
class TransportScheduleSpiderMiddleware(object):
def process_spider_output(self, response, result: Iterable[TransportInfo], spider):
required_min_seats = int(spider.settings['MIN_SEATS'])
required_transport_num = spider.settings['NUM']
required_seat_type = spider.settings['SEAT_TYPE']
def eligible_transport(transport: TransportInfo) -> bool:
return required_transport_num is None or required_transport_num == transport['id']
def eligible_seat(seat: SeatInfo) -> bool:
return required_seat_type is None or seat['type'] == required_seat_type
def eligible_seats(seats: Iterable[SeatInfo]) -> Iterable[SeatInfo]:
return filter(eligible_seat, seats)
def available_seat(seat: SeatInfo) -> bool:
remaining = seat['remaining']
if remaining is None:
return False
return int(remaining) >= required_min_seats
found_any = False
for transport in result:
found = False
if eligible_transport(transport):
seats = eligible_seats(transport['seats'])
for seat in seats:
if available_seat(seat):
found = True
found_any = found_any or found
if found:
yield transport
if not found_any:
yield response.request
class MockedDownloaderMiddleware(object):
def process_request(self, request, spider):
from scrapy.http import HtmlResponse
with open(MOCKED_DATA_PATH, 'r') as fin:
body = fin.read()
response = HtmlResponse(url=request.url,
body=body)
return response |
def process_response(self, request, response, spider):
# Called with the response returned from the downloader. |
StarRatingView.tsx | import * as React from "react";
import { IViewProps } from "./IViewProps";
import { IStarRatingProps } from "../../models/field.properties";
const Rate = React.lazy(() => import(/* webpackChunkName: "starrating" */ "antd/es/rate"));
import { useObserver } from "mobx-react";
export const StarRatingView: React.FC<IViewProps> = (props) => {
let component = props.field.componentProps as IStarRatingProps;
return useObserver(() => { | <Rate {...component} onChange={props.onChange}/>
</React.Suspense>
});
}; | return <React.Suspense fallback=""> |
annotationCustomSections.component.ts | import { IComponentOptions, IController, ISCEService, IInterpolateService, module } from 'angular';
import { get, partition } from 'lodash';
import * as DOMPurify from 'dompurify';
interface IAnnotationsMap {
[key: string]: string;
}
interface ICustomSection {
title: string;
key: string;
isHtml: boolean;
content: string;
}
interface ICustomSectionMap {
[key: string]: ICustomSection[];
}
class | implements IController {
private resource: any;
public manifest: any;
public customSections: ICustomSectionMap;
public static $inject = ['$sce', '$interpolate'];
constructor(private $sce: ISCEService, private $interpolate: IInterpolateService) {}
public $onInit() {
const annotations: IAnnotationsMap = get(this, ['manifest', 'metadata', 'annotations']);
if (annotations == null) {
return;
}
this.populateCustomSections(annotations);
}
private populateCustomSections(annotations: IAnnotationsMap) {
const customSections: ICustomSectionMap = Object.keys(annotations).reduce(
(memo: ICustomSectionMap, annotationKey: string) => {
const entry = this.annotationToEntry(annotations[annotationKey], annotationKey);
if (entry != null && entry.title) {
memo[entry.title] = memo[entry.title] || [];
memo[entry.title].push(entry);
}
return memo;
},
{},
);
// Sort section contents such that text entries appear before HTML entries.
this.customSections = Object.keys(customSections).reduce((memo: ICustomSectionMap, sectionTitle: string) => {
const entriesHtmlText = partition(customSections[sectionTitle], section => section.isHtml);
memo[sectionTitle] = entriesHtmlText[1].concat(entriesHtmlText[0]);
return memo;
}, {});
}
private annotationToEntry(content: string, annotationKey: string): ICustomSection {
const parsed = this.parseAnnotationKey(annotationKey);
if (parsed == null) {
return null;
}
if (this.resource && content.includes('{{')) {
content = this.$interpolate(content)({ ...this.resource });
}
return {
title: parsed.title.replace(/-/g, ' ').trim(),
key: parsed.key.replace(/-/g, ' ').trim(),
content: parsed.isHtml ? this.sanitizeContent(content) : content,
isHtml: parsed.isHtml,
};
}
private parseAnnotationKey(annotationKey: string): { title: string; key: string; isHtml: boolean } {
const keyParts = /([^.]+)\.details\.(html\.)?spinnaker\.io(?:\/(.*))?/.exec(annotationKey);
if (keyParts == null || keyParts.length !== 4) {
return null;
}
return {
title: keyParts[1] || '',
key: keyParts[3] || '',
isHtml: !!keyParts[2],
};
}
private sanitizeContent(unsanitized: string): any {
const sanitized = DOMPurify.sanitize(unsanitized, {
ADD_ATTR: ['target'],
});
return this.$sce.trustAsHtml(sanitized);
}
}
const kubernetesAnnotationCustomSectionsComponent: IComponentOptions = {
bindings: { manifest: '<', resource: '<' },
controller: ['$sce', '$interpolate', KubernetesAnnotationCustomSections],
controllerAs: 'ctrl',
template: `
<collapsible-section expanded="true" ng-if="ctrl.manifest" ng-repeat="(section, entries) in ctrl.customSections" heading="{{ section }}">
<div ng-repeat="entry in entries">
<div ng-if="entry.isHtml" ng-bind-html="entry.content"></div>
<div ng-if="!entry.isHtml">
<span ng-if="entry.key" style="font-weight:bold">{{ entry.key }}</span>
<span>{{ entry.content }}</span>
</div>
</div>
</collapsible-section>
`,
};
export const KUBERNETES_ANNOTATION_CUSTOM_SECTIONS = 'spinnaker.kubernetes.v2.manifest.annotation.custom.sections';
module(KUBERNETES_ANNOTATION_CUSTOM_SECTIONS, []).component(
'kubernetesAnnotationCustomSections',
kubernetesAnnotationCustomSectionsComponent,
);
| KubernetesAnnotationCustomSections |
index.ts | import addon from "../../core/addon";
import { NodeWidget } from "../QWidget";
import { BaseWidgetEvents } from "../../core/EventWidget";
import { NativeElement } from "../../core/Component";
export const QRadioButtonEvents = Object.freeze({
...BaseWidgetEvents
});
export class | extends NodeWidget {
native: NativeElement;
constructor(parent?: NodeWidget) {
let native;
if (parent) {
native = new addon.QRadioButton(parent.native);
} else {
native = new addon.QRadioButton();
}
super(native);
this.native = native;
this.parent = parent;
// bind member functions
this.setText.bind(this);
}
setText(text: string | number) {
this.native.setText(`${text}`);
}
}
| QRadioButton |
lib.rs | /* EVMC: Ethereum Client-VM Connector API.
* Copyright 2019 The EVMC Authors.
* Licensed under the Apache License, Version 2.0.
*/
mod container;
pub use container::EvmcContainer;
pub use evmc_sys as ffi;
pub trait EvmcVm {
fn init() -> Self;
fn execute(&self, code: &[u8], context: &ExecutionContext) -> ExecutionResult;
}
/// EVMC result structure.
pub struct ExecutionResult {
status_code: ffi::evmc_status_code,
gas_left: i64,
output: Option<Vec<u8>>,
create_address: Option<ffi::evmc_address>,
}
/// EVMC context structure. Exposes the EVMC host functions, message data, and transaction context
/// to the executing VM.
pub struct ExecutionContext<'a> {
message: &'a ffi::evmc_message,
context: &'a mut ffi::evmc_context,
tx_context: ffi::evmc_tx_context,
}
impl ExecutionResult {
pub fn new(
_status_code: ffi::evmc_status_code,
_gas_left: i64,
_output: Option<Vec<u8>>,
) -> Self {
ExecutionResult {
status_code: _status_code,
gas_left: _gas_left,
output: _output,
create_address: None,
}
}
pub fn failure() -> Self {
ExecutionResult::new(ffi::evmc_status_code::EVMC_FAILURE, 0, None)
}
pub fn success(_gas_left: i64, _output: Option<Vec<u8>>) -> Self {
ExecutionResult::new(ffi::evmc_status_code::EVMC_SUCCESS, _gas_left, _output)
}
pub fn get_status_code(&self) -> ffi::evmc_status_code {
self.status_code
}
pub fn get_gas_left(&self) -> i64 {
self.gas_left
}
pub fn get_output(&self) -> Option<&Vec<u8>> {
self.output.as_ref()
}
pub fn get_create_address(&self) -> Option<&ffi::evmc_address> {
self.create_address.as_ref()
}
}
impl<'a> ExecutionContext<'a> {
pub fn new(_message: &'a ffi::evmc_message, _context: &'a mut ffi::evmc_context) -> Self {
let _tx_context = unsafe {
assert!((*(_context.host)).get_tx_context.is_some());
(*(_context.host)).get_tx_context.unwrap()(_context as *mut ffi::evmc_context)
};
ExecutionContext {
message: _message,
context: _context,
tx_context: _tx_context,
}
}
pub fn get_message(&self) -> &ffi::evmc_message {
&self.message
}
pub fn get_tx_context(&mut self) -> &ffi::evmc_tx_context {
&self.tx_context
}
pub fn account_exists(&mut self, address: &ffi::evmc_address) -> bool {
unsafe {
assert!((*self.context.host).account_exists.is_some());
(*self.context.host).account_exists.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
)
}
}
pub fn get_storage(
&mut self,
address: &ffi::evmc_address,
key: &ffi::evmc_bytes32,
) -> ffi::evmc_bytes32 {
unsafe {
assert!((*self.context.host).get_storage.is_some());
(*self.context.host).get_storage.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
key as *const ffi::evmc_bytes32,
)
}
}
pub fn set_storage(
&mut self,
address: &ffi::evmc_address,
key: &ffi::evmc_bytes32,
value: &ffi::evmc_bytes32,
) -> ffi::evmc_storage_status {
unsafe {
assert!((*self.context.host).set_storage.is_some());
(*self.context.host).set_storage.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
key as *const ffi::evmc_bytes32,
value as *const ffi::evmc_bytes32,
)
}
}
pub fn get_balance(&mut self, address: &ffi::evmc_address) -> ffi::evmc_bytes32 {
unsafe {
assert!((*self.context.host).get_balance.is_some());
(*self.context.host).get_balance.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
)
}
}
pub fn get_code_size(&mut self, address: &ffi::evmc_address) -> usize {
unsafe {
assert!((*self.context.host).get_code_size.is_some());
(*self.context.host).get_code_size.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
)
}
}
pub fn get_code_hash(&mut self, address: &ffi::evmc_address) -> ffi::evmc_bytes32 {
unsafe {
assert!((*self.context.host).get_code_size.is_some());
(*self.context.host).get_code_hash.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
)
}
}
pub fn copy_code(
&mut self,
address: &ffi::evmc_address,
code_offset: usize,
buffer: &mut [u8],
) -> usize {
unsafe {
assert!((*self.context.host).copy_code.is_some());
(*self.context.host).copy_code.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
code_offset,
// FIXME: ensure that alignment of the array elements is OK
buffer.as_mut_ptr(),
buffer.len(),
)
}
}
pub fn selfdestruct(&mut self, address: &ffi::evmc_address, beneficiary: &ffi::evmc_address) {
unsafe {
assert!((*self.context.host).selfdestruct.is_some());
(*self.context.host).selfdestruct.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
beneficiary as *const ffi::evmc_address,
)
}
}
pub fn call(&mut self, message: &ffi::evmc_message) -> ExecutionResult {
unsafe {
assert!((*self.context.host).call.is_some());
(*self.context.host).call.unwrap()(
self.context as *mut ffi::evmc_context,
message as *const ffi::evmc_message,
)
.into()
}
}
pub fn get_block_hash(&mut self, num: i64) -> ffi::evmc_bytes32 {
unsafe {
assert!((*self.context.host).get_block_hash.is_some());
(*self.context.host).get_block_hash.unwrap()(
self.context as *mut ffi::evmc_context,
num,
)
}
}
pub fn emit_log(
&mut self,
address: &ffi::evmc_address,
data: &[u8],
topics: &[ffi::evmc_bytes32],
) {
unsafe {
assert!((*self.context.host).emit_log.is_some());
(*self.context.host).emit_log.unwrap()(
self.context as *mut ffi::evmc_context,
address as *const ffi::evmc_address,
// FIXME: ensure that alignment of the array elements is OK
data.as_ptr(),
data.len(),
topics.as_ptr(),
topics.len(),
)
}
}
}
impl From<ffi::evmc_result> for ExecutionResult {
fn from(result: ffi::evmc_result) -> Self {
let ret = ExecutionResult {
status_code: result.status_code,
gas_left: result.gas_left,
output: if !result.output_data.is_null() {
// Pre-allocate a vector.
let mut buf: Vec<u8> = Vec::with_capacity(result.output_size);
unsafe {
// Set the len of the vec manually.
buf.set_len(result.output_size);
// Copy from the C struct's buffer to the vec's buffer.
std::ptr::copy(result.output_data, buf.as_mut_ptr(), result.output_size);
}
Some(buf)
} else {
None
},
// Consider it is always valid.
create_address: Some(result.create_address),
};
// Release allocated ffi struct.
if result.release.is_some() {
unsafe {
result.release.unwrap()(&result as *const ffi::evmc_result);
}
}
ret
}
}
fn allocate_output_data(output: Option<Vec<u8>>) -> (*const u8, usize) {
if let Some(buf) = output {
let buf_len = buf.len();
// Manually allocate heap memory for the new home of the output buffer.
let memlayout = std::alloc::Layout::from_size_align(buf_len, 1).expect("Bad layout");
let new_buf = unsafe { std::alloc::alloc(memlayout) };
unsafe {
// Copy the data into the allocated buffer.
std::ptr::copy(buf.as_ptr(), new_buf, buf_len);
}
(new_buf as *const u8, buf_len)
} else {
(std::ptr::null(), 0)
}
}
unsafe fn deallocate_output_data(ptr: *const u8, size: usize) {
if !ptr.is_null() {
let buf_layout = std::alloc::Layout::from_size_align(size, 1).expect("Bad layout");
std::alloc::dealloc(ptr as *mut u8, buf_layout);
}
}
/// Returns a pointer to a heap-allocated evmc_result.
impl Into<*const ffi::evmc_result> for ExecutionResult {
fn into(self) -> *const ffi::evmc_result {
let mut result: ffi::evmc_result = self.into();
result.release = Some(release_heap_result);
Box::into_raw(Box::new(result))
}
}
/// Callback to pass across FFI, de-allocating the optional output_data.
extern "C" fn release_heap_result(result: *const ffi::evmc_result) {
unsafe {
let tmp = Box::from_raw(result as *mut ffi::evmc_result);
deallocate_output_data(tmp.output_data, tmp.output_size);
}
}
/// Returns a pointer to a stack-allocated evmc_result.
impl Into<ffi::evmc_result> for ExecutionResult {
fn into(self) -> ffi::evmc_result {
let (buffer, len) = allocate_output_data(self.output);
ffi::evmc_result {
status_code: self.status_code,
gas_left: self.gas_left,
output_data: buffer,
output_size: len,
release: Some(release_stack_result),
create_address: if self.create_address.is_some() {
self.create_address.unwrap()
} else {
ffi::evmc_address { bytes: [0u8; 20] }
},
padding: [0u8; 4],
}
}
}
/// Callback to pass across FFI, de-allocating the optional output_data.
extern "C" fn release_stack_result(result: *const ffi::evmc_result) {
unsafe {
let tmp = *result;
deallocate_output_data(tmp.output_data, tmp.output_size);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_result() {
let r = ExecutionResult::new(ffi::evmc_status_code::EVMC_FAILURE, 420, None);
assert!(r.get_status_code() == ffi::evmc_status_code::EVMC_FAILURE);
assert!(r.get_gas_left() == 420);
assert!(r.get_output().is_none());
assert!(r.get_create_address().is_none());
}
// Test-specific helper to dispose of execution results in unit tests
extern "C" fn test_result_dispose(result: *const ffi::evmc_result) {
unsafe {
if !result.is_null() {
let owned = *result;
Vec::from_raw_parts(
owned.output_data as *mut u8,
owned.output_size,
owned.output_size,
);
}
}
}
#[test]
fn from_ffi() {
let f = ffi::evmc_result {
status_code: ffi::evmc_status_code::EVMC_SUCCESS,
gas_left: 1337,
output_data: Box::into_raw(Box::new([0xde, 0xad, 0xbe, 0xef])) as *const u8,
output_size: 4,
release: Some(test_result_dispose),
create_address: ffi::evmc_address { bytes: [0u8; 20] },
padding: [0u8; 4],
};
let r: ExecutionResult = f.into();
assert!(r.get_status_code() == ffi::evmc_status_code::EVMC_SUCCESS);
assert!(r.get_gas_left() == 1337);
assert!(r.get_output().is_some());
assert!(r.get_output().unwrap().len() == 4);
assert!(r.get_create_address().is_some());
}
#[test]
fn into_heap_ffi() {
let r = ExecutionResult::new(
ffi::evmc_status_code::EVMC_FAILURE,
420,
Some(vec![0xc0, 0xff, 0xee, 0x71, 0x75]),
);
let f: *const ffi::evmc_result = r.into();
assert!(!f.is_null());
unsafe {
assert!((*f).status_code == ffi::evmc_status_code::EVMC_FAILURE);
assert!((*f).gas_left == 420);
assert!(!(*f).output_data.is_null());
assert!((*f).output_size == 5);
assert!(
std::slice::from_raw_parts((*f).output_data, 5) as &[u8]
== &[0xc0, 0xff, 0xee, 0x71, 0x75]
);
assert!((*f).create_address.bytes == [0u8; 20]);
if (*f).release.is_some() {
(*f).release.unwrap()(f);
}
}
}
#[test]
fn into_heap_ffi_empty_data() {
let r = ExecutionResult::new(ffi::evmc_status_code::EVMC_FAILURE, 420, None);
let f: *const ffi::evmc_result = r.into();
assert!(!f.is_null());
unsafe {
assert!((*f).status_code == ffi::evmc_status_code::EVMC_FAILURE);
assert!((*f).gas_left == 420);
assert!((*f).output_data.is_null());
assert!((*f).output_size == 0);
assert!((*f).create_address.bytes == [0u8; 20]);
if (*f).release.is_some() {
(*f).release.unwrap()(f);
}
}
}
#[test]
fn into_stack_ffi() {
let r = ExecutionResult::new(
ffi::evmc_status_code::EVMC_FAILURE,
420,
Some(vec![0xc0, 0xff, 0xee, 0x71, 0x75]),
);
let f: ffi::evmc_result = r.into();
unsafe {
assert!(f.status_code == ffi::evmc_status_code::EVMC_FAILURE);
assert!(f.gas_left == 420);
assert!(!f.output_data.is_null());
assert!(f.output_size == 5);
assert!(
std::slice::from_raw_parts(f.output_data, 5) as &[u8]
== &[0xc0, 0xff, 0xee, 0x71, 0x75]
);
assert!(f.create_address.bytes == [0u8; 20]);
if f.release.is_some() {
f.release.unwrap()(&f);
}
}
}
#[test]
fn into_stack_ffi_empty_data() {
let r = ExecutionResult::new(ffi::evmc_status_code::EVMC_FAILURE, 420, None);
let f: ffi::evmc_result = r.into();
unsafe {
assert!(f.status_code == ffi::evmc_status_code::EVMC_FAILURE);
assert!(f.gas_left == 420);
assert!(f.output_data.is_null());
assert!(f.output_size == 0);
assert!(f.create_address.bytes == [0u8; 20]);
if f.release.is_some() {
f.release.unwrap()(&f);
}
}
}
unsafe extern "C" fn get_dummy_tx_context(
_context: *mut ffi::evmc_context,
) -> ffi::evmc_tx_context {
ffi::evmc_tx_context {
tx_gas_price: ffi::evmc_uint256be { bytes: [0u8; 32] },
tx_origin: ffi::evmc_address { bytes: [0u8; 20] },
block_coinbase: ffi::evmc_address { bytes: [0u8; 20] },
block_number: 42,
block_timestamp: 235117,
block_gas_limit: 105023,
block_difficulty: ffi::evmc_uint256be { bytes: [0xaa; 32] },
}
}
unsafe extern "C" fn get_dummy_code_size(
_context: *mut ffi::evmc_context,
_addr: *const ffi::evmc_address,
) -> usize {
105023 as usize
}
// Update these when needed for tests
fn get_dummy_context() -> ffi::evmc_context {
ffi::evmc_context {
host: Box::into_raw(Box::new(ffi::evmc_host_interface {
account_exists: None,
get_storage: None,
set_storage: None,
get_balance: None,
get_code_size: Some(get_dummy_code_size),
get_code_hash: None,
copy_code: None,
selfdestruct: None,
call: None,
get_tx_context: Some(get_dummy_tx_context),
get_block_hash: None,
emit_log: None,
})),
}
}
// Helper to safely dispose of the dummy context, and not bring up false positives in the
// sanitizers.
fn dummy_context_dispose(context: ffi::evmc_context) {
unsafe {
Box::from_raw(context.host as *mut ffi::evmc_host_interface);
}
}
fn get_dummy_message() -> ffi::evmc_message {
ffi::evmc_message {
kind: ffi::evmc_call_kind::EVMC_CALL,
flags: 0,
depth: 123,
gas: 105023,
destination: ffi::evmc_address { bytes: [0u8; 20] },
sender: ffi::evmc_address { bytes: [0u8; 20] },
input_data: std::ptr::null() as *const u8,
input_size: 0,
value: ffi::evmc_uint256be { bytes: [0u8; 32] },
create2_salt: ffi::evmc_uint256be { bytes: [0u8; 32] },
}
}
#[test]
fn execution_context() {
let msg = get_dummy_message();
let mut context_raw = get_dummy_context();
// Make a copy here so we don't let get_dummy_context() go out of scope when called again
// in get_dummy_tx_context() and cause LLVM
// sanitizers to complain
let mut context_raw_copy = context_raw.clone();
let mut exe_context = ExecutionContext::new(&msg, &mut context_raw);
let a = exe_context.get_tx_context();
let b = unsafe { get_dummy_tx_context(&mut context_raw_copy as *mut ffi::evmc_context) };
assert_eq!(a.block_gas_limit, b.block_gas_limit);
assert_eq!(a.block_timestamp, b.block_timestamp);
assert_eq!(a.block_number, b.block_number);
let c = exe_context.get_message();
let d = get_dummy_message();
assert_eq!(c.kind, d.kind);
assert_eq!(c.flags, d.flags);
assert_eq!(c.depth, d.depth);
assert_eq!(c.gas, d.gas);
assert_eq!(c.input_data, d.input_data);
assert_eq!(c.input_size, d.input_size);
dummy_context_dispose(context_raw);
}
#[test]
fn get_code_size() {
let msg = get_dummy_message();
// This address is useless. Just a dummy parameter for the interface function.
let test_addr = ffi::evmc_address { bytes: [0u8; 20] };
let mut context_raw = get_dummy_context();
let mut exe_context = ExecutionContext::new(&msg, &mut context_raw);
let a: usize = 105023;
let b = exe_context.get_code_size(&test_addr);
assert_eq!(a, b);
| dummy_context_dispose(context_raw);
}
} | |
bench_limit_query_sql.rs | // Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
use criterion::criterion_group;
use criterion::criterion_main;
use criterion::Criterion;
use crate::suites::criterion_benchmark_suite;
fn | (c: &mut Criterion) {
let queries = vec!["SELECT number FROM numbers_mt(10000000) LIMIT 1"];
for query in queries {
criterion_benchmark_suite(c, query);
}
}
criterion_group!(benches, criterion_benchmark_limit_query);
criterion_main!(benches);
| criterion_benchmark_limit_query |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { SuperTabsModule } from '@ionic-super-tabs/angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot({ mode: 'ios', backButtonText: '' }),
AppRoutingModule,
SuperTabsModule.forRoot(),
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class | {}
| AppModule |
setter.go | package db2
import (
"database/sql"
"github.com/pkg/errors"
"github.com/rbastic/dyndao/object"
"github.com/rbastic/dyndao/schema"
sg "github.com/rbastic/dyndao/sqlgen"
"time"
)
// DynamicObjectSetter is used to dynamically set the values of an object by
// checking the necessary types (via sql.ColumnType, and what the driver tells
// us we have for column types)
func DynamicObjectSetter(s *sg.SQLGenerator, schTable *schema.Table, columnNames []string, columnPointers []interface{}, columnTypes []*sql.ColumnType, obj *object.Object) error {
// NOTE: Read this post for more info on why the code below is written this way:
// https://stackoverflow.com/questions/23507531/is-golangs-sql-package-incapable-of-ad-hoc-exploratory-queries/23507765#23507765
for i, v := range columnPointers {
ct := columnTypes[i]
typeName := schTable.GetColumn(columnNames[i]).DBType
if s.IsTimestampType(typeName) {
val := v.(*time.Time)
obj.Set(columnNames[i], *val)
continue
} else if s.IsStringType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
val := v.(*sql.NullString)
obj.Set(columnNames[i], *val)
} else {
val := v.(*string)
obj.Set(columnNames[i], *val)
}
continue
} else if s.IsNumberType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
val := v.(*sql.NullInt64)
if val.Valid {
obj.Set(columnNames[i], val.Int64)
}
} else {
val := v.(*int64)
obj.Set(columnNames[i], *val)
}
continue
} else if s.IsFloatingType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
val := v.(*sql.NullFloat64)
if val.Valid {
obj.Set(columnNames[i], val.Float64)
}
} else {
val := v.(*float64)
obj.Set(columnNames[i], *val)
}
continue
} else if s.IsLOBType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
val := v.(*sql.NullString)
obj.Set(columnNames[i], *val)
} else {
val := v.(*string)
obj.Set(columnNames[i], *val)
}
continue
}
return errors.New("DynamicObjectSetter: Unrecognized type: " + typeName)
}
return nil
}
func MakeColumnPointers(s *sg.SQLGenerator, schTable *schema.Table, columnNames []string, columnTypes []*sql.ColumnType) ([]interface{}, error) | {
sliceLen := len(columnNames)
columnPointers := make([]interface{}, sliceLen)
for i := 0; i < sliceLen; i++ {
ct := columnTypes[i]
typeName := schTable.GetColumn(columnNames[i]).DBType
if typeName == "" {
panic("dyndao MakeColumnPointers: ct.DatabaseTypeName() does not appear to be implemented - typeName was an empty string")
}
if s.IsNumberType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
var j sql.NullInt64
columnPointers[i] = &j
} else {
var j int64
columnPointers[i] = &j
}
} else if s.IsTimestampType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
var j time.Time
columnPointers[i] = &j
} else {
var j time.Time
columnPointers[i] = &j
}
} else if s.IsLOBType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
var s sql.NullString
columnPointers[i] = &s
} else {
var s string
columnPointers[i] = &s
}
} else if s.IsStringType(typeName) {
nullable, _ := ct.Nullable()
if nullable {
var s sql.NullString
columnPointers[i] = &s
} else {
var s string
columnPointers[i] = &s
}
} else {
return nil, errors.New("MakeColumnPointers: Unrecognized type: " + typeName)
}
}
return columnPointers, nil
} |
|
application-suite.route.js | (function () {
'use strict';
window.app
.config(TenantUserRoute);
TenantUserRoute.$inject = ['$stateProvider'];
function TenantUserRoute($stateProvider) {
let states = [
{ name: 'tenantUser.applicationSuite.home', url: '/application-suite', component: 'tenantUserApplicationSuiteHome' },
{ name: 'tenantUser.applicationSuite.home.applicationInstance', url: '/{applicationSuiteId}', component: 'tenantUserApplicationSuiteTableApplicationInstance' },
{ name: 'tenantUser.applicationSuite.formNewInstance', url: '/new-instance/{applicationSuiteId}', component: 'tenantUserApplicationSuiteFormNewInstance' },
{ name: 'tenantUser.applicationSuite.formUpdateInstance', url: '/reconfigure-instance/{applicationSuiteId}/{applicationInstanceId}', component: 'tenantUserApplicationSuiteFormUpdateApplicationInstance' },
{ name: 'tenantUser.applicationSuite.listSchedulerApplicationInstance', url: '/scheduler/{applicationSuiteId}/{applicationInstanceId}', component: 'tenantUserApplicationSuiteListSchedulerApplicationInstance' },
{ name: 'tenantUser.applicationSuite.output', url: '/output/{applicationSuiteId}/{applicationInstanceId}', component: 'tenantUserApplicationSuiteOutputApplicationInstance' }
];
states.forEach(state => $stateProvider.state(state));
} | })(); |
|
YandexDiskUploadAdapter.ts | import { createReadStream } from "fs";
import createClient = require("webdav");
export interface IYandexDiskUploadAdapterConfig {
username: string;
password: string;
uploadDir: string;
logger: { log: (...args: any[]) => void };
}
class | {
protected client: any;
constructor(protected config: IYandexDiskUploadAdapterConfig) {
this.client = createClient(
"https://webdav.yandex.ru",
this.config.username,
this.config.password,
);
}
public async list() {
const res = await this.client.getDirectoryContents(this.config.uploadDir);
return res;
}
public async remove(filename: string) {
return this.client.unlink(filename);
}
public async upload(inputFile: string, filename: string) {
const uploadDir = this.config.uploadDir + "/" + filename;
const out = this.client.createWriteStream(uploadDir);
const inp = createReadStream(inputFile);
return new Promise<void>((resolve, reject) => {
this.config.logger.log("Upload to " + uploadDir);
inp.pipe(out);
inp.on("error", (err) => reject(err));
out.on("error", (err: any) => reject(err));
inp.on("end", () => {
this.config.logger.log("Uploaded");
resolve();
});
});
}
}
export default YandexDiskUploadAdapter;
| YandexDiskUploadAdapter |
consumer.rs | use fluvio::{
ConsumerConfig as NativeConsumerConfig, PartitionConsumer as NativePartitionConsumer,
};
use js_sys::{Promise, Reflect};
use std::cell::RefCell;
use std::pin::Pin;
use std::rc::Rc;
use tokio_stream::Stream;
use tokio_stream::StreamExt;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::future_to_promise;
use crate::{FluvioError, Offset, Record};
use std::convert::{TryFrom, TryInto};
#[wasm_bindgen(typescript_custom_section)]
const CONSUMER_CONFIG_TYPE: &str = r#"
export type SmartStreamType = "filter" | "map" | "aggregate";
export type ConsumerConfig = {
max_bytes?: number,
smartstreamType?: SmartStreamType,
smartstream?: string,
accumulator?: string,
}
"#;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "SmartStream")]
pub type SmartStream;
#[wasm_bindgen(typescript_type = "ConsumerConfig")]
pub type ConsumerConfig;
}
impl TryFrom<ConsumerConfig> for NativeConsumerConfig {
type Error = String;
fn try_from(js: ConsumerConfig) -> Result<Self, String> {
let max_bytes = Reflect::get(&js, &"maxBytes".into())
.ok()
.and_then(|it| it.as_f64())
.map(|it| it.round() as i32);
let smartstream_type = Reflect::get(&js, &"smartstreamType".into())
.ok()
.and_then(|it| it.as_string());
let smartstream_base64 = Reflect::get(&js, &"smartstream".into())
.ok()
.and_then(|it| it.as_string());
let smartstream_accumulator = Reflect::get(&js, &"accumulator".into())
.ok()
.and_then(|it| it.as_string());
// Builder for NativeConsumerConfig
let mut builder = NativeConsumerConfig::builder();
if let Some(max_bytes) = max_bytes {
builder.max_bytes(max_bytes);
}
if let Some(wasm_base64) = smartstream_base64 {
let wasm = base64::decode(wasm_base64)
.map_err(|e| format!("Failed to decode SmartStream as a base64 string: {:?}", e))?;
match smartstream_type.as_deref() {
Some("filter") => {
builder.wasm_filter(wasm);
}
Some("map") => {
builder.wasm_map(wasm);
}
Some("aggregate") => {
let accumulator = smartstream_accumulator
.map(|acc| {
base64::decode(acc).map_err(|e| {
format!("Failed to decode Accumulator as a base64 string: {:?}", e)
})
})
.transpose()?
.unwrap_or_default();
builder.wasm_aggregate(wasm, accumulator);
}
_ => {
return Err(
"smartstreamType is required and must be 'filter', 'map', or 'aggregate'"
.to_string(),
)
}
}
}
let config = builder.build().map_err(|e| format!("{}", e))?;
Ok(config)
}
}
#[wasm_bindgen]
pub struct PartitionConsumerStream {
#[allow(clippy::type_complexity)]
inner: Rc<RefCell<Pin<Box<dyn Stream<Item = Result<Record, FluvioError>>>>>>,
}
#[wasm_bindgen]
impl PartitionConsumerStream {
pub fn next(&self) -> Promise {
let rc = self.inner.clone();
future_to_promise(async move {
match rc.borrow_mut().next().await.transpose() {
Ok(Some(val)) => Ok(val.into()),
Ok(None) => Err(FluvioError::from("No value".to_string()).into()),
Err(e) => Err(e.into()),
}
})
}
}
impl PartitionConsumerStream {
pub async fn next_val(&self) -> Option<Result<Record, FluvioError>> {
self.inner.borrow_mut().next().await
}
}
#[wasm_bindgen]
pub struct PartitionConsumer {
inner: NativePartitionConsumer,
}
#[wasm_bindgen]
impl PartitionConsumer {
pub async fn | (
self,
offset: Offset,
) -> Result<PartitionConsumerStream, wasm_bindgen::JsValue> {
Ok(PartitionConsumerStream {
inner: Rc::new(RefCell::new(Box::pin(
self.inner
.stream(offset.inner)
.await
.map_err(FluvioError::from)?
.map(|result| {
result
.map(|record| record.into())
.map_err(FluvioError::from)
}),
))),
})
}
#[wasm_bindgen(js_name = "streamWithConfig")]
pub async fn stream_with_config(
self,
offset: Offset,
config: ConsumerConfig,
) -> Result<PartitionConsumerStream, wasm_bindgen::JsValue> {
let config: NativeConsumerConfig = config.try_into()?;
Ok(PartitionConsumerStream {
inner: Rc::new(RefCell::new(Box::pin(
self.inner
.stream_with_config(offset.inner, config)
.await
.map_err(FluvioError::from)?
.map(|result| {
result
.map(|record| record.into())
.map_err(FluvioError::from)
}),
))),
})
}
}
impl From<NativePartitionConsumer> for PartitionConsumer {
fn from(inner: NativePartitionConsumer) -> Self {
Self { inner }
}
}
| stream |
capture_ae.go | // Copyright (C) 2016 Space Monkey, 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.
// +build appengine
package spacelog
import (
"fmt"
)
func | (fd int) error {
return fmt.Errorf("CaptureOutputToFd not supported on App Engine")
}
| CaptureOutputToFd |
test_nullable_class.py | # coding: utf-8
|
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import sys
import unittest
import petstore_api
from petstore_api.model.nullable_class import NullableClass
class TestNullableClass(unittest.TestCase):
"""NullableClass unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNullableClass(self):
"""Test NullableClass"""
# FIXME: construct object with mandatory attributes with example values
# model = NullableClass() # noqa: E501
pass
if __name__ == '__main__':
unittest.main() | """
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 |
bed.py | # -*- coding: utf-8 -*-
__author__ = 'bars'
from io import StringIO
import pandas as pd
from collections import defaultdict
class Bed:
"""description"""
def __init__(self, bed_file, mode='file'):
self.bed_file = bed_file
self.mode = mode
def get_header(self):
lines_to_skip = 0
header = defaultdict(list)
if self.mode == 'str':
for line in self.bed_file.split('\n'):
if line.startswith('track'):
header['track'].append(line)
lines_to_skip += 1
elif line.startswith('browser'):
header['browser'].append(line)
lines_to_skip += 1
else:
break
else:
with open(self.bed_file) as f:
lines = f.read().splitlines()
for line in lines:
if line.startswith('track'):
header['track'].append(line)
lines_to_skip += 1
elif line.startswith('browser'):
header['browser'].append(line)
lines_to_skip += 1
else:
break
return lines_to_skip, header
def from_file(self):
lines_to_skip, header = self.get_header()
df_bed = pd.read_csv(
self.bed_file,
sep='\t',
usecols=[0, 1, 2],
names=['CHR', 'START', 'END'],
dtype={'START': int, 'END': int},
skiprows=lines_to_skip
)
return df_bed
def | (self):
lines_to_skip, header = self.get_header()
df_bed = pd.read_csv(
StringIO(self.bed_file),
sep='\t',
usecols=[0, 1, 2],
names=['CHR', 'START', 'END'],
dtype={'START': int, 'END': int},
skiprows=lines_to_skip
)
return df_bed
| from_string |
go1.13.go | // Copyright 2021 xgfone
//
// 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. | // +build go1.13
package loadbalancer
import (
"context"
"io"
"net/http"
)
// newHTTPRequestWithContext is the compatibility of http.NewRequestWithContext.
func newHTTPRequestWithContext(ctx context.Context, method, url string,
body io.Reader) (*http.Request, error) {
return http.NewRequestWithContext(ctx, method, url, body)
} | // See the License for the specific language governing permissions and
// limitations under the License.
|
output.js | function | (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
// valid uses of arrays of function types
var x = [
function() {
return 1;
},
function() {
}
];
var r2 = x[0]();
var C = function C() {
"use strict";
_classCallCheck(this, C);
};
var y = [
C,
C
];
var r3 = new y[0]();
var a;
var b;
var c;
var z = [
a,
b,
c
];
var r4 = z[0];
var r5 = r4(''); // any not string
var r5b = r4(1);
var a2;
var b2;
var c2;
var z2 = [
a2,
b2,
c2
];
var r6 = z2[0];
var r7 = r6(''); // any not string
| _classCallCheck |
DivisiblePairCount2.py | def DivisiblePairCount(arr) :
|
if __name__ == "__main__":
#give input in form of a list -- [1,2,3]
arr = [int(item) for item in ''.join(list(input())[1:-1]).split(',')]
print(DivisiblePairCount(arr))
| count = 0
k = len(arr)
for i in range(0, k):
for j in range(i+1, k):
if (arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0):
count += 1
return count |
testAddTimeTravelToEdges.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created in February 2017 in ComplexCity Lab
@author: github.com/fpfaende
what it does
add metric distance between two nodes of an edge
distance is computed in specified projection system
to maximize precision
parameters
graph
epsg code for targeted projection
how it works
1 - prepare coordinate projection translation
2 - for each edge, get source node and target node
3 - create nodes lines and transform accordingly
4 - get line length and update metric distance dict
5 - update whole graph with metric distance dict
return
graph with new attribute length on edges
'''
import sys
import networkx as nx
sys.path.insert(0, '/Users/fabien/workspace/github/policosm')
from policosm.utils.levels import France
def pedestrianTime(graph):
pedestrian = {}
for edge in graph.edges():
u,v = edge
length = graph[u][v]['length']
level = graph[u][v]['level']
speed = France['speeds'][level]
pedestrianAllowed = True if level < 5 else False
if pedestrianAllowed:
pedestrianSpeed = speed if speed <= 5.0 else 5.0
pedestrian[edge] = length / (pedestrianSpeed* 1000 / 3600.0)
else:
|
return pedestrian
def motoristTime(graph):
motorist = {}
for edge in graph.edges():
u,v = edge
length = graph[u][v]['length']
level = graph[u][v]['level']
speed = France['speeds'][level]
motoristAllowed = True if level > 1 else False
if motoristAllowed:
motorist[edge] = length / (speed * 1000 / 3600.0)
else:
motorist[edge] = None
return motorist
def publicTransportation(graph, publicTransportLevels=[0,1,2,3,4,5,6,7,8]):
# TODO not implemented yet, sorry (*´ο`*)
return None
def addTimeTraveltoEdges(graph, transportation=['pedestrian, motorist']):
print 'motorist in transportation', 'motorist' in transportation
if 'pedestrian' in transportation:
nx.set_edge_attributes(graph, 'pedestrian', pedestrianTime(graph))
if 'motorist' in transportation:
nx.set_edge_attributes(graph, 'motorist', motoristTime(graph))
if 'publicTransportation' in transportation:
nx.set_edge_attributes(graph, 'publicTransportation', motoristTime(graph))
return graph
| pedestrian[edge] = None |
client_interceptors.go | // Copyright 2017 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_logrus
import (
"path"
"time"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// UnaryClientInterceptor returns a new unary client interceptor that optionally logs the execution of external gRPC calls.
func UnaryClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryClientInterceptor {
o := evaluateClientOpt(opts)
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
fields := newClientLoggerFields(ctx, method)
startTime := time.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client unary call")
return err
}
}
// StreamServerInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls.
func StreamClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamClientInterceptor {
o := evaluateClientOpt(opts)
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
fields := newClientLoggerFields(ctx, method)
startTime := time.Now()
clientStream, err := streamer(ctx, desc, cc, method, opts...)
logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client streaming call")
return clientStream, err
}
}
func logFinalClientLine(o *options, entry *logrus.Entry, startTime time.Time, err error, msg string) { | level := o.levelFunc(code)
durField, durVal := o.durationFunc(time.Now().Sub(startTime))
fields := logrus.Fields{
"grpc.code": code.String(),
durField: durVal,
}
if err != nil {
fields[logrus.ErrorKey] = err
}
levelLogf(
entry.WithFields(fields),
level,
msg)
}
func newClientLoggerFields(ctx context.Context, fullMethodString string) logrus.Fields {
service := path.Dir(fullMethodString)[1:]
method := path.Base(fullMethodString)
return logrus.Fields{
SystemField: "grpc",
KindField: "client",
"grpc.service": service,
"grpc.method": method,
}
} | code := o.codeFunc(err) |
compat.rs | //! This module provides a compatibility shim between traits in the `futures` and `tokio` crate.
use pin_project::pin_project;
use std::{
io,
pin::Pin,
task::{self, Poll},
};
/// `IoCompat` provides a compatibility shim between the `AsyncRead`/`AsyncWrite` traits provided by
/// the `futures` library and those provided by the `tokio` library since they are different and
/// incompatible with one another.
#[pin_project]
#[derive(Copy, Clone, Debug)]
pub struct IoCompat<T> {
#[pin]
inner: T,
}
impl<T> IoCompat<T> {
pub fn new(inner: T) -> Self {
IoCompat { inner }
}
}
impl<T> tokio::io::AsyncRead for IoCompat<T>
where
T: futures::io::AsyncRead,
{
fn | (
self: Pin<&mut Self>,
cx: &mut task::Context,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
futures::io::AsyncRead::poll_read(self.project().inner, cx, buf)
}
}
impl<T> futures::io::AsyncRead for IoCompat<T>
where
T: tokio::io::AsyncRead,
{
fn poll_read(
self: Pin<&mut Self>,
cx: &mut task::Context,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
tokio::io::AsyncRead::poll_read(self.project().inner, cx, buf)
}
}
impl<T> tokio::io::AsyncWrite for IoCompat<T>
where
T: futures::io::AsyncWrite,
{
fn poll_write(
self: Pin<&mut Self>,
cx: &mut task::Context,
buf: &[u8],
) -> Poll<io::Result<usize>> {
futures::io::AsyncWrite::poll_write(self.project().inner, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> {
futures::io::AsyncWrite::poll_flush(self.project().inner, cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> {
futures::io::AsyncWrite::poll_close(self.project().inner, cx)
}
}
impl<T> futures::io::AsyncWrite for IoCompat<T>
where
T: tokio::io::AsyncWrite,
{
fn poll_write(
self: Pin<&mut Self>,
cx: &mut task::Context,
buf: &[u8],
) -> Poll<io::Result<usize>> {
tokio::io::AsyncWrite::poll_write(self.project().inner, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> {
tokio::io::AsyncWrite::poll_flush(self.project().inner, cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<io::Result<()>> {
tokio::io::AsyncWrite::poll_shutdown(self.project().inner, cx)
}
}
| poll_read |
Format.ts | import {
arg,
Command,
format,
formatSchema,
getDMMF,
getSchemaPath,
HelpError,
} from '@prisma/sdk'
import chalk from 'chalk'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { formatms } from './utils/formatms'
/**
* $ prisma format
*/
export class | implements Command {
public static new(): Format {
return new Format()
}
private static help = format(`
Format a Prisma schema.
${chalk.bold('Usage')}
${chalk.dim('$')} prisma format [options]
${chalk.bold('Options')}
-h, --help Display this help message
--schema Custom path to your Prisma schema
${chalk.bold('Examples')}
With an existing Prisma schema
${chalk.dim('$')} prisma format
Or specify a Prisma schema path
${chalk.dim('$')} prisma format --schema=./schema.prisma
`)
public async parse(argv: string[]): Promise<string | Error> {
const before = Date.now()
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
'--schema': String,
'--telemetry-information': String,
})
if (args instanceof Error) {
return this.help(args.message)
}
if (args['--help']) {
return this.help()
}
const schemaPath = await getSchemaPath(args['--schema'])
if (!schemaPath) {
throw new Error(
`Could not find a ${chalk.bold(
'schema.prisma',
)} file that is required for this command.\nYou can either provide it with ${chalk.greenBright(
'--schema',
)}, set it as \`prisma.schema\` in your package.json or put it into the default location ${chalk.greenBright(
'./prisma/schema.prisma',
)} https://pris.ly/d/prisma-schema-location`,
)
}
console.log(
chalk.dim(
`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`,
),
)
const schema = fs.readFileSync(schemaPath, 'utf-8')
let output = await formatSchema({
schemaPath,
})
await getDMMF({
datamodel: output,
})
output = output.trimEnd() + os.EOL
fs.writeFileSync(schemaPath, output)
const after = Date.now()
return `Formatted ${chalk.underline(schemaPath)} in ${formatms(
after - before,
)} 🚀`
}
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${Format.help}`)
}
return Format.help
}
}
| Format |
certificates_test.go | package commands
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/digitalocean/doctl"
"github.com/digitalocean/doctl/do"
"github.com/digitalocean/godo"
"github.com/stretchr/testify/assert"
)
var (
testCertificate = do.Certificate{
Certificate: &godo.Certificate{
ID: "892071a0-bb95-49bc-8021-3afd67a210bf",
Name: "web-cert-01",
NotAfter: "2017-02-22T00:23:00Z",
SHA1Fingerprint: "dfcc9f57d86bf58e321c2c6c31c7a971be244ac7",
Created: "2017-02-08T16:02:37Z",
},
}
testCertificateList = do.Certificates{testCertificate}
)
func TestCertificateCommand(t *testing.T) |
func TestCertificateGetNoID(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
err := RunCertificateGet(config)
assert.Error(t, err)
})
}
func TestCertificateGet(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
cID := "892071a0-bb95-49bc-8021-3afd67a210bf"
tm.certificates.On("Get", cID).Return(&testCertificate, nil)
config.Args = append(config.Args, cID)
err := RunCertificateGet(config)
assert.NoError(t, err)
})
}
func TestCertificatesCreate(t *testing.T) {
tests := []struct {
desc string
certName string
DNSNames []string
privateKeyPath string
certLeafPath string
certChainPath string
certType string
certificate godo.CertificateRequest
}{
{
desc: "creates custom certificate",
certName: "custom-cert",
privateKeyPath: filepath.Join(os.TempDir(), "cer-key.crt"),
certLeafPath: filepath.Join(os.TempDir(), "leaf-cer.crt"),
certChainPath: filepath.Join(os.TempDir(), "cer-chain.crt"),
certificate: godo.CertificateRequest{
Name: "custom-cert",
PrivateKey: "-----BEGIN PRIVATE KEY-----",
LeafCertificate: "-----BEGIN CERTIFICATE-----",
CertificateChain: "-----BEGIN CERTIFICATE-----",
},
},
{
desc: "creates custom cerftificate without specifying chain",
certName: "cert-without-chain",
privateKeyPath: filepath.Join(os.TempDir(), "cer-key.crt"),
certLeafPath: filepath.Join(os.TempDir(), "leaf-cer.crt"),
certificate: godo.CertificateRequest{
Name: "cert-without-chain",
PrivateKey: "-----BEGIN PRIVATE KEY-----",
LeafCertificate: "-----BEGIN CERTIFICATE-----",
CertificateChain: "",
},
},
{
desc: "creates lets_encrypt cerftificate",
certName: "lets-encrypt-cert",
DNSNames: []string{"sampledomain.org", "api.sampledomain.org"},
certType: "lets_encrypt",
certificate: godo.CertificateRequest{
Name: "lets-encrypt-cert",
DNSNames: []string{"sampledomain.org", "api.sampledomain.org"},
Type: "lets_encrypt",
},
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
if test.privateKeyPath != "" {
pkErr := ioutil.WriteFile(test.privateKeyPath, []byte("-----BEGIN PRIVATE KEY-----"), 0600)
assert.NoError(t, pkErr)
defer os.Remove(test.privateKeyPath)
}
if test.certLeafPath != "" {
certErr := ioutil.WriteFile(test.certLeafPath, []byte("-----BEGIN CERTIFICATE-----"), 0600)
assert.NoError(t, certErr)
defer os.Remove(test.certLeafPath)
}
if test.certChainPath != "" {
certErr := ioutil.WriteFile(test.certChainPath, []byte("-----BEGIN CERTIFICATE-----"), 0600)
assert.NoError(t, certErr)
defer os.Remove(test.certChainPath)
}
tm.certificates.On("Create", &test.certificate).Return(&testCertificate, nil)
config.Doit.Set(config.NS, doctl.ArgCertificateName, test.certName)
if test.privateKeyPath != "" {
config.Doit.Set(config.NS, doctl.ArgPrivateKeyPath, test.privateKeyPath)
}
if test.certLeafPath != "" {
config.Doit.Set(config.NS, doctl.ArgLeafCertificatePath, test.certLeafPath)
}
if test.certChainPath != "" {
config.Doit.Set(config.NS, doctl.ArgCertificateChainPath, test.certChainPath)
}
if test.DNSNames != nil {
config.Doit.Set(config.NS, doctl.ArgCertificateDNSNames, test.DNSNames)
}
if test.certType != "" {
config.Doit.Set(config.NS, doctl.ArgCertificateType, test.certType)
}
err := RunCertificateCreate(config)
assert.NoError(t, err)
})
})
}
}
func TestCertificateList(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
tm.certificates.On("List").Return(testCertificateList, nil)
err := RunCertificateList(config)
assert.NoError(t, err)
})
}
func TestCertificateDelete(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
cID := "892071a0-bb95-49bc-8021-3afd67a210bf"
tm.certificates.On("Delete", cID).Return(nil)
config.Args = append(config.Args, cID)
config.Doit.Set(config.NS, doctl.ArgForce, true)
err := RunCertificateDelete(config)
assert.NoError(t, err)
})
}
func TestCertificateDeleteNoID(t *testing.T) {
withTestClient(t, func(config *CmdConfig, tm *tcMocks) {
err := RunCertificateDelete(config)
assert.Error(t, err)
})
}
| {
cmd := Certificate()
assert.NotNil(t, cmd)
assertCommandNames(t, cmd, "get", "create", "list", "delete")
} |
inventory.rs | use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::error::Error;
use std::fmt::Debug;
use std::fs::{self, OpenOptions};
use std::io::{BufReader, Result as IoResult};
use std::path::{Path, PathBuf};
use log::debug;
use serde::{Deserialize, Serialize};
use crate::file_err;
use crate::hash::{HashAlgorithm, HashValue, Hasher};
use crate::iterdir::RelativePathIterator;
use crate::util::{self, FileError};
/// Inventory configuration.
#[derive(Debug, Deserialize, Serialize)]
pub struct Configuration {
/// Version of the app used to build the inventory.
version: String,
/// Skip hidden files.
skip_hidden: bool,
/// Hash algorithms to use.
hash_algorithms: BTreeSet<HashAlgorithm>,
}
impl Configuration {
/// Returns an empty configuration.
pub fn | () -> Self {
Configuration::default()
}
/// Sets the `skip_hidden` mode.
pub fn set_skip_hidden(&mut self, skip_hidden: bool) -> &mut Self {
self.skip_hidden = skip_hidden;
self
}
/// Sets the hash algorithms to use.
pub fn set_hash_algorithms(&mut self, algorithms: &[HashAlgorithm]) {
self.hash_algorithms.clear();
self.hash_algorithms.extend(algorithms.iter());
}
}
impl Default for Configuration {
fn default() -> Self {
Configuration {
version: env!("CARGO_PKG_VERSION").to_string(),
skip_hidden: false,
hash_algorithms: BTreeSet::new(),
}
}
}
/// An inventory record.
#[derive(Debug, Deserialize, Serialize)]
struct Record {
/// Hashes of the file.
hashes: BTreeMap<HashAlgorithm, HashValue>,
/// Size of the file.
size: u64,
}
impl Record {
/// Creates a new inventory record.
fn new(size: u64, hashes: Vec<(HashAlgorithm, HashValue)>) -> Self {
Record {
hashes: hashes.into_iter().collect(),
size,
}
}
}
/// Inventory verification failure kind.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum FailureKind {
/// A file is present in the inventory but missing from the repository.
MissingFromRepository,
/// A file is found in the repository but missing from the inventory.
MissingFromInventory,
/// Actual file size does not match the size recorded in the inventory.
SizeMismatch,
/// Actual file hash value does not match the value recorded in the inventory.
HashMismatch,
}
/// Inventory verification report.
#[derive(Default)]
pub struct Report {
/// Issues found during the verification and the corresponding file paths.
contents: HashMap<FailureKind, HashSet<PathBuf>>,
}
impl Report {
/// Returns a new empty report.
fn new() -> Self {
Report::default()
}
/// Returns `true` if the report is empty, `false` otherwise.
pub fn is_empty(&self) -> bool {
self.contents.is_empty()
}
/// Returns a list of the discovered failure kinds.
pub fn failures(&self) -> Vec<FailureKind> {
self.contents.keys().copied().collect()
}
/// Returns a list of files that caused the specific failure.
pub fn by_failure(&self, kind: FailureKind) -> Option<impl Iterator<Item = &Path>> {
self.contents
.get(&kind)
.map(|h| h.iter().map(|p| p.as_path()))
}
/// Records a failure in the report.
fn add_failure<P: AsRef<Path>>(&mut self, file: P, kind: FailureKind) {
self.contents
.entry(kind)
.or_default()
.insert(file.as_ref().to_path_buf());
}
}
/// Inventory structure.
#[derive(Debug, Deserialize, Serialize)]
pub struct Inventory {
/// Inventory configuration.
configuration: Configuration,
/// File records.
records: BTreeMap<PathBuf, Record>,
}
impl Inventory {
/// Creates a new inventory with the provided configuration.
pub fn new(configuration: Configuration) -> Self {
Inventory {
records: BTreeMap::new(),
configuration,
}
}
/// Builds an inventory for the provided repository directory.
pub fn build(configuration: Configuration, repository: &Path) -> Result<Self, Box<dyn Error>> {
let mut hasher = Hasher::new(configuration.hash_algorithms.iter().copied());
let mut inventory = Inventory::new(configuration);
let files = inventory.repo_files(repository)?;
// Add the discovered files to the inventory.
files
.into_iter()
.try_for_each(|p| inventory.add_file(repository, &p, &mut hasher))?;
Ok(inventory)
}
/// Checks the repository and produces the verification report.
pub fn check(&self, repository: &Path, check_hashes: bool) -> Result<Report, Box<dyn Error>> {
let mut hasher = Hasher::new(self.configuration.hash_algorithms.iter().copied());
// Build a set of repository file paths and a set of file paths recorded in the inventory.
let repository_files = self.repo_files(repository)?;
let inventory_files: BTreeSet<_> = self.records.keys().cloned().collect();
let mut report = Report::new();
// Find files present in the repository but missing from the inventory.
repository_files
.difference(&inventory_files)
.for_each(|p| report.add_failure(p, FailureKind::MissingFromInventory));
// Find files present in the inventory but missing from the repository.
inventory_files
.difference(&repository_files)
.for_each(|p| report.add_failure(p, FailureKind::MissingFromRepository));
// Verify files one by one.
for file in inventory_files.intersection(&repository_files) {
debug!("Verifying file {:?}", file);
let rec = self.records.get(file).unwrap();
// Produce the absolute path to the file.
let mut file_abs = repository.to_path_buf();
file_abs.push(file);
// Check size first. It does not make sense to check hashes if sizes
// don't match.
let attr = fs::metadata(&file_abs).or_else(|e| file_err!(&file_abs, e))?;
if attr.len() != rec.size {
report.add_failure(file, FailureKind::SizeMismatch);
} else if check_hashes {
let reader = BufReader::new(
OpenOptions::new()
.read(true)
.open(&file_abs)
.or_else(|e| file_err!(&file_abs, e))?,
);
let hashes: BTreeMap<_, _> = hasher.compute(reader)?.into_iter().collect();
if hashes != rec.hashes {
report.add_failure(file, FailureKind::HashMismatch);
}
}
}
Ok(report)
}
/// Updates the inventory by adding new files and removing missing files.
pub fn update(
&mut self,
repository: &Path,
remove_missing: bool,
) -> Result<(), Box<dyn Error>> {
let mut hasher = Hasher::new(self.configuration.hash_algorithms.iter().copied());
// Build a set of repository file paths and a set of file paths recorded in the inventory.
let repository_files = self.repo_files(repository)?;
let inventory_files: BTreeSet<_> = self.records.keys().cloned().collect();
// Discover files missing from the inventory and add them.
repository_files
.difference(&inventory_files)
.try_for_each(|p| self.add_file(repository, p, &mut hasher))?;
// If enabled, remove missing files from the inventory.
if remove_missing {
inventory_files.difference(&repository_files).for_each(|p| {
self.records.remove(p);
});
}
Ok(())
}
/// Returns a set of repository files.
fn repo_files<P>(&self, repository: P) -> IoResult<BTreeSet<PathBuf>>
where
P: AsRef<Path>,
{
self.repo_iter(repository)?.collect()
}
/// Returns an iterator over the repository files.
fn repo_iter<P>(&self, repository: P) -> IoResult<impl Iterator<Item = IoResult<PathBuf>>>
where
P: AsRef<Path>,
{
Ok(RepositoryIterator::new(
RelativePathIterator::new(repository)?,
&self.configuration,
))
}
/// Produces a file record for the specified file and adds it to the inventory.
fn add_file<P: AsRef<Path>>(
&mut self,
repository: P,
rel_path: P,
hasher: &mut Hasher,
) -> Result<(), Box<dyn Error>> {
debug!("Adding file {:?}", rel_path.as_ref());
// Produce the absolute path to the file.
let mut abs_path = repository.as_ref().to_path_buf();
abs_path.push(&rel_path);
let attr = abs_path.metadata().or_else(|e| file_err!(&abs_path, e))?;
// Create a reader to compute the hash(es) of the file contents.
let reader = BufReader::new(
OpenOptions::new()
.read(true)
.open(&abs_path)
.or_else(|e| file_err!(&abs_path, e))?,
);
let hashes = hasher.compute(reader)?;
let rec = Record::new(attr.len(), hashes);
self.records.insert(rel_path.as_ref().to_path_buf(), rec);
Ok(())
}
}
/// An iterator over the repository file paths.
///
/// This iterator honors the inventory settings (e.g. filters out hidden files
/// if needed).
struct RepositoryIterator<I> {
iter: I,
skip_hidden: bool,
}
impl<I: Iterator<Item = IoResult<PathBuf>>> RepositoryIterator<I> {
// Creates a new repository file iterator.
fn new(iter: I, config: &Configuration) -> Self {
RepositoryIterator {
skip_hidden: config.skip_hidden,
iter,
}
}
}
impl<I: Iterator<Item = IoResult<PathBuf>>> Iterator for RepositoryIterator<I> {
type Item = IoResult<PathBuf>;
fn next(&mut self) -> Option<Self::Item> {
for item in self.iter.by_ref() {
match item {
Ok(path) => {
if self.skip_hidden && util::is_hidden(&path) {
continue;
} else {
return Some(Ok(path));
}
}
Err(e) => return Some(Err(e)),
}
}
None
}
}
| new |
level.py | __author__ = 'marble_xu'
import os
import json
import pygame as pg
from source import setup, tools
from source import constants as c
from source.states import level_state
from source.components import info, stuff, brick, box, enemy, coin
if c.HUMAN_PLAYER:
from source.components import player
else:
from source.components import fast_player as player
from ray.rllib.env import atari_wrappers as wrappers
maps_path = os.path.join(os.path.dirname(os.path.realpath(__file__).replace('/states', '')), 'data', 'maps')
class Level(tools.State):
def __init__(self):
tools.State.__init__(self)
self.player = None
def startup(self, current_time, persist):
level_state.state = [[c.AIR_ID for _ in range(c.COL_HEIGHT)]]
self.game_info = persist
self.persist = self.game_info
self.game_info[c.CURRENT_TIME] = current_time
self.death_timer = 0
self.castle_timer = 0
self.moving_score_list = []
self.overhead_info = info.Info(self.game_info, c.LEVEL)
self.load_map()
self.setup_background()
self.setup_maps()
self.ground_group = self.setup_collide(c.MAP_GROUND)
self.step_group = self.setup_collide(c.MAP_STEP)
self.setup_pipe()
self.setup_slider()
self.setup_static_coin()
self.setup_brick_and_box()
self.setup_player()
self.setup_enemies()
self.setup_checkpoints()
self.setup_flagpole()
self.setup_sprite_groups()
self.observation = None
if c.PRINT_LEVEL:
level_state.print_2d(level_state.state)
def load_map(self):
map_file = os.path.join(maps_path, 'level_' + str(self.game_info[c.LEVEL_NUM]) + '.json')
f = open(map_file)
self.map_data = json.load(f)
f.close()
def setup_background(self):
img_name = self.map_data[c.MAP_IMAGE]
self.background = setup.GFX[img_name]
self.bg_rect = self.background.get_rect()
self.background = pg.transform.scale(self.background,
(int(self.bg_rect.width * c.BACKGROUND_MULTIPLER),
int(self.bg_rect.height * c.BACKGROUND_MULTIPLER)))
self.bg_rect = self.background.get_rect()
self.level = pg.Surface((self.bg_rect.w, self.bg_rect.h)).convert()
self.viewport = setup.SCREEN.get_rect(bottom=self.bg_rect.bottom)
def setup_maps(self):
self.map_list = []
if c.MAP_MAPS in self.map_data:
for data in self.map_data[c.MAP_MAPS]:
self.map_list.append((data['start_x'], data['end_x'], data['player_x'], data['player_y']))
self.start_x, self.end_x, self.player_x, self.player_y = self.map_list[0]
else:
self.start_x = 0
self.end_x = self.bg_rect.w
self.player_x = 110
self.player_y = c.GROUND_HEIGHT
def change_map(self, index, type):
self.start_x, self.end_x, self.player_x, self.player_y = self.map_list[index]
self.viewport.x = self.start_x
if type == c.CHECKPOINT_TYPE_MAP:
self.player.rect.x = self.viewport.x + self.player_x
self.player.rect.bottom = self.player_y
self.player.state = c.STAND
elif type == c.CHECKPOINT_TYPE_PIPE_UP:
self.player.rect.x = self.viewport.x + self.player_x
self.player.rect.bottom = c.GROUND_HEIGHT
self.player.state = c.UP_OUT_PIPE
self.player.up_pipe_y = self.player_y
def setup_collide(self, name):
group = pg.sprite.Group()
if name in self.map_data:
for data in self.map_data[name]:
group.add(stuff.Collider(data['x'], data['y'],
data['width'], data['height'], name))
return group
def setup_pipe(self):
self.pipe_group = pg.sprite.Group()
if c.MAP_PIPE in self.map_data:
for data in self.map_data[c.MAP_PIPE]:
self.pipe_group.add(stuff.Pipe(data['x'], data['y'],
data['width'], data['height'], data['type']))
def setup_slider(self):
self.slider_group = pg.sprite.Group()
if c.MAP_SLIDER in self.map_data:
for data in self.map_data[c.MAP_SLIDER]:
if c.VELOCITY in data:
vel = data[c.VELOCITY]
else:
vel = 1
self.slider_group.add(stuff.Slider(data['x'], data['y'], data['num'],
data['direction'], data['range_start'], data['range_end'], vel))
def setup_static_coin(self):
self.static_coin_group = pg.sprite.Group()
if c.MAP_COIN in self.map_data:
for data in self.map_data[c.MAP_COIN]:
self.static_coin_group.add(coin.StaticCoin(data['x'], data['y']))
def setup_brick_and_box(self):
self.coin_group = pg.sprite.Group()
self.powerup_group = pg.sprite.Group()
self.brick_group = pg.sprite.Group()
self.brickpiece_group = pg.sprite.Group()
if c.MAP_BRICK in self.map_data:
for data in self.map_data[c.MAP_BRICK]:
brick.create_brick(self.brick_group, data, self)
self.box_group = pg.sprite.Group()
if c.MAP_BOX in self.map_data:
for data in self.map_data[c.MAP_BOX]:
if data['type'] == c.TYPE_COIN:
self.box_group.add(box.Box(data['x'], data['y'], data['type'], self.coin_group))
else:
self.box_group.add(box.Box(data['x'], data['y'], data['type'], self.powerup_group))
def setup_player(self):
if self.player is None:
self.player = player.Player(self.game_info[c.PLAYER_NAME])
else:
self.player.restart()
self.player.rect.x = self.viewport.x + self.player_x
self.player.rect.bottom = self.player_y
if c.DEBUG:
self.player.rect.x = self.viewport.x + c.DEBUG_START_X
self.player.rect.bottom = c.DEBUG_START_Y
self.viewport.x = self.player.rect.x - 110
def setup_enemies(self):
self.enemy_group_list = []
index = 0
for data in self.map_data[c.MAP_ENEMY]:
group = pg.sprite.Group()
for item in data[str(index)]:
group.add(enemy.create_enemy(item, self))
self.enemy_group_list.append(group)
index += 1
def setup_checkpoints(self):
self.checkpoint_group = pg.sprite.Group()
for data in self.map_data[c.MAP_CHECKPOINT]:
if c.ENEMY_GROUPID in data:
enemy_groupid = data[c.ENEMY_GROUPID]
else:
enemy_groupid = 0
if c.MAP_INDEX in data:
map_index = data[c.MAP_INDEX]
else:
map_index = 0
self.checkpoint_group.add(stuff.Checkpoint(data['x'], data['y'], data['width'],
data['height'], data['type'], enemy_groupid, map_index))
def setup_flagpole(self):
self.flagpole_group = pg.sprite.Group()
if c.MAP_FLAGPOLE in self.map_data:
for data in self.map_data[c.MAP_FLAGPOLE]:
if data['type'] == c.FLAGPOLE_TYPE_FLAG:
sprite = stuff.Flag(data['x'], data['y'])
self.flag = sprite
elif data['type'] == c.FLAGPOLE_TYPE_POLE:
sprite = stuff.Pole(data['x'], data['y'])
else:
sprite = stuff.PoleTop(data['x'], data['y'])
self.flagpole_group.add(sprite)
def setup_sprite_groups(self):
self.dying_group = pg.sprite.Group()
self.enemy_group = pg.sprite.Group()
self.shell_group = pg.sprite.Group()
self.ground_step_pipe_group = pg.sprite.Group(self.ground_group,
self.pipe_group, self.step_group, self.slider_group)
self.player_group = pg.sprite.Group(self.player)
def get_collide_groups(self):
return pg.sprite.Group(self.ground_step_pipe_group,
self.brick_group,
self.box_group)
def update(self, surface, keys, current_time):
if self.player.state == c.FLAGPOLE and not c.HUMAN_PLAYER:
self.done = True
return
if c.PRINT_OBSERVATION and c.HUMAN_PLAYER:
self.new_observation = level_state.get_observation(self.player)
if self.observation != self.new_observation:
level_state.print_2d(self.new_observation)
self.observation = self.new_observation
self.game_info[c.CURRENT_TIME] = self.current_time = current_time
self.handle_states(keys)
self.draw(surface)
def handle_states(self, keys):
self.update_all_sprites(keys)
def update_all_sprites(self, keys):
if self.player.dead:
self.player.update(keys, self.game_info, self.powerup_group)
if self.current_time - self.death_timer > 3000:
self.update_game_info()
self.done = True
elif self.player.state == c.IN_CASTLE:
self.player.update(keys, self.game_info, None)
self.flagpole_group.update()
if self.current_time - self.castle_timer > 2000:
self.update_game_info()
self.done = True
elif self.in_frozen_state():
self.player.update(keys, self.game_info, None)
self.check_checkpoints()
self.update_viewport()
self.overhead_info.update(self.game_info, self.player)
for score in self.moving_score_list:
score.update(self.moving_score_list)
else:
self.player.update(keys, self.game_info, self.powerup_group)
self.flagpole_group.update()
self.check_checkpoints()
self.slider_group.update()
self.static_coin_group.update(self.game_info)
self.enemy_group.update(self.game_info, self.player.rect.x, self)
self.shell_group.update(self.game_info, self.player.rect.x, self)
self.brick_group.update()
self.box_group.update(self.game_info, self.player.rect.x)
self.powerup_group.update(self.game_info, self)
self.coin_group.update(self.game_info)
self.brickpiece_group.update()
self.dying_group.update(self.game_info, self.player.rect.x, self)
self.update_player_position()
self.check_for_player_death()
self.update_viewport()
self.overhead_info.update(self.game_info, self.player)
for score in self.moving_score_list:
score.update(self.moving_score_list)
def | (self):
checkpoint = pg.sprite.spritecollideany(self.player, self.checkpoint_group)
if checkpoint:
if checkpoint.type == c.CHECKPOINT_TYPE_ENEMY:
group = self.enemy_group_list[checkpoint.enemy_groupid]
self.enemy_group.add(group)
elif checkpoint.type == c.CHECKPOINT_TYPE_FLAG:
self.player.state = c.FLAGPOLE
if self.player.rect.bottom < self.flag.rect.y:
self.player.rect.bottom = self.flag.rect.y
self.flag.state = c.SLIDE_DOWN
self.update_flag_score()
elif checkpoint.type == c.CHECKPOINT_TYPE_CASTLE:
self.player.state = c.IN_CASTLE
self.player.x_vel = 0
self.castle_timer = self.current_time
self.flagpole_group.add(stuff.CastleFlag(8745, 322))
elif (checkpoint.type == c.CHECKPOINT_TYPE_MUSHROOM and
self.player.y_vel < 0):
mushroom_box = box.Box(checkpoint.rect.x, checkpoint.rect.bottom - 40,
c.TYPE_LIFEMUSHROOM, self.powerup_group)
mushroom_box.start_bump(self.moving_score_list)
self.box_group.add(mushroom_box)
self.player.y_vel = 7
self.player.rect.y = mushroom_box.rect.bottom
self.player.state = c.FALL
elif checkpoint.type == c.CHECKPOINT_TYPE_PIPE:
self.player.state = c.WALK_AUTO
elif checkpoint.type == c.CHECKPOINT_TYPE_PIPE_UP:
self.change_map(checkpoint.map_index, checkpoint.type)
elif checkpoint.type == c.CHECKPOINT_TYPE_MAP:
self.change_map(checkpoint.map_index, checkpoint.type)
elif checkpoint.type == c.CHECKPOINT_TYPE_BOSS:
self.player.state = c.WALK_AUTO
checkpoint.kill()
def update_flag_score(self):
base_y = c.GROUND_HEIGHT - 80
y_score_list = [(base_y, 100), (base_y - 120, 400),
(base_y - 200, 800), (base_y - 320, 2000),
(0, 5000)]
for y, score in y_score_list:
if self.player.rect.y > y:
self.update_score(score, self.flag)
break
def update_player_position(self):
if self.player.state == c.UP_OUT_PIPE:
return
self.player.rect.x += round(self.player.x_vel)
if self.player.rect.x < self.start_x:
self.player.rect.x = self.start_x
elif self.player.rect.right > self.end_x:
self.player.rect.right = self.end_x
self.check_player_x_collisions()
if not self.player.dead:
self.player.rect.y += round(self.player.y_vel)
self.check_player_y_collisions()
def check_player_x_collisions(self):
ground_step_pipe = pg.sprite.spritecollideany(self.player, self.ground_step_pipe_group)
brick = pg.sprite.spritecollideany(self.player, self.brick_group)
box = pg.sprite.spritecollideany(self.player, self.box_group)
enemy = pg.sprite.spritecollideany(self.player, self.enemy_group)
shell = pg.sprite.spritecollideany(self.player, self.shell_group)
powerup = pg.sprite.spritecollideany(self.player, self.powerup_group)
coin = pg.sprite.spritecollideany(self.player, self.static_coin_group)
if box:
self.adjust_player_for_x_collisions(box)
elif brick:
self.adjust_player_for_x_collisions(brick)
elif ground_step_pipe:
if (ground_step_pipe.name == c.MAP_PIPE and
ground_step_pipe.type == c.PIPE_TYPE_HORIZONTAL):
return
self.adjust_player_for_x_collisions(ground_step_pipe)
elif powerup:
if powerup.type == c.TYPE_MUSHROOM:
self.update_score(1000, powerup, 0)
if not self.player.big:
self.player.y_vel = -1
self.player.state = c.SMALL_TO_BIG
elif powerup.type == c.TYPE_FIREFLOWER:
self.update_score(1000, powerup, 0)
if not self.player.big:
self.player.state = c.SMALL_TO_BIG
elif self.player.big and not self.player.fire:
self.player.state = c.BIG_TO_FIRE
elif powerup.type == c.TYPE_STAR:
self.update_score(1000, powerup, 0)
self.player.invincible = True
elif powerup.type == c.TYPE_LIFEMUSHROOM:
self.update_score(500, powerup, 0)
self.game_info[c.LIVES] += 1
if powerup.type != c.TYPE_FIREBALL:
powerup.kill()
powerup.update_level_state()
elif enemy:
if self.player.invincible:
self.update_score(100, enemy, 0)
self.move_to_dying_group(self.enemy_group, enemy)
direction = c.RIGHT if self.player.facing_right else c.LEFT
enemy.start_death_jump(direction)
elif self.player.hurt_invincible:
pass
elif self.player.big:
self.player.y_vel = -1
self.player.state = c.BIG_TO_SMALL
else:
self.player.start_death_jump(self.game_info)
self.death_timer = self.current_time
elif shell:
if shell.state == c.SHELL_SLIDE:
if self.player.invincible:
self.update_score(200, shell, 0)
self.move_to_dying_group(self.shell_group, shell)
direction = c.RIGHT if self.player.facing_right else c.LEFT
shell.start_death_jump(direction)
elif self.player.hurt_invincible:
pass
elif self.player.big:
self.player.y_vel = -1
self.player.state = c.BIG_TO_SMALL
else:
self.player.start_death_jump(self.game_info)
self.death_timer = self.current_time
else:
self.update_score(400, shell, 0)
if self.player.rect.x < shell.rect.x:
self.player.rect.left = shell.rect.x
shell.direction = c.RIGHT
shell.x_vel = 10
else:
self.player.rect.x = shell.rect.left
shell.direction = c.LEFT
shell.x_vel = -10
shell.rect.x += shell.x_vel * 4
shell.state = c.SHELL_SLIDE
elif coin:
self.update_score(100, coin, 1)
coin.kill()
# coin.update_level_state()
def adjust_player_for_x_collisions(self, collider):
if collider.name == c.MAP_SLIDER:
return
if self.player.rect.x < collider.rect.x:
self.player.rect.right = collider.rect.left
else:
self.player.rect.left = collider.rect.right
self.player.x_vel = 0
def check_player_y_collisions(self):
ground_step_pipe = pg.sprite.spritecollideany(self.player, self.ground_step_pipe_group)
enemy = pg.sprite.spritecollideany(self.player, self.enemy_group)
shell = pg.sprite.spritecollideany(self.player, self.shell_group)
# decrease runtime delay: when player is on the ground, don't check brick and box
# +2 because the ground is at 540 in level 2
if self.player.rect.bottom < c.GROUND_HEIGHT+2:
brick = pg.sprite.spritecollideany(self.player, self.brick_group)
box = pg.sprite.spritecollideany(self.player, self.box_group)
brick, box = self.prevent_collision_conflict(brick, box)
else:
brick, box = False, False
if box:
self.adjust_player_for_y_collisions(box)
elif brick:
self.adjust_player_for_y_collisions(brick)
elif ground_step_pipe:
self.adjust_player_for_y_collisions(ground_step_pipe)
elif enemy:
if self.player.invincible:
self.update_score(100, enemy, 0)
self.move_to_dying_group(self.enemy_group, enemy)
direction = c.RIGHT if self.player.facing_right else c.LEFT
enemy.start_death_jump(direction)
elif (enemy.name == c.PIRANHA or
enemy.name == c.FIRESTICK or
enemy.name == c.FIRE_KOOPA or
enemy.name == c.FIRE):
pass
elif self.player.y_vel > 0:
self.update_score(100, enemy, 0)
enemy.state = c.JUMPED_ON
if enemy.name == c.GOOMBA:
self.move_to_dying_group(self.enemy_group, enemy)
elif enemy.name == c.KOOPA or enemy.name == c.FLY_KOOPA:
self.enemy_group.remove(enemy)
self.shell_group.add(enemy)
self.player.rect.bottom = enemy.rect.top
self.player.state = c.JUMP
self.player.y_vel = -7
elif shell:
if self.player.y_vel > 0:
if shell.state != c.SHELL_SLIDE:
shell.state = c.SHELL_SLIDE
if self.player.rect.centerx < shell.rect.centerx:
shell.direction = c.RIGHT
shell.rect.left = self.player.rect.right + 5
else:
shell.direction = c.LEFT
shell.rect.right = self.player.rect.left - 5
self.check_is_falling(self.player)
self.check_if_player_on_IN_pipe()
def prevent_collision_conflict(self, sprite1, sprite2):
if sprite1 and sprite2:
distance1 = abs(self.player.rect.centerx - sprite1.rect.centerx)
distance2 = abs(self.player.rect.centerx - sprite2.rect.centerx)
if distance1 < distance2:
sprite2 = False
else:
sprite1 = False
return sprite1, sprite2
def adjust_player_for_y_collisions(self, sprite):
if self.player.rect.top > sprite.rect.top:
if sprite.name == c.MAP_BRICK:
self.check_if_enemy_on_brick_box(sprite)
if sprite.state == c.RESTING:
if self.player.big and sprite.type == c.TYPE_NONE:
sprite.change_to_piece(self.dying_group)
else:
if sprite.type == c.TYPE_COIN:
self.update_score(200, sprite, 1)
sprite.start_bump(self.moving_score_list)
elif sprite.name == c.MAP_BOX:
self.check_if_enemy_on_brick_box(sprite)
if sprite.state == c.RESTING:
if sprite.type == c.TYPE_COIN:
self.update_score(200, sprite, 1)
sprite.start_bump(self.moving_score_list)
elif (sprite.name == c.MAP_PIPE and
sprite.type == c.PIPE_TYPE_HORIZONTAL):
return
self.player.y_vel = 7
self.player.rect.top = sprite.rect.bottom
self.player.state = c.FALL
else:
self.player.y_vel = 0
self.player.rect.bottom = sprite.rect.top
if self.player.state == c.FLAGPOLE:
self.player.state = c.WALK_AUTO
elif self.player.state == c.END_OF_LEVEL_FALL:
self.player.state = c.WALK_AUTO
else:
self.player.state = c.WALK
def check_if_enemy_on_brick_box(self, brick):
brick.rect.y -= 5
enemy = pg.sprite.spritecollideany(brick, self.enemy_group)
if enemy:
self.update_score(100, enemy, 0)
self.move_to_dying_group(self.enemy_group, enemy)
if self.player.rect.centerx > brick.rect.centerx:
direction = c.RIGHT
else:
direction = c.LEFT
enemy.start_death_jump(direction)
brick.rect.y += 5
def in_frozen_state(self):
if (self.player.state == c.SMALL_TO_BIG or
self.player.state == c.BIG_TO_SMALL or
self.player.state == c.BIG_TO_FIRE or
self.player.state == c.DEATH_JUMP or
self.player.state == c.DOWN_TO_PIPE or
self.player.state == c.UP_OUT_PIPE):
return True
else:
return False
def check_is_falling(self, sprite):
sprite.rect.y += 1
check_group = pg.sprite.Group(self.ground_step_pipe_group,
self.brick_group, self.box_group)
if pg.sprite.spritecollideany(sprite, check_group) is None:
if (sprite.state == c.WALK_AUTO or
sprite.state == c.END_OF_LEVEL_FALL):
sprite.state = c.END_OF_LEVEL_FALL
elif (sprite.state != c.JUMP and
sprite.state != c.FLAGPOLE and
not self.in_frozen_state()):
sprite.state = c.FALL
sprite.rect.y -= 1
def check_for_player_death(self):
if (self.player.rect.y > c.SCREEN_HEIGHT or
self.overhead_info.time <= 0):
self.player.start_death_jump(self.game_info)
self.death_timer = self.current_time
def check_if_player_on_IN_pipe(self):
'''check if player is on the pipe which can go down in to it '''
self.player.rect.y += 1
pipe = pg.sprite.spritecollideany(self.player, self.pipe_group)
if pipe and pipe.type == c.PIPE_TYPE_IN:
if (self.player.crouching and
self.player.rect.x < pipe.rect.centerx and
self.player.rect.right > pipe.rect.centerx):
self.player.state = c.DOWN_TO_PIPE
self.player.rect.y -= 1
def update_game_info(self):
if self.player.dead:
self.persist[c.LIVES] -= 1
if self.persist[c.LIVES] == 0:
self.next = c.GAME_OVER
elif self.overhead_info.time == 0:
self.next = c.TIME_OUT
elif self.player.dead:
self.next = c.LOAD_SCREEN
else:
self.game_info[c.LEVEL_NUM] = (self.game_info[c.LEVEL_NUM] % 4) + 1
self.next = c.LOAD_SCREEN
def update_viewport(self):
third = self.viewport.x + self.viewport.w // 3
player_center = self.player.rect.centerx
if (self.player.x_vel > 0 and
player_center >= third and
self.viewport.right < self.end_x):
self.viewport.x += round(self.player.x_vel)
elif self.player.x_vel < 0 and self.viewport.x > self.start_x:
self.viewport.x += round(self.player.x_vel)
def move_to_dying_group(self, group, sprite):
group.remove(sprite)
self.dying_group.add(sprite)
def update_score(self, score, sprite, coin_num=0):
self.game_info[c.SCORE] += score
self.game_info[c.COIN_TOTAL] += coin_num
x = sprite.rect.x
y = sprite.rect.y - 10
self.moving_score_list.append(stuff.Score(x, y, score))
def draw(self, surface):
self.level.blit(self.background, self.viewport, self.viewport)
self.powerup_group.draw(self.level)
self.brick_group.draw(self.level)
self.box_group.draw(self.level)
self.coin_group.draw(self.level)
self.dying_group.draw(self.level)
self.brickpiece_group.draw(self.level)
self.flagpole_group.draw(self.level)
self.shell_group.draw(self.level)
self.enemy_group.draw(self.level)
self.player_group.draw(self.level)
self.static_coin_group.draw(self.level)
self.slider_group.draw(self.level)
self.pipe_group.draw(self.level)
for score in self.moving_score_list:
score.draw(self.level)
if c.DEBUG:
self.ground_step_pipe_group.draw(self.level)
self.checkpoint_group.draw(self.level)
surface.blit(self.level, (0, 0), self.viewport)
self.overhead_info.draw(surface)
| check_checkpoints |
terminator.rs | //! Types that are useful in combination with the `Termination` trait.
use std::{
error,
fmt::{self, Debug, Formatter},
};
use crate::ErrorExt;
/// An error that wraps all other error types for a nicer debug output.
///
/// Given the current implementation of the `Termination` trait, and the
/// implementation for every type that implements `Debug`, having a `main`
/// function that returns a `Result` requires either using a type that
/// implements the `Debug` trait poorly or dealing with an output that isn't
/// very user friendly.
///
/// The types here help alleviate those issues. To begin with, we have an
/// `Error` type that simply wraps any possible error and implements `Debug` in
/// such a way as to make the output look nice. Additionally, there is a
/// `Result` specialization in order to make the `main` function a little
/// cleaner. | {
inner: Box<dyn error::Error + 'static>,
}
impl Debug for Terminator
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result
{
writeln!(f, "{}", self.inner)?;
for cause in self.inner.iter_causes() {
writeln!(f, "Caused by: {}", cause)?;
}
Ok(())
}
}
impl<E: error::Error + 'static> From<E> for Terminator
{
fn from(err: E) -> Terminator { Terminator { inner: Box::new(err) } }
} | pub struct Terminator |
api_images.go | /*
* Anchore Engine API Server
*
* This is the Anchore Engine API. Provides the primary external API for users of the service.
*
* API version: 0.1.16
* Contact: [email protected]
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package external
import (
_context "context"
_ioutil "io/ioutil"
_nethttp "net/http"
_neturl "net/url"
"strings"
"github.com/antihax/optional"
)
// Linger please
var (
_ _context.Context
)
// ImagesApiService ImagesApi service
type ImagesApiService service
// AddImageOpts Optional parameters for the method 'AddImage'
type AddImageOpts struct {
Force optional.Bool
Autosubscribe optional.Bool
XAnchoreAccount optional.String
}
/*
AddImage Submit a new image for analysis by the engine
Creates a new analysis task that is executed asynchronously
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param image
* @param optional nil or *AddImageOpts - Optional Parameters:
* @param "Force" (optional.Bool) - Override any existing entry in the system
* @param "Autosubscribe" (optional.Bool) - Instruct engine to automatically begin watching the added tag for updates from registry
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []AnchoreImage
*/
func (a *ImagesApiService) AddImage(ctx _context.Context, image ImageAnalysisRequest, localVarOptionals *AddImageOpts) ([]AnchoreImage, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodPost
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []AnchoreImage
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.Force.IsSet() {
localVarQueryParams.Add("force", parameterToString(localVarOptionals.Force.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.Autosubscribe.IsSet() {
localVarQueryParams.Add("autosubscribe", parameterToString(localVarOptionals.Autosubscribe.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{"application/json"}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
// body params
localVarPostBody = &image
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// DeleteImageOpts Optional parameters for the method 'DeleteImage'
type DeleteImageOpts struct {
Force optional.Bool
XAnchoreAccount optional.String
}
/*
DeleteImage Delete an image analysis
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *DeleteImageOpts - Optional Parameters:
* @param "Force" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return DeleteImageResponse
*/
func (a *ImagesApiService) DeleteImage(ctx _context.Context, imageDigest string, localVarOptionals *DeleteImageOpts) (DeleteImageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodDelete
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue DeleteImageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.Force.IsSet() {
localVarQueryParams.Add("force", parameterToString(localVarOptionals.Force.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// DeleteImageByImageIdOpts Optional parameters for the method 'DeleteImageByImageId'
type DeleteImageByImageIdOpts struct {
Force optional.Bool
XAnchoreAccount optional.String
}
/*
DeleteImageByImageId Delete image by docker imageId
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param optional nil or *DeleteImageByImageIdOpts - Optional Parameters:
* @param "Force" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return DeleteImageResponse
*/
func (a *ImagesApiService) DeleteImageByImageId(ctx _context.Context, imageId string, localVarOptionals *DeleteImageByImageIdOpts) (DeleteImageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodDelete
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue DeleteImageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.Force.IsSet() {
localVarQueryParams.Add("force", parameterToString(localVarOptionals.Force.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// DeleteImagesAsyncOpts Optional parameters for the method 'DeleteImagesAsync'
type DeleteImagesAsyncOpts struct {
Force optional.Bool
XAnchoreAccount optional.String
}
/*
DeleteImagesAsync Bulk mark images for deletion
Delete analysis for image digests in the list asynchronously
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigests
* @param optional nil or *DeleteImagesAsyncOpts - Optional Parameters:
* @param "Force" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []DeleteImageResponse
*/
func (a *ImagesApiService) DeleteImagesAsync(ctx _context.Context, imageDigests []string, localVarOptionals *DeleteImagesAsyncOpts) ([]DeleteImageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodDelete
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []DeleteImageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
localVarQueryParams.Add("imageDigests", parameterToString(imageDigests, "csv"))
if localVarOptionals != nil && localVarOptionals.Force.IsSet() {
localVarQueryParams.Add("force", parameterToString(localVarOptionals.Force.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageOpts Optional parameters for the method 'GetImage'
type GetImageOpts struct {
XAnchoreAccount optional.String
}
/*
GetImage Get image metadata
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *GetImageOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []AnchoreImage
*/
func (a *ImagesApiService) GetImage(ctx _context.Context, imageDigest string, localVarOptionals *GetImageOpts) ([]AnchoreImage, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []AnchoreImage
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageByImageIdOpts Optional parameters for the method 'GetImageByImageId'
type GetImageByImageIdOpts struct {
XAnchoreAccount optional.String
}
| * @param imageId
* @param optional nil or *GetImageByImageIdOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []AnchoreImage
*/
func (a *ImagesApiService) GetImageByImageId(ctx _context.Context, imageId string, localVarOptionals *GetImageByImageIdOpts) ([]AnchoreImage, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []AnchoreImage
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeOpts Optional parameters for the method 'GetImageContentByType'
type GetImageContentByTypeOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByType Get the content of an image by type
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param ctype
* @param optional nil or *GetImageContentByTypeOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentPackageResponse
*/
func (a *ImagesApiService) GetImageContentByType(ctx _context.Context, imageDigest string, ctype string, localVarOptionals *GetImageContentByTypeOpts) (ContentPackageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentPackageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/content/{ctype}"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarPath = strings.Replace(localVarPath, "{"+"ctype"+"}", _neturl.QueryEscape(parameterToString(ctype, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeFilesOpts Optional parameters for the method 'GetImageContentByTypeFiles'
type GetImageContentByTypeFilesOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeFiles Get the content of an image by type files
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *GetImageContentByTypeFilesOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentFilesResponse
*/
func (a *ImagesApiService) GetImageContentByTypeFiles(ctx _context.Context, imageDigest string, localVarOptionals *GetImageContentByTypeFilesOpts) (ContentFilesResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentFilesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/content/files"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeImageIdOpts Optional parameters for the method 'GetImageContentByTypeImageId'
type GetImageContentByTypeImageIdOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeImageId Get the content of an image by type
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param ctype
* @param optional nil or *GetImageContentByTypeImageIdOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentPackageResponse
*/
func (a *ImagesApiService) GetImageContentByTypeImageId(ctx _context.Context, imageId string, ctype string, localVarOptionals *GetImageContentByTypeImageIdOpts) (ContentPackageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentPackageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/content/{ctype}"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarPath = strings.Replace(localVarPath, "{"+"ctype"+"}", _neturl.QueryEscape(parameterToString(ctype, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeImageIdFilesOpts Optional parameters for the method 'GetImageContentByTypeImageIdFiles'
type GetImageContentByTypeImageIdFilesOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeImageIdFiles Get the content of an image by type files
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param optional nil or *GetImageContentByTypeImageIdFilesOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentFilesResponse
*/
func (a *ImagesApiService) GetImageContentByTypeImageIdFiles(ctx _context.Context, imageId string, localVarOptionals *GetImageContentByTypeImageIdFilesOpts) (ContentFilesResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentFilesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/content/files"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeImageIdJavapackageOpts Optional parameters for the method 'GetImageContentByTypeImageIdJavapackage'
type GetImageContentByTypeImageIdJavapackageOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeImageIdJavapackage Get the content of an image by type java
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param optional nil or *GetImageContentByTypeImageIdJavapackageOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentJavaPackageResponse
*/
func (a *ImagesApiService) GetImageContentByTypeImageIdJavapackage(ctx _context.Context, imageId string, localVarOptionals *GetImageContentByTypeImageIdJavapackageOpts) (ContentJavaPackageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentJavaPackageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/content/java"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeJavapackageOpts Optional parameters for the method 'GetImageContentByTypeJavapackage'
type GetImageContentByTypeJavapackageOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeJavapackage Get the content of an image by type java
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *GetImageContentByTypeJavapackageOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentJavaPackageResponse
*/
func (a *ImagesApiService) GetImageContentByTypeJavapackage(ctx _context.Context, imageDigest string, localVarOptionals *GetImageContentByTypeJavapackageOpts) (ContentJavaPackageResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentJavaPackageResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/content/java"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageContentByTypeMalwareOpts Optional parameters for the method 'GetImageContentByTypeMalware'
type GetImageContentByTypeMalwareOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageContentByTypeMalware Get the content of an image by type malware
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *GetImageContentByTypeMalwareOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return ContentMalwareResponse
*/
func (a *ImagesApiService) GetImageContentByTypeMalware(ctx _context.Context, imageDigest string, localVarOptionals *GetImageContentByTypeMalwareOpts) (ContentMalwareResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue ContentMalwareResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/content/malware"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageMetadataByTypeOpts Optional parameters for the method 'GetImageMetadataByType'
type GetImageMetadataByTypeOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageMetadataByType Get the metadata of an image by type
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param mtype
* @param optional nil or *GetImageMetadataByTypeOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return MetadataResponse
*/
func (a *ImagesApiService) GetImageMetadataByType(ctx _context.Context, imageDigest string, mtype string, localVarOptionals *GetImageMetadataByTypeOpts) (MetadataResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue MetadataResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/metadata/{mtype}"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarPath = strings.Replace(localVarPath, "{"+"mtype"+"}", _neturl.QueryEscape(parameterToString(mtype, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImagePolicyCheckOpts Optional parameters for the method 'GetImagePolicyCheck'
type GetImagePolicyCheckOpts struct {
PolicyId optional.String
Detail optional.Bool
History optional.Bool
Interactive optional.Bool
XAnchoreAccount optional.String
}
/*
GetImagePolicyCheck Check policy evaluation status for image
Get the policy evaluation for the given image
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param tag
* @param optional nil or *GetImagePolicyCheckOpts - Optional Parameters:
* @param "PolicyId" (optional.String) -
* @param "Detail" (optional.Bool) -
* @param "History" (optional.Bool) -
* @param "Interactive" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []interface{}
*/
func (a *ImagesApiService) GetImagePolicyCheck(ctx _context.Context, imageDigest string, tag string, localVarOptionals *GetImagePolicyCheckOpts) ([]interface{}, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []interface{}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/check"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.PolicyId.IsSet() {
localVarQueryParams.Add("policyId", parameterToString(localVarOptionals.PolicyId.Value(), ""))
}
localVarQueryParams.Add("tag", parameterToString(tag, ""))
if localVarOptionals != nil && localVarOptionals.Detail.IsSet() {
localVarQueryParams.Add("detail", parameterToString(localVarOptionals.Detail.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.History.IsSet() {
localVarQueryParams.Add("history", parameterToString(localVarOptionals.History.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.Interactive.IsSet() {
localVarQueryParams.Add("interactive", parameterToString(localVarOptionals.Interactive.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImagePolicyCheckByImageIdOpts Optional parameters for the method 'GetImagePolicyCheckByImageId'
type GetImagePolicyCheckByImageIdOpts struct {
PolicyId optional.String
Detail optional.Bool
History optional.Bool
XAnchoreAccount optional.String
}
/*
GetImagePolicyCheckByImageId Check policy evaluation status for image
Get the policy evaluation for the given image
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param tag
* @param optional nil or *GetImagePolicyCheckByImageIdOpts - Optional Parameters:
* @param "PolicyId" (optional.String) -
* @param "Detail" (optional.Bool) -
* @param "History" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []interface{}
*/
func (a *ImagesApiService) GetImagePolicyCheckByImageId(ctx _context.Context, imageId string, tag string, localVarOptionals *GetImagePolicyCheckByImageIdOpts) ([]interface{}, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []interface{}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/check"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.PolicyId.IsSet() {
localVarQueryParams.Add("policyId", parameterToString(localVarOptionals.PolicyId.Value(), ""))
}
localVarQueryParams.Add("tag", parameterToString(tag, ""))
if localVarOptionals != nil && localVarOptionals.Detail.IsSet() {
localVarQueryParams.Add("detail", parameterToString(localVarOptionals.Detail.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.History.IsSet() {
localVarQueryParams.Add("history", parameterToString(localVarOptionals.History.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageVulnerabilitiesByTypeOpts Optional parameters for the method 'GetImageVulnerabilitiesByType'
type GetImageVulnerabilitiesByTypeOpts struct {
ForceRefresh optional.Bool
VendorOnly optional.Bool
XAnchoreAccount optional.String
}
/*
GetImageVulnerabilitiesByType Get vulnerabilities by type
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param vtype
* @param optional nil or *GetImageVulnerabilitiesByTypeOpts - Optional Parameters:
* @param "ForceRefresh" (optional.Bool) -
* @param "VendorOnly" (optional.Bool) -
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return VulnerabilityResponse
*/
func (a *ImagesApiService) GetImageVulnerabilitiesByType(ctx _context.Context, imageDigest string, vtype string, localVarOptionals *GetImageVulnerabilitiesByTypeOpts) (VulnerabilityResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue VulnerabilityResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/vuln/{vtype}"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarPath = strings.Replace(localVarPath, "{"+"vtype"+"}", _neturl.QueryEscape(parameterToString(vtype, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.ForceRefresh.IsSet() {
localVarQueryParams.Add("force_refresh", parameterToString(localVarOptionals.ForceRefresh.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.VendorOnly.IsSet() {
localVarQueryParams.Add("vendor_only", parameterToString(localVarOptionals.VendorOnly.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageVulnerabilitiesByTypeImageIdOpts Optional parameters for the method 'GetImageVulnerabilitiesByTypeImageId'
type GetImageVulnerabilitiesByTypeImageIdOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageVulnerabilitiesByTypeImageId Get vulnerabilities by type
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param vtype
* @param optional nil or *GetImageVulnerabilitiesByTypeImageIdOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return VulnerabilityResponse
*/
func (a *ImagesApiService) GetImageVulnerabilitiesByTypeImageId(ctx _context.Context, imageId string, vtype string, localVarOptionals *GetImageVulnerabilitiesByTypeImageIdOpts) (VulnerabilityResponse, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue VulnerabilityResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/vuln/{vtype}"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarPath = strings.Replace(localVarPath, "{"+"vtype"+"}", _neturl.QueryEscape(parameterToString(vtype, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageVulnerabilityTypesOpts Optional parameters for the method 'GetImageVulnerabilityTypes'
type GetImageVulnerabilityTypesOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageVulnerabilityTypes Get vulnerability types
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *GetImageVulnerabilityTypesOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []string
*/
func (a *ImagesApiService) GetImageVulnerabilityTypes(ctx _context.Context, imageDigest string, localVarOptionals *GetImageVulnerabilityTypesOpts) ([]string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/vuln"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// GetImageVulnerabilityTypesByImageIdOpts Optional parameters for the method 'GetImageVulnerabilityTypesByImageId'
type GetImageVulnerabilityTypesByImageIdOpts struct {
XAnchoreAccount optional.String
}
/*
GetImageVulnerabilityTypesByImageId Get vulnerability types
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param optional nil or *GetImageVulnerabilityTypesByImageIdOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []string
*/
func (a *ImagesApiService) GetImageVulnerabilityTypesByImageId(ctx _context.Context, imageId string, localVarOptionals *GetImageVulnerabilityTypesByImageIdOpts) ([]string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/vuln"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// ListImageContentOpts Optional parameters for the method 'ListImageContent'
type ListImageContentOpts struct {
XAnchoreAccount optional.String
}
/*
ListImageContent List image content types
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *ListImageContentOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []string
*/
func (a *ImagesApiService) ListImageContent(ctx _context.Context, imageDigest string, localVarOptionals *ListImageContentOpts) ([]string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/content"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// ListImageContentByImageidOpts Optional parameters for the method 'ListImageContentByImageid'
type ListImageContentByImageidOpts struct {
XAnchoreAccount optional.String
}
/*
ListImageContentByImageid List image content types
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageId
* @param optional nil or *ListImageContentByImageidOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []string
*/
func (a *ImagesApiService) ListImageContentByImageid(ctx _context.Context, imageId string, localVarOptionals *ListImageContentByImageidOpts) ([]string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/by_id/{imageId}/content"
localVarPath = strings.Replace(localVarPath, "{"+"imageId"+"}", _neturl.QueryEscape(parameterToString(imageId, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// ListImageMetadataOpts Optional parameters for the method 'ListImageMetadata'
type ListImageMetadataOpts struct {
XAnchoreAccount optional.String
}
/*
ListImageMetadata List image metadata types
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param imageDigest
* @param optional nil or *ListImageMetadataOpts - Optional Parameters:
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []string
*/
func (a *ImagesApiService) ListImageMetadata(ctx _context.Context, imageDigest string, localVarOptionals *ListImageMetadataOpts) ([]string, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []string
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images/{imageDigest}/metadata"
localVarPath = strings.Replace(localVarPath, "{"+"imageDigest"+"}", _neturl.QueryEscape(parameterToString(imageDigest, "")) , -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
}
// ListImagesOpts Optional parameters for the method 'ListImages'
type ListImagesOpts struct {
History optional.Bool
Fulltag optional.String
ImageStatus optional.String
AnalysisStatus optional.String
XAnchoreAccount optional.String
}
/*
ListImages List all visible images
List all images visible to the user
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param optional nil or *ListImagesOpts - Optional Parameters:
* @param "History" (optional.Bool) - Include image history in the response
* @param "Fulltag" (optional.String) - Full docker-pull string to filter results by (e.g. docker.io/library/nginx:latest, or myhost.com:5000/testimages:v1.1.1)
* @param "ImageStatus" (optional.String) - Filter by image_status value on the record. Default if omitted is 'active'.
* @param "AnalysisStatus" (optional.String) - Filter by analysis_status value on the record.
* @param "XAnchoreAccount" (optional.String) - An account name to change the resource scope of the request to that account, if permissions allow (admin only)
@return []AnchoreImage
*/
func (a *ImagesApiService) ListImages(ctx _context.Context, localVarOptionals *ListImagesOpts) ([]AnchoreImage, *_nethttp.Response, error) {
var (
localVarHTTPMethod = _nethttp.MethodGet
localVarPostBody interface{}
localVarFormFileName string
localVarFileName string
localVarFileBytes []byte
localVarReturnValue []AnchoreImage
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/images"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := _neturl.Values{}
localVarFormParams := _neturl.Values{}
if localVarOptionals != nil && localVarOptionals.History.IsSet() {
localVarQueryParams.Add("history", parameterToString(localVarOptionals.History.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.Fulltag.IsSet() {
localVarQueryParams.Add("fulltag", parameterToString(localVarOptionals.Fulltag.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.ImageStatus.IsSet() {
localVarQueryParams.Add("image_status", parameterToString(localVarOptionals.ImageStatus.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.AnalysisStatus.IsSet() {
localVarQueryParams.Add("analysis_status", parameterToString(localVarOptionals.AnalysisStatus.Value(), ""))
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if localVarOptionals != nil && localVarOptionals.XAnchoreAccount.IsSet() {
localVarHeaderParams["x-anchore-account"] = parameterToString(localVarOptionals.XAnchoreAccount.Value(), "")
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(r)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 500 {
var v ApiErrorResponse
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
return localVarReturnValue, localVarHTTPResponse, nil
} | /*
GetImageByImageId Lookup image by docker imageId
* @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). |
zhujima.js | // 汉字拼音首字母列表 本列表包含了20902个汉字,用于配合 ToChineseSpell
//函数使用,本表收录的字符的Unicode编码范围为19968至40869, XDesigner 整理
var strChineseFirstPY = "YDYQSXMWZSSXJBYMGCCZQPSSQBYCDSCDQLDYLYBSSJGYZZJJFKCCLZDHWDWZJLJPFYYNWJJTMYHZWZHFLZPPQHGSCYYYNJQYXXGJHHSDSJNKKTMOMLCRXYPSNQSECCQZGGLLYJLMYZZSECYKYYHQWJSSGGYXYZYJWWKDJHYCHMYXJTLXJYQBYXZLDWRDJRWYSRLDZJPCBZJJBRCFTLECZSTZFXXZHTRQHYBDLYCZSSYMMRFMYQZPWWJJYFCRWFDFZQPYDDWYXKYJAWJFFXYPSFTZYHHYZYSWCJYXSCLCXXWZZXNBGNNXBXLZSZSBSGPYSYZDHMDZBQBZCWDZZYYTZHBTSYYBZGNTNXQYWQSKBPHHLXGYBFMJEBJHHGQTJCYSXSTKZHLYCKGLYSMZXYALMELDCCXGZYRJXSDLTYZCQKCNNJWHJTZZCQLJSTSTBNXBTYXCEQXGKWJYFLZQLYHYXSPSFXLMPBYSXXXYDJCZYLLLSJXFHJXPJBTFFYABYXBHZZBJYZLWLCZGGBTSSMDTJZXPTHYQTGLJSCQFZKJZJQNLZWLSLHDZBWJNCJZYZSQQYCQYRZCJJWYBRTWPYFTWEXCSKDZCTBZHYZZYYJXZCFFZZMJYXXSDZZOTTBZLQWFCKSZSXFYRLNYJMBDTHJXSQQCCSBXYYTSYFBXDZTGBCNSLCYZZPSAZYZZSCJCSHZQYDXLBPJLLMQXTYDZXSQJTZPXLCGLQTZWJBHCTSYJSFXYEJJTLBGXSXJMYJQQPFZASYJNTYDJXKJCDJSZCBARTDCLYJQMWNQNCLLLKBYBZZSYHQQLTWLCCXTXLLZNTYLNEWYZYXCZXXGRKRMTCNDNJTSYYSSDQDGHSDBJGHRWRQLYBGLXHLGTGXBQJDZPYJSJYJCTMRNYMGRZJCZGJMZMGXMPRYXKJNYMSGMZJYMKMFXMLDTGFBHCJHKYLPFMDXLQJJSMTQGZSJLQDLDGJYCALCMZCSDJLLNXDJFFFFJCZFMZFFPFKHKGDPSXKTACJDHHZDDCRRCFQYJKQCCWJDXHWJLYLLZGCFCQDSMLZPBJJPLSBCJGGDCKKDEZSQCCKJGCGKDJTJDLZYCXKLQSCGJCLTFPCQCZGWPJDQYZJJBYJHSJDZWGFSJGZKQCCZLLPSPKJGQJHZZLJPLGJGJJTHJJYJZCZMLZLYQBGJWMLJKXZDZNJQSYZMLJLLJKYWXMKJLHSKJGBMCLYYMKXJQLBMLLKMDXXKWYXYSLMLPSJQQJQXYXFJTJDXMXXLLCXQBSYJBGWYMBGGBCYXPJYGPEPFGDJGBHBNSQJYZJKJKHXQFGQZKFHYGKHDKLLSDJQXPQYKYBNQSXQNSZSWHBSXWHXWBZZXDMNSJBSBKBBZKLYLXGWXDRWYQZMYWSJQLCJXXJXKJEQXSCYETLZHLYYYSDZPAQYZCMTLSHTZCFYZYXYLJSDCJQAGYSLCQLYYYSHMRQQKLDXZSCSSSYDYCJYSFSJBFRSSZQSBXXPXJYSDRCKGJLGDKZJZBDKTCSYQPYHSTCLDJDHMXMCGXYZHJDDTMHLTXZXYLYMOHYJCLTYFBQQXPFBDFHHTKSQHZYYWCNXXCRWHOWGYJLEGWDQCWGFJYCSNTMYTOLBYGWQWESJPWNMLRYDZSZTXYQPZGCWXHNGPYXSHMYQJXZTDPPBFYHZHTJYFDZWKGKZBLDNTSXHQEEGZZYLZMMZYJZGXZXKHKSTXNXXWYLYAPSTHXDWHZYMPXAGKYDXBHNHXKDPJNMYHYLPMGOCSLNZHKXXLPZZLBMLSFBHHGYGYYGGBHSCYAQTYWLXTZQCEZYDQDQMMHTKLLSZHLSJZWFYHQSWSCWLQAZYNYTLSXTHAZNKZZSZZLAXXZWWCTGQQTDDYZTCCHYQZFLXPSLZYGPZSZNGLNDQTBDLXGTCTAJDKYWNSYZLJHHZZCWNYYZYWMHYCHHYXHJKZWSXHZYXLYSKQYSPSLYZWMYPPKBYGLKZHTYXAXQSYSHXASMCHKDSCRSWJPWXSGZJLWWSCHSJHSQNHCSEGNDAQTBAALZZMSSTDQJCJKTSCJAXPLGGXHHGXXZCXPDMMHLDGTYBYSJMXHMRCPXXJZCKZXSHMLQXXTTHXWZFKHCCZDYTCJYXQHLXDHYPJQXYLSYYDZOZJNYXQEZYSQYAYXWYPDGXDDXSPPYZNDLTWRHXYDXZZJHTCXMCZLHPYYYYMHZLLHNXMYLLLMDCPPXHMXDKYCYRDLTXJCHHZZXZLCCLYLNZSHZJZZLNNRLWHYQSNJHXYNTTTKYJPYCHHYEGKCTTWLGQRLGGTGTYGYHPYHYLQYQGCWYQKPYYYTTTTLHYHLLTYTTSPLKYZXGZWGPYDSSZZDQXSKCQNMJJZZBXYQMJRTFFBTKHZKBXLJJKDXJTLBWFZPPTKQTZTGPDGNTPJYFALQMKGXBDCLZFHZCLLLLADPMXDJHLCCLGYHDZFGYDDGCYYFGYDXKSSEBDHYKDKDKHNAXXYBPBYYHXZQGAFFQYJXDMLJCSQZLLPCHBSXGJYNDYBYQSPZWJLZKSDDTACTBXZDYZYPJZQSJNKKTKNJDJGYYPGTLFYQKASDNTCYHBLWDZHBBYDWJRYGKZYHEYYFJMSDTYFZJJHGCXPLXHLDWXXJKYTCYKSSSMTWCTTQZLPBSZDZWZXGZAGYKTYWXLHLSPBCLLOQMMZSSLCMBJCSZZKYDCZJGQQDSMCYTZQQLWZQZXSSFPTTFQMDDZDSHDTDWFHTDYZJYQJQKYPBDJYYXTLJHDRQXXXHAYDHRJLKLYTWHLLRLLRCXYLBWSRSZZSYMKZZHHKYHXKSMDSYDYCJPBZBSQLFCXXXNXKXWYWSDZYQOGGQMMYHCDZTTFJYYBGSTTTYBYKJDHKYXBELHTYPJQNFXFDYKZHQKZBYJTZBXHFDXKDASWTAWAJLDYJSFHBLDNNTNQJTJNCHXFJSRFWHZFMDRYJYJWZPDJKZYJYMPCYZNYNXFBYTFYFWYGDBNZZZDNYTXZEMMQBSQEHXFZMBMFLZZSRXYMJGSXWZJSPRYDJSJGXHJJGLJJYNZZJXHGXKYMLPYYYCXYTWQZSWHWLYRJLPXSLSXMFSWWKLCTNXNYNPSJSZHDZEPTXMYYWXYYSYWLXJQZQXZDCLEEELMCPJPCLWBXSQHFWWTFFJTNQJHJQDXHWLBYZNFJLALKYYJLDXHHYCSTYYWNRJYXYWTRMDRQHWQCMFJDYZMHMYYXJWMYZQZXTLMRSPWWCHAQBXYGZYPXYYRRCLMPYMGKSJSZYSRMYJSNXTPLNBAPPYPYLXYYZKYNLDZYJZCZNNLMZHHARQMPGWQTZMXXMLLHGDZXYHXKYXYCJMFFYYHJFSBSSQLXXNDYCANNMTCJCYPRRNYTYQNYYMBMSXNDLYLYSLJRLXYSXQMLLYZLZJJJKYZZCSFBZXXMSTBJGNXYZHLXNMCWSCYZYFZLXBRNNNYLBNRTGZQYSATSWRYHYJZMZDHZGZDWYBSSCSKXSYHYTXXGCQGXZZSHYXJSCRHMKKBXCZJYJYMKQHZJFNBHMQHYSNJNZYBKNQMCLGQHWLZNZSWXKHLJHYYBQLBFCDSXDLDSPFZPSKJYZWZXZDDXJSMMEGJSCSSMGCLXXKYYYLNYPWWWGYDKZJGGGZGGSYCKNJWNJPCXBJJTQTJWDSSPJXZXNZXUMELPXFSXTLLXCLJXJJLJZXCTPSWXLYDHLYQRWHSYCSQYYBYAYWJJJQFWQCQQCJQGXALDBZZYJGKGXPLTZYFXJLTPADKYQHPMATLCPDCKBMTXYBHKLENXDLEEGQDYMSAWHZMLJTWYGXLYQZLJEEYYBQQFFNLYXRDSCTGJGXYYNKLLYQKCCTLHJLQMKKZGCYYGLLLJDZGYDHZWXPYSJBZKDZGYZZHYWYFQYTYZSZYEZZLYMHJJHTSMQWYZLKYYWZCSRKQYTLTDXWCTYJKLWSQZWBDCQYNCJSRSZJLKCDCDTLZZZACQQZZDDXYPLXZBQJYLZLLLQDDZQJYJYJZYXNYYYNYJXKXDAZWYRDLJYYYRJLXLLDYXJCYWYWNQCCLDDNYYYNYCKCZHXXCCLGZQJGKWPPCQQJYSBZZXYJSQPXJPZBSBDSFNSFPZXHDWZTDWPPTFLZZBZDMYYPQJRSDZSQZSQXBDGCPZSWDWCSQZGMDHZXMWWFYBPDGPHTMJTHZSMMBGZMBZJCFZWFZBBZMQCFMBDMCJXLGPNJBBXGYHYYJGPTZGZMQBQTCGYXJXLWZKYDPDYMGCFTPFXYZTZXDZXTGKMTYBBCLBJASKYTSSQYYMSZXFJEWLXLLSZBQJJJAKLYLXLYCCTSXMCWFKKKBSXLLLLJYXTYLTJYYTDPJHNHNNKBYQNFQYYZBYYESSESSGDYHFHWTCJBSDZZTFDMXHCNJZYMQWSRYJDZJQPDQBBSTJGGFBKJBXTGQHNGWJXJGDLLTHZHHYYYYYYSXWTYYYCCBDBPYPZYCCZYJPZYWCBDLFWZCWJDXXHYHLHWZZXJTCZLCDPXUJCZZZLYXJJTXPHFXWPYWXZPTDZZBDZCYHJHMLXBQXSBYLRDTGJRRCTTTHYTCZWMXFYTWWZCWJWXJYWCSKYBZSCCTZQNHXNWXXKHKFHTSWOCCJYBCMPZZYKBNNZPBZHHZDLSYDDYTYFJPXYNGFXBYQXCBHXCPSXTYZDMKYSNXSXLHKMZXLYHDHKWHXXSSKQYHHCJYXGLHZXCSNHEKDTGZXQYPKDHEXTYKCNYMYYYPKQYYYKXZLTHJQTBYQHXBMYHSQCKWWYLLHCYYLNNEQXQWMCFBDCCMLJGGXDQKTLXKGNQCDGZJWYJJLYHHQTTTNWCHMXCXWHWSZJYDJCCDBQCDGDNYXZTHCQRXCBHZTQCBXWGQWYYBXHMBYMYQTYEXMQKYAQYRGYZSLFYKKQHYSSQYSHJGJCNXKZYCXSBXYXHYYLSTYCXQTHYSMGSCPMMGCCCCCMTZTASMGQZJHKLOSQYLSWTMXSYQKDZLJQQYPLSYCZTCQQPBBQJZCLPKHQZYYXXDTDDTSJCXFFLLCHQXMJLWCJCXTSPYCXNDTJSHJWXDQQJSKXYAMYLSJHMLALYKXCYYDMNMDQMXMCZNNCYBZKKYFLMCHCMLHXRCJJHSYLNMTJZGZGYWJXSRXCWJGJQHQZDQJDCJJZKJKGDZQGJJYJYLXZXXCDQHHHEYTMHLFSBDJSYYSHFYSTCZQLPBDRFRZTZYKYWHSZYQKWDQZRKMSYNBCRXQBJYFAZPZZEDZCJYWBCJWHYJBQSZYWRYSZPTDKZPFPBNZTKLQYHBBZPNPPTYZZYBQNYDCPJMMCYCQMCYFZZDCMNLFPBPLNGQJTBTTNJZPZBBZNJKLJQYLNBZQHKSJZNGGQSZZKYXSHPZSNBCGZKDDZQANZHJKDRTLZLSWJLJZLYWTJNDJZJHXYAYNCBGTZCSSQMNJPJYTYSWXZFKWJQTKHTZPLBHSNJZSYZBWZZZZLSYLSBJHDWWQPSLMMFBJDWAQYZTCJTBNNWZXQXCDSLQGDSDPDZHJTQQPSWLYYJZLGYXYZLCTCBJTKTYCZJTQKBSJLGMGZDMCSGPYNJZYQYYKNXRPWSZXMTNCSZZYXYBYHYZAXYWQCJTLLCKJJTJHGDXDXYQYZZBYWDLWQCGLZGJGQRQZCZSSBCRPCSKYDZNXJSQGXSSJMYDNSTZTPBDLTKZWXQWQTZEXNQCZGWEZKSSBYBRTSSSLCCGBPSZQSZLCCGLLLZXHZQTHCZMQGYZQZNMCOCSZJMMZSQPJYGQLJYJPPLDXRGZYXCCSXHSHGTZNLZWZKJCXTCFCJXLBMQBCZZWPQDNHXLJCTHYZLGYLNLSZZPCXDSCQQHJQKSXZPBAJYEMSMJTZDXLCJYRYYNWJBNGZZTMJXLTBSLYRZPYLSSCNXPHLLHYLLQQZQLXYMRSYCXZLMMCZLTZSDWTJJLLNZGGQXPFSKYGYGHBFZPDKMWGHCXMSGDXJMCJZDYCABXJDLNBCDQYGSKYDQTXDJJYXMSZQAZDZFSLQXYJSJZYLBTXXWXQQZBJZUFBBLYLWDSLJHXJYZJWTDJCZFQZQZZDZSXZZQLZCDZFJHYSPYMPQZMLPPLFFXJJNZZYLSJEYQZFPFZKSYWJJJHRDJZZXTXXGLGHYDXCSKYSWMMZCWYBAZBJKSHFHJCXMHFQHYXXYZFTSJYZFXYXPZLCHMZMBXHZZSXYFYMNCWDABAZLXKTCSHHXKXJJZJSTHYGXSXYYHHHJWXKZXSSBZZWHHHCWTZZZPJXSNXQQJGZYZYWLLCWXZFXXYXYHXMKYYSWSQMNLNAYCYSPMJKHWCQHYLAJJMZXHMMCNZHBHXCLXTJPLTXYJHDYYLTTXFSZHYXXSJBJYAYRSMXYPLCKDUYHLXRLNLLSTYZYYQYGYHHSCCSMZCTZQXKYQFPYYRPFFLKQUNTSZLLZMWWTCQQYZWTLLMLMPWMBZSSTZRBPDDTLQJJBXZCSRZQQYGWCSXFWZLXCCRSZDZMCYGGDZQSGTJSWLJMYMMZYHFBJDGYXCCPSHXNZCSBSJYJGJMPPWAFFYFNXHYZXZYLREMZGZCYZSSZDLLJCSQFNXZKPTXZGXJJGFMYYYSNBTYLBNLHPFZDCYFBMGQRRSSSZXYSGTZRNYDZZCDGPJAFJFZKNZBLCZSZPSGCYCJSZLMLRSZBZZLDLSLLYSXSQZQLYXZLSKKBRXBRBZCYCXZZZEEYFGKLZLYYHGZSGZLFJHGTGWKRAAJYZKZQTSSHJJXDCYZUYJLZYRZDQQHGJZXSSZBYKJPBFRTJXLLFQWJHYLQTYMBLPZDXTZYGBDHZZRBGXHWNJTJXLKSCFSMWLSDQYSJTXKZSCFWJLBXFTZLLJZLLQBLSQMQQCGCZFPBPHZCZJLPYYGGDTGWDCFCZQYYYQYSSCLXZSKLZZZGFFCQNWGLHQYZJJCZLQZZYJPJZZBPDCCMHJGXDQDGDLZQMFGPSYTSDYFWWDJZJYSXYYCZCYHZWPBYKXRYLYBHKJKSFXTZJMMCKHLLTNYYMSYXYZPYJQYCSYCWMTJJKQYRHLLQXPSGTLYYCLJSCPXJYZFNMLRGJJTYZBXYZMSJYJHHFZQMSYXRSZCWTLRTQZSSTKXGQKGSPTGCZNJSJCQCXHMXGGZTQYDJKZDLBZSXJLHYQGGGTHQSZPYHJHHGYYGKGGCWJZZYLCZLXQSFTGZSLLLMLJSKCTBLLZZSZMMNYTPZSXQHJCJYQXYZXZQZCPSHKZZYSXCDFGMWQRLLQXRFZTLYSTCTMJCXJJXHJNXTNRZTZFQYHQGLLGCXSZSJDJLJCYDSJTLNYXHSZXCGJZYQPYLFHDJSBPCCZHJJJQZJQDYBSSLLCMYTTMQTBHJQNNYGKYRQYQMZGCJKPDCGMYZHQLLSLLCLMHOLZGDYYFZSLJCQZLYLZQJESHNYLLJXGJXLYSYYYXNBZLJSSZCQQCJYLLZLTJYLLZLLBNYLGQCHXYYXOXCXQKYJXXXYKLXSXXYQXCYKQXQCSGYXXYQXYGYTQOHXHXPYXXXULCYEYCHZZCBWQBBWJQZSCSZSSLZYLKDESJZWMYMCYTSDSXXSCJPQQSQYLYYZYCMDJDZYWCBTJSYDJKCYDDJLBDJJSODZYSYXQQYXDHHGQQYQHDYXWGMMMAJDYBBBPPBCMUUPLJZSMTXERXJMHQNUTPJDCBSSMSSSTKJTSSMMTRCPLZSZMLQDSDMJMQPNQDXCFYNBFSDQXYXHYAYKQYDDLQYYYSSZBYDSLNTFQTZQPZMCHDHCZCWFDXTMYQSPHQYYXSRGJCWTJTZZQMGWJJTJHTQJBBHWZPXXHYQFXXQYWYYHYSCDYDHHQMNMTMWCPBSZPPZZGLMZFOLLCFWHMMSJZTTDHZZYFFYTZZGZYSKYJXQYJZQBHMBZZLYGHGFMSHPZFZSNCLPBQSNJXZSLXXFPMTYJYGBXLLDLXPZJYZJYHHZCYWHJYLSJEXFSZZYWXKZJLUYDTMLYMQJPWXYHXSKTQJEZRPXXZHHMHWQPWQLYJJQJJZSZCPHJLCHHNXJLQWZJHBMZYXBDHHYPZLHLHLGFWLCHYYTLHJXCJMSCPXSTKPNHQXSRTYXXTESYJCTLSSLSTDLLLWWYHDHRJZSFGXTSYCZYNYHTDHWJSLHTZDQDJZXXQHGYLTZPHCSQFCLNJTCLZPFSTPDYNYLGMJLLYCQHYSSHCHYLHQYQTMZYPBYWRFQYKQSYSLZDQJMPXYYSSRHZJNYWTQDFZBWWTWWRXCWHGYHXMKMYYYQMSMZHNGCEPMLQQMTCWCTMMPXJPJJHFXYYZSXZHTYBMSTSYJTTQQQYYLHYNPYQZLCYZHZWSMYLKFJXLWGXYPJYTYSYXYMZCKTTWLKSMZSYLMPWLZWXWQZSSAQSYXYRHSSNTSRAPXCPWCMGDXHXZDZYFJHGZTTSBJHGYZSZYSMYCLLLXBTYXHBBZJKSSDMALXHYCFYGMQYPJYCQXJLLLJGSLZGQLYCJCCZOTYXMTMTTLLWTGPXYMZMKLPSZZZXHKQYSXCTYJZYHXSHYXZKXLZWPSQPYHJWPJPWXQQYLXSDHMRSLZZYZWTTCYXYSZZSHBSCCSTPLWSSCJCHNLCGCHSSPHYLHFHHXJSXYLLNYLSZDHZXYLSXLWZYKCLDYAXZCMDDYSPJTQJZLNWQPSSSWCTSTSZLBLNXSMNYYMJQBQHRZWTYYDCHQLXKPZWBGQYBKFCMZWPZLLYYLSZYDWHXPSBCMLJBSCGBHXLQHYRLJXYSWXWXZSLDFHLSLYNJLZYFLYJYCDRJLFSYZFSLLCQYQFGJYHYXZLYLMSTDJCYHBZLLNWLXXYGYYHSMGDHXXHHLZZJZXCZZZCYQZFNGWPYLCPKPYYPMCLQKDGXZGGWQBDXZZKZFBXXLZXJTPJPTTBYTSZZDWSLCHZHSLTYXHQLHYXXXYYZYSWTXZKHLXZXZPYHGCHKCFSYHUTJRLXFJXPTZTWHPLYXFCRHXSHXKYXXYHZQDXQWULHYHMJTBFLKHTXCWHJFWJCFPQRYQXCYYYQYGRPYWSGSUNGWCHKZDXYFLXXHJJBYZWTSXXNCYJJYMSWZJQRMHXZWFQSYLZJZGBHYNSLBGTTCSYBYXXWXYHXYYXNSQYXMQYWRGYQLXBBZLJSYLPSYTJZYHYZAWLRORJMKSCZJXXXYXCHDYXRYXXJDTSQFXLYLTSFFYXLMTYJMJUYYYXLTZCSXQZQHZXLYYXZHDNBRXXXJCTYHLBRLMBRLLAXKYLLLJLYXXLYCRYLCJTGJCMTLZLLCYZZPZPCYAWHJJFYBDYYZSMPCKZDQYQPBPCJPDCYZMDPBCYYDYCNNPLMTMLRMFMMGWYZBSJGYGSMZQQQZTXMKQWGXLLPJGZBQCDJJJFPKJKCXBLJMSWMDTQJXLDLPPBXCWRCQFBFQJCZAHZGMYKPHYYHZYKNDKZMBPJYXPXYHLFPNYYGXJDBKXNXHJMZJXSTRSTLDXSKZYSYBZXJLXYSLBZYSLHXJPFXPQNBYLLJQKYGZMCYZZYMCCSLCLHZFWFWYXZMWSXTYNXJHPYYMCYSPMHYSMYDYSHQYZCHMJJMZCAAGCFJBBHPLYZYLXXSDJGXDHKXXTXXNBHRMLYJSLTXMRHNLXQJXYZLLYSWQGDLBJHDCGJYQYCMHWFMJYBMBYJYJWYMDPWHXQLDYGPDFXXBCGJSPCKRSSYZJMSLBZZJFLJJJLGXZGYXYXLSZQYXBEXYXHGCXBPLDYHWETTWWCJMBTXCHXYQXLLXFLYXLLJLSSFWDPZSMYJCLMWYTCZPCHQEKCQBWLCQYDPLQPPQZQFJQDJHYMMCXTXDRMJWRHXCJZYLQXDYYNHYYHRSLSRSYWWZJYMTLTLLGTQCJZYABTCKZCJYCCQLJZQXALMZYHYWLWDXZXQDLLQSHGPJFJLJHJABCQZDJGTKHSSTCYJLPSWZLXZXRWGLDLZRLZXTGSLLLLZLYXXWGDZYGBDPHZPBRLWSXQBPFDWOFMWHLYPCBJCCLDMBZPBZZLCYQXLDOMZBLZWPDWYYGDSTTHCSQSCCRSSSYSLFYBFNTYJSZDFNDPDHDZZMBBLSLCMYFFGTJJQWFTMTPJWFNLBZCMMJTGBDZLQLPYFHYYMJYLSDCHDZJWJCCTLJCLDTLJJCPDDSQDSSZYBNDBJLGGJZXSXNLYCYBJXQYCBYLZCFZPPGKCXZDZFZTJJFJSJXZBNZYJQTTYJYHTYCZHYMDJXTTMPXSPLZCDWSLSHXYPZGTFMLCJTYCBPMGDKWYCYZCDSZZYHFLYCTYGWHKJYYLSJCXGYWJCBLLCSNDDBTZBSCLYZCZZSSQDLLMQYYHFSLQLLXFTYHABXGWNYWYYPLLSDLDLLBJCYXJZMLHLJDXYYQYTDLLLBUGBFDFBBQJZZMDPJHGCLGMJJPGAEHHBWCQXAXHHHZCHXYPHJAXHLPHJPGPZJQCQZGJJZZUZDMQYYBZZPHYHYBWHAZYJHYKFGDPFQSDLZMLJXKXGALXZDAGLMDGXMWZQYXXDXXPFDMMSSYMPFMDMMKXKSYZYSHDZKXSYSMMZZZMSYDNZZCZXFPLSTMZDNMXCKJMZTYYMZMZZMSXHHDCZJEMXXKLJSTLWLSQLYJZLLZJSSDPPMHNLZJCZYHMXXHGZCJMDHXTKGRMXFWMCGMWKDTKSXQMMMFZZYDKMSCLCMPCGMHSPXQPZDSSLCXKYXTWLWJYAHZJGZQMCSNXYYMMPMLKJXMHLMLQMXCTKZMJQYSZJSYSZHSYJZJCDAJZYBSDQJZGWZQQXFKDMSDJLFWEHKZQKJPEYPZYSZCDWYJFFMZZYLTTDZZEFMZLBNPPLPLPEPSZALLTYLKCKQZKGENQLWAGYXYDPXLHSXQQWQCQXQCLHYXXMLYCCWLYMQYSKGCHLCJNSZKPYZKCQZQLJPDMDZHLASXLBYDWQLWDNBQCRYDDZTJYBKBWSZDXDTNPJDTCTQDFXQQMGNXECLTTBKPWSLCTYQLPWYZZKLPYGZCQQPLLKCCYLPQMZCZQCLJSLQZDJXLDDHPZQDLJJXZQDXYZQKZLJCYQDYJPPYPQYKJYRMPCBYMCXKLLZLLFQPYLLLMBSGLCYSSLRSYSQTMXYXZQZFDZUYSYZTFFMZZSMZQHZSSCCMLYXWTPZGXZJGZGSJSGKDDHTQGGZLLBJDZLCBCHYXYZHZFYWXYZYMSDBZZYJGTSMTFXQYXQSTDGSLNXDLRYZZLRYYLXQHTXSRTZNGZXBNQQZFMYKMZJBZYMKBPNLYZPBLMCNQYZZZSJZHJCTZKHYZZJRDYZHNPXGLFZTLKGJTCTSSYLLGZRZBBQZZKLPKLCZYSSUYXBJFPNJZZXCDWXZYJXZZDJJKGGRSRJKMSMZJLSJYWQSKYHQJSXPJZZZLSNSHRNYPZTWCHKLPSRZLZXYJQXQKYSJYCZTLQZYBBYBWZPQDWWYZCYTJCJXCKCWDKKZXSGKDZXWWYYJQYYTCYTDLLXWKCZKKLCCLZCQQDZLQLCSFQCHQHSFSMQZZLNBJJZBSJHTSZDYSJQJPDLZCDCWJKJZZLPYCGMZWDJJBSJQZSYZYHHXJPBJYDSSXDZNCGLQMBTSFSBPDZDLZNFGFJGFSMPXJQLMBLGQCYYXBQKDJJQYRFKZTJDHCZKLBSDZCFJTPLLJGXHYXZCSSZZXSTJYGKGCKGYOQXJPLZPBPGTGYJZGHZQZZLBJLSQFZGKQQJZGYCZBZQTLDXRJXBSXXPZXHYZYCLWDXJJHXMFDZPFZHQHQMQGKSLYHTYCGFRZGNQXCLPDLBZCSCZQLLJBLHBZCYPZZPPDYMZZSGYHCKCPZJGSLJLNSCDSLDLXBMSTLDDFJMKDJDHZLZXLSZQPQPGJLLYBDSZGQLBZLSLKYYHZTTNTJYQTZZPSZQZTLLJTYYLLQLLQYZQLBDZLSLYYZYMDFSZSNHLXZNCZQZPBWSKRFBSYZMTHBLGJPMCZZLSTLXSHTCSYZLZBLFEQHLXFLCJLYLJQCBZLZJHHSSTBRMHXZHJZCLXFNBGXGTQJCZTMSFZKJMSSNXLJKBHSJXNTNLZDNTLMSJXGZJYJCZXYJYJWRWWQNZTNFJSZPZSHZJFYRDJSFSZJZBJFZQZZHZLXFYSBZQLZSGYFTZDCSZXZJBQMSZKJRHYJZCKMJKHCHGTXKXQGLXPXFXTRTYLXJXHDTSJXHJZJXZWZLCQSBTXWXGXTXXHXFTSDKFJHZYJFJXRZSDLLLTQSQQZQWZXSYQTWGWBZCGZLLYZBCLMQQTZHZXZXLJFRMYZFLXYSQXXJKXRMQDZDMMYYBSQBHGZMWFWXGMXLZPYYTGZYCCDXYZXYWGSYJYZNBHPZJSQSYXSXRTFYZGRHZTXSZZTHCBFCLSYXZLZQMZLMPLMXZJXSFLBYZMYQHXJSXRXSQZZZSSLYFRCZJRCRXHHZXQYDYHXSJJHZCXZBTYNSYSXJBQLPXZQPYMLXZKYXLXCJLCYSXXZZLXDLLLJJYHZXGYJWKJRWYHCPSGNRZLFZWFZZNSXGXFLZSXZZZBFCSYJDBRJKRDHHGXJLJJTGXJXXSTJTJXLYXQFCSGSWMSBCTLQZZWLZZKXJMLTMJYHSDDBXGZHDLBMYJFRZFSGCLYJBPMLYSMSXLSZJQQHJZFXGFQFQBPXZGYYQXGZTCQWYLTLGWSGWHRLFSFGZJMGMGBGTJFSYZZGZYZAFLSSPMLPFLCWBJZCLJJMZLPJJLYMQDMYYYFBGYGYZMLYZDXQYXRQQQHSYYYQXYLJTYXFSFSLLGNQCYHYCWFHCCCFXPYLYPLLZYXXXXXKQHHXSHJZCFZSCZJXCPZWHHHHHAPYLQALPQAFYHXDYLUKMZQGGGDDESRNNZLTZGCHYPPYSQJJHCLLJTOLNJPZLJLHYMHEYDYDSQYCDDHGZUNDZCLZYZLLZNTNYZGSLHSLPJJBDGWXPCDUTJCKLKCLWKLLCASSTKZZDNQNTTLYYZSSYSSZZRYLJQKCQDHHCRXRZYDGRGCWCGZQFFFPPJFZYNAKRGYWYQPQXXFKJTSZZXSWZDDFBBXTBGTZKZNPZZPZXZPJSZBMQHKCYXYLDKLJNYPKYGHGDZJXXEAHPNZKZTZCMXCXMMJXNKSZQNMNLWBWWXJKYHCPSTMCSQTZJYXTPCTPDTNNPGLLLZSJLSPBLPLQHDTNJNLYYRSZFFJFQWDPHZDWMRZCCLODAXNSSNYZRESTYJWJYJDBCFXNMWTTBYLWSTSZGYBLJPXGLBOCLHPCBJLTMXZLJYLZXCLTPNCLCKXTPZJSWCYXSFYSZDKNTLBYJCYJLLSTGQCBXRYZXBXKLYLHZLQZLNZCXWJZLJZJNCJHXMNZZGJZZXTZJXYCYYCXXJYYXJJXSSSJSTSSTTPPGQTCSXWZDCSYFPTFBFHFBBLZJCLZZDBXGCXLQPXKFZFLSYLTUWBMQJHSZBMDDBCYSCCLDXYCDDQLYJJWMQLLCSGLJJSYFPYYCCYLTJANTJJPWYCMMGQYYSXDXQMZHSZXPFTWWZQSWQRFKJLZJQQYFBRXJHHFWJJZYQAZMYFRHCYYBYQWLPEXCCZSTYRLTTDMQLYKMBBGMYYJPRKZNPBSXYXBHYZDJDNGHPMFSGMWFZMFQMMBCMZZCJJLCNUXYQLMLRYGQZCYXZLWJGCJCGGMCJNFYZZJHYCPRRCMTZQZXHFQGTJXCCJEAQCRJYHPLQLSZDJRBCQHQDYRHYLYXJSYMHZYDWLDFRYHBPYDTSSCNWBXGLPZMLZZTQSSCPJMXXYCSJYTYCGHYCJWYRXXLFEMWJNMKLLSWTXHYYYNCMMCWJDQDJZGLLJWJRKHPZGGFLCCSCZMCBLTBHBQJXQDSPDJZZGKGLFQYWBZYZJLTSTDHQHCTCBCHFLQMPWDSHYYTQWCNZZJTLBYMBPDYYYXSQKXWYYFLXXNCWCXYPMAELYKKJMZZZBRXYYQJFLJPFHHHYTZZXSGQQMHSPGDZQWBWPJHZJDYSCQWZKTXXSQLZYYMYSDZGRXCKKUJLWPYSYSCSYZLRMLQSYLJXBCXTLWDQZPCYCYKPPPNSXFYZJJRCEMHSZMSXLXGLRWGCSTLRSXBZGBZGZTCPLUJLSLYLYMTXMTZPALZXPXJTJWTCYYZLBLXBZLQMYLXPGHDSLSSDMXMBDZZSXWHAMLCZCPJMCNHJYSNSYGCHSKQMZZQDLLKABLWJXSFMOCDXJRRLYQZKJMYBYQLYHETFJZFRFKSRYXFJTWDSXXSYSQJYSLYXWJHSNLXYYXHBHAWHHJZXWMYLJCSSLKYDZTXBZSYFDXGXZJKHSXXYBSSXDPYNZWRPTQZCZENYGCXQFJYKJBZMLJCMQQXUOXSLYXXLYLLJDZBTYMHPFSTTQQWLHOKYBLZZALZXQLHZWRRQHLSTMYPYXJJXMQSJFNBXYXYJXXYQYLTHYLQYFMLKLJTMLLHSZWKZHLJMLHLJKLJSTLQXYLMBHHLNLZXQJHXCFXXLHYHJJGBYZZKBXSCQDJQDSUJZYYHZHHMGSXCSYMXFEBCQWWRBPYYJQTYZCYQYQQZYHMWFFHGZFRJFCDPXNTQYZPDYKHJLFRZXPPXZDBBGZQSTLGDGYLCQMLCHHMFYWLZYXKJLYPQHSYWMQQGQZMLZJNSQXJQSYJYCBEHSXFSZPXZWFLLBCYYJDYTDTHWZSFJMQQYJLMQXXLLDTTKHHYBFPWTYYSQQWNQWLGWDEBZWCMYGCULKJXTMXMYJSXHYBRWFYMWFRXYQMXYSZTZZTFYKMLDHQDXWYYNLCRYJBLPSXCXYWLSPRRJWXHQYPHTYDNXHHMMYWYTZCSQMTSSCCDALWZTCPQPYJLLQZYJSWXMZZMMYLMXCLMXCZMXMZSQTZPPQQBLPGXQZHFLJJHYTJSRXWZXSCCDLXTYJDCQJXSLQYCLZXLZZXMXQRJMHRHZJBHMFLJLMLCLQNLDXZLLLPYPSYJYSXCQQDCMQJZZXHNPNXZMEKMXHYKYQLXSXTXJYYHWDCWDZHQYYBGYBCYSCFGPSJNZDYZZJZXRZRQJJYMCANYRJTLDPPYZBSTJKXXZYPFDWFGZZRPYMTNGXZQBYXNBUFNQKRJQZMJEGRZGYCLKXZDSKKNSXKCLJSPJYYZLQQJYBZSSQLLLKJXTBKTYLCCDDBLSPPFYLGYDTZJYQGGKQTTFZXBDKTYYHYBBFYTYYBCLPDYTGDHRYRNJSPTCSNYJQHKLLLZSLYDXXWBCJQSPXBPJZJCJDZFFXXBRMLAZHCSNDLBJDSZBLPRZTSWSBXBCLLXXLZDJZSJPYLYXXYFTFFFBHJJXGBYXJPMMMPSSJZJMTLYZJXSWXTYLEDQPJMYGQZJGDJLQJWJQLLSJGJGYGMSCLJJXDTYGJQJQJCJZCJGDZZSXQGSJGGCXHQXSNQLZZBXHSGZXCXYLJXYXYYDFQQJHJFXDHCTXJYRXYSQTJXYEFYYSSYYJXNCYZXFXMSYSZXYYSCHSHXZZZGZZZGFJDLTYLNPZGYJYZYYQZPBXQBDZTZCZYXXYHHSQXSHDHGQHJHGYWSZTMZMLHYXGEBTYLZKQWYTJZRCLEKYSTDBCYKQQSAYXCJXWWGSBHJYZYDHCSJKQCXSWXFLTYNYZPZCCZJQTZWJQDZZZQZLJJXLSBHPYXXPSXSHHEZTXFPTLQYZZXHYTXNCFZYYHXGNXMYWXTZSJPTHHGYMXMXQZXTSBCZYJYXXTYYZYPCQLMMSZMJZZLLZXGXZAAJZYXJMZXWDXZSXZDZXLEYJJZQBHZWZZZQTZPSXZTDSXJJJZNYAZPHXYYSRNQDTHZHYYKYJHDZXZLSWCLYBZYECWCYCRYLCXNHZYDZYDYJDFRJJHTRSQTXYXJRJHOJYNXELXSFSFJZGHPZSXZSZDZCQZBYYKLSGSJHCZSHDGQGXYZGXCHXZJWYQWGYHKSSEQZZNDZFKWYSSTCLZSTSYMCDHJXXYWEYXCZAYDMPXMDSXYBSQMJMZJMTZQLPJYQZCGQHXJHHLXXHLHDLDJQCLDWBSXFZZYYSCHTYTYYBHECXHYKGJPXHHYZJFXHWHBDZFYZBCAPNPGNYDMSXHMMMMAMYNBYJTMPXYYMCTHJBZYFCGTYHWPHFTWZZEZSBZEGPFMTSKFTYCMHFLLHGPZJXZJGZJYXZSBBQSCZZLZCCSTPGXMJSFTCCZJZDJXCYBZLFCJSYZFGSZLYBCWZZBYZDZYPSWYJZXZBDSYUXLZZBZFYGCZXBZHZFTPBGZGEJBSTGKDMFHYZZJHZLLZZGJQZLSFDJSSCBZGPDLFZFZSZYZYZSYGCXSNXXCHCZXTZZLJFZGQSQYXZJQDCCZTQCDXZJYQJQCHXZTDLGSCXZSYQJQTZWLQDQZTQCHQQJZYEZZZPBWKDJFCJPZTYPQYQTTYNLMBDKTJZPQZQZZFPZSBNJLGYJDXJDZZKZGQKXDLPZJTCJDQBXDJQJSTCKNXBXZMSLYJCQMTJQWWCJQNJNLLLHJCWQTBZQYDZCZPZZDZYDDCYZZZCCJTTJFZDPRRTZTJDCQTQZDTJNPLZBCLLCTZSXKJZQZPZLBZRBTJDCXFCZDBCCJJLTQQPLDCGZDBBZJCQDCJWYNLLZYZCCDWLLXWZLXRXNTQQCZXKQLSGDFQTDDGLRLAJJTKUYMKQLLTZYTDYYCZGJWYXDXFRSKSTQTENQMRKQZHHQKDLDAZFKYPBGGPZREBZZYKZZSPEGJXGYKQZZZSLYSYYYZWFQZYLZZLZHWCHKYPQGNPGBLPLRRJYXCCSYYHSFZFYBZYYTGZXYLXCZWXXZJZBLFFLGSKHYJZEYJHLPLLLLCZGXDRZELRHGKLZZYHZLYQSZZJZQLJZFLNBHGWLCZCFJYSPYXZLZLXGCCPZBLLCYBBBBUBBCBPCRNNZCZYRBFSRLDCGQYYQXYGMQZWTZYTYJXYFWTEHZZJYWLCCNTZYJJZDEDPZDZTSYQJHDYMBJNYJZLXTSSTPHNDJXXBYXQTZQDDTJTDYYTGWSCSZQFLSHLGLBCZPHDLYZJYCKWTYTYLBNYTSDSYCCTYSZYYEBHEXHQDTWNYGYCLXTSZYSTQMYGZAZCCSZZDSLZCLZRQXYYELJSBYMXSXZTEMBBLLYYLLYTDQYSHYMRQWKFKBFXNXSBYCHXBWJYHTQBPBSBWDZYLKGZSKYHXQZJXHXJXGNLJKZLYYCDXLFYFGHLJGJYBXQLYBXQPQGZTZPLNCYPXDJYQYDYMRBESJYYHKXXSTMXRCZZYWXYQYBMCLLYZHQYZWQXDBXBZWZMSLPDMYSKFMZKLZCYQYCZLQXFZZYDQZPZYGYJYZMZXDZFYFYTTQTZHGSPCZMLCCYTZXJCYTJMKSLPZHYSNZLLYTPZCTZZCKTXDHXXTQCYFKSMQCCYYAZHTJPCYLZLYJBJXTPNYLJYYNRXSYLMMNXJSMYBCSYSYLZYLXJJQYLDZLPQBFZZBLFNDXQKCZFYWHGQMRDSXYCYTXNQQJZYYPFZXDYZFPRXEJDGYQBXRCNFYYQPGHYJDYZXGRHTKYLNWDZNTSMPKLBTHBPYSZBZTJZSZZJTYYXZPHSSZZBZCZPTQFZMYFLYPYBBJQXZMXXDJMTSYSKKBJZXHJCKLPSMKYJZCXTMLJYXRZZQSLXXQPYZXMKYXXXJCLJPRMYYGADYSKQLSNDHYZKQXZYZTCGHZTLMLWZYBWSYCTBHJHJFCWZTXWYTKZLXQSHLYJZJXTMPLPYCGLTBZZTLZJCYJGDTCLKLPLLQPJMZPAPXYZLKKTKDZCZZBNZDYDYQZJYJGMCTXLTGXSZLMLHBGLKFWNWZHDXUHLFMKYSLGXDTWWFRJEJZTZHYDXYKSHWFZCQSHKTMQQHTZHYMJDJSKHXZJZBZZXYMPAGQMSTPXLSKLZYNWRTSQLSZBPSPSGZWYHTLKSSSWHZZLYYTNXJGMJSZSUFWNLSOZTXGXLSAMMLBWLDSZYLAKQCQCTMYCFJBSLXCLZZCLXXKSBZQCLHJPSQPLSXXCKSLNHPSFQQYTXYJZLQLDXZQJZDYYDJNZPTUZDSKJFSLJHYLZSQZLBTXYDGTQFDBYAZXDZHZJNHHQBYKNXJJQCZMLLJZKSPLDYCLBBLXKLELXJLBQYCXJXGCNLCQPLZLZYJTZLJGYZDZPLTQCSXFDMNYCXGBTJDCZNBGBQYQJWGKFHTNPYQZQGBKPBBYZMTJDYTBLSQMPSXTBNPDXKLEMYYCJYNZCTLDYKZZXDDXHQSHDGMZSJYCCTAYRZLPYLTLKXSLZCGGEXCLFXLKJRTLQJAQZNCMBYDKKCXGLCZJZXJHPTDJJMZQYKQSECQZDSHHADMLZFMMZBGNTJNNLGBYJBRBTMLBYJDZXLCJLPLDLPCQDHLXZLYCBLCXZZJADJLNZMMSSSMYBHBSQKBHRSXXJMXSDZNZPXLGBRHWGGFCXGMSKLLTSJYYCQLTSKYWYYHYWXBXQYWPYWYKQLSQPTNTKHQCWDQKTWPXXHCPTHTWUMSSYHBWCRWXHJMKMZNGWTMLKFGHKJYLSYYCXWHYECLQHKQHTTQKHFZLDXQWYZYYDESBPKYRZPJFYYZJCEQDZZDLATZBBFJLLCXDLMJSSXEGYGSJQXCWBXSSZPDYZCXDNYXPPZYDLYJCZPLTXLSXYZYRXCYYYDYLWWNZSAHJSYQYHGYWWAXTJZDAXYSRLTDPSSYYFNEJDXYZHLXLLLZQZSJNYQYQQXYJGHZGZCYJCHZLYCDSHWSHJZYJXCLLNXZJJYYXNFXMWFPYLCYLLABWDDHWDXJMCXZTZPMLQZHSFHZYNZTLLDYWLSLXHYMMYLMBWWKYXYADTXYLLDJPYBPWUXJMWMLLSAFDLLYFLBHHHBQQLTZJCQJLDJTFFKMMMBYTHYGDCQRDDWRQJXNBYSNWZDBYYTBJHPYBYTTJXAAHGQDQTMYSTQXKBTZPKJLZRBEQQSSMJJBDJOTGTBXPGBKTLHQXJJJCTHXQDWJLWRFWQGWSHCKRYSWGFTGYGBXSDWDWRFHWYTJJXXXJYZYSLPYYYPAYXHYDQKXSHXYXGSKQHYWFDDDPPLCJLQQEEWXKSYYKDYPLTJTHKJLTCYYHHJTTPLTZZCDLTHQKZXQYSTEEYWYYZYXXYYSTTJKLLPZMCYHQGXYHSRMBXPLLNQYDQHXSXXWGDQBSHYLLPJJJTHYJKYPPTHYYKTYEZYENMDSHLCRPQFDGFXZPSFTLJXXJBSWYYSKSFLXLPPLBBBLBSFXFYZBSJSSYLPBBFFFFSSCJDSTZSXZRYYSYFFSYZYZBJTBCTSBSDHRTJJBYTCXYJEYLXCBNEBJDSYXYKGSJZBXBYTFZWGENYHHTHZHHXFWGCSTBGXKLSXYWMTMBYXJSTZSCDYQRCYTWXZFHMYMCXLZNSDJTTTXRYCFYJSBSDYERXJLJXBBDEYNJGHXGCKGSCYMBLXJMSZNSKGXFBNBPTHFJAAFXYXFPXMYPQDTZCXZZPXRSYWZDLYBBKTYQPQJPZYPZJZNJPZJLZZFYSBTTSLMPTZRTDXQSJEHBZYLZDHLJSQMLHTXTJECXSLZZSPKTLZKQQYFSYGYWPCPQFHQHYTQXZKRSGTTSQCZLPTXCDYYZXSQZSLXLZMYCPCQBZYXHBSXLZDLTCDXTYLZJYYZPZYZLTXJSJXHLPMYTXCQRBLZSSFJZZTNJYTXMYJHLHPPLCYXQJQQKZZSCPZKSWALQSBLCCZJSXGWWWYGYKTJBBZTDKHXHKGTGPBKQYSLPXPJCKBMLLXDZSTBKLGGQKQLSBKKTFXRMDKBFTPZFRTBBRFERQGXYJPZSSTLBZTPSZQZSJDHLJQLZBPMSMMSXLQQNHKNBLRDDNXXDHDDJCYYGYLXGZLXSYGMQQGKHBPMXYXLYTQWLWGCPBMQXCYZYDRJBHTDJYHQSHTMJSBYPLWHLZFFNYPMHXXHPLTBQPFBJWQDBYGPNZTPFZJGSDDTQSHZEAWZZYLLTYYBWJKXXGHLFKXDJTMSZSQYNZGGSWQSPHTLSSKMCLZXYSZQZXNCJDQGZDLFNYKLJCJLLZLMZZNHYDSSHTHZZLZZBBHQZWWYCRZHLYQQJBEYFXXXWHSRXWQHWPSLMSSKZTTYGYQQWRSLALHMJTQJSMXQBJJZJXZYZKXBYQXBJXSHZTSFJLXMXZXFGHKZSZGGYLCLSARJYHSLLLMZXELGLXYDJYTLFBHBPNLYZFBBHPTGJKWETZHKJJXZXXGLLJLSTGSHJJYQLQZFKCGNNDJSSZFDBCTWWSEQFHQJBSAQTGYPQLBXBMMYWXGSLZHGLZGQYFLZBYFZJFRYSFMBYZHQGFWZSYFYJJPHZBYYZFFWODGRLMFTWLBZGYCQXCDJYGZYYYYTYTYDWEGAZYHXJLZYYHLRMGRXXZCLHNELJJTJTPWJYBJJBXJJTJTEEKHWSLJPLPSFYZPQQBDLQJJTYYQLYZKDKSQJYYQZLDQTGJQYZJSUCMRYQTHTEJMFCTYHYPKMHYZWJDQFHYYXWSHCTXRLJHQXHCCYYYJLTKTTYTMXGTCJTZAYYOCZLYLBSZYWJYTSJYHBYSHFJLYGJXXTMZYYLTXXYPZLXYJZYZYYPNHMYMDYYLBLHLSYYQQLLNJJYMSOYQBZGDLYXYLCQYXTSZEGXHZGLHWBLJHEYXTWQMAKBPQCGYSHHEGQCMWYYWLJYJHYYZLLJJYLHZYHMGSLJLJXCJJYCLYCJPCPZJZJMMYLCQLNQLJQJSXYJMLSZLJQLYCMMHCFMMFPQQMFYLQMCFFQMMMMHMZNFHHJGTTHHKHSLNCHHYQDXTMMQDCYZYXYQMYQYLTDCYYYZAZZCYMZYDLZFFFMMYCQZWZZMABTBYZTDMNZZGGDFTYPCGQYTTSSFFWFDTZQSSYSTWXJHXYTSXXYLBYQHWWKXHZXWZNNZZJZJJQJCCCHYYXBZXZCYZTLLCQXYNJYCYYCYNZZQYYYEWYCZDCJYCCHYJLBTZYYCQWMPWPYMLGKDLDLGKQQBGYCHJXY";
//此处收录了375个多音字,数据来自于http://www.51window.net/page/pinyin
var oMultiDiff={"19969":"DZ","19975":"WM","19988":"QJ","20048":"YL","20056":"SC","20060":"NM","20094":"QG","20127":"QJ","20167":"QC","20193":"YG","20250":"KH","20256":"ZC","20282":"SC","20285":"QJG","20291":"TD","20314":"YD","20340":"NE","20375":"TD","20389":"YJ","20391":"CZ","20415":"PB","20446":"YS","20447":"SQ","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20985":"AW","21032":"PB","21048":"XQ","21049":"SC","21089":"YS","21119":"JC","21242":"SB","21273":"SC","21305":"YP","21306":"QO","21330":"ZC","21333":"SDC","21345":"QK","21378":"CA","21397":"SC","21414":"XS","21442":"SC","21477":"JG","21480":"TD","21484":"ZS","21494":"YX","21505":"YX","21512":"HG","21523":"XH","21537":"PB","21542":"PF","21549":"KH","21571":"E","21574":"DA","21588":"TD","21589":"O","21618":"ZC","21621":"KHA","21632":"ZJ","21654":"KG","21679":"LKG","21683":"KH","21710":"A","21719":"YH","21734":"WOE","21769":"A","21780":"WN","21804":"XH","21834":"A","21899":"ZD","21903":"RN","21908":"WO","21939":"ZC","21956":"SA","21964":"YA","21970":"TD","22003":"A","22031":"JG","22040":"XS","22060":"ZC","22066":"ZC","22079":"MH","22129":"XJ","22179":"XA","22237":"NJ","22244":"TD","22280":"JQ","22300":"YH","22313":"XW","22331":"YQ","22343":"YJ","22351":"PH","22395":"DC","22412":"TD","22484":"PB","22500":"PB","22534":"ZD","22549":"DH","22561":"PB","22612":"TD","22771":"KQ","22831":"HB","22841":"JG","22855":"QJ","22865":"XQ","23013":"ML","23081":"WM","23487":"SX","23558":"QJ","23561":"YW","23586":"YW","23614":"YW","23615":"SN","23631":"PB","23646":"ZS","23663":"ZT","23673":"YG","23762":"TD","23769":"ZS","23780":"QJ","23884":"QK","24055":"XH","24113":"DC","24162":"ZC","24191":"GA","24273":"QJ","24324":"NL","24377":"TD","24378":"QJ","24439":"PF","24554":"ZS","24683":"TD","24694":"WE","24733":"LK","24925":"TN","25094":"ZG","25100":"XQ","25103":"XH","25153":"PB","25170":"PB","25179":"KG","25203":"PB","25240":"ZS","25282":"FB","25303":"NA","25324":"KG","25341":"ZY","25373":"WZ","25375":"XJ","25384":"A","25457":"A","25528":"SD","25530":"SC","25552":"TD","25774":"ZC","25874":"ZC","26044":"YW","26080":"WM","26292":"PB","26333":"PB","26355":"ZY","26366":"CZ","26397":"ZC","26399":"QJ","26415":"ZS","26451":"SB","26526":"ZC","26552":"JG","26561":"TD","26588":"JG","26597":"CZ","26629":"ZS","26638":"YL","26646":"XQ","26653":"KG","26657":"XJ","26727":"HG","26894":"ZC","26937":"ZS","26946":"ZC","26999":"KJ","27099":"KJ","27449":"YQ","27481":"XS","27542":"ZS","27663":"ZS","27748":"TS","27784":"SC","27788":"ZD","27795":"TD","27812":"O","27850":"PB","27852":"MB","27895":"SL","27898":"PL","27973":"QJ","27981":"KH","27986":"HX","27994":"XJ","28044":"YC","28065":"WG","28177":"SM","28267":"QJ","28291":"KH","28337":"ZQ","28463":"TL","28548":"DC","28601":"TD","28689":"PB","28805":"JG","28820":"QG","28846":"PB","28952":"TD","28975":"ZC","29100":"A","29325":"QJ","29575":"SL","29602":"FB","30010":"TD","30044":"CX","30058":"PF","30091":"YSP","30111":"YN","30229":"XJ","30427":"SC","30465":"SX","30631":"YQ","30655":"QJ","30684":"QJG","30707":"SD","30729":"XH","30796":"LG","30917":"PB","31074":"NM","31085":"JZ","31109":"SC","31181":"ZC","31192":"MLB","31293":"JQ","31400":"YX","31584":"YJ","31896":"ZN","31909":"ZY","31995":"XJ","32321":"PF","32327":"ZY","32418":"HG","32420":"XQ","32421":"HG","32438":"LG","32473":"GJ","32488":"TD","32521":"QJ","32527":"PB","32562":"ZSQ","32564":"JZ","32735":"ZD","32793":"PB","33071":"PF","33098":"XL","33100":"YA","33152":"PB","33261":"CX","33324":"BP","33333":"TD","33406":"YA","33426":"WM","33432":"PB","33445":"JG","33486":"ZN","33493":"TS","33507":"QJ","33540":"QJ","33544":"ZC","33564":"XQ","33617":"YT","33632":"QJ","33636":"XH","33637":"YX","33694":"WG","33705":"PF","33728":"YW","33882":"SR","34067":"WM","34074":"YW","34121":"QJ","34255":"ZC","34259":"XL","34425":"JH","34430":"XH","34485":"KH","34503":"YS","34532":"HG","34552":"XS","34558":"YE","34593":"ZL","34660":"YQ","34892":"XH","34928":"SC","34999":"QJ","35048":"PB","35059":"SC","35098":"ZC","35203":"TQ","35265":"JX","35299":"JX","35782":"SZ","35828":"YS","35830":"E","35843":"TD","35895":"YG","35977":"MH","36158":"JG","36228":"QJ","36426":"XQ","36466":"DC","36710":"JC","36711":"ZYG","36767":"PB","36866":"SK","36951":"YW","37034":"YX","37063":"XH","37218":"ZC","37325":"ZC","38063":"PB","38079":"TD","38085":"QY","38107":"DC","38116":"TD","38123":"YD","38224":"HG","38241":"XTC","38271":"ZC","38415":"YE","38426":"KH","38461":"YD","38463":"AE","38466":"PB","38477":"XJ","38518":"YT","38551":"WK","38585":"ZC","38704":"XS","38739":"LJ","38761":"GJ","38808":"SQ","39048":"JG","39049":"XJ","39052":"HG","39076":"CZ","39271":"XT","39534":"TD","39552":"TD","39584":"PB","39647":"SB","39730":"LG","39748":"TPB","40109":"ZQ","40479":"ND","40516":"HG","40536":"HG","40583":"QJ","40765":"YQ","40784":"QJ","40840":"YK","40863":"QJG"};
//参数,中文字符串
//返回值:拼音首字母串数组
function makePy(str){
if(typeof(str) != "string")
throw new Error(-1,"函数makePy需要字符串类型参数!");
var arrResult = new Array(); //保存中间结果的数组
for( | 0,len=str.length;i<len;i++){
//获得unicode码
var ch = str.charAt(i);
//检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理
arrResult.push(checkCh(ch));
}
//处理arrResult,返回所有可能的拼音首字母串数组
return mkRslt(arrResult);
}
function checkCh(ch){
var uni = ch.charCodeAt(0);
//如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数
if(uni > 40869 || uni < 19968)
return ch; //dealWithOthers(ch);
//检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母
return (oMultiDiff[uni]?oMultiDiff[uni]:(strChineseFirstPY.charAt(uni-19968)));
}
function mkRslt(arr){
var arrRslt = [""];
for(var i=0,len=arr.length;i<len;i++){
var str = arr[i];
var strlen = str.length;
if(strlen == 1){
for(var k=0;k<arrRslt.length;k++){
arrRslt[k] += str;
}
}else{
var tmpArr = arrRslt.slice(0);
arrRslt = [];
for(k=0;k<strlen;k++){
//复制一个相同的arrRslt
var tmp = tmpArr.slice(0);
//把当前字符str[k]添加到每个元素末尾
for(var j=0;j<tmp.length;j++){
tmp[j] += str.charAt(k);
}
//把复制并修改后的数组连接到arrRslt上
arrRslt = arrRslt.concat(tmp);
}
}
}
return arrRslt;
}
//两端去空格函数
String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g,""); }
| var i= |
setup.py | #!/usr/bin/env python
# Inspired by:
# https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/
import codecs
import os
import re
import sys
from pybind11.setup_helpers import Pybind11Extension, build_ext
from setuptools import find_packages, setup
# PROJECT SPECIFIC
NAME = "celerite2"
PACKAGES = find_packages(where="python")
META_PATH = os.path.join("python", "celerite2", "__init__.py")
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
]
INSTALL_REQUIRES = ["numpy>=1.13.0"]
SETUP_REQUIRES = INSTALL_REQUIRES + [
"pybind11>=2.4",
"setuptools>=40.6.0",
"setuptools_scm",
"wheel",
]
EXTRA_REQUIRE = {
"style": ["isort", "black", "black_nbconvert"],
"test": [
"coverage[toml]",
"pytest",
"pytest-cov",
"scipy",
"celerite>=0.3.1",
],
"pymc3": [
"pymc3>=3.9, <3.12",
"aesara-theano-fallback>=0.0.2",
],
"jax": ["jax", "jaxlib"],
"release": ["pep517", "twine"],
"docs": [
"sphinx",
"sphinx-material",
"sphinx_copybutton",
"rtds_action",
"nbsphinx",
"breathe",
"ipython",
],
"tutorials": [
"jupytext",
"jupyter",
"nbconvert",
"matplotlib",
"scipy",
"emcee",
"pymc3>=3.9, <3.12",
"aesara-theano-fallback>=0.0.2",
"tqdm",
"numpyro",
],
}
EXTRA_REQUIRE["theano"] = EXTRA_REQUIRE["pymc3"]
EXTRA_REQUIRE["dev"] = (
EXTRA_REQUIRE["style"]
+ EXTRA_REQUIRE["test"]
+ EXTRA_REQUIRE["release"]
+ ["pre-commit", "nbstripout", "flake8"]
)
include_dirs = [
"c++/include",
"c++/vendor/eigen",
"python/celerite2",
]
if "READTHEDOCS" in os.environ:
ext_modules = []
else:
ext_modules = [
Pybind11Extension(
"celerite2.driver",
["python/celerite2/driver.cpp"],
include_dirs=include_dirs,
language="c++",
),
Pybind11Extension(
"celerite2.backprop",
["python/celerite2/backprop.cpp"],
include_dirs=include_dirs,
language="c++",
),
Pybind11Extension(
"celerite2.jax.xla_ops",
["python/celerite2/jax/xla_ops.cpp"],
include_dirs=include_dirs,
language="c++",
),
]
# END PROJECT SPECIFIC
HERE = os.path.dirname(os.path.realpath(__file__))
def read(*parts):
with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
return f.read()
def | (meta, meta_file=read(META_PATH)):
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), meta_file, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
if __name__ == "__main__":
setup(
name=NAME,
use_scm_version={
"write_to": os.path.join(
"python", NAME, "{0}_version.py".format(NAME)
),
"write_to_template": '__version__ = "{version}"\n',
},
author=find_meta("author"),
author_email=find_meta("email"),
maintainer=find_meta("author"),
maintainer_email=find_meta("email"),
url=find_meta("uri"),
license=find_meta("license"),
description=find_meta("description"),
long_description=read("README.md"),
long_description_content_type="text/markdown",
packages=PACKAGES,
package_dir={"": "python"},
include_package_data=True,
python_requires=">=3.6",
install_requires=INSTALL_REQUIRES,
setup_requires=SETUP_REQUIRES,
extras_require=EXTRA_REQUIRE,
classifiers=CLASSIFIERS,
zip_safe=False,
ext_modules=ext_modules,
cmdclass={"build_ext": build_ext},
)
| find_meta |
class-impl-very-parameterized-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
use core::container::{Container, Mutable, Map}; | impl cmp::Eq for cat_type {
fn eq(&self, other: &cat_type) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &cat_type) -> bool { !(*self).eq(other) }
}
// Very silly -- this just returns the value of the name field
// for any int value that's less than the meows field
// ok: T should be in scope when resolving the trait ref for map
struct cat<T> {
// Yes, you can have negative meows
priv meows : int,
how_hungry : int,
name : T,
}
pub impl<T> cat<T> {
fn speak(&mut self) { self.meow(); }
fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} else {
error!("Not hungry!");
return false;
}
}
}
impl<T> Container for cat<T> {
fn len(&const self) -> uint { self.meows as uint }
fn is_empty(&const self) -> bool { self.meows == 0 }
}
impl<T> Mutable for cat<T> {
fn clear(&mut self) {}
}
impl<T> Map<int, T> for cat<T> {
fn each<'a>(&'a self, f: &fn(&int, &'a T) -> bool) -> bool {
let mut n = int::abs(self.meows);
while n > 0 {
if !f(&n, &self.name) { return false; }
n -= 1;
}
return true;
}
fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
fn each_key(&self, f: &fn(v: &int) -> bool) -> bool {
self.each(|k, _| f(k))
}
fn each_value<'a>(&'a self, f: &fn(v: &'a T) -> bool) -> bool {
self.each(|_, v| f(v))
}
fn mutate_values(&mut self, _f: &fn(&int, &mut T) -> bool) -> bool {
fail!("nope")
}
fn insert(&mut self, k: int, _: T) -> bool {
self.meows += k;
true
}
fn find<'a>(&'a self, k: &int) -> Option<&'a T> {
if *k <= self.meows {
Some(&self.name)
} else {
None
}
}
fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() }
fn remove(&mut self, k: &int) -> bool {
if self.find(k).is_some() {
self.meows -= *k; true
} else {
false
}
}
fn pop(&mut self, _k: &int) -> Option<T> { fail!() }
fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() }
}
pub impl<T> cat<T> {
fn get<'a>(&'a self, k: &int) -> &'a T {
match self.find(k) {
Some(v) => { v }
None => { fail!("epic fail"); }
}
}
fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
cat{meows: in_x, how_hungry: in_y, name: in_name }
}
}
priv impl<T> cat<T> {
fn meow(&mut self) {
self.meows += 1;
error!("Meow %d", self.meows);
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
pub fn main() {
let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan");
for uint::range(1, 5) |_| { nyan.speak(); }
assert!((*nyan.find(&1).unwrap() == ~"nyan"));
assert!((nyan.find(&10) == None));
let mut spotty: cat<cat_type> = cat::new(2, 57, tuxedo);
for uint::range(0, 6) |_| { spotty.speak(); }
assert!((spotty.len() == 8));
assert!((spotty.contains_key(&2)));
assert!((spotty.get(&3) == &tuxedo));
} | use core::old_iter::BaseIter;
enum cat_type { tuxedo, tabby, tortoiseshell }
|
tree.go | // Copyright 2014 beego Author. 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 beego
import (
"path"
"regexp"
"strings"
"github.com/prima101112/beego/context"
"github.com/prima101112/beego/utils"
)
var (
allowSuffixExt = []string{".json", ".xml", ".html"}
)
// Tree has three elements: FixRouter/wildcard/leaves
// fixRouter sotres Fixed Router
// wildcard stores params
// leaves store the endpoint information
type Tree struct {
//prefix set for static router
prefix string
//search fix route first
fixrouters []*Tree
//if set, failure to match fixrouters search then search wildcard
wildcard *Tree
//if set, failure to match wildcard search
leaves []*leafInfo
}
// NewTree return a new Tree
func NewTree() *Tree {
return &Tree{}
}
// AddTree will add tree to the exist Tree
// prefix should has no params
func (t *Tree) AddTree(prefix string, tree *Tree) {
t.addtree(splitPath(prefix), tree, nil, "")
}
func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg string) {
if len(segments) == 0 {
panic("prefix should has path")
}
seg := segments[0]
iswild, params, regexpStr := splitSegment(seg)
// if it's ? meaning can igone this, so add one more rule for it
if len(params) > 0 && params[0] == ":" {
params = params[1:]
if len(segments[1:]) > 0 {
t.addtree(segments[1:], tree, append(wildcards, params...), reg)
} else {
filterTreeWithPrefix(tree, wildcards, reg)
}
}
//Rule: /login/*/access match /login/2009/11/access
//if already has *, and when loop the access, should as a regexpStr
if !iswild && utils.InSlice(":splat", wildcards) {
iswild = true
regexpStr = seg
}
//Rule: /user/:id/*
if seg == "*" && len(wildcards) > 0 && reg == "" {
regexpStr = "(.+)"
}
if len(segments) == 1 {
if iswild {
if regexpStr != "" {
if reg == "" {
rr := ""
for _, w := range wildcards {
if w == ":splat" {
rr = rr + "(.+)/"
} else {
rr = rr + "([^/]+)/"
}
}
regexpStr = rr + regexpStr
} else {
regexpStr = "/" + regexpStr
}
} else if reg != "" {
if seg == "*.*" {
regexpStr = "([^.]+).(.+)"
} else {
for _, w := range params {
if w == "." || w == ":" {
continue
}
regexpStr = "([^/]+)/" + regexpStr
}
}
}
reg = strings.Trim(reg+"/"+regexpStr, "/")
filterTreeWithPrefix(tree, append(wildcards, params...), reg)
t.wildcard = tree
} else {
reg = strings.Trim(reg+"/"+regexpStr, "/")
filterTreeWithPrefix(tree, append(wildcards, params...), reg)
tree.prefix = seg
t.fixrouters = append(t.fixrouters, tree)
}
return
}
if iswild {
if t.wildcard == nil {
t.wildcard = NewTree()
}
if regexpStr != "" {
if reg == "" {
rr := ""
for _, w := range wildcards {
if w == ":splat" {
rr = rr + "(.+)/"
} else {
rr = rr + "([^/]+)/"
}
}
regexpStr = rr + regexpStr
} else {
regexpStr = "/" + regexpStr
}
} else if reg != "" {
if seg == "*.*" {
regexpStr = "([^.]+).(.+)"
params = params[1:]
} else {
for range params {
regexpStr = "([^/]+)/" + regexpStr
}
}
} else {
if seg == "*.*" {
params = params[1:]
}
}
reg = strings.TrimRight(strings.TrimRight(reg, "/")+"/"+regexpStr, "/")
t.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg)
} else {
subTree := NewTree()
subTree.prefix = seg
t.fixrouters = append(t.fixrouters, subTree)
subTree.addtree(segments[1:], tree, append(wildcards, params...), reg)
}
}
func | (t *Tree, wildcards []string, reg string) {
for _, v := range t.fixrouters {
filterTreeWithPrefix(v, wildcards, reg)
}
if t.wildcard != nil {
filterTreeWithPrefix(t.wildcard, wildcards, reg)
}
for _, l := range t.leaves {
if reg != "" {
if l.regexps != nil {
l.wildcards = append(wildcards, l.wildcards...)
l.regexps = regexp.MustCompile("^" + reg + "/" + strings.Trim(l.regexps.String(), "^$") + "$")
} else {
for _, v := range l.wildcards {
if v == ":splat" {
reg = reg + "/(.+)"
} else {
reg = reg + "/([^/]+)"
}
}
l.regexps = regexp.MustCompile("^" + reg + "$")
l.wildcards = append(wildcards, l.wildcards...)
}
} else {
l.wildcards = append(wildcards, l.wildcards...)
if l.regexps != nil {
for _, w := range wildcards {
if w == ":splat" {
reg = "(.+)/" + reg
} else {
reg = "([^/]+)/" + reg
}
}
l.regexps = regexp.MustCompile("^" + reg + strings.Trim(l.regexps.String(), "^$") + "$")
}
}
}
}
// AddRouter call addseg function
func (t *Tree) AddRouter(pattern string, runObject interface{}) {
t.addseg(splitPath(pattern), runObject, nil, "")
}
// "/"
// "admin" ->
func (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) {
if len(segments) == 0 {
if reg != "" {
t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile("^" + reg + "$")})
} else {
t.leaves = append(t.leaves, &leafInfo{runObject: route, wildcards: wildcards})
}
} else {
seg := segments[0]
iswild, params, regexpStr := splitSegment(seg)
// if it's ? meaning can igone this, so add one more rule for it
if len(params) > 0 && params[0] == ":" {
t.addseg(segments[1:], route, wildcards, reg)
params = params[1:]
}
//Rule: /login/*/access match /login/2009/11/access
//if already has *, and when loop the access, should as a regexpStr
if !iswild && utils.InSlice(":splat", wildcards) {
iswild = true
regexpStr = seg
}
//Rule: /user/:id/*
if seg == "*" && len(wildcards) > 0 && reg == "" {
regexpStr = "(.+)"
}
if iswild {
if t.wildcard == nil {
t.wildcard = NewTree()
}
if regexpStr != "" {
if reg == "" {
rr := ""
for _, w := range wildcards {
if w == ":splat" {
rr = rr + "(.+)/"
} else {
rr = rr + "([^/]+)/"
}
}
regexpStr = rr + regexpStr
} else {
regexpStr = "/" + regexpStr
}
} else if reg != "" {
if seg == "*.*" {
regexpStr = "/([^.]+).(.+)"
params = params[1:]
} else {
for range params {
regexpStr = "/([^/]+)" + regexpStr
}
}
} else {
if seg == "*.*" {
params = params[1:]
}
}
t.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr)
} else {
var ok bool
var subTree *Tree
for _, subTree = range t.fixrouters {
if t.prefix == seg {
ok = true
break
}
}
if !ok {
subTree = NewTree()
subTree.prefix = seg
t.fixrouters = append(t.fixrouters, subTree)
}
subTree.addseg(segments[1:], route, wildcards, reg)
}
}
}
// Match router to runObject & params
func (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{}) {
if len(pattern) == 0 || pattern[0] != '/' {
return nil
}
w := make([]string, 0, 20)
return t.match(pattern, w, ctx)
}
func (t *Tree) match(pattern string, wildcardValues []string, ctx *context.Context) (runObject interface{}) {
if len(pattern) > 0 {
i := 0
for ; i < len(pattern) && pattern[i] == '/'; i++ {
}
pattern = pattern[i:]
}
// Handle leaf nodes:
if len(pattern) == 0 {
for _, l := range t.leaves {
if ok := l.match(wildcardValues, ctx); ok {
return l.runObject
}
}
if t.wildcard != nil {
for _, l := range t.wildcard.leaves {
if ok := l.match(wildcardValues, ctx); ok {
return l.runObject
}
}
}
return nil
}
var seg string
i, l := 0, len(pattern)
for ; i < l && pattern[i] != '/'; i++ {
}
if i == 0 {
seg = pattern
pattern = ""
} else {
seg = pattern[:i]
pattern = pattern[i:]
}
for _, subTree := range t.fixrouters {
if subTree.prefix == seg {
runObject = subTree.match(pattern, wildcardValues, ctx)
if runObject != nil {
break
}
}
}
if runObject == nil && len(t.fixrouters) > 0 {
// Filter the .json .xml .html extension
for _, str := range allowSuffixExt {
if strings.HasSuffix(seg, str) {
for _, subTree := range t.fixrouters {
if subTree.prefix == seg[:len(seg)-len(str)] {
runObject = subTree.match(pattern, wildcardValues, ctx)
if runObject != nil {
ctx.Input.SetParam(":ext", str[1:])
}
}
}
}
}
}
if runObject == nil && t.wildcard != nil {
runObject = t.wildcard.match(pattern, append(wildcardValues, seg), ctx)
}
if runObject == nil && len(t.leaves) > 0 {
wildcardValues = append(wildcardValues, seg)
start, i := 0, 0
for ; i < len(pattern); i++ {
if pattern[i] == '/' {
if i != 0 && start < len(pattern) {
wildcardValues = append(wildcardValues, pattern[start:i])
}
start = i + 1
continue
}
}
if start > 0 {
wildcardValues = append(wildcardValues, pattern[start:i])
}
for _, l := range t.leaves {
if ok := l.match(wildcardValues, ctx); ok {
return l.runObject
}
}
}
return runObject
}
type leafInfo struct {
// names of wildcards that lead to this leaf. eg, ["id" "name"] for the wildcard ":id" and ":name"
wildcards []string
// if the leaf is regexp
regexps *regexp.Regexp
runObject interface{}
}
func (leaf *leafInfo) match(wildcardValues []string, ctx *context.Context) (ok bool) {
//fmt.Println("Leaf:", wildcardValues, leaf.wildcards, leaf.regexps)
if leaf.regexps == nil {
if len(wildcardValues) == 0 { // static path
return true
}
// match *
if len(leaf.wildcards) == 1 && leaf.wildcards[0] == ":splat" {
ctx.Input.SetParam(":splat", path.Join(wildcardValues...))
return true
}
// match *.* or :id
if len(leaf.wildcards) >= 2 && leaf.wildcards[len(leaf.wildcards)-2] == ":path" && leaf.wildcards[len(leaf.wildcards)-1] == ":ext" {
if len(leaf.wildcards) == 2 {
lastone := wildcardValues[len(wildcardValues)-1]
strs := strings.SplitN(lastone, ".", 2)
if len(strs) == 2 {
ctx.Input.SetParam(":ext", strs[1])
}
ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[:len(wildcardValues)-1]...), strs[0]))
return true
} else if len(wildcardValues) < 2 {
return false
}
var index int
for index = 0; index < len(leaf.wildcards)-2; index++ {
ctx.Input.SetParam(leaf.wildcards[index], wildcardValues[index])
}
lastone := wildcardValues[len(wildcardValues)-1]
strs := strings.SplitN(lastone, ".", 2)
if len(strs) == 2 {
ctx.Input.SetParam(":ext", strs[1])
}
ctx.Input.SetParam(":path", path.Join(path.Join(wildcardValues[index:len(wildcardValues)-1]...), strs[0]))
return true
}
// match :id
if len(leaf.wildcards) != len(wildcardValues) {
return false
}
for j, v := range leaf.wildcards {
ctx.Input.SetParam(v, wildcardValues[j])
}
return true
}
if !leaf.regexps.MatchString(path.Join(wildcardValues...)) {
return false
}
matches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...))
for i, match := range matches[1:] {
ctx.Input.SetParam(leaf.wildcards[i], match)
}
return true
}
// "/" -> []
// "/admin" -> ["admin"]
// "/admin/" -> ["admin"]
// "/admin/users" -> ["admin", "users"]
func splitPath(key string) []string {
if key == "" {
return []string{}
}
elements := strings.Split(key, "/")
if elements[0] == "" {
elements = elements[1:]
}
if elements[len(elements)-1] == "" {
elements = elements[:len(elements)-1]
}
return elements
}
// "admin" -> false, nil, ""
// ":id" -> true, [:id], ""
// "?:id" -> true, [: :id], "" : meaning can empty
// ":id:int" -> true, [:id], ([0-9]+)
// ":name:string" -> true, [:name], ([\w]+)
// ":id([0-9]+)" -> true, [:id], ([0-9]+)
// ":id([0-9]+)_:name" -> true, [:id :name], ([0-9]+)_(.+)
// "cms_:id_:page.html" -> true, [:id_ :page], cms_(.+)(.+).html
// "cms_:id(.+)_:page.html" -> true, [:id :page], cms_(.+)_(.+).html
// "*" -> true, [:splat], ""
// "*.*" -> true,[. :path :ext], "" . meaning separator
func splitSegment(key string) (bool, []string, string) {
if strings.HasPrefix(key, "*") {
if key == "*.*" {
return true, []string{".", ":path", ":ext"}, ""
}
return true, []string{":splat"}, ""
}
if strings.ContainsAny(key, ":") {
var paramsNum int
var out []rune
var start bool
var startexp bool
var param []rune
var expt []rune
var skipnum int
params := []string{}
reg := regexp.MustCompile(`[a-zA-Z0-9_]+`)
for i, v := range key {
if skipnum > 0 {
skipnum--
continue
}
if start {
//:id:int and :name:string
if v == ':' {
if len(key) >= i+4 {
if key[i+1:i+4] == "int" {
out = append(out, []rune("([0-9]+)")...)
params = append(params, ":"+string(param))
start = false
startexp = false
skipnum = 3
param = make([]rune, 0)
paramsNum++
continue
}
}
if len(key) >= i+7 {
if key[i+1:i+7] == "string" {
out = append(out, []rune(`([\w]+)`)...)
params = append(params, ":"+string(param))
paramsNum++
start = false
startexp = false
skipnum = 6
param = make([]rune, 0)
continue
}
}
}
// params only support a-zA-Z0-9
if reg.MatchString(string(v)) {
param = append(param, v)
continue
}
if v != '(' {
out = append(out, []rune(`(.+)`)...)
params = append(params, ":"+string(param))
param = make([]rune, 0)
paramsNum++
start = false
startexp = false
}
}
if startexp {
if v != ')' {
expt = append(expt, v)
continue
}
}
if v == ':' {
param = make([]rune, 0)
start = true
} else if v == '(' {
startexp = true
start = false
params = append(params, ":"+string(param))
paramsNum++
expt = make([]rune, 0)
expt = append(expt, '(')
} else if v == ')' {
startexp = false
expt = append(expt, ')')
out = append(out, expt...)
param = make([]rune, 0)
} else if v == '?' {
params = append(params, ":")
} else {
out = append(out, v)
}
}
if len(param) > 0 {
if paramsNum > 0 {
out = append(out, []rune(`(.+)`)...)
}
params = append(params, ":"+string(param))
}
return true, params, string(out)
}
return false, nil, ""
}
| filterTreeWithPrefix |
test_vessel_parser.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import unittest
import yaml
from maro.data_lib.ecr.vessel_parser import VesselsParser
from maro.data_lib.ecr.entities import VesselSetting
conf_str = """
vessels:
rt1_vessel_001:
capacity: 92400
parking:
duration: 1
noise: 0
route:
initial_port_name: supply_port_001
route_name: route_001
sailing:
noise: 0
speed: 10
rt1_vessel_002:
capacity: 92400
parking:
duration: 1
noise: 0
route:
initial_port_name: demand_port_001
route_name: route_001
sailing:
noise: 0
speed: 10
"""
class TestVesselParser(unittest.TestCase):
def test_vessel_parse(self):
conf = yaml.safe_load(conf_str)
parser = VesselsParser()
vessel_mapping, vessels = parser.parse(conf["vessels"])
self.assertEqual(2, len(vessel_mapping))
self.assertEqual(2, len(vessels))
self.assertEqual("rt1_vessel_001", vessels[0].name)
self.assertEqual("rt1_vessel_002", vessels[1].name)
# check capacity
self.assertListEqual([92400, 92400], [v.capacity for v in vessels])
self.assertListEqual([1, 1], [v.parking_duration for v in vessels])
self.assertListEqual([0, 0], [v.parking_noise for v in vessels])
self.assertListEqual([10, 10], [v.sailing_speed for v in vessels])
self.assertListEqual([0, 0], [v.sailing_noise for v in vessels])
if __name__=="__main__":
unittest.main() | ||
calc_vg_sim_fragment_length_stats.py |
'''
calc_vg_sim_fragment_length_stats.py
Calculates fragment length mean and standard deviation
from vg sim path position output.
'''
import sys
import gzip
import numpy
from utils import *
printScriptHeader()
if len(sys.argv) != 3:
print("Usage: python calc_vg_sim_fragment_length_stats.py <input_name> <read_length>\n")
sys.exit(1)
pos_file = gzip.open(sys.argv[1], "rb")
read_length = int(sys.argv[2])
frag_lengths = {}
unpaired_mates = {}
num_reads = 0
for line in pos_file:
line_split = line.split("\t")
assert(len(line_split) == 4)
if line_split[0] != "read":
num_reads += 1
read_split = line_split[0].split("_")
assert(len(read_split) == 5)
if read_split[3] in unpaired_mates:
cur_pos1 = unpaired_mates.pop(read_split[3])
cur_length = abs(cur_pos1 - int(line_split[2])) + read_length
if cur_length in frag_lengths:
frag_lengths[cur_length] += 1
else:
|
else:
unpaired_mates[read_split[3]] = int(line_split[2])
if num_reads % 10000000 == 0:
print num_reads
pos_file.close()
print num_reads
print(frag_lengths)
total_count = 0.0;
sum_count = 0.0;
for key, value in frag_lengths.items():
total_count += value
sum_count += (key * value)
mean = (sum_count / total_count);
sum_var = 0.0;
for key, value in frag_lengths.items():
sum_var += (((float(key) - mean) ** 2) * value);
sd = ((sum_var / (total_count - 1)) ** 0.5);
print("mean: ", mean)
print("sd: ", sd)
| frag_lengths[cur_length] = 1 |
webuploader.flashonly.js | /*! WebUploader 0.1.2 */
/**
* @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。
*
* AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。
*/
(function( root, factory ) {
var modules = {},
// 内部require, 简单不完全实现。
// https://github.com/amdjs/amdjs-api/wiki/require
_require = function( deps, callback ) {
var args, len, i;
// 如果deps不是数组,则直接返回指定module
if ( typeof deps === 'string' ) {
return getModule( deps );
} else {
args = [];
for( len = deps.length, i = 0; i < len; i++ ) {
args.push( getModule( deps[ i ] ) );
}
return callback.apply( null, args );
}
},
// 内部define,暂时不支持不指定id.
_define = function( id, deps, factory ) {
if ( arguments.length === 2 ) {
factory = deps;
deps = null;
}
_require( deps || [], function() {
setModule( id, factory, arguments );
});
},
// 设置module, 兼容CommonJs写法。
setModule = function( id, factory, args ) {
var module = {
exports: factory
},
returned;
if ( typeof factory === 'function' ) {
args.length || (args = [ _require, module.exports, module ]);
returned = factory.apply( null, args );
returned !== undefined && (module.exports = returned);
}
modules[ id ] = module.exports;
},
// 根据id获取module
getModule = function( id ) {
var module = modules[ id ] || root[ id ];
if ( !module ) {
throw new Error( '`' + id + '` is undefined' );
}
return module;
},
// 将所有modules,将路径ids装换成对象。
exportsTo = function( obj ) {
var key, host, parts, part, last, ucFirst;
// make the first character upper case.
ucFirst = function( str ) {
return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 ));
};
for ( key in modules ) {
host = obj;
if ( !modules.hasOwnProperty( key ) ) {
continue;
}
parts = key.split('/');
last = ucFirst( parts.pop() );
while( (part = ucFirst( parts.shift() )) ) {
host[ part ] = host[ part ] || {};
host = host[ part ]; | }
host[ last ] = modules[ key ];
}
},
exports = factory( root, _define, _require ),
origin;
// exports every module.
exportsTo( exports );
if ( typeof module === 'object' && typeof module.exports === 'object' ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
module.exports = exports;
} else if ( typeof define === 'function' && define.amd ) {
// Allow using this built library as an AMD module
// in another project. That other project will only
// see this AMD call, not the internal modules in
// the closure below.
define([], exports );
} else {
// Browser globals case. Just assign the
// result to a property on the global.
origin = root.WebUploader;
root.WebUploader = exports;
root.WebUploader.noConflict = function() {
root.WebUploader = origin;
};
}
})( this, function( window, define, require ) {
/**
* @fileOverview jQuery or Zepto
*/
define('dollar-third',[],function() {
return window.jQuery || window.Zepto;
});
/**
* @fileOverview Dom 操作相关
*/
define('dollar',[
'dollar-third'
], function( _ ) {
return _;
});
/**
* @fileOverview 使用jQuery的Promise
*/
define('promise-third',[
'dollar'
], function( $ ) {
return {
Deferred: $.Deferred,
when: $.when,
isPromise: function( anything ) {
return anything && typeof anything.then === 'function';
}
};
});
/**
* @fileOverview Promise/A+
*/
define('promise',[
'promise-third'
], function( _ ) {
return _;
});
/**
* @fileOverview 基础类方法。
*/
/**
* Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。
*
* As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id.
* 默认module id该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如:
*
* * module `base`:WebUploader.Base
* * module `file`: WebUploader.File
* * module `lib/dnd`: WebUploader.Lib.Dnd
* * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd
*
*
* 以下文档将可能省略`WebUploader`前缀。
* @module WebUploader
* @title WebUploader API文档
*/
define('base',[
'dollar',
'promise'
], function( $, promise ) {
var noop = function() {},
call = Function.call;
// http://jsperf.com/uncurrythis
// 反科里化
function uncurryThis( fn ) {
return function() {
return call.apply( fn, arguments );
};
}
function bindFn( fn, context ) {
return function() {
return fn.apply( context, arguments );
};
}
function createObject( proto ) {
var f;
if ( Object.create ) {
return Object.create( proto );
} else {
f = function() {};
f.prototype = proto;
return new f();
}
}
/**
* 基础类,提供一些简单常用的方法。
* @class Base
*/
return {
/**
* @property {String} version 当前版本号。
*/
version: '0.1.2',
/**
* @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。
*/
$: $,
Deferred: promise.Deferred,
isPromise: promise.isPromise,
when: promise.when,
/**
* @description 简单的浏览器检查结果。
*
* * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。
* * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。
* * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+**
* * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。
* * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。
* * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。
*
* @property {Object} [browser]
*/
browser: (function( ua ) {
var ret = {},
webkit = ua.match( /WebKit\/([\d.]+)/ ),
chrome = ua.match( /Chrome\/([\d.]+)/ ) ||
ua.match( /CriOS\/([\d.]+)/ ),
ie = ua.match( /MSIE\s([\d\.]+)/ ) ||
ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i),
firefox = ua.match( /Firefox\/([\d.]+)/ ),
safari = ua.match( /Safari\/([\d.]+)/ ),
opera = ua.match( /OPR\/([\d.]+)/ );
webkit && (ret.webkit = parseFloat( webkit[ 1 ] ));
chrome && (ret.chrome = parseFloat( chrome[ 1 ] ));
ie && (ret.ie = parseFloat( ie[ 1 ] ));
firefox && (ret.firefox = parseFloat( firefox[ 1 ] ));
safari && (ret.safari = parseFloat( safari[ 1 ] ));
opera && (ret.opera = parseFloat( opera[ 1 ] ));
return ret;
})( navigator.userAgent ),
/**
* @description 操作系统检查结果。
*
* * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。
* * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。
* @property {Object} [os]
*/
os: (function( ua ) {
var ret = {},
// osx = !!ua.match( /\(Macintosh\; Intel / ),
android = ua.match( /(?:Android);?[\s\/]+([\d.]+)?/ ),
ios = ua.match( /(?:iPad|iPod|iPhone).*OS\s([\d_]+)/ );
// osx && (ret.osx = true);
android && (ret.android = parseFloat( android[ 1 ] ));
ios && (ret.ios = parseFloat( ios[ 1 ].replace( /_/g, '.' ) ));
return ret;
})( navigator.userAgent ),
/**
* 实现类与类之间的继承。
* @method inherits
* @grammar Base.inherits( super ) => child
* @grammar Base.inherits( super, protos ) => child
* @grammar Base.inherits( super, protos, statics ) => child
* @param {Class} super 父类
* @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。
* @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。
* @param {Object} [statics] 静态属性或方法。
* @return {Class} 返回子类。
* @example
* function Person() {
* console.log( 'Super' );
* }
* Person.prototype.hello = function() {
* console.log( 'hello' );
* };
*
* var Manager = Base.inherits( Person, {
* world: function() {
* console.log( 'World' );
* }
* });
*
* // 因为没有指定构造器,父类的构造器将会执行。
* var instance = new Manager(); // => Super
*
* // 继承子父类的方法
* instance.hello(); // => hello
* instance.world(); // => World
*
* // 子类的__super__属性指向父类
* console.log( Manager.__super__ === Person ); // => true
*/
inherits: function( Super, protos, staticProtos ) {
var child;
if ( typeof protos === 'function' ) {
child = protos;
protos = null;
} else if ( protos && protos.hasOwnProperty('constructor') ) {
child = protos.constructor;
} else {
child = function() {
return Super.apply( this, arguments );
};
}
// 复制静态方法
$.extend( true, child, Super, staticProtos || {} );
/* jshint camelcase: false */
// 让子类的__super__属性指向父类。
child.__super__ = Super.prototype;
// 构建原型,添加原型方法或属性。
// 暂时用Object.create实现。
child.prototype = createObject( Super.prototype );
protos && $.extend( true, child.prototype, protos );
return child;
},
/**
* 一个不做任何事情的方法。可以用来赋值给默认的callback.
* @method noop
*/
noop: noop,
/**
* 返回一个新的方法,此方法将已指定的`context`来执行。
* @grammar Base.bindFn( fn, context ) => Function
* @method bindFn
* @example
* var doSomething = function() {
* console.log( this.name );
* },
* obj = {
* name: 'Object Name'
* },
* aliasFn = Base.bind( doSomething, obj );
*
* aliasFn(); // => Object Name
*
*/
bindFn: bindFn,
/**
* 引用Console.log如果存在的话,否则引用一个[空函数loop](#WebUploader:Base.log)。
* @grammar Base.log( args... ) => undefined
* @method log
*/
log: (function() {
if ( window.console ) {
return bindFn( console.log, console );
}
return noop;
})(),
nextTick: (function() {
return function( cb ) {
setTimeout( cb, 1 );
};
// @bug 当浏览器不在当前窗口时就停了。
// var next = window.requestAnimationFrame ||
// window.webkitRequestAnimationFrame ||
// window.mozRequestAnimationFrame ||
// function( cb ) {
// window.setTimeout( cb, 1000 / 60 );
// };
// // fix: Uncaught TypeError: Illegal invocation
// return bindFn( next, window );
})(),
/**
* 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。
* 将用来将非数组对象转化成数组对象。
* @grammar Base.slice( target, start[, end] ) => Array
* @method slice
* @example
* function doSomthing() {
* var args = Base.slice( arguments, 1 );
* console.log( args );
* }
*
* doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"]
*/
slice: uncurryThis( [].slice ),
/**
* 生成唯一的ID
* @method guid
* @grammar Base.guid() => String
* @grammar Base.guid( prefx ) => String
*/
guid: (function() {
var counter = 0;
return function( prefix ) {
var guid = (+new Date()).toString( 32 ),
i = 0;
for ( ; i < 5; i++ ) {
guid += Math.floor( Math.random() * 65535 ).toString( 32 );
}
return (prefix || 'wu_') + guid + (counter++).toString( 32 );
};
})(),
/**
* 格式化文件大小, 输出成带单位的字符串
* @method formatSize
* @grammar Base.formatSize( size ) => String
* @grammar Base.formatSize( size, pointLength ) => String
* @grammar Base.formatSize( size, pointLength, units ) => String
* @param {Number} size 文件大小
* @param {Number} [pointLength=2] 精确到的小数点数。
* @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K.
* @example
* console.log( Base.formatSize( 100 ) ); // => 100B
* console.log( Base.formatSize( 1024 ) ); // => 1.00K
* console.log( Base.formatSize( 1024, 0 ) ); // => 1K
* console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M
* console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G
* console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB
*/
formatSize: function( size, pointLength, units ) {
var unit;
units = units || [ 'B', 'K', 'M', 'G', 'TB' ];
while ( (unit = units.shift()) && size > 1024 ) {
size = size / 1024;
}
return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) +
unit;
}
};
});
/**
* 事件处理类,可以独立使用,也可以扩展给对象使用。
* @fileOverview Mediator
*/
define('mediator',[
'base'
], function( Base ) {
var $ = Base.$,
slice = [].slice,
separator = /\s+/,
protos;
// 根据条件过滤出事件handlers.
function findHandlers( arr, name, callback, context ) {
return $.grep( arr, function( handler ) {
return handler &&
(!name || handler.e === name) &&
(!callback || handler.cb === callback ||
handler.cb._cb === callback) &&
(!context || handler.ctx === context);
});
}
function eachEvent( events, callback, iterator ) {
// 不支持对象,只支持多个event用空格隔开
$.each( (events || '').split( separator ), function( _, key ) {
iterator( key, callback );
});
}
function triggerHanders( events, args ) {
var stoped = false,
i = -1,
len = events.length,
handler;
while ( ++i < len ) {
handler = events[ i ];
if ( handler.cb.apply( handler.ctx2, args ) === false ) {
stoped = true;
break;
}
}
return !stoped;
}
protos = {
/**
* 绑定事件。
*
* `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如
* ```javascript
* var obj = {};
*
* // 使得obj有事件行为
* Mediator.installTo( obj );
*
* obj.on( 'testa', function( arg1, arg2 ) {
* console.log( arg1, arg2 ); // => 'arg1', 'arg2'
* });
*
* obj.trigger( 'testa', 'arg1', 'arg2' );
* ```
*
* 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。
* 切会影响到`trigger`方法的返回值,为`false`。
*
* `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处,
* 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。
* ```javascript
* obj.on( 'all', function( type, arg1, arg2 ) {
* console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2'
* });
* ```
*
* @method on
* @grammar on( name, callback[, context] ) => self
* @param {String} name 事件名,支持多个事件用空格隔开
* @param {Function} callback 事件处理器
* @param {Object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
* @class Mediator
*/
on: function( name, callback, context ) {
var me = this,
set;
if ( !callback ) {
return this;
}
set = this._events || (this._events = []);
eachEvent( name, callback, function( name, callback ) {
var handler = { e: name };
handler.cb = callback;
handler.ctx = context;
handler.ctx2 = context || me;
handler.id = set.length;
set.push( handler );
});
return this;
},
/**
* 绑定事件,且当handler执行完后,自动解除绑定。
* @method once
* @grammar once( name, callback[, context] ) => self
* @param {String} name 事件名
* @param {Function} callback 事件处理器
* @param {Object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
*/
once: function( name, callback, context ) {
var me = this;
if ( !callback ) {
return me;
}
eachEvent( name, callback, function( name, callback ) {
var once = function() {
me.off( name, once );
return callback.apply( context || me, arguments );
};
once._cb = callback;
me.on( name, once, context );
});
return me;
},
/**
* 解除事件绑定
* @method off
* @grammar off( [name[, callback[, context] ] ] ) => self
* @param {String} [name] 事件名
* @param {Function} [callback] 事件处理器
* @param {Object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
*/
off: function( name, cb, ctx ) {
var events = this._events;
if ( !events ) {
return this;
}
if ( !name && !cb && !ctx ) {
this._events = [];
return this;
}
eachEvent( name, cb, function( name, cb ) {
$.each( findHandlers( events, name, cb, ctx ), function() {
delete events[ this.id ];
});
});
return this;
},
/**
* 触发事件
* @method trigger
* @grammar trigger( name[, args...] ) => self
* @param {String} type 事件名
* @param {*} [...] 任意参数
* @return {Boolean} 如果handler中return false了,则返回false, 否则返回true
*/
trigger: function( type ) {
var args, events, allEvents;
if ( !this._events || !type ) {
return this;
}
args = slice.call( arguments, 1 );
events = findHandlers( this._events, type );
allEvents = findHandlers( this._events, 'all' );
return triggerHanders( events, args ) &&
triggerHanders( allEvents, arguments );
}
};
/**
* 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。
* 主要目的是负责模块与模块之间的合作,降低耦合度。
*
* @class Mediator
*/
return $.extend({
/**
* 可以通过这个接口,使任何对象具备事件功能。
* @method installTo
* @param {Object} obj 需要具备事件行为的对象。
* @return {Object} 返回obj.
*/
installTo: function( obj ) {
return $.extend( obj, protos );
}
}, protos );
});
/**
* @fileOverview Uploader上传类
*/
define('uploader',[
'base',
'mediator'
], function( Base, Mediator ) {
var $ = Base.$;
/**
* 上传入口类。
* @class Uploader
* @constructor
* @grammar new Uploader( opts ) => Uploader
* @example
* var uploader = WebUploader.Uploader({
* swf: 'path_of_swf/Uploader.swf',
*
* // 开起分片上传。
* chunked: true
* });
*/
function Uploader( opts ) {
this.options = $.extend( true, {}, Uploader.options, opts );
this._init( this.options );
}
// default Options
// widgets中有相应扩展
Uploader.options = {};
Mediator.installTo( Uploader.prototype );
// 批量添加纯命令式方法。
$.each({
upload: 'start-upload',
stop: 'stop-upload',
getFile: 'get-file',
getFiles: 'get-files',
addFile: 'add-file',
addFiles: 'add-file',
sort: 'sort-files',
removeFile: 'remove-file',
skipFile: 'skip-file',
retry: 'retry',
isInProgress: 'is-in-progress',
makeThumb: 'make-thumb',
getDimension: 'get-dimension',
addButton: 'add-btn',
getRuntimeType: 'get-runtime-type',
refresh: 'refresh',
disable: 'disable',
enable: 'enable',
reset: 'reset'
}, function( fn, command ) {
Uploader.prototype[ fn ] = function() {
return this.request( command, arguments );
};
});
$.extend( Uploader.prototype, {
state: 'pending',
_init: function( opts ) {
var me = this;
me.request( 'init', opts, function() {
me.state = 'ready';
me.trigger('ready');
});
},
/**
* 获取或者设置Uploader配置项。
* @method option
* @grammar option( key ) => *
* @grammar option( key, val ) => self
* @example
*
* // 初始状态图片上传前不会压缩
* var uploader = new WebUploader.Uploader({
* resize: null;
* });
*
* // 修改后图片上传前,尝试将图片压缩到1600 * 1600
* uploader.options( 'resize', {
* width: 1600,
* height: 1600
* });
*/
option: function( key, val ) {
var opts = this.options;
// setter
if ( arguments.length > 1 ) {
if ( $.isPlainObject( val ) &&
$.isPlainObject( opts[ key ] ) ) {
$.extend( opts[ key ], val );
} else {
opts[ key ] = val;
}
} else { // getter
return key ? opts[ key ] : opts;
}
},
/**
* 获取文件统计信息。返回一个包含一下信息的对象。
* * `successNum` 上传成功的文件数
* * `uploadFailNum` 上传失败的文件数
* * `cancelNum` 被删除的文件数
* * `invalidNum` 无效的文件数
* * `queueNum` 还在队列中的文件数
* @method getStats
* @grammar getStats() => Object
*/
getStats: function() {
// return this._mgr.getStats.apply( this._mgr, arguments );
var stats = this.request('get-stats');
return {
successNum: stats.numOfSuccess,
// who care?
// queueFailNum: 0,
cancelNum: stats.numOfCancel,
invalidNum: stats.numOfInvalid,
uploadFailNum: stats.numOfUploadFailed,
queueNum: stats.numOfQueue
};
},
// 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器
trigger: function( type/*, args...*/ ) {
var args = [].slice.call( arguments, 1 ),
opts = this.options,
name = 'on' + type.substring( 0, 1 ).toUpperCase() +
type.substring( 1 );
if (
// 调用通过on方法注册的handler.
Mediator.trigger.apply( this, arguments ) === false ||
// 调用opts.onEvent
$.isFunction( opts[ name ] ) &&
opts[ name ].apply( this, args ) === false ||
// 调用this.onEvent
$.isFunction( this[ name ] ) &&
this[ name ].apply( this, args ) === false ||
// 广播所有uploader的事件。
Mediator.trigger.apply( Mediator,
[ this, type ].concat( args ) ) === false ) {
return false;
}
return true;
},
// widgets/widget.js将补充此方法的详细文档。
request: Base.noop
});
/**
* 创建Uploader实例,等同于new Uploader( opts );
* @method create
* @class Base
* @static
* @grammar Base.create( opts ) => Uploader
*/
Base.create = Uploader.create = function( opts ) {
return new Uploader( opts );
};
// 暴露Uploader,可以通过它来扩展业务逻辑。
Base.Uploader = Uploader;
return Uploader;
});
/**
* @fileOverview Runtime管理器,负责Runtime的选择, 连接
*/
define('runtime/runtime',[
'base',
'mediator'
], function( Base, Mediator ) {
var $ = Base.$,
factories = {},
// 获取对象的第一个key
getFirstKey = function( obj ) {
for ( var key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
return key;
}
}
return null;
};
// 接口类。
function Runtime( options ) {
this.options = $.extend({
container: document.body
}, options );
this.uid = Base.guid('rt_');
}
$.extend( Runtime.prototype, {
getContainer: function() {
var opts = this.options,
parent, container;
if ( this._container ) {
return this._container;
}
parent = $( opts.container || document.body );
container = $( document.createElement('div') );
container.attr( 'id', 'rt_' + this.uid );
container.css({
position: 'absolute',
top: '0px',
left: '0px',
width: '1px',
height: '1px',
overflow: 'hidden'
});
parent.append( container );
parent.addClass('webuploader-container');
this._container = container;
return container;
},
init: Base.noop,
exec: Base.noop,
destroy: function() {
if ( this._container ) {
this._container.parentNode.removeChild( this.__container );
}
this.off();
}
});
Runtime.orders = 'html5,flash';
/**
* 添加Runtime实现。
* @param {String} type 类型
* @param {Runtime} factory 具体Runtime实现。
*/
Runtime.addRuntime = function( type, factory ) {
factories[ type ] = factory;
};
Runtime.hasRuntime = function( type ) {
return !!(type ? factories[ type ] : getFirstKey( factories ));
};
Runtime.create = function( opts, orders ) {
var type, runtime;
orders = orders || Runtime.orders;
$.each( orders.split( /\s*,\s*/g ), function() {
if ( factories[ this ] ) {
type = this;
return false;
}
});
type = type || getFirstKey( factories );
if ( !type ) {
throw new Error('Runtime Error');
}
runtime = new factories[ type ]( opts );
return runtime;
};
Mediator.installTo( Runtime.prototype );
return Runtime;
});
/**
* @fileOverview Runtime管理器,负责Runtime的选择, 连接
*/
define('runtime/client',[
'base',
'mediator',
'runtime/runtime'
], function( Base, Mediator, Runtime ) {
var cache;
cache = (function() {
var obj = {};
return {
add: function( runtime ) {
obj[ runtime.uid ] = runtime;
},
get: function( ruid, standalone ) {
var i;
if ( ruid ) {
return obj[ ruid ];
}
for ( i in obj ) {
// 有些类型不能重用,比如filepicker.
if ( standalone && obj[ i ].__standalone ) {
continue;
}
return obj[ i ];
}
return null;
},
remove: function( runtime ) {
delete obj[ runtime.uid ];
}
};
})();
function RuntimeClient( component, standalone ) {
var deferred = Base.Deferred(),
runtime;
this.uid = Base.guid('client_');
// 允许runtime没有初始化之前,注册一些方法在初始化后执行。
this.runtimeReady = function( cb ) {
return deferred.done( cb );
};
this.connectRuntime = function( opts, cb ) {
// already connected.
if ( runtime ) {
throw new Error('already connected!');
}
deferred.done( cb );
if ( typeof opts === 'string' && cache.get( opts ) ) {
runtime = cache.get( opts );
}
// 像filePicker只能独立存在,不能公用。
runtime = runtime || cache.get( null, standalone );
// 需要创建
if ( !runtime ) {
runtime = Runtime.detail( opts, opts.runtimeOrder );
runtime.__promise = deferred.promise();
runtime.once( 'ready', deferred.resolve );
runtime.init();
cache.add( runtime );
runtime.__client = 1;
} else {
// 来自cache
Base.$.extend( runtime.options, opts );
runtime.__promise.then( deferred.resolve );
runtime.__client++;
}
standalone && (runtime.__standalone = standalone);
return runtime;
};
this.getRuntime = function() {
return runtime;
};
this.disconnectRuntime = function() {
if ( !runtime ) {
return;
}
runtime.__client--;
if ( runtime.__client <= 0 ) {
cache.remove( runtime );
delete runtime.__promise;
runtime.destroy();
}
runtime = null;
};
this.exec = function() {
if ( !runtime ) {
return;
}
var args = Base.slice( arguments );
component && args.unshift( component );
return runtime.exec.apply( this, args );
};
this.getRuid = function() {
return runtime && runtime.uid;
};
this.destroy = (function( destroy ) {
return function() {
destroy && destroy.apply( this, arguments );
this.trigger('destroy');
this.off();
this.exec('destroy');
this.disconnectRuntime();
};
})( this.destroy );
}
Mediator.installTo( RuntimeClient.prototype );
return RuntimeClient;
});
/**
* @fileOverview Blob
*/
define('lib/blob',[
'base',
'runtime/client'
], function( Base, RuntimeClient ) {
function Blob( ruid, source ) {
var me = this;
me.source = source;
me.ruid = ruid;
RuntimeClient.call( me, 'Blob' );
this.uid = source.uid || this.uid;
this.type = source.type || '';
this.size = source.size || 0;
if ( ruid ) {
me.connectRuntime( ruid );
}
}
Base.inherits( RuntimeClient, {
constructor: Blob,
slice: function( start, end ) {
return this.exec( 'slice', start, end );
},
getSource: function() {
return this.source;
}
});
return Blob;
});
/**
* 为了统一化Flash的File和HTML5的File而存在。
* 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
* @fileOverview File
*/
define('lib/file',[
'base',
'lib/blob'
], function( Base, Blob ) {
var uid = 1,
rExt = /\.([^.]+)$/;
function File( ruid, file ) {
var ext;
Blob.apply( this, arguments );
this.name = file.name || ('untitled' + uid++);
ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
// todo 支持其他类型文件的转换。
// 如果有mimetype, 但是文件名里面没有找出后缀规律
if ( !ext && this.type ) {
ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( this.type ) ?
RegExp.$1.toLowerCase() : '';
this.name += '.' + ext;
}
// 如果没有指定mimetype, 但是知道文件后缀。
if ( !this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf( ext ) ) {
this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
}
this.ext = ext;
this.lastModifiedDate = file.lastModifiedDate ||
(new Date()).toLocaleString();
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClent, File ) {
var $ = Base.$;
function FilePicker( opts ) {
opts = this.options = $.extend({}, FilePicker.options, opts );
opts.container = $( opts.id );
if ( !opts.container.length ) {
throw new Error('按钮指定错误');
}
opts.innerHTML = opts.innerHTML || opts.label ||
opts.container.html() || '';
opts.button = $( opts.button || document.createElement('div') );
opts.button.html( opts.innerHTML );
opts.container.html( opts.button );
RuntimeClent.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file'
};
Base.inherits( RuntimeClent, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button;
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
button.removeClass('webuploader-pick-hover');
break;
case 'change':
files = me.exec('getFiles');
me.trigger( 'select', $.map( files, function( file ) {
file = new File( me.getRuid(), file );
// 记录来源。
file._refer = opts.container;
return file;
}), opts.container );
break;
}
});
me.connectRuntime( opts, function() {
me.refresh();
me.exec( 'init', opts );
me.trigger('ready');
});
$( window ).on( 'resize', function() {
me.refresh();
});
},
refresh: function() {
var shimContainer = this.getRuntime().getContainer(),
button = this.options.button,
width = button.outerWidth ?
button.outerWidth() : button.width(),
height = button.outerHeight ?
button.outerHeight() : button.height(),
pos = button.offset();
width && height && shimContainer.css({
bottom: 'auto',
right: 'auto',
width: width + 'px',
height: height + 'px'
}).offset( pos );
},
enable: function() {
var btn = this.options.button;
btn.removeClass('webuploader-pick-disable');
this.refresh();
},
disable: function() {
var btn = this.options.button;
this.getRuntime().getContainer().css({
top: '-99999px'
});
btn.addClass('webuploader-pick-disable');
},
destroy: function() {
if ( this.runtime ) {
this.exec('destroy');
this.disconnectRuntime();
}
}
});
return FilePicker;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/widget',[
'base',
'uploader'
], function( Base, Uploader ) {
var $ = Base.$,
_init = Uploader.prototype._init,
IGNORE = {},
widgetClass = [];
function isArrayLike( obj ) {
if ( !obj ) {
return false;
}
var length = obj.length,
type = $.type( obj );
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === 'array' || type !== 'function' && type !== 'string' &&
(length === 0 || typeof length === 'number' && length > 0 &&
(length - 1) in obj);
}
function Widget( uploader ) {
this.owner = uploader;
this.options = uploader.options;
}
$.extend( Widget.prototype, {
init: Base.noop,
// 类Backbone的事件监听声明,监听uploader实例上的事件
// widget直接无法监听事件,事件只能通过uploader来传递
invoke: function( apiName, args ) {
/*
{
'make-thumb': 'makeThumb'
}
*/
var map = this.responseMap;
// 如果无API响应声明则忽略
if ( !map || !(apiName in map) || !(map[ apiName ] in this) ||
!$.isFunction( this[ map[ apiName ] ] ) ) {
return IGNORE;
}
return this[ map[ apiName ] ].apply( this, args );
},
/**
* 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
* @method request
* @grammar request( command, args ) => * | Promise
* @grammar request( command, args, callback ) => Promise
* @for Uploader
*/
request: function() {
return this.owner.request.apply( this.owner, arguments );
}
});
// 扩展Uploader.
$.extend( Uploader.prototype, {
// 覆写_init用来初始化widgets
_init: function() {
var me = this,
widgets = me._widgets = [];
$.each( widgetClass, function( _, klass ) {
widgets.push( new klass( me ) );
});
return _init.apply( me, arguments );
},
request: function( apiName, args, callback ) {
var i = 0,
widgets = this._widgets,
len = widgets.length,
rlts = [],
dfds = [],
widget, rlt, promise, key;
args = isArrayLike( args ) ? args : [ args ];
for ( ; i < len; i++ ) {
widget = widgets[ i ];
rlt = widget.invoke( apiName, args );
if ( rlt !== IGNORE ) {
// Deferred对象
if ( Base.isPromise( rlt ) ) {
dfds.push( rlt );
} else {
rlts.push( rlt );
}
}
}
// 如果有callback,则用异步方式。
if ( callback || dfds.length ) {
promise = Base.when.apply( Base, dfds );
key = promise.pipe ? 'pipe' : 'then';
// 很重要不能删除。删除了会死循环。
// 保证执行顺序。让callback总是在下一个tick中执行。
return promise[ key ](function() {
var deferred = Base.Deferred(),
args = arguments;
setTimeout(function() {
deferred.resolve.apply( deferred, args );
}, 1 );
return deferred.promise();
})[ key ]( callback || Base.noop );
} else {
return rlts[ 0 ];
}
}
});
/**
* 添加组件
* @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
* @param {object} responseMap API名称与函数实现的映射
* @example
* Uploader.register( {
* init: function( options ) {},
* makeThumb: function() {}
* }, {
* 'make-thumb': 'makeThumb'
* } );
*/
Uploader.register = Widget.register = function( responseMap, widgetProto ) {
var map = { init: 'init' },
klass;
if ( arguments.length === 1 ) {
widgetProto = responseMap;
widgetProto.responseMap = map;
} else {
widgetProto.responseMap = $.extend( map, responseMap );
}
klass = Base.inherits( Widget, widgetProto );
widgetClass.push( klass );
return klass;
};
return Widget;
});
/**
* @fileOverview 文件选择相关
*/
define('widgets/filepicker',[
'base',
'uploader',
'lib/filepicker',
'widgets/widget'
], function( Base, Uploader, FilePicker ) {
var $ = Base.$;
$.extend( Uploader.options, {
/**
* @property {Selector | Object} [pick=undefined]
* @namespace options
* @for Uploader
* @description 指定选择文件的按钮容器,不指定则不创建按钮。
*
* * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
* * `label` {String} 请采用 `innerHTML` 代替
* * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
* * `multiple` {Boolean} 是否开起同时选择多个文件能力。
*/
pick: null,
/**
* @property {Arroy} [accept=null]
* @namespace options
* @for Uploader
* @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
*
* * `title` {String} 文字描述
* * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
* * `mimeTypes` {String} 多个用逗号分割。
*
* 如:
*
* ```
* {
* title: 'Images',
* extensions: 'gif,jpg,jpeg,bmp,png',
* mimeTypes: 'image/*'
* }
* ```
*/
accept: null/*{
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}*/
});
return Uploader.register({
'add-btn': 'addButton',
refresh: 'refresh',
disable: 'disable',
enable: 'enable'
}, {
init: function( opts ) {
this.pickers = [];
return opts.pick && this.addButton( opts.pick );
},
refresh: function() {
$.each( this.pickers, function() {
this.refresh();
});
},
/**
* @method addButton
* @for Uploader
* @grammar addButton( pick ) => Promise
* @description
* 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
* @example
* uploader.addButton({
* id: '#btnContainer',
* innerHTML: '选择文件'
* });
*/
addButton: function( pick ) {
var me = this,
opts = me.options,
accept = opts.accept,
options, picker, deferred;
if ( !pick ) {
return;
}
deferred = Base.Deferred();
$.isPlainObject( pick ) || (pick = {
id: pick
});
options = $.extend({}, pick, {
accept: $.isPlainObject( accept ) ? [ accept ] : accept,
swf: opts.swf,
runtimeOrder: opts.runtimeOrder
});
picker = new FilePicker( options );
picker.once( 'ready', deferred.resolve );
picker.on( 'select', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
picker.init();
this.pickers.push( picker );
return deferred.promise();
},
disable: function() {
$.each( this.pickers, function() {
this.disable();
});
},
enable: function() {
$.each( this.pickers, function() {
this.enable();
});
}
});
});
/**
* @fileOverview Image
*/
define('lib/image',[
'base',
'runtime/client',
'lib/blob'
], function( Base, RuntimeClient, Blob ) {
var $ = Base.$;
// 构造器。
function Image( opts ) {
this.options = $.extend({}, Image.options, opts );
RuntimeClient.call( this, 'Image' );
this.on( 'load', function() {
this._info = this.exec('info');
this._meta = this.exec('meta');
});
}
// 默认选项。
Image.options = {
// 默认的图片处理质量
quality: 90,
// 是否裁剪
crop: false,
// 是否保留头部信息
preserveHeaders: true,
// 是否允许放大。
allowMagnify: true
};
// 继承RuntimeClient.
Base.inherits( RuntimeClient, {
constructor: Image,
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._meta = val;
return this;
}
// getter
return this._meta;
},
loadFromBlob: function( blob ) {
var me = this,
ruid = blob.getRuid();
this.connectRuntime( ruid, function() {
me.exec( 'init', me.options );
me.exec( 'loadFromBlob', blob );
});
},
resize: function() {
var args = Base.slice( arguments );
return this.exec.apply( this, [ 'resize' ].concat( args ) );
},
getAsDataUrl: function( type ) {
return this.exec( 'getAsDataUrl', type );
},
getAsBlob: function( type ) {
var blob = this.exec( 'getAsBlob', type );
return new Blob( this.getRuid(), blob );
}
});
return Image;
});
/**
* @fileOverview 图片操作, 负责预览图片和上传前压缩图片
*/
define('widgets/image',[
'base',
'uploader',
'lib/image',
'widgets/widget'
], function( Base, Uploader, Image ) {
var $ = Base.$,
throttle;
// 根据要处理的文件大小来节流,一次不能处理太多,会卡。
throttle = (function( max ) {
var occupied = 0,
waiting = [],
tick = function() {
var item;
while ( waiting.length && occupied < max ) {
item = waiting.shift();
occupied += item[ 0 ];
item[ 1 ]();
}
};
return function( emiter, size, cb ) {
waiting.push([ size, cb ]);
emiter.once( 'destroy', function() {
occupied -= size;
setTimeout( tick, 1 );
});
setTimeout( tick, 1 );
};
})( 5 * 1024 * 1024 );
$.extend( Uploader.options, {
/**
* @property {Object} [thumb]
* @namespace options
* @for Uploader
* @description 配置生成缩略图的选项。
*
* 默认为:
*
* ```javascript
* {
* width: 110,
* height: 110,
*
* // 图片质量,只有type为`image/jpeg`的时候才有效。
* quality: 70,
*
* // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
* allowMagnify: true,
*
* // 是否允许裁剪。
* crop: true,
*
* // 是否保留头部meta信息。
* preserveHeaders: false,
*
* // 为空的话则保留原有图片格式。
* // 否则强制转换成指定的类型。
* type: 'image/jpeg'
* }
* ```
*/
thumb: {
width: 110,
height: 110,
quality: 70,
allowMagnify: true,
crop: true,
preserveHeaders: false,
// 为空的话则保留原有图片格式。
// 否则强制转换成指定的类型。
// IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
// 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
type: 'image/jpeg'
},
/**
* @property {Object} [compress]
* @namespace options
* @for Uploader
* @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
*
* 默认为:
*
* ```javascript
* {
* width: 1600,
* height: 1600,
*
* // 图片质量,只有type为`image/jpeg`的时候才有效。
* quality: 90,
*
* // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
* allowMagnify: false,
*
* // 是否允许裁剪。
* crop: false,
*
* // 是否保留头部meta信息。
* preserveHeaders: true
* }
* ```
*/
compress: {
width: 1600,
height: 1600,
quality: 90,
allowMagnify: false,
crop: false,
preserveHeaders: true
}
});
return Uploader.register({
'make-thumb': 'makeThumb',
'before-send-file': 'compressImage'
}, {
/**
* 生成缩略图,此过程为异步,所以需要传入`callback`。
* 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
*
* `callback`中可以接收到两个参数。
* * 第一个为error,如果生成缩略图有错误,此error将为真。
* * 第二个为ret, 缩略图的Data URL值。
*
* **注意**
* Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
*
*
* @method makeThumb
* @grammar makeThumb( file, callback ) => undefined
* @grammar makeThumb( file, callback, width, height ) => undefined
* @for Uploader
* @example
*
* uploader.on( 'fileQueued', function( file ) {
* var $li = ...;
*
* uploader.makeThumb( file, function( error, ret ) {
* if ( error ) {
* $li.text('预览错误');
* } else {
* $li.append('<img alt="" src="' + ret + '" />');
* }
* });
*
* });
*/
makeThumb: function( file, cb, width, height ) {
var opts, image;
file = this.request( 'get-file', file );
// 只预览图片格式。
if ( !file.type.match( /^image/ ) ) {
cb( true );
return;
}
opts = $.extend({}, this.options.thumb );
// 如果传入的是object.
if ( $.isPlainObject( width ) ) {
opts = $.extend( opts, width );
width = null;
}
width = width || opts.width;
height = height || opts.height;
image = new Image( opts );
image.once( 'load', function() {
file._info = file._info || image.info();
file._meta = file._meta || image.meta();
image.resize( width, height );
});
image.once( 'complete', function() {
cb( false, image.getAsDataUrl( opts.type ) );
image.destroy();
});
image.once( 'error', function() {
cb( true );
image.destroy();
});
throttle( image, file.source.size, function() {
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadFromBlob( file.source );
});
},
compressImage: function( file ) {
var opts = this.options.compress || this.options.resize,
compressSize = opts && opts.compressSize || 300 * 1024,
image, deferred;
file = this.request( 'get-file', file );
// 只预览图片格式。
if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) ||
file.size < compressSize ||
file._compressed ) {
return;
}
opts = $.extend({}, opts );
deferred = Base.Deferred();
image = new Image( opts );
deferred.always(function() {
image.destroy();
image = null;
});
image.once( 'error', deferred.reject );
image.once( 'load', function() {
file._info = file._info || image.info();
file._meta = file._meta || image.meta();
image.resize( opts.width, opts.height );
});
image.once( 'complete', function() {
var blob, size;
// 移动端 UC / qq 浏览器的无图模式下
// ctx.getImageData 处理大图的时候会报 Exception
// INDEX_SIZE_ERR: DOM Exception 1
try {
blob = image.getAsBlob( opts.type );
size = file.size;
// 如果压缩后,比原来还大则不用压缩后的。
if ( blob.size < size ) {
// file.source.destroy && file.source.destroy();
file.source = blob;
file.size = blob.size;
file.trigger( 'resize', blob.size, size );
}
// 标记,避免重复压缩。
file._compressed = true;
deferred.resolve();
} catch ( e ) {
// 出错了直接继续,让其上传原始图片
deferred.resolve();
}
});
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadFromBlob( file.source );
return deferred.promise();
}
});
});
/**
* @fileOverview 文件属性封装
*/
define('file',[
'base',
'mediator'
], function( Base, Mediator ) {
var $ = Base.$,
idPrefix = 'WU_FILE_',
idSuffix = 0,
rExt = /\.([^.]+)$/,
statusMap = {};
function gid() {
return idPrefix + idSuffix++;
}
/**
* 文件类
* @class File
* @constructor 构造函数
* @grammar new File( source ) => File
* @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
*/
function WUFile( source ) {
/**
* 文件名,包括扩展名(后缀)
* @property name
* @type {string}
*/
this.name = source.name || 'Untitled';
/**
* 文件体积(字节)
* @property size
* @type {uint}
* @default 0
*/
this.size = source.size || 0;
/**
* 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
* @property type
* @type {string}
* @default 'application'
*/
this.type = source.type || 'application';
/**
* 文件最后修改日期
* @property lastModifiedDate
* @type {int}
* @default 当前时间戳
*/
this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
/**
* 文件ID,每个对象具有唯一ID,与文件名无关
* @property id
* @type {string}
*/
this.id = gid();
/**
* 文件扩展名,通过文件名获取,例如test.png的扩展名为png
* @property ext
* @type {string}
*/
this.ext = rExt.exec( this.name ) ? RegExp.$1 : '';
/**
* 状态文字说明。在不同的status语境下有不同的用途。
* @property statusText
* @type {string}
*/
this.statusText = '';
// 存储文件状态,防止通过属性直接修改
statusMap[ this.id ] = WUFile.Status.INITED;
this.source = source;
this.loaded = 0;
this.on( 'error', function( msg ) {
this.setStatus( WUFile.Status.ERROR, msg );
});
}
$.extend( WUFile.prototype, {
/**
* 设置状态,状态变化时会触发`change`事件。
* @method setStatus
* @grammar setStatus( status[, statusText] );
* @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
* @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
*/
setStatus: function( status, text ) {
var prevStatus = statusMap[ this.id ];
typeof text !== 'undefined' && (this.statusText = text);
if ( status !== prevStatus ) {
statusMap[ this.id ] = status;
/**
* 文件状态变化
* @event statuschange
*/
this.trigger( 'statuschange', status, prevStatus );
}
},
/**
* 获取文件状态
* @return {File.Status}
* @example
文件状态具体包括以下几种类型:
{
// 初始化
INITED: 0,
// 已入队列
QUEUED: 1,
// 正在上传
PROGRESS: 2,
// 上传出错
ERROR: 3,
// 上传成功
COMPLETE: 4,
// 上传取消
CANCELLED: 5
}
*/
getStatus: function() {
return statusMap[ this.id ];
},
/**
* 获取文件原始信息。
* @return {*}
*/
getSource: function() {
return this.source;
},
destory: function() {
delete statusMap[ this.id ];
}
});
Mediator.installTo( WUFile.prototype );
/**
* 文件状态值,具体包括以下几种类型:
* * `inited` 初始状态
* * `queued` 已经进入队列, 等待上传
* * `progress` 上传中
* * `complete` 上传完成。
* * `error` 上传出错,可重试
* * `interrupt` 上传中断,可续传。
* * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
* * `cancelled` 文件被移除。
* @property {Object} Status
* @namespace File
* @class File
* @static
*/
WUFile.Status = {
INITED: 'inited', // 初始状态
QUEUED: 'queued', // 已经进入队列, 等待上传
PROGRESS: 'progress', // 上传中
ERROR: 'error', // 上传出错,可重试
COMPLETE: 'complete', // 上传完成。
CANCELLED: 'cancelled', // 上传取消。
INTERRUPT: 'interrupt', // 上传中断,可续传。
INVALID: 'invalid' // 文件不合格,不能重试上传。
};
return WUFile;
});
/**
* @fileOverview 文件队列
*/
define('queue',[
'base',
'mediator',
'file'
], function( Base, Mediator, WUFile ) {
var $ = Base.$,
STATUS = WUFile.Status;
/**
* 文件队列, 用来存储各个状态中的文件。
* @class Queue
* @extends Mediator
*/
function Queue() {
/**
* 统计文件数。
* * `numOfQueue` 队列中的文件数。
* * `numOfSuccess` 上传成功的文件数
* * `numOfCancel` 被移除的文件数
* * `numOfProgress` 正在上传中的文件数
* * `numOfUploadFailed` 上传错误的文件数。
* * `numOfInvalid` 无效的文件数。
* @property {Object} stats
*/
this.stats = {
numOfQueue: 0,
numOfSuccess: 0,
numOfCancel: 0,
numOfProgress: 0,
numOfUploadFailed: 0,
numOfInvalid: 0
};
// 上传队列,仅包括等待上传的文件
this._queue = [];
// 存储所有文件
this._map = {};
}
$.extend( Queue.prototype, {
/**
* 将新文件加入对队列尾部
*
* @method append
* @param {File} file 文件对象
*/
append: function( file ) {
this._queue.push( file );
this._fileAdded( file );
return this;
},
/**
* 将新文件加入对队列头部
*
* @method prepend
* @param {File} file 文件对象
*/
prepend: function( file ) {
this._queue.unshift( file );
this._fileAdded( file );
return this;
},
/**
* 获取文件对象
*
* @method getFile
* @param {String} fileId 文件ID
* @return {File}
*/
getFile: function( fileId ) {
if ( typeof fileId !== 'string' ) {
return fileId;
}
return this._map[ fileId ];
},
/**
* 从队列中取出一个指定状态的文件。
* @grammar fetch( status ) => File
* @method fetch
* @param {String} status [文件状态值](#WebUploader:File:File.Status)
* @return {File} [File](#WebUploader:File)
*/
fetch: function( status ) {
var len = this._queue.length,
i, file;
status = status || STATUS.QUEUED;
for ( i = 0; i < len; i++ ) {
file = this._queue[ i ];
if ( status === file.getStatus() ) {
return file;
}
}
return null;
},
/**
* 对队列进行排序,能够控制文件上传顺序。
* @grammar sort( fn ) => undefined
* @method sort
* @param {Function} fn 排序方法
*/
sort: function( fn ) {
if ( typeof fn === 'function' ) {
this._queue.sort( fn );
}
},
/**
* 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
* @grammar getFiles( [status1[, status2 ...]] ) => Array
* @method getFiles
* @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
*/
getFiles: function() {
var sts = [].slice.call( arguments, 0 ),
ret = [],
i = 0,
len = this._queue.length,
file;
for ( ; i < len; i++ ) {
file = this._queue[ i ];
if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) {
continue;
}
ret.push( file );
}
return ret;
},
_fileAdded: function( file ) {
var me = this,
existing = this._map[ file.id ];
if ( !existing ) {
this._map[ file.id ] = file;
file.on( 'statuschange', function( cur, pre ) {
me._onFileStatusChange( cur, pre );
});
}
file.setStatus( STATUS.QUEUED );
},
_onFileStatusChange: function( curStatus, preStatus ) {
var stats = this.stats;
switch ( preStatus ) {
case STATUS.PROGRESS:
stats.numOfProgress--;
break;
case STATUS.QUEUED:
stats.numOfQueue --;
break;
case STATUS.ERROR:
stats.numOfUploadFailed--;
break;
case STATUS.INVALID:
stats.numOfInvalid--;
break;
}
switch ( curStatus ) {
case STATUS.QUEUED:
stats.numOfQueue++;
break;
case STATUS.PROGRESS:
stats.numOfProgress++;
break;
case STATUS.ERROR:
stats.numOfUploadFailed++;
break;
case STATUS.COMPLETE:
stats.numOfSuccess++;
break;
case STATUS.CANCELLED:
stats.numOfCancel++;
break;
case STATUS.INVALID:
stats.numOfInvalid++;
break;
}
}
});
Mediator.installTo( Queue.prototype );
return Queue;
});
/**
* @fileOverview 队列
*/
define('widgets/queue',[
'base',
'uploader',
'queue',
'file',
'lib/file',
'runtime/client',
'widgets/widget'
], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) {
var $ = Base.$,
rExt = /\.\w+$/,
Status = WUFile.Status;
return Uploader.register({
'sort-files': 'sortFiles',
'add-file': 'addFiles',
'get-file': 'getFile',
'fetch-file': 'fetchFile',
'get-stats': 'getStats',
'get-files': 'getFiles',
'remove-file': 'removeFile',
'retry': 'retry',
'reset': 'reset',
'accept-file': 'acceptFile'
}, {
init: function( opts ) {
var me = this,
deferred, len, i, item, arr, accept, runtime;
if ( $.isPlainObject( opts.accept ) ) {
opts.accept = [ opts.accept ];
}
// accept中的中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].extensions;
item && arr.push( item );
}
if ( arr.length ) {
accept = '\\.' + arr.join(',')
.replace( /,/g, '$|\\.' )
.replace( /\*/g, '.*' ) + '$';
}
me.accept = new RegExp( accept, 'i' );
}
me.queue = new Queue();
me.stats = me.queue.stats;
// 如果当前不是html5运行时,那就算了。
// 不执行后续操作
if ( this.request('predict-runtime-type') !== 'html5' ) {
return;
}
// 创建一个 html5 运行时的 placeholder
// 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
deferred = Base.Deferred();
runtime = new RuntimeClient('Placeholder');
runtime.connectRuntime({
runtimeOrder: 'html5'
}, function() {
me._ruid = runtime.getRuid();
deferred.resolve();
});
return deferred.promise();
},
// 为了支持外部直接添加一个原生File对象。
_wrapFile: function( file ) {
if ( !(file instanceof WUFile) ) {
if ( !(file instanceof File) ) {
if ( !this._ruid ) {
throw new Error('Can\'t add external files.');
}
file = new File( this._ruid, file );
}
file = new WUFile( file );
}
return file;
},
// 判断文件是否可以被加入队列
acceptFile: function( file ) {
var invalid = !file || file.size < 6 || this.accept &&
// 如果名字中有后缀,才做后缀白名单处理。
rExt.exec( file.name ) && !this.accept.test( file.name );
return !invalid;
},
/**
* @event beforeFileQueued
* @param {File} file File对象
* @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
* @for Uploader
*/
/**
* @event fileQueued
* @param {File} file File对象
* @description 当文件被加入队列以后触发。
* @for Uploader
*/
_addFile: function( file ) {
var me = this;
file = me._wrapFile( file );
// 不过类型判断允许不允许,先派送 `beforeFileQueued`
if ( !me.owner.trigger( 'beforeFileQueued', file ) ) {
return;
}
// 类型不匹配,则派送错误事件,并返回。
if ( !me.acceptFile( file ) ) {
me.owner.trigger( 'error', 'Q_TYPE_DENIED', file );
return;
}
me.queue.append( file );
me.owner.trigger( 'fileQueued', file );
return file;
},
getFile: function( fileId ) {
return this.queue.getFile( fileId );
},
/**
* @event filesQueued
* @param {File} files 数组,内容为原始File(lib/File)对象。
* @description 当一批文件添加进队列以后触发。
* @for Uploader
*/
/**
* @method addFiles
* @grammar addFiles( file ) => undefined
* @grammar addFiles( [file1, file2 ...] ) => undefined
* @param {Array of File or File} [files] Files 对象 数组
* @description 添加文件到队列
* @for Uploader
*/
addFiles: function( files ) {
var me = this;
if ( !files.length ) {
files = [ files ];
}
files = $.map( files, function( file ) {
return me._addFile( file );
});
me.owner.trigger( 'filesQueued', files );
if ( me.options.auto ) {
me.request('start-upload');
}
},
getStats: function() {
return this.stats;
},
/**
* @event fileDequeued
* @param {File} file File对象
* @description 当文件被移除队列后触发。
* @for Uploader
*/
/**
* @method removeFile
* @grammar removeFile( file ) => undefined
* @grammar removeFile( id ) => undefined
* @param {File|id} file File对象或这File对象的id
* @description 移除某一文件。
* @for Uploader
* @example
*
* $li.on('click', '.remove-this', function() {
* uploader.removeFile( file );
* })
*/
removeFile: function( file ) {
var me = this;
file = file.id ? file : me.queue.getFile( file );
file.setStatus( Status.CANCELLED );
me.owner.trigger( 'fileDequeued', file );
},
/**
* @method getFiles
* @grammar getFiles() => Array
* @grammar getFiles( status1, status2, status... ) => Array
* @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
* @for Uploader
* @example
* console.log( uploader.getFiles() ); // => all files
* console.log( uploader.getFiles('error') ) // => all error files.
*/
getFiles: function() {
return this.queue.getFiles.apply( this.queue, arguments );
},
fetchFile: function() {
return this.queue.fetch.apply( this.queue, arguments );
},
/**
* @method retry
* @grammar retry() => undefined
* @grammar retry( file ) => undefined
* @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
* @for Uploader
* @example
* function retry() {
* uploader.retry();
* }
*/
retry: function( file, noForceStart ) {
var me = this,
files, i, len;
if ( file ) {
file = file.id ? file : me.queue.getFile( file );
file.setStatus( Status.QUEUED );
noForceStart || me.request('start-upload');
return;
}
files = me.queue.getFiles( Status.ERROR );
i = 0;
len = files.length;
for ( ; i < len; i++ ) {
file = files[ i ];
file.setStatus( Status.QUEUED );
}
me.request('start-upload');
},
/**
* @method sort
* @grammar sort( fn ) => undefined
* @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
* @for Uploader
*/
sortFiles: function() {
return this.queue.sort.apply( this.queue, arguments );
},
/**
* @method reset
* @grammar reset() => undefined
* @description 重置uploader。目前只重置了队列。
* @for Uploader
* @example
* uploader.reset();
*/
reset: function() {
this.queue = new Queue();
this.stats = this.queue.stats;
}
});
});
/**
* @fileOverview 添加获取Runtime相关信息的方法。
*/
define('widgets/runtime',[
'uploader',
'runtime/runtime',
'widgets/widget'
], function( Uploader, Runtime ) {
Uploader.support = function() {
return Runtime.hasRuntime.apply( Runtime, arguments );
};
return Uploader.register({
'predict-runtime-type': 'predictRuntmeType'
}, {
init: function() {
if ( !this.predictRuntmeType() ) {
throw Error('Runtime Error');
}
},
/**
* 预测Uploader将采用哪个`Runtime`
* @grammar predictRuntmeType() => String
* @method predictRuntmeType
* @for Uploader
*/
predictRuntmeType: function() {
var orders = this.options.runtimeOrder || Runtime.orders,
type = this.type,
i, len;
if ( !type ) {
orders = orders.split( /\s*,\s*/g );
for ( i = 0, len = orders.length; i < len; i++ ) {
if ( Runtime.hasRuntime( orders[ i ] ) ) {
this.type = type = orders[ i ];
break;
}
}
}
return type;
}
});
});
/**
* @fileOverview Transport
*/
define('lib/transport',[
'base',
'runtime/client',
'mediator'
], function( Base, RuntimeClient, Mediator ) {
var $ = Base.$;
function Transport( opts ) {
var me = this;
opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
RuntimeClient.call( this, 'Transport' );
this._blob = null;
this._formData = opts.formData || {};
this._headers = opts.headers || {};
this.on( 'progress', this._timeout );
this.on( 'load error', function() {
me.trigger( 'progress', 1 );
clearTimeout( me._timer );
});
}
Transport.options = {
server: '',
method: 'POST',
// 跨域时,是否允许携带cookie, 只有html5 runtime才有效
withCredentials: false,
fileVal: 'file',
timeout: 2 * 60 * 1000, // 2分钟
formData: {},
headers: {},
sendAsBinary: false
};
$.extend( Transport.prototype, {
// 添加Blob, 只能添加一次,最后一次有效。
appendBlob: function( key, blob, filename ) {
var me = this,
opts = me.options;
if ( me.getRuid() ) {
me.disconnectRuntime();
}
// 连接到blob归属的同一个runtime.
me.connectRuntime( blob.ruid, function() {
me.exec('init');
});
me._blob = blob;
opts.fileVal = key || opts.fileVal;
opts.filename = filename || opts.filename;
},
// 添加其他字段
append: function( key, value ) {
if ( typeof key === 'object' ) {
$.extend( this._formData, key );
} else {
this._formData[ key ] = value;
}
},
setRequestHeader: function( key, value ) {
if ( typeof key === 'object' ) {
$.extend( this._headers, key );
} else {
this._headers[ key ] = value;
}
},
send: function( method ) {
this.exec( 'send', method );
this._timeout();
},
abort: function() {
clearTimeout( this._timer );
return this.exec('abort');
},
destroy: function() {
this.trigger('destroy');
this.off();
this.exec('destroy');
this.disconnectRuntime();
},
getResponse: function() {
return this.exec('getResponse');
},
getResponseAsJson: function() {
return this.exec('getResponseAsJson');
},
getStatus: function() {
return this.exec('getStatus');
},
_timeout: function() {
var me = this,
duration = me.options.timeout;
if ( !duration ) {
return;
}
clearTimeout( me._timer );
me._timer = setTimeout(function() {
me.abort();
me.trigger( 'error', 'timeout' );
}, duration );
}
});
// 让Transport具备事件功能。
Mediator.installTo( Transport.prototype );
return Transport;
});
/**
* @fileOverview 负责文件上传相关。
*/
define('widgets/upload',[
'base',
'uploader',
'file',
'lib/transport',
'widgets/widget'
], function( Base, Uploader, WUFile, Transport ) {
var $ = Base.$,
isPromise = Base.isPromise,
Status = WUFile.Status;
// 添加默认配置项
$.extend( Uploader.options, {
/**
* @property {Boolean} [prepareNextFile=false]
* @namespace options
* @for Uploader
* @description 是否允许在文件传输时提前把下一个文件准备好。
* 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
* 如果能提前在当前文件传输期处理,可以节省总体耗时。
*/
prepareNextFile: false,
/**
* @property {Boolean} [chunked=false]
* @namespace options
* @for Uploader
* @description 是否要分片处理大文件上传。
*/
chunked: false,
/**
* @property {Boolean} [chunkSize=5242880]
* @namespace options
* @for Uploader
* @description 如果要分片,分多大一片? 默认大小为5M.
*/
chunkSize: 5 * 1024 * 1024,
/**
* @property {Boolean} [chunkRetry=2]
* @namespace options
* @for Uploader
* @description 如果某个分片由于网络问题出错,允许自动重传多少次?
*/
chunkRetry: 2,
/**
* @property {Boolean} [threads=3]
* @namespace options
* @for Uploader
* @description 上传并发数。允许同时最大上传进程数。
*/
threads: 3,
/**
* @property {Object} [formData]
* @namespace options
* @for Uploader
* @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
*/
formData: null
/**
* @property {Object} [fileVal='file']
* @namespace options
* @for Uploader
* @description 设置文件上传域的name。
*/
/**
* @property {Object} [method='POST']
* @namespace options
* @for Uploader
* @description 文件上传方式,`POST`或者`GET`。
*/
/**
* @property {Object} [sendAsBinary=false]
* @namespace options
* @for Uploader
* @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
* 其他参数在$_GET数组中。
*/
});
// 负责将文件切片。
function CuteFile( file, chunkSize ) {
var pending = [],
blob = file.source,
total = blob.size,
chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
start = 0,
index = 0,
len;
while ( index < chunks ) {
len = Math.min( chunkSize, total - start );
pending.push({
file: file,
start: start,
end: chunkSize ? (start + len) : total,
total: total,
chunks: chunks,
chunk: index++
});
start += len;
}
file.blocks = pending.concat();
file.remaning = pending.length;
return {
file: file,
has: function() {
return !!pending.length;
},
fetch: function() {
return pending.shift();
}
};
}
Uploader.register({
'start-upload': 'start',
'stop-upload': 'stop',
'skip-file': 'skipFile',
'is-in-progress': 'isInProgress'
}, {
init: function() {
var owner = this.owner;
this.runing = false;
// 记录当前正在传的数据,跟threads相关
this.pool = [];
// 缓存即将上传的文件。
this.pending = [];
// 跟踪还有多少分片没有完成上传。
this.remaning = 0;
this.__tick = Base.bindFn( this._tick, this );
owner.on( 'uploadComplete', function( file ) {
// 把其他块取消了。
file.blocks && $.each( file.blocks, function( _, v ) {
v.transport && (v.transport.abort(), v.transport.destroy());
delete v.transport;
});
delete file.blocks;
delete file.remaning;
});
},
/**
* @event startUpload
* @description 当开始上传流程时触发。
* @for Uploader
*/
/**
* 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
* @grammar upload() => undefined
* @method upload
* @for Uploader
*/
start: function() {
var me = this;
// 移出invalid的文件
$.each( me.request( 'get-files', Status.INVALID ), function() {
me.request( 'remove-file', this );
});
if ( me.runing ) {
return;
}
me.runing = true;
// 如果有暂停的,则续传
$.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
file.setStatus( Status.PROGRESS );
me._trigged = false;
v.transport && v.transport.send();
}
});
me._trigged = false;
me.owner.trigger('startUpload');
Base.nextTick( me.__tick );
},
/**
* @event stopUpload
* @description 当开始上传流程暂停时触发。
* @for Uploader
*/
/**
* 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
* @grammar stop() => undefined
* @grammar stop( true ) => undefined
* @method stop
* @for Uploader
*/
stop: function( interrupt ) {
var me = this;
if ( me.runing === false ) {
return;
}
me.runing = false;
interrupt && $.each( me.pool, function( _, v ) {
v.transport && v.transport.abort();
v.file.setStatus( Status.INTERRUPT );
});
me.owner.trigger('stopUpload');
},
/**
* 判断`Uplaode`r是否正在上传中。
* @grammar isInProgress() => Boolean
* @method isInProgress
* @for Uploader
*/
isInProgress: function() {
return !!this.runing;
},
getStats: function() {
return this.request('get-stats');
},
/**
* 掉过一个文件上传,直接标记指定文件为已上传状态。
* @grammar skipFile( file ) => undefined
* @method skipFile
* @for Uploader
*/
skipFile: function( file, status ) {
file = this.request( 'get-file', file );
file.setStatus( status || Status.COMPLETE );
file.skipped = true;
// 如果正在上传。
file.blocks && $.each( file.blocks, function( _, v ) {
var _tr = v.transport;
if ( _tr ) {
_tr.abort();
_tr.destroy();
delete v.transport;
}
});
this.owner.trigger( 'uploadSkip', file );
},
/**
* @event uploadFinished
* @description 当所有文件上传结束时触发。
* @for Uploader
*/
_tick: function() {
var me = this,
opts = me.options,
fn, val;
// 上一个promise还没有结束,则等待完成后再执行。
if ( me._promise ) {
return me._promise.always( me.__tick );
}
// 还有位置,且还有文件要处理的话。
if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
me._trigged = false;
fn = function( val ) {
me._promise = null;
// 有可能是reject过来的,所以要检测val的类型。
val && val.file && me._startSend( val );
Base.nextTick( me.__tick );
};
me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
// 没有要上传的了,且没有正在传输的了。
} else if ( !me.remaning && !me.getStats().numOfQueue ) {
me.runing = false;
me._trigged || Base.nextTick(function() {
me.owner.trigger('uploadFinished');
});
me._trigged = true;
}
},
_nextBlock: function() {
var me = this,
act = me._act,
opts = me.options,
next, done;
// 如果当前文件还有没有需要传输的,则直接返回剩下的。
if ( act && act.has() &&
act.file.getStatus() === Status.PROGRESS ) {
// 是否提前准备下一个文件
if ( opts.prepareNextFile && !me.pending.length ) {
me._prepareNextFile();
}
return act.fetch();
// 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
} else if ( me.runing ) {
// 如果缓存中有,则直接在缓存中取,没有则去queue中取。
if ( !me.pending.length && me.getStats().numOfQueue ) {
me._prepareNextFile();
}
next = me.pending.shift();
done = function( file ) {
if ( !file ) {
return null;
}
act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
me._act = act;
return act.fetch();
};
// 文件可能还在prepare中,也有可能已经完全准备好了。
return isPromise( next ) ?
next[ next.pipe ? 'pipe' : 'then']( done ) :
done( next );
}
},
/**
* @event uploadStart
* @param {File} file File对象
* @description 某个文件开始上传前触发,一个文件只会触发一次。
* @for Uploader
*/
_prepareNextFile: function() {
var me = this,
file = me.request('fetch-file'),
pending = me.pending,
promise;
if ( file ) {
promise = me.request( 'before-send-file', file, function() {
// 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
if ( file.getStatus() === Status.QUEUED ) {
me.owner.trigger( 'uploadStart', file );
file.setStatus( Status.PROGRESS );
return file;
}
return me._finishFile( file );
});
// 如果还在pending中,则替换成文件本身。
promise.done(function() {
var idx = $.inArray( promise, pending );
~idx && pending.splice( idx, 1, file );
});
// befeore-send-file的钩子就有错误发生。
promise.fail(function( reason ) {
file.setStatus( Status.ERROR, reason );
me.owner.trigger( 'uploadError', file, reason );
me.owner.trigger( 'uploadComplete', file );
});
pending.push( promise );
}
},
// 让出位置了,可以让其他分片开始上传
_popBlock: function( block ) {
var idx = $.inArray( block, this.pool );
this.pool.splice( idx, 1 );
block.file.remaning--;
this.remaning--;
},
// 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
_startSend: function( block ) {
var me = this,
file = block.file,
promise;
me.pool.push( block );
me.remaning++;
// 如果没有分片,则直接使用原始的。
// 不会丢失content-type信息。
block.blob = block.chunks === 1 ? file.source :
file.source.slice( block.start, block.end );
// hook, 每个分片发送之前可能要做些异步的事情。
promise = me.request( 'before-send', block, function() {
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else {
me._popBlock( block );
Base.nextTick( me.__tick );
}
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
if ( file.remaning === 1 ) {
me._finishFile( file ).always(function() {
block.percentage = 1;
me._popBlock( block );
me.owner.trigger( 'uploadComplete', file );
Base.nextTick( me.__tick );
});
} else {
block.percentage = 1;
me._popBlock( block );
Base.nextTick( me.__tick );
}
});
},
/**
* @event uploadBeforeSend
* @param {Object} object
* @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
* @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
* @for Uploader
*/
/**
* @event uploadAccept
* @param {Object} object
* @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
* @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
* @for Uploader
*/
/**
* @event uploadProgress
* @param {File} file File对象
* @param {Number} percentage 上传进度
* @description 上传过程中触发,携带上传进度。
* @for Uploader
*/
/**
* @event uploadError
* @param {File} file File对象
* @param {String} reason 出错的code
* @description 当文件上传出错时触发。
* @for Uploader
*/
/**
* @event uploadSuccess
* @param {File} file File对象
* @param {Object} response 服务端返回的数据
* @description 当文件上传成功时触发。
* @for Uploader
*/
/**
* @event uploadComplete
* @param {File} [file] File对象
* @description 不管成功或者失败,文件上传完成时触发。
* @for Uploader
*/
// 做上传操作。
_doSend: function( block ) {
var me = this,
owner = me.owner,
opts = me.options,
file = block.file,
tr = new Transport( opts ),
data = $.extend({}, opts.formData ),
headers = $.extend({}, opts.headers ),
requestAccept, ret;
block.transport = tr;
tr.on( 'destroy', function() {
delete block.transport;
me._popBlock( block );
Base.nextTick( me.__tick );
});
// 广播上传进度。以文件为单位。
tr.on( 'progress', function( percentage ) {
var totalPercent = 0,
uploaded = 0;
// 可能没有abort掉,progress还是执行进来了。
// if ( !file.blocks ) {
// return;
// }
totalPercent = block.percentage = percentage;
if ( block.chunks > 1 ) { // 计算文件的整体速度。
$.each( file.blocks, function( _, v ) {
uploaded += (v.percentage || 0) * (v.end - v.start);
});
totalPercent = uploaded / file.size;
}
owner.trigger( 'uploadProgress', file, totalPercent || 0 );
});
// 用来询问,是否返回的结果是有错误的。
requestAccept = function( reject ) {
var fn;
ret = tr.getResponseAsJson() || {};
ret._raw = tr.getResponse();
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
tr.send();
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type );
owner.trigger( 'uploadComplete', file );
}
});
// 上传成功
tr.on( 'load', function() {
var reason;
// 如果非预期,转向上传出错。
if ( (reason = requestAccept()) ) {
tr.trigger( 'error', reason, true );
return;
}
// 全部上传完成。
if ( file.remaning === 1 ) {
me._finishFile( file, ret );
} else {
tr.destroy();
}
});
// 配置默认的上传字段。
data = $.extend( data, {
id: file.id,
name: file.name,
type: file.type,
lastModifiedDate: file.lastModifiedDate,
size: file.size
});
block.chunks > 1 && $.extend( data, {
chunks: block.chunks,
chunk: block.chunk
});
// 在发送之间可以添加字段什么的。。。
// 如果默认的字段不够使用,可以通过监听此事件来扩展
owner.trigger( 'uploadBeforeSend', block, data, headers );
// 开始发送。
tr.appendBlob( opts.fileVal, block.blob, file.name );
tr.append( data );
tr.setRequestHeader( headers );
tr.send();
},
// 完成上传。
_finishFile: function( file, ret, hds ) {
var owner = this.owner;
return owner
.request( 'after-send-file', arguments, function() {
file.setStatus( Status.COMPLETE );
owner.trigger( 'uploadSuccess', file, ret, hds );
})
.fail(function( reason ) {
// 如果外部已经标记为invalid什么的,不再改状态。
if ( file.getStatus() === Status.PROGRESS ) {
file.setStatus( Status.ERROR, reason );
}
owner.trigger( 'uploadError', file, reason );
})
.always(function() {
owner.trigger( 'uploadComplete', file );
});
}
});
});
/**
* @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
*/
define('widgets/validator',[
'base',
'uploader',
'file',
'widgets/widget'
], function( Base, Uploader, WUFile ) {
var $ = Base.$,
validators = {},
api;
/**
* @event error
* @param {String} type 错误类型。
* @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
*
* * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
* * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
* @for Uploader
*/
// 暴露给外面的api
api = {
// 添加验证器
addValidator: function( type, cb ) {
validators[ type ] = cb;
},
// 移除验证器
removeValidator: function( type ) {
delete validators[ type ];
}
};
// 在Uploader初始化的时候启动Validators的初始化
Uploader.register({
init: function() {
var me = this;
$.each( validators, function() {
this.call( me.owner );
});
}
});
/**
* @property {int} [fileNumLimit=undefined]
* @namespace options
* @for Uploader
* @description 验证文件总数量, 超出则不允许加入队列。
*/
api.addValidator( 'fileNumLimit', function() {
var uploader = this,
opts = uploader.options,
count = 0,
max = opts.fileNumLimit >> 0,
flag = true;
if ( !max ) {
return;
}
uploader.on( 'beforeFileQueued', function( file ) {
if ( count >= max && flag ) {
flag = false;
this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file );
setTimeout(function() {
flag = true;
}, 1 );
}
return count >= max ? false : true;
});
uploader.on( 'fileQueued', function() {
count++;
});
uploader.on( 'fileDequeued', function() {
count--;
});
uploader.on( 'uploadFinished', function() {
count = 0;
});
});
/**
* @property {int} [fileSizeLimit=undefined]
* @namespace options
* @for Uploader
* @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
*/
api.addValidator( 'fileSizeLimit', function() {
var uploader = this,
opts = uploader.options,
count = 0,
max = opts.fileSizeLimit >> 0,
flag = true;
if ( !max ) {
return;
}
uploader.on( 'beforeFileQueued', function( file ) {
var invalid = count + file.size > max;
if ( invalid && flag ) {
flag = false;
this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file );
setTimeout(function() {
flag = true;
}, 1 );
}
return invalid ? false : true;
});
uploader.on( 'fileQueued', function( file ) {
count += file.size;
});
uploader.on( 'fileDequeued', function( file ) {
count -= file.size;
});
uploader.on( 'uploadFinished', function() {
count = 0;
});
});
/**
* @property {int} [fileSingleSizeLimit=undefined]
* @namespace options
* @for Uploader
* @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
*/
api.addValidator( 'fileSingleSizeLimit', function() {
var uploader = this,
opts = uploader.options,
max = opts.fileSingleSizeLimit;
if ( !max ) {
return;
}
uploader.on( 'beforeFileQueued', function( file ) {
if ( file.size > max ) {
file.setStatus( WUFile.Status.INVALID, 'exceed_size' );
this.trigger( 'error', 'F_EXCEED_SIZE', file );
return false;
}
});
});
/**
* @property {int} [duplicate=undefined]
* @namespace options
* @for Uploader
* @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
*/
api.addValidator( 'duplicate', function() {
var uploader = this,
opts = uploader.options,
mapping = {};
if ( opts.duplicate ) {
return;
}
function hashString( str ) {
var hash = 0,
i = 0,
len = str.length,
_char;
for ( ; i < len; i++ ) {
_char = str.charCodeAt( i );
hash = _char + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
uploader.on( 'beforeFileQueued', function( file ) {
var hash = file.__hash || (file.__hash = hashString( file.name +
file.size + file.lastModifiedDate ));
// 已经重复了
if ( mapping[ hash ] ) {
this.trigger( 'error', 'F_DUPLICATE', file );
return false;
}
});
uploader.on( 'fileQueued', function( file ) {
var hash = file.__hash;
hash && (mapping[ hash ] = true);
});
uploader.on( 'fileDequeued', function( file ) {
var hash = file.__hash;
hash && (delete mapping[ hash ]);
});
});
return api;
});
/**
* @fileOverview Runtime管理器,负责Runtime的选择, 连接
*/
define('runtime/compbase',[],function() {
function CompBase( owner, runtime ) {
this.owner = owner;
this.options = owner.options;
this.getRuntime = function() {
return runtime;
};
this.getRuid = function() {
return runtime.uid;
};
this.trigger = function() {
return owner.trigger.apply( owner, arguments );
};
}
return CompBase;
});
/**
* @fileOverview FlashRuntime
*/
define('runtime/flash/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var $ = Base.$,
type = 'flash',
components = {};
function getFlashVersion() {
var version;
try {
version = navigator.plugins[ 'Shockwave Flash' ];
version = version.description;
} catch ( ex ) {
try {
version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
.GetVariable('$version');
} catch ( ex2 ) {
version = '0.0';
}
}
version = version.match( /\d+/g );
return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
}
function FlashRuntime() {
var pool = {},
clients = {},
destory = this.destory,
me = this,
jsreciver = Base.guid('webuploader_');
Runtime.apply( me, arguments );
me.type = type;
// 这个方法的调用者,实际上是RuntimeClient
me.exec = function( comp, fn/*, args...*/ ) {
var client = this,
uid = client.uid,
args = Base.slice( arguments, 2 ),
instance;
clients[ uid ] = client;
if ( components[ comp ] ) {
if ( !pool[ uid ] ) {
pool[ uid ] = new components[ comp ]( client, me );
}
instance = pool[ uid ];
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
return me.flashExec.apply( client, arguments );
};
function handler( evt, obj ) {
var type = evt.type || evt,
parts, uid;
parts = type.split('::');
uid = parts[ 0 ];
type = parts[ 1 ];
// console.log.apply( console, arguments );
if ( type === 'Ready' && uid === me.uid ) {
me.trigger('ready');
} else if ( clients[ uid ] ) {
clients[ uid ].trigger( type.toLowerCase(), evt, obj );
}
// Base.log( evt, obj );
}
// flash的接受器。
window[ jsreciver ] = function() {
var args = arguments;
// 为了能捕获得到。
setTimeout(function() {
handler.apply( null, args );
}, 1 );
};
this.jsreciver = jsreciver;
this.destory = function() {
// @todo 删除池子中的所有实例
return destory && destory.apply( this, arguments );
};
this.flashExec = function( comp, fn ) {
var flash = me.getFlash(),
args = Base.slice( arguments, 2 );
return flash.exec( this.uid, comp, fn, args );
};
// @todo
}
Base.inherits( Runtime, {
constructor: FlashRuntime,
init: function() {
var container = this.getContainer(),
opts = this.options,
html;
// if not the minimal height, shims are not initialized
// in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
container.css({
position: 'absolute',
top: '-8px',
left: '-8px',
width: '9px',
height: '9px',
overflow: 'hidden'
});
// insert flash object
html = '<object id="' + this.uid + '" type="application/' +
'x-shockwave-flash" data="' + opts.swf + '" ';
if ( Base.browser.ie ) {
html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
}
html += 'width="100%" height="100%" style="outline:0">' +
'<param name="movie" value="' + opts.swf + '" />' +
'<param name="flashvars" value="uid=' + this.uid +
'&jsreciver=' + this.jsreciver + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowscriptaccess" value="always" />' +
'</object>';
container.html( html );
},
getFlash: function() {
if ( this._flash ) {
return this._flash;
}
this._flash = $( '#' + this.uid ).get( 0 );
return this._flash;
}
});
FlashRuntime.register = function( name, component ) {
component = components[ name ] = Base.inherits( CompBase, $.extend({
// @todo fix this later
flashExec: function() {
var owner = this.owner,
runtime = this.getRuntime();
return runtime.flashExec.apply( owner, arguments );
}
}, component ) );
return component;
};
if ( getFlashVersion() >= 11.4 ) {
Runtime.addRuntime( type, FlashRuntime );
}
return FlashRuntime;
});
/**
* @fileOverview FilePicker
*/
define('runtime/flash/filepicker',[
'base',
'runtime/flash/runtime'
], function( Base, FlashRuntime ) {
var $ = Base.$;
return FlashRuntime.register( 'FilePicker', {
init: function( opts ) {
var copy = $.extend({}, opts ),
len, i;
// 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug.
len = copy.accept && copy.accept.length;
for ( i = 0; i < len; i++ ) {
if ( !copy.accept[ i ].title ) {
copy.accept[ i ].title = 'Files';
}
}
delete copy.button;
delete copy.container;
this.flashExec( 'FilePicker', 'init', copy );
},
destroy: function() {
// todo
}
});
});
/**
* @fileOverview 图片压缩
*/
define('runtime/flash/image',[
'runtime/flash/runtime'
], function( FlashRuntime ) {
return FlashRuntime.register( 'Image', {
// init: function( options ) {
// var owner = this.owner;
// this.flashExec( 'Image', 'init', options );
// owner.on( 'load', function() {
// debugger;
// });
// },
loadFromBlob: function( blob ) {
var owner = this.owner;
owner.info() && this.flashExec( 'Image', 'info', owner.info() );
owner.meta() && this.flashExec( 'Image', 'meta', owner.meta() );
this.flashExec( 'Image', 'loadFromBlob', blob.uid );
}
});
});
/**
* @fileOverview Transport flash实现
*/
define('runtime/flash/transport',[
'base',
'runtime/flash/runtime',
'runtime/client'
], function( Base, FlashRuntime, RuntimeClient ) {
var $ = Base.$;
return FlashRuntime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
this._responseJson = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
binary;
xhr.connectRuntime( blob.ruid );
if ( opts.sendAsBinary ) {
server += (/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData );
binary = blob.uid;
} else {
$.each( owner._formData, function( k, v ) {
xhr.exec( 'append', k, v );
});
xhr.exec( 'appendBlob', opts.fileVal, blob.uid,
opts.filename || owner._formData.name || '' );
}
this._setRequestHeader( xhr, opts.headers );
xhr.exec( 'send', {
method: opts.method,
url: server
}, binary );
},
getStatus: function() {
return this._status;
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._responseJson;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.exec('abort');
xhr.destroy();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_initAjax: function() {
var me = this,
xhr = new RuntimeClient('XMLHttpRequest');
xhr.on( 'uploadprogress progress', function( e ) {
return me.trigger( 'progress', e.loaded / e.total );
});
xhr.on( 'load', function() {
var status = xhr.exec('getStatus'),
err = '';
xhr.off();
me._xhr = null;
if ( status >= 200 && status < 300 ) {
me._response = xhr.exec('getResponse');
me._responseJson = xhr.exec('getResponseAsJson');
} else if ( status >= 500 && status < 600 ) {
me._response = xhr.exec('getResponse');
me._responseJson = xhr.exec('getResponseAsJson');
err = 'server';
} else {
err = 'http';
}
xhr.destroy();
xhr = null;
return err ? me.trigger( 'error', err ) : me.trigger('load');
});
xhr.on( 'error', function() {
xhr.off();
me._xhr = null;
me.trigger( 'error', 'http' );
});
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setRequestHeader', key, val );
});
}
});
});
/**
* @fileOverview 只有flash实现的文件版本。
*/
define('preset/flashonly',[
'base',
// widgets
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// flash
'runtime/flash/filepicker',
'runtime/flash/image',
'runtime/flash/transport'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/flashonly'
], function( preset ) {
return preset;
});
return require('webuploader');
}); | |
test_attribute_base.py | #
# Copyright (c) 2020, Neptune Labs Sp. z o.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import random
import threading
import time
import unittest
import uuid
from typing import Optional
from mock import MagicMock
from neptune.new.internal.container_type import ContainerType
from neptune.new.internal.id_formats import UniqueId
from neptune.new.internal.operation_processors.operation_processor import (
OperationProcessor,
)
from neptune.new.internal.operation_processors.sync_operation_processor import (
SyncOperationProcessor,
)
from neptune.new.internal.backends.neptune_backend_mock import NeptuneBackendMock
from neptune.new.metadata_containers import Run
_now = time.time()
class TestAttributeBase(unittest.TestCase):
# TODO: test Projects, Model and ModelVersion
@staticmethod
def _create_run(processor: Optional[OperationProcessor] = None):
backend = NeptuneBackendMock()
exp = backend.create_run(UniqueId(str(uuid.uuid4())))
if processor is None:
processor = SyncOperationProcessor(exp.id, ContainerType.RUN, backend)
_run = Run(
id_=exp.id,
backend=backend,
op_processor=processor,
background_job=MagicMock(),
lock=threading.RLock(),
workspace=MagicMock(),
project_id=MagicMock(),
project_name=MagicMock(),
sys_id=MagicMock(),
)
_run.sync()
_run.start()
return _run
@staticmethod
def _random_path():
return ["some", "random", "path", str(uuid.uuid4())]
@staticmethod
def _random_wait():
return bool(random.getrandbits(1))
| @staticmethod
def _now():
return _now | |
PageDetails.js | const { Schema, model } = require('mongoose');
const uuid = require('uuid');
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const pageComponentSchema = new Schema({
_id: { type: String, min: 36, max: 36, default: uuid.v4 },
treeNodeLabel: { type: String, max: 255 },
attributes: { type: Object },
componentPatternId: { type: Schema.Types.ObjectId, required: true, ref: 'ComponentPattern' },
data: { type: Object },
parentComponentId: { type: String, min: 36, max: 36 },
});
const pageDetailsSchema = new Schema(
{
components: [pageComponentSchema],
country: { type: Schema.Types.ObjectId, require: true, ref: 'Country' },
default: { type: Boolean, default: false }, | description: { type: String, require: true, max: 250 },
name: { type: String, require: true, min: 3, max: 50, default: 'default' },
pageId: { type: Schema.Types.ObjectId, require: true, ref: 'Page' },
title: { type: String, require: true, min: 3, max: 100 },
},
{
timestamps: true,
optimisticConcurrency: true,
versionKey: 'version',
}
);
const pageComponentValidationSchema = Joi.object({
_id: Joi.string().min(36).max(36),
treeNodeLabel: Joi.string().max(255),
attributes: Joi.object(),
componentPatternId: Joi.objectId().required(),
data: Joi.object(),
parentComponentId: Joi.string().min(36).max(36),
});
const pageDetailsValidationSchema = Joi.object({
attributes: Joi.object(),
components: Joi.array().items(pageComponentValidationSchema),
country: Joi.objectId().required(),
default: Joi.boolean(),
description: Joi.string().required().max(250),
name: Joi.string().min(3).max(50).required(),
pageId: Joi.objectId().required(),
title: Joi.string().required().min(3).max(100),
});
const PageDetails = model('PageDetails', pageDetailsSchema);
module.exports = {
pageComponentSchema,
pageDetailsSchema,
pageComponentValidationSchema,
pageDetailsValidationSchema,
PageDetails,
}; | |
test_histogram2d.py | import numpy as np
import pytest
from just_bin_it.histograms.histogram2d import Histogram2d
IRRELEVANT_TOPIC = "some-topic"
class | :
@pytest.fixture(autouse=True)
def prepare(self):
self.pulse_time = 1234
self.num_bins = (5, 10)
self.tof_range = (0, 10)
self.det_range = (0, 5)
self.data = np.array([x for x in range(self.num_bins[0])])
self.hist = Histogram2d("topic", self.num_bins, self.tof_range, self.det_range)
def test_if_single_value_for_num_bins_then_value_used_for_both_x_and_y(self):
num_bins = 5
hist = Histogram2d("topic", num_bins, self.tof_range, self.det_range)
assert len(hist.x_edges) == num_bins + 1
assert len(hist.y_edges) == num_bins + 1
assert hist.shape == (num_bins, num_bins)
def test_on_construction_histogram_is_uninitialised(self):
assert self.hist.x_edges is not None
assert self.hist.y_edges is not None
assert self.hist.shape == self.num_bins
assert len(self.hist.x_edges) == self.num_bins[0] + 1
assert len(self.hist.y_edges) == self.num_bins[1] + 1
assert self.hist.x_edges[0] == self.data[0]
assert self.hist.x_edges[-1] == 10
assert self.hist.y_edges[0] == self.data[0]
assert self.hist.y_edges[-1] == 5
assert self.hist.data.sum() == 0
def test_adding_data_to_initialised_histogram_new_data_is_added(self):
self.hist.add_data(self.pulse_time, self.data, self.data)
first_sum = self.hist.data.sum()
# Add the data again
self.hist.add_data(self.pulse_time, self.data, self.data)
# Sum should be double
assert self.hist.data.sum() == first_sum * 2
def test_adding_data_outside_initial_bins_is_ignored(self):
self.hist.add_data(self.pulse_time, self.data, self.data)
first_sum = self.hist.data.sum()
x_edges = self.hist.x_edges[:]
y_edges = self.hist.y_edges[:]
# Add data that is outside the edges
new_data = np.array([x + self.num_bins[0] + 1 for x in range(self.num_bins[0])])
self.hist.add_data(self.pulse_time, new_data, new_data)
# Sum should not change
assert self.hist.data.sum() == first_sum
# Edges should not change
assert np.array_equal(self.hist.x_edges, x_edges)
assert np.array_equal(self.hist.y_edges, y_edges)
def test_if_no_id_supplied_then_defaults_to_empty_string(self):
assert self.hist.identifier == ""
def test_id_supplied_then_is_set(self):
example_id = "abcdef"
hist = Histogram2d(
"topic1",
self.num_bins,
self.tof_range,
self.det_range,
identifier=example_id,
)
assert hist.identifier == example_id
def test_only_data_with_correct_source_is_added(self):
hist = Histogram2d(
"topic", self.num_bins, self.tof_range, self.det_range, source="source1"
)
hist.add_data(self.pulse_time, self.data, self.data, source="source1")
hist.add_data(self.pulse_time, self.data, self.data, source="source1")
hist.add_data(self.pulse_time, self.data, self.data, source="OTHER")
assert hist.data.sum() == 10
def test_clearing_histogram_data_clears_histogram(self):
self.hist.add_data(self.pulse_time, self.data, self.data)
self.hist.clear_data()
assert self.hist.data.sum() == 0
def test_after_clearing_histogram_can_add_data(self):
self.hist.add_data(self.pulse_time, self.data, self.data)
self.hist.clear_data()
self.hist.add_data(self.pulse_time, self.data, self.data)
assert self.hist.shape == self.num_bins
assert self.hist.data.sum() == 5
def test_adding_empty_data_does_nothing(self):
self.hist.add_data(self.pulse_time, [], [])
assert self.hist.data.sum() == 0
def test_histogram_keeps_track_of_last_pulse_time_processed(self):
self.hist.add_data(1234, self.data, self.data)
self.hist.add_data(1235, self.data, self.data)
self.hist.add_data(1236, self.data, self.data)
assert self.hist.last_pulse_time == 1236
| TestHistogram2dFunctionality |
symbols.ts | import { InjectionToken } from '@angular/core';
|
/** Provide alternate console.log implementation */
logger?: any;
/** Disable the logger. Useful for prod mode. */
disabled?: boolean;
}
export const NGXS_LOGGER_PLUGIN_OPTIONS = new InjectionToken('NGXS_LOGGER_PLUGIN_OPTIONS'); | export interface NgxsLoggerPluginOptions {
/** Auto expand logged actions */
collapsed?: boolean; |
common.rs | // Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors
// SPDX-License-Identifier: MIT
use std::{
io::Read,
slice::Chunks,
sync::mpsc::{channel, TryRecvError},
time::Duration,
};
use std::convert::{TryFrom, TryInto};
use bytes::BufMut;
use criterion::Criterion;
use crypto::{
crypto_box::{PrecomputedKey, PublicKey, SecretKey},
hash::{BlockHash, ContextHash, CryptoboxPublicKeyHash, OperationListListHash},
nonce::{Nonce, NoncePair},
};
use networking::p2p::stream::{
Crypto, EncryptedMessageReaderBase, MessageStream, CONTENT_LENGTH_MAX,
};
use slog::{debug, o, Drain};
use tezos_messages::p2p::{
binary_message::BinaryChunk,
encoding::{
limits::BLOCK_HEADER_PROTOCOL_DATA_MAX_SIZE,
peer::{PeerMessage, PeerMessageResponse},
},
};
use tezos_messages::p2p::binary_message::BinaryRead;
use tokio::{runtime::Builder, time::Instant};
pub struct BinaryChunks<'a> {
chunks: Chunks<'a, u8>,
}
impl<'a> From<Chunks<'a, u8>> for BinaryChunks<'a> {
fn from(chunks: Chunks<'a, u8>) -> Self {
Self { chunks }
}
}
impl Iterator for BinaryChunks<'_> {
type Item = BinaryChunk;
fn next(&mut self) -> Option<Self::Item> {
self.chunks
.next()
.map(|chunk| BinaryChunk::from_content(chunk).expect("Error constructing binary chunk"))
}
}
static REMOTE_MSG: [u8; 32] = [0x0f; 32];
static LOCAL_MSG: [u8; 32] = [0xf0; 32];
pub struct CryptoMock {
pub local: CryptoMockHalf,
pub remote: CryptoMockHalf,
}
impl CryptoMock {
pub fn new() -> Self {
let local_nonce_pair =
crypto::nonce::generate_nonces(&LOCAL_MSG, &REMOTE_MSG, false).unwrap();
let remote_nonce_pair =
crypto::nonce::generate_nonces(&REMOTE_MSG, &LOCAL_MSG, true).unwrap();
let (local_sk, local_pk, local_pkh) = crypto::crypto_box::random_keypair().unwrap();
let (remote_sk, remote_pk, remote_pkh) = crypto::crypto_box::random_keypair().unwrap();
let local_precomp_key = PrecomputedKey::precompute(&remote_pk, &local_sk);
let remote_precomp_key = PrecomputedKey::precompute(&local_pk, &remote_sk);
CryptoMock {
local: CryptoMockHalf {
sk: local_sk,
pk: local_pk,
pkh: local_pkh,
precompute_key: local_precomp_key,
nonce_pair: local_nonce_pair,
},
remote: CryptoMockHalf {
sk: remote_sk,
pk: remote_pk,
pkh: remote_pkh,
precompute_key: remote_precomp_key,
nonce_pair: remote_nonce_pair,
},
}
}
}
pub struct CryptoMockHalf {
pub sk: SecretKey,
pub pk: PublicKey,
pub pkh: CryptoboxPublicKeyHash,
pub precompute_key: PrecomputedKey,
pub nonce_pair: NoncePair,
}
pub struct PeerMock<W> {
crypt: Crypto,
chunk_size: usize,
write: W,
}
impl<W: std::io::Write> PeerMock<W> {
pub fn | (precomputed_key: PrecomputedKey, nonce: Nonce, write: W) -> Self {
Self {
crypt: Crypto::new(precomputed_key, nonce),
chunk_size: CONTENT_LENGTH_MAX,
write,
}
}
pub fn chunk_size(&mut self, chunk_size: usize) {
self.chunk_size = chunk_size;
}
pub fn send_message<T: AsRef<[u8]>>(&mut self, message: T) {
message
.as_ref()
.chunks(self.chunk_size as usize)
.for_each(|chunk| {
let encrypted = self.crypt.encrypt(&chunk).unwrap();
let binary_chunk = BinaryChunk::from_content(&encrypted).unwrap();
self.write.write_all(binary_chunk.raw()).unwrap();
});
}
}
pub fn data_sample(size: u16, byte: u8) -> Vec<u8> {
std::iter::repeat(byte).take(size.into()).collect()
}
pub fn block_header_message_encoded(data_size: usize) -> Vec<u8> {
let mut res = vec![];
res.put_u16(0x0021); // Tag
res.put_u32(28014); // level
res.put_u8(0x01); // proto
res.put_slice(
BlockHash::try_from("BKjYUUtYXtXjEuL49jB8ZbFwVdg4hU6U7oKKSC5vp6stYsfFDVN")
.unwrap()
.as_ref(),
); // predecessor
res.put_u64(1544713848); // timestamp
res.put_u8(0x04); // validation pass
res.put_slice(
OperationListListHash::try_from("LLoZi3xywrX9swZQgC82m7vj5hmuz6LGAatNq2Muh34oNn71JruZs")
.unwrap()
.as_ref(),
); // operation hash
res.put_u32(0x00000000); // empty fitness
res.put_slice(
ContextHash::try_from("CoWZVRSM6DdNUpn3mamy7e8rUSxQVWkQCQfJBg7DrTVXUjzGZGCa")
.unwrap()
.as_ref(),
); // context
let data_size = std::cmp::min(data_size, BLOCK_HEADER_PROTOCOL_DATA_MAX_SIZE);
res.extend(std::iter::repeat(0xff).take(data_size));
let mut res1: Vec<u8> = vec![];
res1.put_u32(res.len() as u32);
res1.extend(res);
assert!(matches!(
PeerMessageResponse::from_bytes(res1.clone())
.unwrap()
.message(),
PeerMessage::BlockHeader(_)
));
res1
}
pub fn new_log() -> slog::Logger {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_envlogger::new(drain);
let drain = slog_async::Async::new(drain).build().fuse();
slog::Logger::root(drain, o!())
}
pub fn read_message_bench(c: &mut Criterion, message: Vec<u8>, chunk_size: Option<usize>) {
let root_log = new_log();
let (addr_send, addr_recv) = channel();
let (stop_tx, stop_rx) = channel();
let crypto_mock = CryptoMock::new();
let (crypto_local, crypto_remote) = (crypto_mock.local, crypto_mock.remote);
let sender_log = root_log.new(o!());
let receiver_log = root_log.new(o!());
let message_len = message.len();
let sender = std::thread::spawn(move || {
use std::net::TcpListener;
debug!(sender_log, "Starting listening");
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let local_addr = listener.local_addr().unwrap();
addr_send.send(local_addr).unwrap();
let log = sender_log.new(o!("sender" => local_addr));
debug!(log, "Listening");
listener.set_nonblocking(true).unwrap();
let precompute_key = crypto_remote.precompute_key;
let nonce = crypto_remote.nonce_pair.local;
loop {
match listener.accept() {
Ok((mut socket, _)) => {
debug!(log, "connected");
let mut buf = [0u8; 10];
socket.read_exact(&mut buf).unwrap();
let iters = u64::from_be_bytes(buf[2..].try_into().unwrap());
let mut mock = PeerMock::new(precompute_key.clone(), nonce.clone(), socket);
if let Some(chunk_size) = chunk_size {
mock.chunk_size(chunk_size);
}
for _ in 0..iters {
mock.send_message(message.clone());
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => (),
Err(e) => panic!("error accepting a connection: {}", e),
}
match stop_rx.try_recv() {
Ok(()) => break,
Err(TryRecvError::Empty) => (),
Err(TryRecvError::Disconnected) => panic!("stop channel disconnected"),
}
std::thread::sleep(Duration::from_millis(10));
}
});
let rt = Builder::new_multi_thread()
.enable_io()
.build()
.expect("Cannot build tokio runtime");
rt.block_on(async move {
use tokio::net::TcpStream;
debug!(receiver_log, "Tokio started");
let addr = addr_recv.recv().unwrap();
let log = receiver_log.new(o!("receiver" => addr));
c.bench_function(
&format!(
"stream reading, message size: {}, chunk size: {}",
message_len,
chunk_size.unwrap_or(CONTENT_LENGTH_MAX)
),
move |b| {
let precompute_key = crypto_local.precompute_key.clone();
let log = log.clone();
let nonce = crypto_local.nonce_pair.remote.clone();
b.iter_custom(move |iters| {
let log = log.clone();
debug!(log, "Iterating for {} times", iters);
let (done_tx, done_rx) = channel();
let precompute_key = precompute_key.clone();
let nonce = nonce.clone();
debug!(log, "Spawning tokio...");
tokio::spawn(async move {
debug!(log, "Tokio spawned...");
let socket = TcpStream::connect(addr).await.unwrap();
let stream = MessageStream::from(socket);
let (reader, mut writer) = stream.split();
debug!(log, "Sending iterations count to sender...");
writer
.write_message(
&BinaryChunk::from_content(&iters.to_be_bytes()).unwrap(),
)
.await
.unwrap();
let mut reader = EncryptedMessageReaderBase::new(
reader,
precompute_key,
nonce,
new_log(),
);
debug!(log, "Starting iterations");
let start = Instant::now();
for _ in 0..iters {
reader.read_message::<PeerMessageResponse>().await.unwrap();
}
done_tx.send(start.elapsed()).unwrap();
debug!(log, "Done iterating");
});
done_rx.recv().unwrap()
})
},
);
stop_tx.send(()).unwrap();
});
sender.join().unwrap();
}
| new |
public_key.go | // Copyright 2022 Paul Greenberg [email protected]
//
// 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 |
package errors
// Public key errors.
const (
ErrPublicKeyEmptyPayload StandardError = "public key payload is empty"
ErrPublicKeyInvalidUsage StandardError = "public key usage %q is invalid"
ErrPublicKeyUsagePayloadMismatch StandardError = "public key usage %q does not match its payload"
ErrPublicKeyBlockType StandardError = "public key block type %q is invalid"
ErrPublicKeyParse StandardError = "public key parse failed: %v"
ErrPublicKeyUsageUnsupported StandardError = "public key usage %q is unsupported"
ErrPublicKeyTypeUnsupported StandardError = "public key type %q is unsupported"
) | // 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. |
jqLiteSpec.js | 'use strict';
describe('jqLite', function() {
var scope, a, b, c;
beforeEach(module(provideLog));
beforeEach(function() {
a = jqLite('<div>A</div>')[0];
b = jqLite('<div>B</div>')[0];
c = jqLite('<div>C</div>')[0];
});
beforeEach(inject(function($rootScope) {
scope = $rootScope;
this.addMatchers({
toJqEqual: function(expected) {
var msg = "Unequal length";
this.message = function() {return msg;};
var value = this.actual && expected && this.actual.length == expected.length;
for (var i = 0; value && i < expected.length; i++) {
var actual = jqLite(this.actual[i])[0];
var expect = jqLite(expected[i])[0];
value = value && equals(expect, actual);
msg = "Not equal at index: " + i
+ " - Expected: " + expect
+ " - Actual: " + actual;
}
return value;
}
});
}));
afterEach(function() {
dealoc(a);
dealoc(b);
dealoc(c);
});
it('should be jqLite when jqLiteMode is on, otherwise jQuery', function() {
expect(jqLite).toBe(_jqLiteMode ? JQLite : _jQuery);
});
describe('construction', function() {
it('should allow construction with text node', function() {
var text = a.firstChild;
var selected = jqLite(text);
expect(selected.length).toEqual(1);
expect(selected[0]).toEqual(text);
});
it('should allow construction with html', function() {
var nodes = jqLite('<div>1</div><span>2</span>');
expect(nodes[0].parentNode).toBeDefined();
expect(nodes[0].parentNode.nodeType).toBe(11); /** Document Fragment **/
expect(nodes[0].parentNode).toBe(nodes[1].parentNode);
expect(nodes.length).toEqual(2);
expect(nodes[0].innerHTML).toEqual('1');
expect(nodes[1].innerHTML).toEqual('2');
});
it('should allow construction of html with leading whitespace', function() {
var nodes = jqLite(' \n\r \r\n<div>1</div><span>2</span>');
expect(nodes[0].parentNode).toBeDefined();
expect(nodes[0].parentNode.nodeType).toBe(11); /** Document Fragment **/
expect(nodes[0].parentNode).toBe(nodes[1].parentNode);
expect(nodes.length).toBe(2);
expect(nodes[0].innerHTML).toBe('1');
expect(nodes[1].innerHTML).toBe('2');
});
it('should allow creation of comment tags', function() {
var nodes = jqLite('<!-- foo -->');
expect(nodes.length).toBe(1);
expect(nodes[0].nodeType).toBe(8);
});
it('should allow creation of script tags', function() {
var nodes = jqLite('<script></script>');
expect(nodes.length).toBe(1);
expect(nodes[0].tagName.toUpperCase()).toBe('SCRIPT');
});
it('should wrap document fragment', function() {
var fragment = jqLite(document.createDocumentFragment());
expect(fragment.length).toBe(1);
expect(fragment[0].nodeType).toBe(11);
});
it('should allow construction of <option> elements', function() {
var nodes = jqLite('<option>');
expect(nodes.length).toBe(1);
expect(nodes[0].nodeName.toLowerCase()).toBe('option');
});
// Special tests for the construction of elements which are restricted (in the HTML5 spec) to
// being children of specific nodes.
forEach([
'caption',
'colgroup',
'col',
'optgroup',
'opt',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr'
], function(name) {
it('should allow construction of <$NAME$> elements'.replace('$NAME$', name), function() {
var nodes = jqLite('<$NAME$>'.replace('$NAME$', name));
expect(nodes.length).toBe(1);
expect(nodes[0].nodeName.toLowerCase()).toBe(name);
});
});
});
describe('_data', function() {
it('should provide access to the data present on the element', function() {
var element = jqLite('<i>foo</i>');
var data = ['value'];
element.data('val', data);
expect(angular.element._data(element[0]).data.val).toBe(data);
dealoc(element);
});
it('should provide access to the events present on the element', function() {
var element = jqLite('<i>foo</i>');
expect(angular.element._data(element[0]).events).toBeUndefined();
element.on('click', function() { });
expect(angular.element._data(element[0]).events.click).toBeDefined();
});
});
describe('inheritedData', function() {
it('should retrieve data attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('myData', 'abc');
expect(element.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should walk up the dom to find data', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('myData', 'abc');
expect(deepChild.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should return undefined when no data was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.inheritedData('myData')).toBeFalsy();
dealoc(element);
});
it('should work with the child html element instead if the current element is the document obj',
function() {
var item = {},
doc = jqLite(document),
html = doc.find('html');
html.data('item', item);
expect(doc.inheritedData('item')).toBe(item);
expect(html.inheritedData('item')).toBe(item);
dealoc(doc);
}
);
it('should return null values', function () {
var ul = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>'),
li = ul.find('li'),
b = li.find('b');
ul.data('foo', 'bar');
li.data('foo', null);
expect(b.inheritedData('foo')).toBe(null);
expect(li.inheritedData('foo')).toBe(null);
expect(ul.inheritedData('foo')).toBe('bar');
dealoc(ul);
});
it('should pass through DocumentFragment boundaries via host', function() {
var host = jqLite('<div></div>'),
frag = document.createDocumentFragment(),
$frag = jqLite(frag);
frag.host = host[0];
host.data("foo", 123);
host.append($frag);
expect($frag.inheritedData("foo")).toBe(123);
dealoc(host);
dealoc($frag);
});
});
describe('scope', function() {
it('should retrieve scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$scope', scope);
expect(element.scope()).toBe(scope);
dealoc(element);
});
it('should retrieve isolate scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$isolateScope', scope);
expect(element.isolateScope()).toBe(scope);
dealoc(element);
});
it('should retrieve scope attached to the html element if it\'s requested on the document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
scope = {};
html.data('$scope', scope);
expect(doc.scope()).toBe(scope);
expect(html.scope()).toBe(scope);
dealoc(doc);
});
it('should walk up the dom to find scope', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('$scope', scope);
expect(deepChild.scope()).toBe(scope);
dealoc(element);
});
it('should return undefined when no scope was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.scope()).toBeFalsy();
dealoc(element);
});
});
describe('isolateScope', function() {
it('should retrieve isolate scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$isolateScope', scope);
expect(element.isolateScope()).toBe(scope);
dealoc(element);
});
it('should not walk up the dom to find scope', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('$isolateScope', scope);
expect(deepChild.isolateScope()).toBeUndefined();
dealoc(element);
});
it('should return undefined when no scope was found', function() {
var element = jqLite('<div></div>');
expect(element.isolateScope()).toBeFalsy();
dealoc(element);
});
});
describe('injector', function() {
it('should retrieve injector attached to the current element or its parent', function() {
var template = jqLite('<div><span></span></div>'),
span = template.children().eq(0),
injector = angular.bootstrap(template);
expect(span.injector()).toBe(injector);
dealoc(template);
});
it('should retrieve injector attached to the html element if it\'s requested on document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
injector = {};
html.data('$injector', injector);
expect(doc.injector()).toBe(injector);
expect(html.injector()).toBe(injector);
dealoc(doc);
});
it('should do nothing with a noncompiled template', function() {
var template = jqLite('<div><span></span></div>');
expect(template.injector()).toBeUndefined();
dealoc(template);
});
});
describe('controller', function() {
it('should retrieve controller attached to the current element or its parent', function() {
var div = jqLite('<div><span></span></div>'),
span = div.find('span');
div.data('$ngControllerController', 'ngController');
span.data('$otherController', 'other');
expect(span.controller()).toBe('ngController');
expect(span.controller('ngController')).toBe('ngController');
expect(span.controller('other')).toBe('other');
expect(div.controller()).toBe('ngController');
expect(div.controller('ngController')).toBe('ngController');
expect(div.controller('other')).toBe(undefined);
dealoc(div);
});
});
describe('data', function() {
it('should set and get and remove data', function() {
var selected = jqLite([a, b, c]);
expect(selected.data('prop')).toBeUndefined();
expect(selected.data('prop', 'value')).toBe(selected);
expect(selected.data('prop')).toBe('value');
expect(jqLite(a).data('prop')).toBe('value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
jqLite(a).data('prop', 'new value');
expect(jqLite(a).data('prop')).toBe('new value');
expect(selected.data('prop')).toBe('new value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
expect(selected.removeData('prop')).toBe(selected);
expect(jqLite(a).data('prop')).toBeUndefined();
expect(jqLite(b).data('prop')).toBeUndefined();
expect(jqLite(c).data('prop')).toBeUndefined();
});
it('should only remove the specified value when providing a property name to removeData', function () {
var selected = jqLite(a);
expect(selected.data('prop1')).toBeUndefined();
selected.data('prop1', 'value');
selected.data('prop2', 'doublevalue');
expect(selected.data('prop1')).toBe('value');
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop1');
expect(selected.data('prop1')).toBeUndefined();
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop2');
});
it('should emit $destroy event if element removed via remove()', function() {
var log = '';
var element = jqLite(a);
element.on('$destroy', function() {log+= 'destroy;';});
element.remove();
expect(log).toEqual('destroy;');
});
it('should emit $destroy event if an element is removed via html(\'\')', inject(function(log) {
var element = jqLite('<div><span>x</span></div>');
element.find('span').on('$destroy', log.fn('destroyed'));
element.html('');
expect(element.html()).toBe('');
expect(log).toEqual('destroyed');
}));
it('should emit $destroy event if an element is removed via empty()', inject(function(log) {
var element = jqLite('<div><span>x</span></div>');
element.find('span').on('$destroy', log.fn('destroyed'));
element.empty();
expect(element.html()).toBe('');
expect(log).toEqual('destroyed');
}));
it('should retrieve all data if called without params', function() {
var element = jqLite(a);
expect(element.data()).toEqual({});
element.data('foo', 'bar');
expect(element.data()).toEqual({foo: 'bar'});
element.data().baz = 'xxx';
expect(element.data()).toEqual({foo: 'bar', baz: 'xxx'});
});
it('should create a new data object if called without args', function() {
var element = jqLite(a),
data = element.data();
expect(data).toEqual({});
element.data('foo', 'bar');
expect(data).toEqual({foo: 'bar'});
});
it('should create a new data object if called with a single object arg', function() {
var element = jqLite(a),
newData = {foo: 'bar'};
element.data(newData);
expect(element.data()).toEqual({foo: 'bar'});
expect(element.data()).not.toBe(newData); // create a copy
});
it('should merge existing data object with a new one if called with a single object arg',
function() {
var element = jqLite(a);
element.data('existing', 'val');
expect(element.data()).toEqual({existing: 'val'});
var oldData = element.data(),
newData = {meLike: 'turtles', 'youLike': 'carrots'};
expect(element.data(newData)).toBe(element);
expect(element.data()).toEqual({meLike: 'turtles', youLike: 'carrots', existing: 'val'});
expect(element.data()).toBe(oldData); // merge into the old object
});
describe('data cleanup', function() {
it('should remove data on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span');
span.data('name', 'angular');
span.remove();
expect(span.data('name')).toBeUndefined();
});
it('should remove event listeners on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span'),
log = '';
span.on('click', function() { log += 'click;'; });
browserTrigger(span);
expect(log).toEqual('click;');
span.remove();
browserTrigger(span);
expect(log).toEqual('click;');
});
});
});
describe('attr', function() {
it('should read write and remove attr', function() {
var selector = jqLite([a, b]);
expect(selector.attr('prop', 'value')).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('value');
expect(jqLite(b).attr('prop')).toEqual('value');
expect(selector.attr({'prop': 'new value'})).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value');
jqLite(b).attr({'prop': 'new value 2'});
expect(jqLite(selector).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value 2');
selector.removeAttr('prop');
expect(jqLite(a).attr('prop')).toBeFalsy();
expect(jqLite(b).attr('prop')).toBeFalsy();
});
it('should read boolean attributes as strings', function() {
var select = jqLite('<select>');
expect(select.attr('multiple')).toBeUndefined();
expect(jqLite('<select multiple>').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="">').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="x">').attr('multiple')).toBe('multiple');
});
it('should add/remove boolean attributes', function() {
var select = jqLite('<select>');
select.attr('multiple', false);
expect(select.attr('multiple')).toBeUndefined();
select.attr('multiple', true);
expect(select.attr('multiple')).toBe('multiple');
});
it('should normalize the case of boolean attributes', function() {
var input = jqLite('<input readonly>');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
expect(input.attr('READONLY')).toBe('readonly');
input.attr('readonly', false);
// attr('readonly') fails in jQuery 1.6.4, so we have to bypass it
//expect(input.attr('readOnly')).toBeUndefined();
//expect(input.attr('readonly')).toBeUndefined();
if (msie < 9) {
expect(input[0].getAttribute('readonly')).toBe('');
} else {
expect(input[0].getAttribute('readonly')).toBe(null);
}
//expect('readOnly' in input[0].attributes).toBe(false);
input.attr('readOnly', 'READonly');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
});
it('should return undefined for non-existing attributes', function() {
var elm = jqLite('<div class="any">a</div>');
expect(elm.attr('non-existing')).toBeUndefined();
});
it('should return undefined for non-existing attributes on input', function() {
var elm = jqLite('<input>');
expect(elm.attr('readonly')).toBeUndefined();
expect(elm.attr('readOnly')).toBeUndefined();
expect(elm.attr('disabled')).toBeUndefined();
});
});
describe('prop', function() {
it('should read element property', function() {
var elm = jqLite('<div class="foo">a</div>');
expect(elm.prop('className')).toBe('foo');
});
it('should set element property to a value', function() {
var elm = jqLite('<div class="foo">a</div>');
elm.prop('className', 'bar');
expect(elm[0].className).toBe('bar');
expect(elm.prop('className')).toBe('bar');
});
it('should set boolean element property', function() {
var elm = jqLite('<input type="checkbox">');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', true);
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', '');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', 'lala');
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', null);
expect(elm.prop('checked')).toBe(false);
});
});
describe('class', function() {
it('should properly do with SVG elements', function() {
// this is a jqLite & SVG only test (jquery doesn't behave this way right now, which is a bug)
if (!window.SVGElement || !_jqLiteMode) return;
var svg = jqLite('<svg><rect></rect></svg>');
var rect = svg.children();
expect(rect.hasClass('foo-class')).toBe(false);
rect.addClass('foo-class');
expect(rect.hasClass('foo-class')).toBe(true);
rect.removeClass('foo-class');
expect(rect.hasClass('foo-class')).toBe(false);
});
it('should ignore comment elements', function() {
var comment = jqLite(document.createComment('something'));
comment.addClass('whatever');
comment.hasClass('whatever');
comment.toggleClass('whatever');
comment.removeClass('whatever');
});
describe('hasClass', function() {
it('should check class', function() {
var selector = jqLite([a, b]);
expect(selector.hasClass('abc')).toEqual(false);
});
it('should make sure that partial class is not checked as a subset', function() {
var selector = jqLite([a, b]);
selector.addClass('a');
selector.addClass('b');
selector.addClass('c');
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(jqLite(a).hasClass('a')).toEqual(true);
expect(jqLite(a).hasClass('b')).toEqual(true);
expect(jqLite(a).hasClass('c')).toEqual(true);
});
});
describe('addClass', function() {
it('should allow adding of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
});
it('should ignore falsy values', function() {
var jqA = jqLite(a);
expect(jqA[0].className).toBe('');
jqA.addClass(undefined);
expect(jqA[0].className).toBe('');
jqA.addClass(null);
expect(jqA[0].className).toBe('');
jqA.addClass(false);
expect(jqA[0].className).toBe('');
});
it('should allow multiple classes to be added in a single string', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
jqA.addClass('foo bar baz');
expect(a.className).toBe('foo bar baz');
});
it('should not add duplicate classes', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
a.className = 'foo';
jqA.addClass('foo');
expect(a.className).toBe('foo');
jqA.addClass('bar foo baz');
expect(a.className).toBe('foo bar baz');
});
});
describe('toggleClass', function() {
it('should allow toggling of class', function() {
var selector = jqLite([a, b]);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(selector.toggleClass('abc'), true).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc'), false).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
it('should allow toggling multiple classes without a condition', function () {
var selector = jqLite([a, b]);
expect(selector.toggleClass('abc cde')).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(true);
expect(jqLite(a).hasClass('cde')).toBe(true);
expect(jqLite(b).hasClass('abc')).toBe(true);
expect(jqLite(b).hasClass('cde')).toBe(true);
expect(selector.toggleClass('abc cde')).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(false);
expect(jqLite(a).hasClass('cde')).toBe(false);
expect(jqLite(b).hasClass('abc')).toBe(false);
expect(jqLite(b).hasClass('cde')).toBe(false);
expect(selector.toggleClass('abc')).toBe(selector);
expect(selector.toggleClass('abc cde')).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(false);
expect(jqLite(a).hasClass('cde')).toBe(true);
expect(jqLite(b).hasClass('abc')).toBe(false);
expect(jqLite(b).hasClass('cde')).toBe(true);
expect(selector.toggleClass('abc cde')).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(true);
expect(jqLite(a).hasClass('cde')).toBe(false);
expect(jqLite(b).hasClass('abc')).toBe(true);
expect(jqLite(b).hasClass('cde')).toBe(false);
});
it('should allow toggling multiple classes with a condition', function () {
var selector = jqLite([a, b]);
selector.addClass('abc');
expect(selector.toggleClass('abc cde', true)).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(true);
expect(jqLite(a).hasClass('cde')).toBe(true);
expect(jqLite(b).hasClass('abc')).toBe(true);
expect(jqLite(b).hasClass('cde')).toBe(true);
selector.removeClass('abc');
expect(selector.toggleClass('abc cde', false)).toBe(selector);
expect(jqLite(a).hasClass('abc')).toBe(false);
expect(jqLite(a).hasClass('cde')).toBe(false);
expect(jqLite(b).hasClass('abc')).toBe(false);
expect(jqLite(b).hasClass('cde')).toBe(false);
});
it('should not break for null / undefined selectors', function () {
var selector = jqLite([a, b]);
expect(selector.toggleClass(null)).toBe(selector);
expect(selector.toggleClass(undefined)).toBe(selector);
});
});
describe('removeClass', function() {
it('should allow removal of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
it('should correctly remove middle class', function() {
var element = jqLite('<div class="foo bar baz"></div>');
expect(element.hasClass('bar')).toBe(true);
element.removeClass('bar');
expect(element.hasClass('foo')).toBe(true);
expect(element.hasClass('bar')).toBe(false);
expect(element.hasClass('baz')).toBe(true);
});
it('should remove multiple classes specified as one string', function() {
var jqA = jqLite(a);
a.className = 'foo bar baz';
jqA.removeClass('foo baz noexistent');
expect(a.className).toBe('bar');
});
});
});
describe('css', function() {
it('should set and read css', function() {
var selector = jqLite([a, b]);
expect(selector.css('margin', '1px')).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('1px');
expect(jqLite(b).css('margin')).toEqual('1px');
expect(selector.css({'margin': '2px'})).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('2px');
jqLite(b).css({'margin': '3px'});
expect(jqLite(selector).css('margin')).toEqual('2px');
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('3px');
selector.css('margin', '');
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(b).css('margin')).toBe('auto');
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(b).css('margin')).toBeFalsy();
}
});
it('should set a bunch of css properties specified via an object', function() {
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(a).css('padding')).toBe('0px');
expect(jqLite(a).css('border')).toBeUndefined();
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(a).css('padding')).toBeFalsy();
expect(jqLite(a).css('border')).toBeFalsy();
}
jqLite(a).css({'margin': '1px', 'padding': '2px', 'border': ''});
expect(jqLite(a).css('margin')).toBe('1px');
expect(jqLite(a).css('padding')).toBe('2px');
expect(jqLite(a).css('border')).toBeFalsy();
});
it('should correctly handle dash-separated and camelCased properties', function() {
var jqA = jqLite(a);
expect(jqA.css('z-index')).toBeOneOf('', 'auto');
expect(jqA.css('zIndex')).toBeOneOf('', 'auto');
jqA.css({'zIndex':5});
expect(jqA.css('z-index')).toBeOneOf('5', 5);
expect(jqA.css('zIndex')).toBeOneOf('5', 5);
jqA.css({'z-index':7});
expect(jqA.css('z-index')).toBeOneOf('7', 7);
expect(jqA.css('zIndex')).toBeOneOf('7', 7);
});
});
describe('text', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().text()).toEqual('');
});
it('should read/write value', function() {
var element = jqLite('<div>ab</div><span>c</span>');
expect(element.length).toEqual(2);
expect(element[0].innerHTML).toEqual('ab');
expect(element[1].innerHTML).toEqual('c');
expect(element.text()).toEqual('abc');
expect(element.text('xyz') == element).toBeTruthy();
expect(element.text()).toEqual('xyzxyz');
});
});
describe('val', function() {
it('should read, write value', function() {
var input = jqLite('<input type="text"/>');
expect(input.val('abc')).toEqual(input);
expect(input[0].value).toEqual('abc');
expect(input.val()).toEqual('abc');
});
it('should get an array of selected elements from a multi select', function () {
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option selected>test 2</option>' +
'</select>').val()).toEqual(['test 1', 'test 2']);
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(['test 1']);
expect(jqLite(
'<select multiple>' +
'<option>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(null);
});
});
describe('html', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().html()).toEqual(null);
});
it('should read/write a value', function() {
var element = jqLite('<div>abc</div>');
expect(element.length).toEqual(1);
expect(element[0].innerHTML).toEqual('abc');
expect(element.html()).toEqual('abc');
expect(element.html('xyz') == element).toBeTruthy();
expect(element.html()).toEqual('xyz');
});
});
describe('empty', function() {
it('should write a value', function() {
var element = jqLite('<div>abc</div>');
expect(element.length).toEqual(1);
expect(element.empty() == element).toBeTruthy();
expect(element.html()).toEqual('');
});
});
describe('on', function() {
it('should bind to window on hashchange', function() {
if (jqLite.fn) return; // don't run in jQuery
var eventFn;
var window = {
document: {},
location: {},
alert: noop,
setInterval: noop,
length:10, // pretend you are an array
addEventListener: function(type, fn){
expect(type).toEqual('hashchange');
eventFn = fn;
},
removeEventListener: noop,
attachEvent: function(type, fn){
expect(type).toEqual('onhashchange');
eventFn = fn;
},
detachEvent: noop
};
var log;
var jWindow = jqLite(window).on('hashchange', function() {
log = 'works!';
});
eventFn({type: 'hashchange'});
expect(log).toEqual('works!');
dealoc(jWindow);
});
it('should bind to all elements and return functions', function() {
var selected = jqLite([a, b]);
var log = '';
expect(selected.on('click', function() {
log += 'click on: ' + jqLite(this).text() + ';';
})).toEqual(selected);
browserTrigger(a, 'click');
expect(log).toEqual('click on: A;');
browserTrigger(b, 'click');
expect(log).toEqual('click on: A;click on: B;');
});
it('should bind to all events separated by space', function() {
var elm = jqLite(a),
callback = jasmine.createSpy('callback');
elm.on('click keypress', callback);
elm.on('click', callback);
browserTrigger(a, 'click');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(2);
callback.reset();
browserTrigger(a, 'keypress');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(1);
});
it('should set event.target on IE', function() {
var elm = jqLite(a);
elm.on('click', function(event) {
expect(event.target).toBe(a);
});
browserTrigger(a, 'click');
});
it('should have event.isDefaultPrevented method', function() {
jqLite(a).on('click', function(e) {
expect(function() {
expect(e.isDefaultPrevented()).toBe(false);
e.preventDefault();
expect(e.isDefaultPrevented()).toBe(true);
}).not.toThrow();
});
browserTrigger(a, 'click');
});
describe('mouseenter-mouseleave', function() {
var root, parent, sibling, child, log;
beforeEach(function() {
log = '';
root = jqLite('<div>root<p>parent<span>child</span></p><ul></ul></div>');
parent = root.find('p');
sibling = root.find('ul');
child = parent.find('span');
parent.on('mouseenter', function() { log += 'parentEnter;'; });
parent.on('mouseleave', function() { log += 'parentLeave;'; });
child.on('mouseenter', function() { log += 'childEnter;'; });
child.on('mouseleave', function() { log += 'childLeave;'; });
});
afterEach(function() {
dealoc(root);
});
it('should fire mouseenter when coming from outside the browser window', function() {
if (window.jQuery) return;
var browserMoveTrigger = function(from, to){
var fireEvent = function(type, element, relatedTarget){
var evnt, msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
if (msie < 9){
evnt = document.createEventObject();
evnt.srcElement = element;
evnt.relatedTarget = relatedTarget;
element.fireEvent('on' + type, evnt);
return;
}
evnt = document.createEvent('MouseEvents');
var originalPreventDefault = evnt.preventDefault,
appWindow = window,
fakeProcessDefault = true,
finalProcessDefault;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
var x = 0, y = 0;
evnt.initMouseEvent(type, true, true, window, 0, x, y, x, y, false, false,
false, false, 0, relatedTarget);
element.dispatchEvent(evnt);
};
fireEvent('mouseout', from[0], to[0]);
fireEvent('mouseover', to[0], from[0]);
};
browserMoveTrigger(root, parent);
expect(log).toEqual('parentEnter;');
browserMoveTrigger(parent, child);
expect(log).toEqual('parentEnter;childEnter;');
browserMoveTrigger(child, parent);
expect(log).toEqual('parentEnter;childEnter;childLeave;');
browserMoveTrigger(parent, root);
expect(log).toEqual('parentEnter;childEnter;childLeave;parentLeave;');
});
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if eventData or a selector is passed', function() {
var elm = jqLite(a),
anObj = {},
aString = '',
aValue = 45,
callback = function() {};
expect(function() {
elm.on('click', anObj, callback);
}).toThrowMinErr('jqLite', 'onargs');
expect(function() {
elm.on('click', null, aString, callback);
}).toThrowMinErr('jqLite', 'onargs');
expect(function() {
elm.on('click', aValue, callback);
}).toThrowMinErr('jqLite', 'onargs');
});
}
});
describe('off', function() {
it('should do nothing when no listener was registered with bound', function() {
var aElem = jqLite(a);
aElem.off();
aElem.off('click');
aElem.off('click', function() {});
});
it('should do nothing when a specific listener was not registered', function () {
var aElem = jqLite(a); | aElem.off('mouseenter', function() {});
});
it('should deregister all listeners', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off();
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister listeners for specific type', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
mouseoverSpy.reset();
aElem.off('mouseover');
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister all listeners for types separated by spaces', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click mouseover');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister specific listener', function() {
var aElem = jqLite(a),
clickSpy1 = jasmine.createSpy('click1'),
clickSpy2 = jasmine.createSpy('click2');
aElem.on('click', clickSpy1);
aElem.on('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy1.reset();
clickSpy2.reset();
aElem.off('click', clickSpy1);
browserTrigger(a, 'click');
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy2.reset();
aElem.off('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy2).not.toHaveBeenCalled();
});
it('should deregister specific listener within the listener and call subsequent listeners', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
clickOnceSpy = jasmine.createSpy('clickOnce').andCallFake(function() {
aElem.off('click', clickOnceSpy);
});
aElem.on('click', clickOnceSpy);
aElem.on('click', clickSpy);
browserTrigger(a, 'click');
expect(clickOnceSpy).toHaveBeenCalledOnce();
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'click');
expect(clickOnceSpy).toHaveBeenCalledOnce();
expect(clickSpy.callCount).toBe(2);
});
it('should deregister specific listener for multiple types separated by spaces', function() {
var aElem = jqLite(a),
masterSpy = jasmine.createSpy('master'),
extraSpy = jasmine.createSpy('extra');
aElem.on('click', masterSpy);
aElem.on('click', extraSpy);
aElem.on('mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy.callCount).toBe(2);
expect(extraSpy).toHaveBeenCalledOnce();
masterSpy.reset();
extraSpy.reset();
aElem.off('click mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy).not.toHaveBeenCalled();
expect(extraSpy).toHaveBeenCalledOnce();
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if a selector is passed', function () {
var aElem = jqLite(a);
aElem.on('click', noop);
expect(function () {
aElem.off('click', noop, '.test');
}).toThrowMatching(/\[jqLite:offargs\]/);
});
}
});
describe('one', function() {
it('should only fire the callback once', function() {
var element = jqLite(a);
var spy = jasmine.createSpy('click');
element.one('click', spy);
browserTrigger(element, 'click');
expect(spy).toHaveBeenCalledOnce();
browserTrigger(element, 'click');
expect(spy).toHaveBeenCalledOnce();
});
it('should deregister when off is called', function() {
var element = jqLite(a);
var spy = jasmine.createSpy('click');
element.one('click', spy);
element.off('click', spy);
browserTrigger(element, 'click');
expect(spy).not.toHaveBeenCalled();
});
it('should return the same event object just as on() does', function() {
var element = jqLite(a);
var eventA, eventB;
element.on('click', function(event) {
eventA = event;
});
element.one('click', function(event) {
eventB = event;
});
browserTrigger(element, 'click');
expect(eventA).toEqual(eventB);
});
it('should not remove other event handlers of the same type after execution', function() {
var element = jqLite(a);
var calls = [];
element.one('click', function(event) {
calls.push('one');
});
element.on('click', function(event) {
calls.push('on');
});
browserTrigger(element, 'click');
browserTrigger(element, 'click');
expect(calls).toEqual(['one','on','on']);
});
});
describe('replaceWith', function() {
it('should replaceWith', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('<span>span-</span><b>bold-</b>')).toEqual(div);
expect(root.text()).toEqual('before-span-bold-after');
});
it('should replaceWith text', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('text-')).toEqual(div);
expect(root.text()).toEqual('before-text-after');
});
});
describe('children', function() {
it('should only select element nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span>');
var div = root.find('div');
var span = root.find('span');
expect(root.children()).toJqEqual([div, span]);
});
});
describe('contents', function() {
it('should select all types child nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span></div>');
var contents = root.contents();
expect(contents.length).toEqual(5);
expect(contents[0].data).toEqual(' some comment ');
expect(contents[1].data).toEqual('before-');
});
// IE8 does not like this test, although the functionality may still work there.
if (!msie || msie > 8) {
it('should select all types iframe contents', function() {
var iframe_ = document.createElement('iframe'), tested,
iframe = jqLite(iframe_);
function test() {
var contents = iframe.contents();
expect(contents[0]).toBeTruthy();
expect(contents.length).toBe(1);
expect(contents.prop('nodeType')).toBe(9);
expect(contents[0].body).toBeTruthy();
expect(jqLite(contents[0].body).contents().length).toBe(3);
iframe.remove();
tested = true;
}
iframe_.onload = iframe_.onreadystatechange = function() {
if (iframe_.contentDocument) test();
};
iframe_.src = "/base/test/fixtures/iframe.html";
jqLite(document).find('body').append(iframe);
// This test is potentially flaky on CI cloud instances, so there is a generous
// wait period...
waitsFor(function() { return tested; }, 2000);
});
}
});
describe('append', function() {
it('should append', function() {
var root = jqLite('<div>');
expect(root.append('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should append text', function() {
var root = jqLite('<div>');
expect(root.append('text')).toEqual(root);
expect(root.html()).toEqual('text');
});
it('should append to document fragment', function() {
var root = jqLite(document.createDocumentFragment());
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(1);
});
it('should not append anything if parent node is not of type element or docfrag', function() {
var root = jqLite('<p>some text node</p>').contents();
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(0);
});
});
describe('wrap', function() {
it('should wrap text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
expect(text.wrap("<span>")[0]).toBe(text[0]);
expect(root.find('span').text()).toEqual('A<a>B</a>C');
});
it('should wrap free text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
text.remove();
expect(root.text()).toBe('');
text.wrap("<span>");
expect(text.parent().text()).toEqual('A<a>B</a>C');
});
});
describe('prepend', function() {
it('should prepend to empty', function() {
var root = jqLite('<div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should prepend to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>text');
});
it('should prepend text to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('abc')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('abctext');
});
it('should prepend array to empty in the right order', function() {
var root = jqLite('<div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div></div>');
});
it('should prepend array to content in the right order', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div>text</div>');
});
});
describe('remove', function() {
it('should remove', function() {
var root = jqLite('<div><span>abc</span></div>');
var span = root.find('span');
expect(span.remove()).toEqual(span);
expect(root.html()).toEqual('');
});
});
describe('after', function() {
it('should after', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
expect(span.after('<i></i><b></b>')).toEqual(span);
expect(root.html().toLowerCase()).toEqual('<span></span><i></i><b></b>');
});
it('should allow taking text', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
span.after('abc');
expect(root.html().toLowerCase()).toEqual('<span></span>abc');
});
});
describe('parent', function() {
it('should return parent or an empty set when no parent', function() {
var parent = jqLite('<div><p>abc</p></div>'),
child = parent.find('p');
expect(parent.parent()).toBeTruthy();
expect(parent.parent().length).toEqual(0);
expect(child.parent().length).toBe(1);
expect(child.parent()[0]).toBe(parent[0]);
});
it('should return empty set when no parent', function() {
var element = jqLite('<div>abc</div>');
expect(element.parent()).toBeTruthy();
expect(element.parent().length).toEqual(0);
});
it('should return empty jqLite object when parent is a document fragment', function() {
//this is quite unfortunate but jQuery 1.5.1 behaves this way
var fragment = document.createDocumentFragment(),
child = jqLite('<p>foo</p>');
fragment.appendChild(child[0]);
expect(child[0].parentNode).toBe(fragment);
expect(child.parent().length).toBe(0);
});
});
describe('next', function() {
it('should return next sibling', function() {
var element = jqLite('<div><b>b</b><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
it('should ignore non-element siblings', function() {
var element = jqLite('<div><b>b</b>TextNode<!-- comment node --><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
});
describe('find', function() {
it('should find child by name', function() {
var root = jqLite('<div><div>text</div></div>');
var innerDiv = root.find('div');
expect(innerDiv.length).toEqual(1);
expect(innerDiv.html()).toEqual('text');
});
it('should find child by name and not care about text nodes', function() {
var divs = jqLite('<div><span>aa</span></div>text<div><span>bb</span></div>');
var innerSpan = divs.find('span');
expect(innerSpan.length).toEqual(2);
});
});
describe('eq', function() {
it('should select the nth element ', function() {
var element = jqLite('<div><span>aa</span></div><div><span>bb</span></div>');
expect(element.find('span').eq(0).html()).toBe('aa');
expect(element.find('span').eq(-1).html()).toBe('bb');
expect(element.find('span').eq(20).length).toBe(0);
});
});
describe('triggerHandler', function() {
it('should trigger all registered handlers for an event', function() {
var element = jqLite('<span>poke</span>'),
pokeSpy = jasmine.createSpy('poke'),
clickSpy1 = jasmine.createSpy('clickSpy1'),
clickSpy2 = jasmine.createSpy('clickSpy2');
element.on('poke', pokeSpy);
element.on('click', clickSpy1);
element.on('click', clickSpy2);
expect(pokeSpy).not.toHaveBeenCalled();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('poke');
expect(pokeSpy).toHaveBeenCalledOnce();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
});
it('should pass in a dummy event', function() {
// we need the event to have at least preventDefault because angular will call it on
// all anchors with no href automatically
var element = jqLite('<a>poke</a>'),
pokeSpy = jasmine.createSpy('poke'),
event;
element.on('click', pokeSpy);
element.triggerHandler('click');
event = pokeSpy.mostRecentCall.args[0];
expect(event.preventDefault).toBeDefined();
});
it('should pass data as an additional argument', function() {
var element = jqLite('<a>poke</a>'),
pokeSpy = jasmine.createSpy('poke'),
data;
element.on('click', pokeSpy);
element.triggerHandler('click', [{hello: "world"}]);
data = pokeSpy.mostRecentCall.args[1];
expect(data.hello).toBe("world");
});
});
describe('camelCase', function() {
it('should leave non-dashed strings alone', function() {
expect(camelCase('foo')).toBe('foo');
expect(camelCase('')).toBe('');
expect(camelCase('fooBar')).toBe('fooBar');
});
it('should covert dash-separated strings to camelCase', function() {
expect(camelCase('foo-bar')).toBe('fooBar');
expect(camelCase('foo-bar-baz')).toBe('fooBarBaz');
expect(camelCase('foo:bar_baz')).toBe('fooBarBaz');
});
it('should covert browser specific css properties', function() {
expect(camelCase('-moz-foo-bar')).toBe('MozFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
});
});
}); | aElem.on('click', function() {});
|
main.go | package golib
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
var (
executable, pathError = os.Executable()
configDir = flag.String("conf", filepath.Dir(executable), "config.json at directory")
)
// LoadConfig is read the configuration from the JSON file into the structure
func LoadConfig(config interface{}, customPath string) error | {
if pathError != nil {
return pathError
}
var configPath string
if customPath != "" {
configPath = customPath
} else {
flag.Parse()
// The default is the same directory as the executable file
if configDir == nil {
configPath = filepath.Dir(executable)
} else {
configPath = (*configDir)
}
}
// Read from config.json
jsonValue, err := ioutil.ReadFile(filepath.Join(configPath, "config.json"))
if err != nil {
return fmt.Errorf("Read file Error: %s", err)
}
// Parse to JSON
if err := json.Unmarshal(jsonValue, config); err != nil {
return fmt.Errorf("Unmarshal error: %s", err)
}
return nil
} |
|
chain.rs | #![allow(clippy::mutable_key_type)]
use gw_block_producer::produce_block::{produce_block, ProduceBlockParam, ProduceBlockResult};
use gw_chain::chain::{Chain, L1Action, L1ActionContext, SyncParam};
use gw_common::{blake2b::new_blake2b, H256};
use gw_config::{BackendConfig, ChainConfig, GenesisConfig, MemPoolConfig};
use gw_generator::{
account_lock_manage::{always_success::AlwaysSuccess, AccountLockManage},
backend_manage::BackendManage,
genesis::init_genesis,
Generator,
};
use gw_mem_pool::pool::{MemPool, OutputParam};
use gw_store::{traits::chain_store::ChainStore, Store};
use gw_types::{
bytes::Bytes,
core::ScriptHashType,
offchain::{CellInfo, CollectedCustodianCells, DepositInfo, RollupContext},
packed::{
CellOutput, DepositLockArgs, DepositRequest, L2BlockCommittedInfo, RawTransaction,
RollupAction, RollupActionUnion, RollupConfig, RollupSubmitBlock, Script, Transaction,
WitnessArgs,
},
prelude::*,
};
use lazy_static::lazy_static;
use smol::lock::Mutex;
use std::{collections::HashSet, time::Duration};
use std::{fs, io::Read, path::PathBuf, sync::Arc};
use super::mem_pool_provider::DummyMemPoolProvider;
const SCRIPT_DIR: &str = "../../.tmp/binaries/godwoken-scripts";
const ALWAYS_SUCCESS_PATH: &str = "always-success";
lazy_static! {
pub static ref ALWAYS_SUCCESS_PROGRAM: Bytes = {
let mut buf = Vec::new();
let mut path = PathBuf::new();
path.push(&SCRIPT_DIR);
path.push(&ALWAYS_SUCCESS_PATH);
let mut f = fs::File::open(&path).expect("load program");
f.read_to_end(&mut buf).expect("read program");
Bytes::from(buf.to_vec())
};
pub static ref ALWAYS_SUCCESS_CODE_HASH: [u8; 32] = {
let mut buf = [0u8; 32];
let mut hasher = new_blake2b();
hasher.update(&ALWAYS_SUCCESS_PROGRAM);
hasher.finalize(&mut buf);
buf
};
}
// meta contract
pub const META_VALIDATOR_PATH: &str =
"../../.tmp/binaries/godwoken-scripts/meta-contract-validator";
pub const META_GENERATOR_PATH: &str =
"../../.tmp/binaries/godwoken-scripts/meta-contract-generator";
pub const META_VALIDATOR_SCRIPT_TYPE_HASH: [u8; 32] = [1u8; 32];
// simple UDT
pub const SUDT_VALIDATOR_PATH: &str = "../../.tmp/binaries/godwoken-scripts/sudt-validator";
pub const SUDT_GENERATOR_PATH: &str = "../../.tmp/binaries/godwoken-scripts/sudt-generator";
pub const DEFAULT_FINALITY_BLOCKS: u64 = 6;
pub fn build_backend_manage(rollup_config: &RollupConfig) -> BackendManage {
let sudt_validator_script_type_hash: [u8; 32] =
rollup_config.l2_sudt_validator_script_type_hash().unpack();
let configs = vec![
BackendConfig {
validator_path: META_VALIDATOR_PATH.into(),
generator_path: META_GENERATOR_PATH.into(),
validator_script_type_hash: META_VALIDATOR_SCRIPT_TYPE_HASH.into(),
backend_type: gw_config::BackendType::Meta,
},
BackendConfig {
validator_path: SUDT_VALIDATOR_PATH.into(),
generator_path: SUDT_GENERATOR_PATH.into(),
validator_script_type_hash: sudt_validator_script_type_hash.into(),
backend_type: gw_config::BackendType::Sudt,
},
];
BackendManage::from_config(configs).expect("default backend")
}
pub fn setup_chain(rollup_type_script: Script) -> Chain {
let mut account_lock_manage = AccountLockManage::default();
let rollup_config = RollupConfig::new_builder()
.allowed_eoa_type_hashes(vec![*ALWAYS_SUCCESS_CODE_HASH].pack())
.finality_blocks(DEFAULT_FINALITY_BLOCKS.pack())
.build();
account_lock_manage
.register_lock_algorithm((*ALWAYS_SUCCESS_CODE_HASH).into(), Box::new(AlwaysSuccess));
let mut chain = setup_chain_with_account_lock_manage(
rollup_type_script,
rollup_config,
account_lock_manage,
None,
None,
None,
);
chain.complete_initial_syncing().unwrap();
chain
}
// Simulate process restart
pub fn restart_chain(
chain: &Chain,
rollup_type_script: Script,
opt_provider: Option<DummyMemPoolProvider>,
) -> Chain |
pub fn chain_generator(chain: &Chain, rollup_type_script: Script) -> Arc<Generator> {
let rollup_config = chain.generator().rollup_context().rollup_config.to_owned();
let mut account_lock_manage = AccountLockManage::default();
account_lock_manage
.register_lock_algorithm((*ALWAYS_SUCCESS_CODE_HASH).into(), Box::new(AlwaysSuccess));
let backend_manage = build_backend_manage(&rollup_config);
let rollup_context = RollupContext {
rollup_script_hash: rollup_type_script.hash().into(),
rollup_config,
};
Arc::new(Generator::new(
backend_manage,
account_lock_manage,
rollup_context,
Default::default(),
))
}
pub fn setup_chain_with_account_lock_manage(
rollup_type_script: Script,
rollup_config: RollupConfig,
account_lock_manage: AccountLockManage,
opt_store: Option<Store>,
opt_mem_pool_config: Option<MemPoolConfig>,
opt_mem_pool_provider: Option<DummyMemPoolProvider>,
) -> Chain {
let store = opt_store.unwrap_or_else(|| Store::open_tmp().unwrap());
let mem_pool_config = opt_mem_pool_config.unwrap_or_else(|| MemPoolConfig {
restore_path: tempfile::TempDir::new().unwrap().path().to_path_buf(),
..Default::default()
});
let rollup_script_hash = rollup_type_script.hash();
let genesis_config = GenesisConfig {
timestamp: 0,
meta_contract_validator_type_hash: Default::default(),
rollup_config: rollup_config.clone().into(),
rollup_type_hash: rollup_script_hash.into(),
secp_data_dep: Default::default(),
};
let genesis_committed_info = L2BlockCommittedInfo::default();
init_genesis(
&store,
&genesis_config,
genesis_committed_info,
Bytes::default(),
)
.unwrap();
let backend_manage = build_backend_manage(&rollup_config);
let rollup_context = RollupContext {
rollup_script_hash: rollup_script_hash.into(),
rollup_config: rollup_config.clone(),
};
let generator = Arc::new(Generator::new(
backend_manage,
account_lock_manage,
rollup_context,
Default::default(),
));
let provider = opt_mem_pool_provider.unwrap_or_default();
let mem_pool = MemPool::create(
0,
store.clone(),
Arc::clone(&generator),
Box::new(provider),
None,
mem_pool_config,
gw_config::NodeMode::FullNode,
)
.unwrap();
Chain::create(
&rollup_config,
&rollup_type_script,
&ChainConfig::default(),
store,
generator,
Some(Arc::new(Mutex::new(mem_pool))),
)
.unwrap()
}
pub fn build_sync_tx(
rollup_cell: CellOutput,
produce_block_result: ProduceBlockResult,
) -> Transaction {
let ProduceBlockResult {
block,
global_state,
} = produce_block_result;
let rollup_action = {
let submit_block = RollupSubmitBlock::new_builder().block(block).build();
RollupAction::new_builder()
.set(RollupActionUnion::RollupSubmitBlock(submit_block))
.build()
};
let witness = WitnessArgs::new_builder()
.output_type(Pack::<_>::pack(&Some(rollup_action.as_bytes())))
.build();
let raw = RawTransaction::new_builder()
.outputs(vec![rollup_cell].pack())
.outputs_data(vec![global_state.as_bytes()].pack())
.build();
Transaction::new_builder()
.raw(raw)
.witnesses(vec![witness.as_bytes()].pack())
.build()
}
pub fn apply_block_result(
chain: &mut Chain,
rollup_cell: CellOutput,
block_result: ProduceBlockResult,
deposit_requests: Vec<DepositRequest>,
deposit_asset_scripts: HashSet<Script>,
) {
let l2block = block_result.block.clone();
let transaction = build_sync_tx(rollup_cell, block_result);
let l2block_committed_info = L2BlockCommittedInfo::default();
let update = L1Action {
context: L1ActionContext::SubmitBlock {
l2block,
deposit_requests,
deposit_asset_scripts,
},
transaction,
l2block_committed_info,
};
let param = SyncParam {
updates: vec![update],
reverts: Default::default(),
};
chain.sync(param).unwrap();
assert!(chain.last_sync_event().is_success());
}
pub fn construct_block(
chain: &Chain,
mem_pool: &mut MemPool,
deposit_requests: Vec<DepositRequest>,
) -> anyhow::Result<ProduceBlockResult> {
let stake_cell_owner_lock_hash = H256::zero();
let db = chain.store().begin_transaction();
let generator = chain.generator();
let rollup_config_hash = (*chain.rollup_config_hash()).into();
let mut collected_custodians = CollectedCustodianCells {
capacity: u128::MAX,
..Default::default()
};
for withdrawal_hash in mem_pool.mem_block().withdrawals().iter() {
let req = db.get_mem_pool_withdrawal(withdrawal_hash)?.unwrap();
if 0 == req.raw().amount().unpack() {
continue;
}
let sudt_script_hash: [u8; 32] = req.raw().sudt_script_hash().unpack();
collected_custodians
.sudt
.insert(sudt_script_hash, (std::u128::MAX, Script::default()));
}
let deposit_lock_type_hash = generator
.rollup_context()
.rollup_config
.deposit_script_type_hash();
let rollup_script_hash = generator.rollup_context().rollup_script_hash;
let lock_args = {
let cancel_timeout = 0xc0000000000004b0u64;
let mut buf: Vec<u8> = Vec::new();
let deposit_args = DepositLockArgs::new_builder()
.cancel_timeout(cancel_timeout.pack())
.build();
buf.extend(rollup_script_hash.as_slice());
buf.extend(deposit_args.as_slice());
buf
};
let deposit_cells = deposit_requests
.into_iter()
.map(|deposit| DepositInfo {
cell: CellInfo {
out_point: Default::default(),
output: CellOutput::new_builder()
.lock(
Script::new_builder()
.code_hash(deposit_lock_type_hash.clone())
.hash_type(ScriptHashType::Type.into())
.args(lock_args.pack())
.build(),
)
.capacity(deposit.capacity())
.build(),
data: Default::default(),
},
request: deposit,
})
.collect();
let provider = DummyMemPoolProvider {
deposit_cells,
fake_blocktime: Duration::from_millis(0),
collected_custodians: collected_custodians.clone(),
};
mem_pool.set_provider(Box::new(provider));
// refresh mem block
smol::block_on(mem_pool.reset_mem_block())?;
let provider = DummyMemPoolProvider {
deposit_cells: Vec::default(),
fake_blocktime: Duration::from_millis(0),
collected_custodians,
};
mem_pool.set_provider(Box::new(provider));
let (_custodians, block_param) =
smol::block_on(mem_pool.output_mem_block(&OutputParam::default())).unwrap();
let param = ProduceBlockParam {
stake_cell_owner_lock_hash,
rollup_config_hash,
reverted_block_root: H256::default(),
block_param,
};
produce_block(&db, generator, param)
}
| {
let mut account_lock_manage = AccountLockManage::default();
let rollup_config = chain.generator().rollup_context().rollup_config.to_owned();
account_lock_manage
.register_lock_algorithm((*ALWAYS_SUCCESS_CODE_HASH).into(), Box::new(AlwaysSuccess));
let restore_path = {
let mem_pool = chain.mem_pool().as_ref().unwrap();
let mem_pool = smol::block_on(mem_pool.lock());
mem_pool.restore_manager().path().to_path_buf()
};
let mem_pool_config = MemPoolConfig {
restore_path,
..Default::default()
};
let mut chain = setup_chain_with_account_lock_manage(
rollup_type_script,
rollup_config,
account_lock_manage,
Some(chain.store().to_owned()),
Some(mem_pool_config),
opt_provider,
);
chain.complete_initial_syncing().unwrap();
chain
} |
program_parser.go | package service
import (
"errors"
"fmt"
"github.com/projectxpolaris/youlink/utils"
)
type ProgramBody struct {
Body []map[string]interface{} `json:"body"`
}
func Parse(body []map[string]interface{}, serviceContext ServiceContext) (*Program, error) {
// for body
program := NewProgram()
// find trigger
entryBlock, err := NewRootBlock(serviceContext)
if err != nil {
return nil, err
}
err = walk(entryBlock, body, serviceContext)
if err != nil {
return nil, err
}
program.Runners = append(program.Runners, entryBlock)
return program, nil
}
func walk(parenBlock *Block, body []map[string]interface{}, serviceContext ServiceContext) error {
for _, value := range body {
if blockType, exist := value["type"]; exist {
if blockType == "function" {
function, err := GenerateFunction(value, serviceContext)
if err != nil {
return err
}
parenBlock.Runners = append(parenBlock.Runners, function)
}
if blockType == "block" {
blockBody := utils.MapConvert(value["body"].([]interface{}))
block, err := NewBlock(value, serviceContext)
if err != nil {
return err
}
err = walk(block, blockBody, serviceContext)
if err != nil {
return err
}
parenBlock.Runners = append(parenBlock.Runners, block)
}
} | name := value["name"]
functionEntity := serviceContext.DefaultFunctionHub.GetEntityByName(name.(string))
if functionEntity == nil {
return nil, errors.New(fmt.Sprintf("function [%s] not found", name))
}
function, err := functionEntity.ToFunction(value)
if err != nil {
return nil, err
}
return function, nil
} | }
return nil
}
func GenerateFunction(value map[string]interface{}, serviceContext ServiceContext) (*Function, error) { |
tracking.py | # Code obtained from django-debug-toolbar sql panel tracking
from __future__ import absolute_import, unicode_literals
import json
from threading import local
from time import time
from django.utils.encoding import force_str
from .types import DjangoDebugSQL
class SQLQueryTriggered(Exception):
|
class ThreadLocalState(local):
def __init__(self):
self.enabled = True
@property
def Wrapper(self):
if self.enabled:
return NormalCursorWrapper
return ExceptionCursorWrapper
def recording(self, v):
self.enabled = v
state = ThreadLocalState()
recording = state.recording # export function
def wrap_cursor(connection, panel):
if not hasattr(connection, "_graphene_cursor"):
connection._graphene_cursor = connection.cursor
def cursor():
return state.Wrapper(connection._graphene_cursor(), connection, panel)
connection.cursor = cursor
return cursor
def unwrap_cursor(connection):
if hasattr(connection, "_graphene_cursor"):
previous_cursor = connection._graphene_cursor
connection.cursor = previous_cursor
del connection._graphene_cursor
class ExceptionCursorWrapper(object):
"""
Wraps a cursor and raises an exception on any operation.
Used in Templates panel.
"""
def __init__(self, cursor, db, logger):
pass
def __getattr__(self, attr):
raise SQLQueryTriggered()
class NormalCursorWrapper(object):
"""
Wraps a cursor and logs queries.
"""
def __init__(self, cursor, db, logger):
self.cursor = cursor
# Instance of a BaseDatabaseWrapper subclass
self.db = db
# logger must implement a ``record`` method
self.logger = logger
def _quote_expr(self, element):
if isinstance(element, str):
return "'%s'" % force_str(element).replace("'", "''")
else:
return repr(element)
def _quote_params(self, params):
if not params:
return params
if isinstance(params, dict):
return dict((key, self._quote_expr(value)) for key, value in params.items())
return list(map(self._quote_expr, params))
def _decode(self, param):
try:
return force_str(param, strings_only=True)
except UnicodeDecodeError:
return "(encoded string)"
def _record(self, method, sql, params):
start_time = time()
try:
return method(sql, params)
finally:
stop_time = time()
duration = stop_time - start_time
_params = ""
try:
_params = json.dumps(list(map(self._decode, params)))
except Exception:
pass # object not JSON serializable
alias = getattr(self.db, "alias", "default")
conn = self.db.connection
vendor = getattr(conn, "vendor", "unknown")
params = {
"vendor": vendor,
"alias": alias,
"sql": self.db.ops.last_executed_query(
self.cursor, sql, self._quote_params(params)
),
"duration": duration,
"raw_sql": sql,
"params": _params,
"start_time": start_time,
"stop_time": stop_time,
"is_slow": duration > 10,
"is_select": sql.lower().strip().startswith("select"),
}
if vendor == "postgresql":
# If an erroneous query was ran on the connection, it might
# be in a state where checking isolation_level raises an
# exception.
try:
iso_level = conn.isolation_level
except conn.InternalError:
iso_level = "unknown"
params.update(
{
"trans_id": self.logger.get_transaction_id(alias),
"trans_status": conn.get_transaction_status(),
"iso_level": iso_level,
"encoding": conn.encoding,
}
)
_sql = DjangoDebugSQL(**params)
# We keep `sql` to maintain backwards compatibility
self.logger.object.sql.append(_sql)
def callproc(self, procname, params=None):
return self._record(self.cursor.callproc, procname, params)
def execute(self, sql, params=None):
return self._record(self.cursor.execute, sql, params)
def executemany(self, sql, param_list):
return self._record(self.cursor.executemany, sql, param_list)
def __getattr__(self, attr):
return getattr(self.cursor, attr)
def __iter__(self):
return iter(self.cursor)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
| """Thrown when template panel triggers a query""" |
pi.py | #!/usr/bin/env python
from decimal import Decimal, getcontext
from fractions import Fraction
digits = 500
getcontext().prec = digits
def leibnitz(n):
|
def calc_pi(n):
"""
Calculate PI.
Parameters
----------
n : int
Number of fractions.
Returns
-------
Fraction
Approximation of pi.
"""
pi = Fraction(0)
for k in range(n):
# print(Fraction(-1,4)**k)
pi += (Fraction(-1, 4)**k * (Fraction(1, 1+2*k)
+ Fraction(2, 1+4*k)
+ Fraction(1, 3+4*k)))
return pi
def get_correct_digits(approx):
"""
Get how many digits were correct.
Parameters
----------
approx : str
String representation of an approximation of pi.
Returns
-------
int
The number of correct digits. If the number has too many correct
digits, -1 is returned.
"""
pi = ("3.14159265358979323846264338327950288419716939937510582097494459230"
"78164062862089986280348253421170679")
for i, el in enumerate(pi):
if len(approx) <= i:
return i-1
if el != approx[i]:
return i
return -1 # Very good!
if __name__ == "__main__":
# for n in range(1,180):
# approx = calc_pi(n)
# dec =Decimal(approx.numerator) / Decimal(approx.denominator)
# #print(dec)
# print("correct digits: %s (n=%i)" % (get_correct_digits(str(dec)),n))
n = digits
approx = calc_pi(n)
dec = Decimal(approx.numerator) / Decimal(approx.denominator)
print(dec)
| """
Parameters
----------
n : int
Returns
-------
Fraction
Approximation of pi.
"""
pi = Fraction(0)
sign = 1
for k in range(1, n, 2):
pi = pi + sign*Fraction(4, k)
sign *= -1
return pi |
messages.ts | import {models} from '../models'
import { Op } from 'sequelize'
import { indexBy } from 'underscore'
import { sendNotification } from '../hub'
import * as socket from '../utils/socket'
import * as jsonUtils from '../utils/json'
import * as helpers from '../helpers'
import { success } from '../utils/res'
import * as timers from '../utils/timers'
import {sendConfirmation} from './confirmations'
import * as path from 'path'
import * as network from '../network'
import * as short from 'short-uuid'
const constants = require(path.join(__dirname,'../../config/constants.json'))
export const getMessages = async (req, res) => {
const dateToReturn = req.query.date;
if (!dateToReturn) {
return getAllMessages(req, res)
}
console.log(dateToReturn)
const owner = await models.Contact.findOne({ where: { isOwner: true } })
// const chatId = req.query.chat_id
let newMessagesWhere = {
date: { [Op.gte]: dateToReturn },
[Op.or]: [
{receiver: owner.id},
{receiver: null}
]
}
let confirmedMessagesWhere = {
updated_at: { [Op.gte]: dateToReturn },
status: {[Op.or]: [
constants.statuses.received,
]},
sender: owner.id
}
let deletedMessagesWhere = {
updated_at: { [Op.gte]: dateToReturn },
status: {[Op.or]: [
constants.statuses.deleted
]},
}
// if (chatId) {
// newMessagesWhere.chat_id = chatId
// confirmedMessagesWhere.chat_id = chatId
// }
const newMessages = await models.Message.findAll({ where: newMessagesWhere })
const confirmedMessages = await models.Message.findAll({ where: confirmedMessagesWhere })
const deletedMessages = await models.Message.findAll({ where: deletedMessagesWhere })
const chatIds: number[] = []
newMessages.forEach(m => {
if(!chatIds.includes(m.chatId)) chatIds.push(m.chatId)
})
confirmedMessages.forEach(m => {
if(!chatIds.includes(m.chatId)) chatIds.push(m.chatId)
})
deletedMessages.forEach(m => {
if(!chatIds.includes(m.chatId)) chatIds.push(m.chatId)
})
let chats = chatIds.length > 0 ? await models.Chat.findAll({ where: {deleted:false, id: chatIds} }) : []
const chatsById = indexBy(chats, 'id')
res.json({
success: true,
response: {
new_messages: newMessages.map(message =>
jsonUtils.messageToJson(message, chatsById[parseInt(message.chatId)])
),
confirmed_messages: confirmedMessages.map(message =>
jsonUtils.messageToJson(message, chatsById[parseInt(message.chatId)])
),
deleted_messages: deletedMessages.map(message =>
jsonUtils.messageToJson(message, chatsById[parseInt(message.chatId)])
)
}
});
res.status(200)
res.end()
}
export const getAllMessages = async (req, res) => {
const limit = (req.query.limit && parseInt(req.query.limit)) || 1000
const offset = (req.query.offset && parseInt(req.query.offset)) || 0
console.log(`=> getAllMessages, limit: ${limit}, offset: ${offset}`)
const messages = await models.Message.findAll({ order: [['chat_id', 'asc']], limit, offset })
console.log('=> got msgs',(messages&&messages.length))
const chatIds:number[] = []
messages.forEach((m) => {
if(!chatIds.includes(m.chatId)) {
chatIds.push(m.chatId)
}
})
let chats = chatIds.length > 0 ? await models.Chat.findAll({ where: {deleted:false, id: chatIds} }) : []
console.log('=> found all chats',(chats&&chats.length))
const chatsById = indexBy(chats, 'id')
console.log('=> indexed chats')
success(res, {
new_messages: messages.map(
message => jsonUtils.messageToJson(message, chatsById[parseInt(message.chatId)])
),
confirmed_messages: []
})
};
export async function deleteMessage(req, res){
const id = parseInt(req.params.id)
const message = await models.Message.findOne({where:{id}})
const uuid = message.uuid
await message.update({status: constants.statuses.deleted})
const chat_id = message.chatId
let chat
if(chat_id) {
chat = await models.Chat.findOne({where:{id:chat_id}})
}
success(res, jsonUtils.messageToJson(message, chat))
if(!chat) return
const isTribe = chat.type===constants.chat_types.tribe
const owner = await models.Contact.findOne({ where: { isOwner: true }})
const isTribeOwner = isTribe && owner.publicKey===chat.ownerPubkey
if(isTribeOwner) {
timers.removeTimerByMsgId(id)
}
network.sendMessage({
chat: chat,
sender: owner,
type: constants.message_types.delete,
message: {id,uuid},
})
}
export const sendMessage = async (req, res) => {
// try {
// schemas.message.validateSync(req.body)
// } catch(e) {
// return failure(res, e.message)
// }
const {
contact_id,
text,
remote_text,
chat_id,
remote_text_map,
amount,
reply_uuid,
} = req.body
var date = new Date();
date.setMilliseconds(0)
const owner = await models.Contact.findOne({ where: { isOwner: true }})
const chat = await helpers.findOrCreateChat({
chat_id,
owner_id: owner.id,
recipient_id: contact_id,
})
const remoteMessageContent = remote_text_map?JSON.stringify(remote_text_map) : remote_text
const msg:{[k:string]:any}={
chatId: chat.id,
uuid: short.generate(),
type: constants.message_types.message,
sender: owner.id,
amount: amount||0,
date: date,
messageContent: text,
remoteMessageContent,
status: constants.statuses.pending,
createdAt: date,
updatedAt: date,
}
if(reply_uuid) msg.replyUuid=reply_uuid
// console.log(msg)
const message = await models.Message.create(msg)
success(res, jsonUtils.messageToJson(message, chat))
const msgToSend:{[k:string]:any} = {
id: message.id,
uuid: message.uuid,
content: remote_text_map || remote_text || text
}
if(reply_uuid) msgToSend.replyUuid=reply_uuid
network.sendMessage({
chat: chat,
sender: owner,
amount: amount||0,
type: constants.message_types.message,
message: msgToSend,
})
}
export const receiveMessage = async (payload) => {
// console.log('received message', { payload })
var date = new Date();
date.setMilliseconds(0)
const total_spent = 1
const {owner, sender, chat, content, remote_content, msg_id, chat_type, sender_alias, msg_uuid, date_string, reply_uuid} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
const text = content
if(date_string) date=new Date(date_string)
const msg:{[k:string]:any} = {
chatId: chat.id,
uuid: msg_uuid,
type: constants.message_types.message,
asciiEncodedTotal: total_spent,
sender: sender.id,
date: date,
messageContent: text,
createdAt: date,
updatedAt: date,
status: constants.statuses.received
}
const isTribe = chat_type===constants.chat_types.tribe
if(isTribe) {
msg.senderAlias = sender_alias
if(remote_content) msg.remoteMessageContent=remote_content
}
if(reply_uuid) msg.replyUuid = reply_uuid
const message = await models.Message.create(msg)
// console.log('saved message', message.dataValues)
socket.sendJson({
type: 'message',
response: jsonUtils.messageToJson(message, chat, sender)
})
sendNotification(chat, msg.senderAlias||sender.alias, 'message')
const theChat = {...chat.dataValues, contactIds:[sender.id]}
sendConfirmation({ chat:theChat, sender: owner, msg_id })
}
export const receiveDeleteMessage = async (payload) => {
console.log('=> received delete message')
const {owner, sender, chat, chat_type, msg_uuid} = await helpers.parseReceiveParams(payload)
if(!owner || !sender || !chat) {
return console.log('=> no group chat!')
}
const isTribe = chat_type===constants.chat_types.tribe
// in tribe this is already validated on admin's node
let where:{[k:string]:any} = {uuid: msg_uuid}
if(!isTribe) {
where.sender = sender.id // validate sender
}
const message = await models.Message.findOne({where})
if(!message) return
await message.update({status: constants.statuses.deleted})
socket.sendJson({
type: 'delete',
response: jsonUtils.messageToJson(message, chat, sender)
})
}
export const readMessages = async (req, res) => {
const chat_id = req.params.chat_id;
const owner = await models.Contact.findOne({ where: { isOwner: true }})
await models.Message.update({ seen: true }, {
where: {
sender: {
[Op.ne]: owner.id
},
chatId: chat_id
}
});
const chat = await models.Chat.findOne({ where: { id: chat_id } })
await chat.update({ seen: true });
success(res, {}) | socket.sendJson({
type: 'chat_seen',
response: jsonUtils.chatToJson(chat)
})
}
export const clearMessages = (req, res) => {
models.Message.destroy({ where: {}, truncate: true })
success(res, {})
} |
sendNotification(chat, '', 'badge') |
chipClasses.ts | import { generateUtilityClass, generateUtilityClasses } from '@mui/base';
export interface ChipClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the root element if `color="primary"`. */
colorPrimary: string;
/** Styles applied to the root element if `color="neutral"`. */
colorNeutral: string;
/** Styles applied to the root element if `color="danger"`. */
colorDanger: string;
/** Styles applied to the root element if `color="info"`. */
colorInfo: string;
/** Styles applied to the root element if `color="success"`. */
colorSuccess: string;
/** Styles applied to the root element if `color="warning"`. */
colorWarning: string;
/** State class applied to the root element if `disabled={true}`. */
disabled: string;
/** Styles applied to the endDecorator element if supplied. */
endDecorator: string;
/** State class applied to the root element if keyboard focused. */
focusVisible: string; | /** Styles applied to the label `span` element if `size="md"`. */
labelMd: string;
/** Styles applied to the label `span` element if `size="lg"`. */
labelLg: string;
/** Styles applied to the root element if `size="sm"`. */
sizeSm: string;
/** Styles applied to the root element if `size="md"`. */
sizeMd: string;
/** Styles applied to the root element if `size="lg"`. */
sizeLg: string;
/** Styles applied to the startDecorator element if supplied. */
startDecorator: string;
/** Styles applied to the root element if `variant="solid"`. */
variantSolid: string;
/** Styles applied to the root element if `variant="soft"`. */
variantSoft: string;
/** Styles applied to the root element if `variant="outlined"`. */
variantOutlined: string;
}
export type ChipClassKey = keyof ChipClasses;
export function getChipUtilityClass(slot: string): string {
return generateUtilityClass('MuiChip', slot);
}
const chipClasses: ChipClasses = generateUtilityClasses('MuiChip', [
'root',
'clickable',
'colorPrimary',
'colorNeutral',
'colorDanger',
'colorInfo',
'colorSuccess',
'colorWarning',
'disabled',
'endDecorator',
'focusVisible',
'label',
'labelSm',
'labelMd',
'labelLg',
'sizeSm',
'sizeMd',
'sizeLg',
'startDecorator',
'variantSolid',
'variantSoft',
'variantOutlined',
]);
export default chipClasses; | /** Styles applied to the label `span` element. */
label: string;
/** Styles applied to the label `span` element if `size="sm"`. */
labelSm: string; |
ImageGen.py | from scipy import signal
from scipy import misc
from scipy import stats as st
import numpy as np
W = 128
L = 128
Body_Width = 3
Border = Body_Width+1
Points = 10
Noise_Max = 10
Body_Separation = 15
Body_Scale = 30
OvScale = 3
def gkern(kernlen=21, nsig=3):
''' 2D Gaussian Kernel. '''
x = np.linspace(-nsig, nsig, kernlen+1)
kern1d = np.diff(st.norm.cdf(x))
kern2d = np.outer(kern1d, kern1d)
return kern2d/kern2d.sum()
def genBackground():
return np.random.rand(W,L)*(Noise_Max)
def genStarCoords():
while True:
star_cords = np.random.rand(Points,3) # N x [x,y,m]
star_cords = star_cords * np.array([[ W-2*Border , L-2*Border , Body_Scale ]])
star_cords = star_cords + np.ones((Points,3)) * np.array([[ Border, Border, Body_Separation ]])
bad = False
for ii in range(0, Points-1):
x0, y0, m0 = star_cords[ii,:]
for jj in range(ii+1, Points):
x1, y1, m1 = star_cords[jj,:]
if np.abs(x0 - x1) < 4*Border and np.abs(y0 - y1) < 4*Border:
'''
x = np.random.random() * (W-2*Border) + Border
y = np.random.random() * (W-2*Border) + Border
star_cords[jj,0] = x
star_cords[jj,1] = y
'''
bad = True
break
if np.abs(m0 - m1) < 5:
star_cords[jj,2] = m1 + 5
if not bad:
break
return star_cords
def starGauss(OvScale):
gausKern = gkern(Body_Width*OvScale, Body_Width/(OvScale/3))
gausKern = gausKern * (Body_Scale/np.max(np.max(gausKern)))
return gausKern
def | (star_cords):
# Overscale it
spots_O = np.zeros((W*OvScale, L*OvScale))
for (x,y,m) in star_cords:
x = OvScale * (x+0.5)
y = OvScale * (y+0.5)
x_0, y_0 = map(int, np.floor([x,y]))
x_1, y_1 = map(int, np.ceil([x,y]))
spots_O[x_0:x_1, y_0:y_1] = m
gausKern = starGauss(OvScale)
spots_B = signal.convolve2d(spots_O, gausKern, boundary='symm', mode='same')
spots = np.zeros((W,L))
for (x,y,m) in star_cords:
x = int(x)
y = int(y)
x0 = max(0, x-Body_Width-1)
x1 = min(W, x+Body_Width+1)
y0 = max(0, y-Body_Width-1)
y1 = min(L, y+Body_Width+1)
for ii in range(x0,x1+1):
for jj in range(y0, y1+1):
spots[ii,jj] = np.mean(spots_B[ii*OvScale:(ii+1)*OvScale, jj*OvScale:(jj+1)*OvScale])
final = np.trunc( np.clip(genBackground() + spots, 0, 255) )
return final
| genImage |
blinky_basic.rs | #![no_std]
#![no_main]
extern crate panic_halt;
extern crate trinket_m0 as hal;
use hal::clock::GenericClockController;
use hal::delay::Delay;
use hal::prelude::*;
use hal::{entry, CorePeripherals, Peripherals};
#[entry]
fn main() -> ! {
let mut peripherals = Peripherals::take().unwrap();
let core = CorePeripherals::take().unwrap();
let mut clocks = GenericClockController::with_internal_32kosc(
peripherals.GCLK,
&mut peripherals.PM, | &mut peripherals.SYSCTRL,
&mut peripherals.NVMCTRL,
);
let mut pins = hal::Pins::new(peripherals.PORT);
let mut red_led = pins.d13.into_open_drain_output(&mut pins.port);
let mut delay = Delay::new(core.SYST, &mut clocks);
loop {
delay.delay_ms(200u8);
red_led.set_high().unwrap();
delay.delay_ms(200u8);
red_led.set_low().unwrap();
}
} | |
pycon.py | # -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import sys
from code import InteractiveInterpreter
def main():
" |
if __name__ == '__main__':
main()
# vim: set expandtab shiftwidth=4 softtabstop=4 :
| ""
Print lines of input along with output.
"""
source_lines = (line.rstrip() for line in sys.stdin)
console = InteractiveInterpreter()
console.runsource('import turicreate')
source = ''
try:
while True:
source = source_lines.next()
more = console.runsource(source)
while more:
next_line = source_lines.next()
print '...', next_line
source += '\n' + next_line
more = console.runsource(source)
except StopIteration:
if more:
print '... '
more = console.runsource(source + '\n')
|
ExperimentList.test.tsx | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import * as Utils from '../lib/Utils';
import ExperimentList from './ExperimentList';
import TestUtils from '../TestUtils';
import { ApiResourceType } from '../apis/run';
import { Apis } from '../lib/Apis';
import { ExpandState } from '../components/CustomTable';
import { NodePhase } from './Status';
import { PageProps } from './Page';
import { RoutePage, QUERY_PARAMS } from '../components/Router';
import { range } from 'lodash';
import { shallow, ReactWrapper } from 'enzyme';
describe('ExperimentList', () => {
const updateBannerSpy = jest.fn();
const updateDialogSpy = jest.fn();
const updateSnackbarSpy = jest.fn();
const updateToolbarSpy = jest.fn();
const historyPushSpy = jest.fn();
const listExperimentsSpy = jest.spyOn(Apis.experimentServiceApi, 'listExperiment');
const listRunsSpy = jest.spyOn(Apis.runServiceApi, 'listRuns');
// We mock this because it uses toLocaleDateString, which causes mismatches between local and CI
// test enviroments
const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString');
function generateProps(): PageProps {
return TestUtils.generatePageProps(ExperimentList, { pathname: RoutePage.EXPERIMENTS } as any,
'' as any, historyPushSpy, updateBannerSpy, updateDialogSpy, updateToolbarSpy, updateSnackbarSpy);
}
async function mountWithNExperiments(n: number, nRuns: number): Promise<ReactWrapper> {
listExperimentsSpy.mockImplementation(() => ({
experiments: range(n).map(i => ({ id: 'test-experiment-id' + i, name: 'test experiment name' + i })),
}));
listRunsSpy.mockImplementation(() => ({
runs: range(nRuns).map(i => ({ id: 'test-run-id' + i, name: 'test run name' + i })),
}));
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
await listExperimentsSpy;
await listRunsSpy;
await TestUtils.flushPromises();
tree.update(); // Make sure the tree is updated before returning it
return tree;
}
beforeEach(() => {
// Reset mocks
updateBannerSpy.mockReset();
updateDialogSpy.mockReset();
updateSnackbarSpy.mockReset();
updateToolbarSpy.mockReset();
listExperimentsSpy.mockReset();
listRunsSpy.mockReset();
formatDateStringSpy.mockImplementation(() => '1/2/2019, 12:34:56 PM');
});
it('renders an empty list with empty state message', () => {
const tree = shallow(<ExperimentList {...generateProps()} />);
expect(tree).toMatchSnapshot();
tree.unmount();
});
it('renders a list of one experiment', async () => {
const tree = shallow(<ExperimentList {...generateProps()} />);
tree.setState({
displayExperiments: [{
description: 'test experiment description',
expandState: ExpandState.COLLAPSED,
name: 'test experiment name',
}]
});
await listExperimentsSpy;
await listRunsSpy;
expect(tree).toMatchSnapshot();
tree.unmount();
});
it('renders a list of one experiment with no description', async () => {
const tree = shallow(<ExperimentList {...generateProps()} />);
tree.setState({
experiments: [{
expandState: ExpandState.COLLAPSED,
name: 'test experiment name',
}]
});
await listExperimentsSpy;
await listRunsSpy;
expect(tree).toMatchSnapshot();
tree.unmount();
});
it('renders a list of one experiment with error', async () => {
const tree = shallow(<ExperimentList {...generateProps()} />);
tree.setState({
experiments: [{
description: 'test experiment description',
error: 'oops! could not load experiment',
expandState: ExpandState.COLLAPSED,
name: 'test experiment name',
}]
});
await listExperimentsSpy;
await listRunsSpy;
expect(tree).toMatchSnapshot();
tree.unmount();
});
it('calls Apis to list experiments, sorted by creation time in descending order', async () => {
const tree = await mountWithNExperiments(1, 1);
expect(listExperimentsSpy).toHaveBeenLastCalledWith('', 10, 'created_at desc', '');
expect(listRunsSpy).toHaveBeenLastCalledWith(undefined, 5, 'created_at desc',
ApiResourceType.EXPERIMENT.toString(), 'test-experiment-id0');
expect(tree.state()).toHaveProperty('displayExperiments', [{
expandState: ExpandState.COLLAPSED,
id: 'test-experiment-id0',
last5Runs: [{ id: 'test-run-id0', name: 'test run name0' }],
name: 'test experiment name0',
}]);
tree.unmount();
});
it('has a Refresh button, clicking it refreshes the experiment list', async () => {
const tree = await mountWithNExperiments(1, 1);
const instance = tree.instance() as ExperimentList;
expect(listExperimentsSpy.mock.calls.length).toBe(1);
const refreshBtn = instance.getInitialToolbarState().actions.find(b => b.title === 'Refresh');
expect(refreshBtn).toBeDefined();
await refreshBtn!.action();
expect(listExperimentsSpy.mock.calls.length).toBe(2);
expect(listExperimentsSpy).toHaveBeenLastCalledWith('', 10, 'created_at desc', '');
expect(updateBannerSpy).toHaveBeenLastCalledWith({});
tree.unmount();
});
it('shows error banner when listing experiments fails', async () => {
TestUtils.makeErrorResponseOnce(listExperimentsSpy, 'bad stuff happened');
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
await listExperimentsSpy;
await TestUtils.flushPromises();
expect(updateBannerSpy).toHaveBeenLastCalledWith(expect.objectContaining({
additionalInfo: 'bad stuff happened',
message: 'Error: failed to retrieve list of experiments. Click Details for more information.',
mode: 'error',
}));
tree.unmount();
});
it('shows error next to experiment when listing its last 5 runs fails', async () => {
// tslint:disable-next-line:no-console
console.error = jest.spyOn(console, 'error').mockImplementation();
listExperimentsSpy.mockImplementationOnce(() => ({ experiments: [{ name: 'exp1' }] }));
TestUtils.makeErrorResponseOnce(listRunsSpy, 'bad stuff happened');
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
await listExperimentsSpy;
await TestUtils.flushPromises();
expect(tree.state()).toHaveProperty('displayExperiments', [{
error: 'Failed to load the last 5 runs of this experiment',
expandState: 0,
name: 'exp1',
}]);
tree.unmount();
});
it('shows error banner when listing experiments fails after refresh', async () => {
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
const instance = tree.instance() as ExperimentList;
const refreshBtn = instance.getInitialToolbarState().actions.find(b => b.title === 'Refresh');
expect(refreshBtn).toBeDefined();
TestUtils.makeErrorResponseOnce(listExperimentsSpy, 'bad stuff happened');
await refreshBtn!.action();
expect(listExperimentsSpy.mock.calls.length).toBe(2);
expect(listExperimentsSpy).toHaveBeenLastCalledWith('', 10, 'created_at desc', '');
expect(updateBannerSpy).toHaveBeenLastCalledWith(expect.objectContaining({
additionalInfo: 'bad stuff happened',
message: 'Error: failed to retrieve list of experiments. Click Details for more information.',
mode: 'error',
}));
tree.unmount();
});
it('hides error banner when listing experiments fails then succeeds', async () => {
TestUtils.makeErrorResponseOnce(listExperimentsSpy, 'bad stuff happened');
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
const instance = tree.instance() as ExperimentList;
await listExperimentsSpy;
await TestUtils.flushPromises();
expect(updateBannerSpy).toHaveBeenLastCalledWith(expect.objectContaining({
additionalInfo: 'bad stuff happened',
message: 'Error: failed to retrieve list of experiments. Click Details for more information.',
mode: 'error',
}));
updateBannerSpy.mockReset();
const refreshBtn = instance.getInitialToolbarState().actions.find(b => b.title === 'Refresh');
listExperimentsSpy.mockImplementationOnce(() => ({ experiments: [{ name: 'experiment1' }] }));
listRunsSpy.mockImplementationOnce(() => ({ runs: [{ name: 'run1' }] }));
await refreshBtn!.action();
expect(listExperimentsSpy.mock.calls.length).toBe(2);
expect(updateBannerSpy).toHaveBeenLastCalledWith({});
tree.unmount();
});
it('can expand an experiment to see its runs', async () => {
const tree = await mountWithNExperiments(1, 1);
tree.find('.tableRow button').at(0).simulate('click');
expect(tree.state()).toHaveProperty('displayExperiments', [{
expandState: ExpandState.EXPANDED,
id: 'test-experiment-id0',
last5Runs: [{ id: 'test-run-id0', name: 'test run name0' }],
name: 'test experiment name0',
}]);
tree.unmount();
});
it('renders a list of runs for given experiment', async () => {
const tree = shallow(<ExperimentList {...generateProps()} />);
tree.setState({ displayExperiments: [{ last5Runs: [{ id: 'run1id' }, { id: 'run2id' }] }] });
const runListTree = (tree.instance() as any)._getExpandedExperimentComponent(0);
expect(runListTree.props.runIdListMask).toEqual(['run1id', 'run2id']);
});
it('navigates to new experiment page when Create experiment button is clicked', async () => {
const tree = TestUtils.mountWithRouter(<ExperimentList {...generateProps()} />);
const createBtn = (tree.instance() as ExperimentList)
.getInitialToolbarState().actions.find(b => b.title === 'Create an experiment');
await createBtn!.action();
expect(historyPushSpy).toHaveBeenLastCalledWith(RoutePage.NEW_EXPERIMENT);
});
it('always has new experiment button enabled', async () => {
const tree = await mountWithNExperiments(1, 1);
const calls = updateToolbarSpy.mock.calls[0];
expect(calls[0].actions.find((b: any) => b.title === 'Create an experiment')).not.toHaveProperty('disabled');
tree.unmount();
});
it('enables clone button when one run is selected', async () => {
const tree = await mountWithNExperiments(1, 1);
(tree.instance() as any)._selectionChanged(['run1']);
expect(updateToolbarSpy).toHaveBeenCalledTimes(2);
expect(updateToolbarSpy.mock.calls[0][0].actions.find((b: any) => b.title === 'Clone run'))
.toHaveProperty('disabled', true);
expect(updateToolbarSpy.mock.calls[1][0].actions.find((b: any) => b.title === 'Clone run'))
.toHaveProperty('disabled', false);
tree.unmount();
});
it('disables clone button when more than one run is selected', async () => {
const tree = await mountWithNExperiments(1, 1);
(tree.instance() as any)._selectionChanged(['run1', 'run2']);
expect(updateToolbarSpy).toHaveBeenCalledTimes(2);
expect(updateToolbarSpy.mock.calls[0][0].actions.find((b: any) => b.title === 'Clone run'))
.toHaveProperty('disabled', true);
expect(updateToolbarSpy.mock.calls[1][0].actions.find((b: any) => b.title === 'Clone run'))
.toHaveProperty('disabled', true);
tree.unmount();
});
it('enables compare runs button only when more than one is selected', async () => {
const tree = await mountWithNExperiments(1, 1);
(tree.instance() as any)._selectionChanged(['run1']);
(tree.instance() as any)._selectionChanged(['run1', 'run2']);
(tree.instance() as any)._selectionChanged(['run1', 'run2', 'run3']);
expect(updateToolbarSpy).toHaveBeenCalledTimes(4);
expect(updateToolbarSpy.mock.calls[0][0].actions.find((b: any) => b.title === 'Compare runs'))
.toHaveProperty('disabled', true);
expect(updateToolbarSpy.mock.calls[1][0].actions.find((b: any) => b.title === 'Compare runs'))
.toHaveProperty('disabled', true);
expect(updateToolbarSpy.mock.calls[2][0].actions.find((b: any) => b.title === 'Compare runs'))
.toHaveProperty('disabled', false);
expect(updateToolbarSpy.mock.calls[3][0].actions.find((b: any) => b.title === 'Compare runs'))
.toHaveProperty('disabled', false);
tree.unmount();
});
it('navigates to compare page with the selected run ids', async () => {
const tree = await mountWithNExperiments(1, 1);
(tree.instance() as any)._selectionChanged(['run1', 'run2', 'run3']);
const compareBtn = (tree.instance() as ExperimentList)
.getInitialToolbarState().actions.find(b => b.title === 'Compare runs');
await compareBtn!.action();
expect(historyPushSpy).toHaveBeenLastCalledWith(
`${RoutePage.COMPARE}?${QUERY_PARAMS.runlist}=run1,run2,run3`);
});
it('navigates to new run page with the selected run id for cloning', async () => {
const tree = await mountWithNExperiments(1, 1);
(tree.instance() as any)._selectionChanged(['run1']);
const cloneBtn = (tree.instance() as ExperimentList)
.getInitialToolbarState().actions.find(b => b.title === 'Clone run');
await cloneBtn!.action();
expect(historyPushSpy).toHaveBeenLastCalledWith(
`${RoutePage.NEW_RUN}?${QUERY_PARAMS.cloneFromRun}=run1`);
});
| ._nameCustomRenderer('experiment name', 'experiment-id'));
expect(tree).toMatchSnapshot();
});
it('renders last 5 runs statuses', async () => {
const tree = shallow((ExperimentList.prototype as any)
._last5RunsCustomRenderer([
{ status: NodePhase.SUCCEEDED },
{ status: NodePhase.PENDING },
{ status: NodePhase.FAILED },
{ status: NodePhase.UNKNOWN },
{ status: NodePhase.SUCCEEDED },
]));
expect(tree).toMatchSnapshot();
});
}); | it('renders experiment names as links to their details pages', async () => {
const tree = TestUtils.mountWithRouter((ExperimentList.prototype as any) |
second.js | const name = 'Zaptec';
function | () {
alert(`Our company is called ${name}.`);
}
| greeting |
conftest.py | import numpy as np
import pytest
import pandas as pd
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
)
@pytest.fixture(
params=[
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
]
)
def dtype(request):
"""Parametrized fixture returning integer 'dtype'"""
return request.param()
@pytest.fixture
def data(dtype):
"""
Fixture returning 'data' array with valid and missing values according to
parametrized integer 'dtype'.
Used to test dtype conversion with and without missing values.
"""
return pd.array(
list(range(8)) + [np.nan] + list(range(10, 98)) + [np.nan] + [99, 100],
dtype=dtype,
)
@pytest.fixture
def data_missing(dtype):
"""
Fixture returning array with exactly one NaN and one valid integer,
according to parametrized integer 'dtype'.
Used to test dtype conversion with and without missing values.
"""
return pd.array([np.nan, 1], dtype=dtype)
@pytest.fixture(params=["data", "data_missing"])
def all_data(request, data, data_missing):
| """Parametrized fixture returning 'data' or 'data_missing' integer arrays.
Used to test dtype conversion with and without missing values.
"""
if request.param == "data":
return data
elif request.param == "data_missing":
return data_missing |
|
zero_baseline.py | from maml_zoo.baselines.base import Baseline
import numpy as np
class ZeroBaseline(Baseline):
"""
Dummy baseline
"""
def __init__(self):
super(ZeroBaseline, self).__init__()
def get_param_values(self, **kwargs):
"""
Returns the parameter values of the baseline object
Returns:
(None): coefficients of the baseline
"""
return None
def set_param_values(self, value, **kwargs):
"""
Sets the parameter values of the baseline object
Args:
value (None): coefficients of the baseline
"""
pass
def | (self, paths, **kwargs):
"""
Improves the quality of zeroes output by baseline
Args:
paths: list of paths
"""
pass
def predict(self, path):
"""
Produces some zeroes
Args:
path (dict): dict of lists/numpy array containing trajectory / path information
such as "observations", "rewards", ...
Returns:
(np.ndarray): numpy array of the same length as paths["observations"] specifying the reward baseline
"""
return np.zeros_like(path["rewards"]) | fit |
nngp.py | #!/usr/bin/env python3
# Copyright 2021 Christian Henning
#
# 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.
#
# @title :nngp/nngp.py
# @author :ch
# @contact :[email protected]
# @created :04/19/2021
# @version :1.0
# @python_version :3.8.5
r"""
Deep Neural Network as Gaussian Process
---------------------------------------
The module :mod:`nngp.nngp` implements helper functions for Bayesian inference
with Gaussian Processes with a focus on kernels derived from neural network
architectures when taken to the infinite-width limit
(cf. :mod:`nngp.mlp_kernel`).
Specifically, we consider a Gaussian Process
:math:`\mathcal{GP}\big(\mu(x), k(x, x')\big)` with mean function
:math:`\mu(\cdot)` and kernel :math:`k(\cdot, \cdot)`. Unless specified
otherwise, we assume the mean function to be :math:`\mu(x) = 0`. Note, that any
multivariate Gaussian prescribed by the :math:`\mathcal{GP}` at a given set of
input locations is consistent (marginalization from any superset of locations
will always lead to the same distribution) and adheres exchangibility (order of
input locations doesn't affect the distribution except for repositioning the
corresponding function values).
For any given set of inputs :math:`X = x_1, \dots, x_n`, the
:math:`\mathcal{GP}` allows us to specify a prior distribution over function
values :math:`p(f_1, \dots, f_n; x_1, \dots, x_n) \equiv p(F; X)`.
In addition to inputs :math:`x` and function values :math:`f`, we consider
observations :math:`y`, which are obtained via a likelihood function
:math:`p(y \mid f)`.
Using the prior distribution over functions (the :math:`\mathcal{GP}`) and a
dataset :math:`\mathcal{D} = \{(x_n, y_n)\}_{n=1}^N` with inputs :math:`X` and
targets :math:`Y`, one can form a posterior distribution over function values
:math:`f` at an unknown location :math:`x^*` via
.. math::
p(f \mid \mathcal{D}; x^*) = p(f \mid Y; x^* X) = \frac{1}{p(Y; X)} \
\int p(Y \mid F) p(F, f; X, x^*) \, dF
Please see
`Rasmussen and Williams <http://www.gaussianprocess.org/gpml/chapters/RW.pdf>`__
for a broader introduction into Gaussian Processes.
"""
import torch
from warnings import warn
def inference_with_isotropic_gaussian_ll(Y, K_train, K_test, K_all, var=1e-10,
L_mat=None, return_cov=False):
r"""Bayesian inference with Gaussian likelihood and :math:`\mathcal{GP}`
prior.
Here, we consider the case
:math:`p(Y \mid F) = \mathcal{N}(Y; F, \sigma_\epsilon^2 I)`, where the
posterior predictive :math:`p(f \mid \mathcal{D}; x^*)` can be analytically
computed
.. math::
p(f \mid \mathcal{D}; x^*) &= \mathcal{N}(f; \mu^*, \Sigma^*) \\ \
\mu^* &= K(x^*, X) \big( K(X, X) + \sigma_\epsilon^2 I \big)^{-1} Y \\ \
\Sigma^* &= k(x^*, x^*) - K(x^*, X) \big( K(X, X) + \
\sigma_\epsilon^2 I \big)^{-1} K(X, x^*)
Args:
Y (torch.Tensor): The labels :math:`Y` from the training set encoded as
vector of shape ``[m]`` or ``[m, 1]``.
K_train (torch.Tensor): The training data kernel matrix :math:`K(X, X)`.
K_test (torch.Tensor): The test data kernel values :math:`k(x^*, x^*)`.
This is a vector either of shape ``[n]``, where ``n`` is the number
test points, or of shape ``[n, 1]``.
K_all (torch.Tensor): The kernel values between train and test points
:math:`K(x^*, X)`. This is expected to be matrix of shape ``[n,m]``,
where ``m`` is the number of training and ``n`` the number of test
points, or simply a vector of shape ``[m]``, if there is only one
test point.
var (float): The variance :math:`\sigma_\epsilon^2` of the likelihood.
L_mat (torch.Tensor, optional): The matrix :math:`L` resulting from a
Cholesky decomposition of :math:`K(X, X) + \sigma_\epsilon^2 I`.
If provided, the arguments ``K_train`` and ``var`` are ignored.
The function :func:`cholesky_adaptive_noise` may be helpful to
compute ``L_mat``.
return_cov (bool): If ``True``, the return value ``cov`` will be the
full covariance matrix. However, this option requires ``K_test``
to be the full ``[n, n]`` kernel matrix.
Returns:
(tuple): Tuple containing:
- **mean** (torch.Tensor): A tensor of shape ``[n]``, where ``n`` is the
number of test points. The tensor encodes the mean for each test point
of the posterior predictive :math:`\mu^*`.
- **cov** (torch.Tensor): Same as ``mean`` but encoding the variance
:math:`\Sigma^*` of each test point, i.e., the diagonal of the full
covariance matrix.
"""
m = K_train.shape[0] if L_mat is None else L_mat.shape[0]
n = K_test.shape[0]
assert Y.numel() == m
assert K_all.numel() == m*n
if Y.ndim == 1:
Y = Y.view(-1, 1)
if return_cov:
assert K_test.numel() == n*n and K_test.ndim == 2
elif K_test.ndim == 2:
K_test = K_test.view(-1)
if K_all.ndim == 1:
assert n == 1
K_all = K_all.view(n, m)
#inv_K = torch.linalg.inv(K_train + var * torch.eye(m).to(K_train.device))
#mu = torch.matmul(K_all, torch.matmul(inv_K, Y))
#if return_cov:
# sigma = K_test - torch.matmul(K_all, torch.matmul(inv_K, K_all.T))
#else:
# #sigma = K_test - torch.bmm(K_all.view(n, 1, m), torch.matmul(inv_K,
# # K_all.view(n, m, 1))).squeeze()
# sigma = K_test - (K_all * torch.matmul(inv_K,
# K_all.view(n, m, 1)).squeeze(dim=2)).sum(dim=1)
# Note, direct matrix inversion is considered extremely numerically
# unstable. Therefore, Rasmussen et al. propose the use of Cholesky
# decomposition, see Appendix A.4 in
# http://www.gaussianprocess.org/gpml/chapters/RW.pdf
if L_mat is None:
L = torch.linalg.cholesky(K_train + \
var * torch.eye(m).to(K_train.device))
else:
L = L_mat
alpha = torch.triangular_solve(torch.triangular_solve(Y, L, upper=False)[0],
L, upper=False, transpose=True)[0]
mu = torch.matmul(K_all, alpha)
v = torch.triangular_solve(K_all.T, L, upper=False)[0]
if return_cov:
sigma = K_test - torch.matmul(v.T, v)
else:
sigma = K_test - (v * v).sum(dim=0)
if torch.any(sigma < 0):
sigma[sigma < 0] = 1e-5
warn('Some entries of the covariance matrix are negative and set to ' +
'1e-5!')
return mu.squeeze(), sigma
def | (X_train, X_test, kernel_func, compute_K_train=True,
full_K_test=False):
r"""Generate the kernel matrices required for inference.
This function generates the kernel matrices / vectors :math:`K(X, X)`,
:math:`K(x^*, X)` and :math:`K(x^*, x^*)`, where :math:`X` are training
inputs and :math:`x^*` are unseen points.
Thus, the function can be seen as helper function for functions like
:func:`inference_with_isotropic_gaussian_ll`.
Args:
X_train (torch.Tensor): A batch of ``m`` training inputs. The tensor
should have shape ``[m, d_in]``, where ``d_in`` is the input
dimensionality. For scalar inputs, one may also pass a tensor of
shape ``[m]``.
X_test (torch.Tensor):A batch of ``n`` unseen test inputs.
kernel_func (func): The kernel function :math:`k(x, x')`. It is expected
to have an interface for a single input ``X`` as described in
the docstring of function:`nngp.mlp_kernel.init_kernel`.
.. code-block:: python
def kernel_func(X):
# Compute kernel values.
return K
compute_K_train (bool): Whether the kernel matrix :math:`K(X, X)`
should be computed. If ``False``, the return value ``K_train`` is
``None``.
full_K_test (bool): Whether the full kernel matrix :math:`K(x^*, x^*)`
of shape ``[n, n]`` should be computed.
Returns:
(tuple): Tuple containing:
- **K_train** (torch.Tensor or None): :math:`K(X, X)`, a tensor of
shape ``[m, m]``.
- **K_test** (torch.Tensor): :math:`K(x^*, x^*)`, a tensor of shape
``[n]``
- **K_all** (torch.Tensor): :math:`K(x^*, X)`, a tensor of shape
``[n,m]``
"""
if compute_K_train:
K_train = kernel_func(X_train)
else:
K_train = None
if full_K_test:
K_test = kernel_func(X_test)
else:
K_test = kernel_func((X_test, X_test))
# Contruct tuples between all train samples and all test samples.
if X_train.ndim == 1: # `d_in == 1`
X_train = X_train.view(-1, 1)
if X_test.ndim == 1:
X_test = X_test.view(-1, 1)
m = X_train.shape[0]
n = X_test.shape[0]
X_all = (X_train.repeat(n, 1),
X_test.view(n, 1, -1).repeat(1, m, 1).view(n*m, -1))
K_all = kernel_func(X_all)
K_all = K_all.view(n, m)
return K_train, K_test, K_all
def cholesky_adaptive_noise(K_train, var=1e-10, var_step=2.):
r"""Cholesky decomposition of a kernel matrix with noise perturbation.
This function computes the Cholesky decomposition of:
.. math::
L L^T = K(X, X) + \sigma_\epsilon^2 I
As kernel matrices :math:`K(X, X)` may easily be (numerically) singular,
tuning the noise :math:`\sigma_\epsilon^2` is crucial. Therefore, this
method will iteratively increase the noise level until the matrix becomes
non-singular.
Args:
(....): See docstring of method :meth:`kernel_efficient`.
var (float or list): The initial variance :math:`\sigma_\epsilon^2`.
If a list of values is provided, then each value in this list is
consecutively tested until a non-singular matrix is constructed.
Note, we assume that the list is sorted from small to large. If none
of the elements in this list will lead to a non-singular matrix, an
exception is raised.
var_step (float): If ``var`` is a single value, then the value specified
here will be iteratively multiplied to increase the variance
:math:`\sigma_\epsilon^2` (therefore ``var_step > 1`` is required).
Returns:
(tuple): Tuple containing:
- **L** (torch.Tensor): The matrix :math:`L` resulting from the
successful Cholesky decomposition.
- **var_chosen** (float): The variance :math:`\sigma_\epsilon^2` that
was chosen to obtain ``L``.
"""
m = K_train.shape[0]
if not isinstance(var, (list, tuple)):
assert var_step > 1.
i = 0
while True:
if isinstance(var, (list, tuple)):
if i >= len(var):
raise RuntimeError('List of variances didn\'t contain high ' +
'enough values.')
curr_var = var[i]
else:
if i == 0:
curr_var = var
else:
curr_var *= var_step
try:
L = torch.linalg.cholesky(K_train + curr_var * torch.eye(m).to( \
K_train.device))
except:
i += 1
continue
return L, curr_var
if __name__ == '__main__':
pass
| gen_inference_kernels |
frequency.py | def frequency(lst, search_term):
"""Return frequency of term in lst.
>>> frequency([1, 4, 3, 4, 4], 4)
3
>>> frequency([1, 4, 3], 7)
0
"""
return lst.count(search_term)
print(F"frequency.py: frequency([1, 4, 3, 4, 4], 4) = `3` = {frequency([1, 4, 3, 4, 4], 4)}") | print(F"frequency.py: frequency([1, 4, 3], 7) = `0` = {frequency([1, 4, 3], 7)}") |
|
Access.ts | import { Attributes, Role, RoleSettings } from "@valkyr/access";
import { getId } from "@valkyr/security";
/*
|--------------------------------------------------------------------------------
| Bitflags
|--------------------------------------------------------------------------------
*/
export const WORKSPACE_FLAGS: Record<string, number> = {
id: 1 << 0,
name: 1 << 1,
members: 1 << 2
};
/*
|--------------------------------------------------------------------------------
| Role
|--------------------------------------------------------------------------------
*/
export class | extends Role<{
workspace: {
setName: boolean;
delete: boolean;
createInvite: boolean;
removeInvite: boolean;
removeMember: boolean;
};
item: {
create: boolean;
remove: boolean;
addItem: boolean;
addItemText: boolean;
setItemDone: boolean;
setItemUndone: boolean;
removeItem: boolean;
};
}> {
public static getAttributes(flag?: number) {
return new Attributes(WORKSPACE_FLAGS, flag);
}
public static getPermissions({
workspace,
item
}: Partial<WorkspaceRole["permissions"]>): WorkspaceRole["permissions"] {
return {
workspace: {
setName: workspace?.setName === true,
delete: workspace?.delete === true,
createInvite: workspace?.createInvite === true,
removeInvite: workspace?.removeInvite === true,
removeMember: workspace?.removeMember === true
},
item: {
create: item?.create === true,
remove: item?.remove === true,
addItem: item?.addItem === true,
addItemText: item?.addItemText === true,
setItemDone: item?.setItemDone === true,
setItemUndone: item?.setItemUndone === true,
removeItem: item?.removeItem === true
}
};
}
}
export const roles = {
admin: (workspaceId: string, members: string[]): RoleSettings<WorkspaceRole["permissions"]> => ({
id: getId(),
tenantId: workspaceId,
name: "Admin",
settings: {},
permissions: {
workspace: {
setName: true,
delete: true,
createInvite: true,
removeInvite: true,
removeMember: true
},
item: {
create: true,
remove: true,
addItem: true,
addItemText: true,
setItemDone: true,
setItemUndone: true,
removeItem: true
}
},
members
}),
member: (workspaceId: string, members: string[]): RoleSettings<WorkspaceRole["permissions"]> => ({
id: getId(),
tenantId: workspaceId,
name: "Member",
settings: {},
permissions: {
workspace: {
setName: false,
delete: false,
createInvite: false,
removeInvite: false,
removeMember: false
},
item: {
create: false,
remove: false,
addItem: true,
addItemText: true,
setItemDone: true,
setItemUndone: true,
removeItem: true
}
},
members
})
};
| WorkspaceRole |
setup.py | import pya
def registerMenuItems():
import os
from . import scripts, lumerical, install
import SiEPIC.__init__
global ACTIONS
count = 0
menu = pya.Application.instance().main_window().menu()
path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"files", "INTERCONNECT_icon.png")
path_flv = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"files", "flv_icon.png")
path_test = os.path.join(os.path.dirname(os.path.realpath(__file__)),
"files", "test_icon.png")
import sys
if int(sys.version[0]) > 2 and sys.platform == 'darwin':
extra = " Py3"
else:
extra = " Py2"
s1 = "siepic_menu"
if not(menu.is_menu(s1)):
menu.insert_menu("help_menu", s1, "SiEPIC %s" % SiEPIC.__init__.__version__ + extra)
s2 = "waveguides"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Waveguides")
s2 = "metal"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Metal")
s2 = "layout"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Layout")
s2 = "exlayout"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Example Layouts")
s2 = "verification"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Verification")
s2 = "simulation_circuits"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Simulation, Circuits")
s2 = "simulation_components"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Simulation, Components")
s2 = "measurements"
if not(menu.is_menu(s1 + "." + s2)):
menu.insert_menu(s1 + ".end", s2, "Measurement Data")
if not(menu.is_menu("@toolbar.cir_sim")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.end", "cir_sim", ACTIONS[count])
ACTIONS[count].title = "Circuit \nSimulation"
ACTIONS[count].on_triggered(lumerical.interconnect.circuit_simulation_toolbar)
ACTIONS[count].icon = path
count += 1
if not(menu.is_menu("@toolbar.verification")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.end", "verification", ACTIONS[count])
ACTIONS[count].title = "Functional\nVerification"
ACTIONS[count].on_triggered(scripts.layout_check)
ACTIONS[count].icon = path_flv
count += 1
if not(menu.is_menu("@toolbar.coordinates")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.end", "coordinates", ACTIONS[count])
ACTIONS[count].title = "Testing\nCoordinates"
ACTIONS[count].on_triggered(scripts.auto_coord_extract)
ACTIONS[count].icon = path_test
count += 1
if 0:
if not(menu.is_menu("@toolbar.cir_sim.mc_sim")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.cir_sim.end", "mc_sim", ACTIONS[count])
ACTIONS[count].title = "INTERCONNECT Monte Carlo Simulations"
ACTIONS[count].on_triggered(lumerical.interconnect.circuit_simulation_monte_carlo)
ACTIONS[count].icon = path
count += 1
if not(menu.is_menu("@toolbar.cir_sim.launch_lumerical")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.cir_sim.end", "launch_lumerical", ACTIONS[count])
ACTIONS[count].title = "INTERCONNECT Circuit Simulation"
ACTIONS[count].on_triggered(lumerical.interconnect.circuit_simulation)
ACTIONS[count].icon = path
count += 1
if not(menu.is_menu("@toolbar.cir_sim.update_netlist")):
ACTIONS.append(pya.Action())
menu.insert_item("@toolbar.cir_sim.end", "update_netlist", ACTIONS[count])
ACTIONS[count].title = "INTERCONNECT Update Netlist"
ACTIONS[count].on_triggered(lumerical.interconnect.circuit_simulation_update_netlist)
ACTIONS[count].icon = path
def | ():
import os
config = pya.Application.instance().get_config('key-bindings')
if config == '':
print('WARNING: get_config(key-bindings) returned null')
mapping = dict()
else:
mapping = dict(item.split(":") for item in config.split(";"))
mapping['edit_menu.clear_all_rulers'] = "'Ctrl+K'"
mapping['edit_menu.copy'] = "'Ctrl+C'"
mapping['edit_menu.cut'] = "'Ctrl+X'"
mapping['edit_menu.paste'] = "'Ctrl+V'"
mapping['edit_menu.redo'] = "'Ctrl+Y'"
mapping['edit_menu.undo'] = "'Ctrl+Z'"
mapping['edit_menu.delete'] = "'Del'"
# mapping['edit_menu.duplicate'] = "'Ctrl+B'"
mapping['edit_menu.mode_menu.move'] = "'M'"
mapping['edit_menu.mode_menu.ruler'] = "'R'"
mapping['edit_menu.mode_menu.select'] = "'S'"
mapping['edit_menu.mode_menu.box'] = "'B'"
mapping['edit_menu.mode_menu.instance'] = "'I'"
mapping['edit_menu.mode_menu.partial'] = "'L'"
mapping['edit_menu.mode_menu.path'] = "'P'"
mapping['edit_menu.mode_menu.polygon'] = "'G'"
mapping['edit_menu.mode_menu.text'] = "'X'"
mapping['edit_menu.select_menu.select_all'] = "'Shift+Ctrl+A'"
mapping['edit_menu.show_properties'] = "'Q'"
mapping['edit_menu.edit_options'] = "'E'"
mapping['edit_menu.selection_menu.change_layer'] = "'Shift+L'"
mapping['edit_menu.selection_menu.sel_flip_x'] = "'Shift+H'"
mapping['edit_menu.selection_menu.sel_flip_y'] = "'Shift+V'"
mapping['edit_menu.selection_menu.sel_move'] = "'Ctrl+M'"
mapping['edit_menu.selection_menu.sel_rot_ccw'] = "'Shift+R'"
mapping['edit_menu.selection_menu.sel_free_rot'] = "'Ctrl+Shift+R'"
mapping['edit_menu.selection_menu.flatten_insts'] = "'Ctrl+Shift+F'"
mapping['edit_menu.selection_menu.make_cell'] = "'Ctrl+Shift+M'"
# mapping['edit_menu.selection_menu.size'] = "'Z'"
# mapping['edit_menu.selection_menu.tap'] = "''"
mapping['file_menu.new_layout'] = "'Ctrl+N'"
mapping['file_menu.close'] = "'Ctrl+W'"
mapping['file_menu.open_new_panel'] = "'Ctrl+O'"
mapping['file_menu.open_same_panel'] = "'Ctrl+Shift+O'"
mapping['file_menu.save'] = "'Ctrl+S'"
mapping['file_menu.save_as'] = "'Ctrl+Shift+S'"
mapping['file_menu.screenshot'] = "'F12'"
# mapping['file_menu.setup'] = "'F4'"
mapping['macros_menu.macro_development'] = "'F5'"
mapping['zoom_menu.max_hier'] = "'Shift+F'"
mapping['zoom_menu.select_current_cell'] = "'Shift+S'" # Display > Show as new top
mapping['zoom_menu.zoom_fit'] = "'F'"
mapping['zoom_menu.zoom_fit_sel'] = "'Shift+F2'"
mapping['zoom_menu.zoom_in'] = "'Return'"
mapping['zoom_menu.zoom_out'] = "'Shift+Return'"
# turn the hash back into a config string
config = ''.join('{}:{};'.format(key, val) for key, val in sorted(mapping.items()))[:-1]
pya.Application.instance().set_config('key-bindings', config)
pya.Application.instance().set_config('edit-connect-angle-mode', 'ortho')
pya.Application.instance().set_config('edit-inst-angle', '0')
pya.Application.instance().set_config('edit-move-angle-mode', 'diagonal')
pya.Application.instance().set_config('edit-snap-to-objects', 'true')
pya.Application.instance().set_config('grid-micron', '0.01')
pya.Application.instance().set_config('edit-top-level-selection', 'true')
pya.Application.instance().set_config('inst-color', '#ffcdcd')
pya.Application.instance().set_config('text-font', '3')
pya.Application.instance().set_config('guiding-shape-line-width', '0')
pya.Application.instance().set_config('rdb-marker-color', '#ff0000')
pya.Application.instance().set_config('rdb-marker-line-width', '8')
# pya.Application.instance().set_config('default-layer-properties', os.path.join(os.path.realpath(__file__), os.pardir, os.pardir, os.pardir, 'libraries', 'klayout_Layers_EBeam.lyp'))
if pya.Application.instance().get_config('edit-mode') == 'false':
pya.Application.instance().set_config('edit-mode', 'true')
pya.MessageBox.warning(
"Restart", "Please restart KLayout. SiEPIC settings have been applied.", pya.MessageBox.Ok)
| registerKeyBindings |
encode_decode_json.py | ######################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# SPDX-License-Identifier: MIT-0 #
######################################################################
import json
import base64
def utf_encode_json(json_dict):
json_dict_str = json.dumps(json_dict)
json_dict_bytes = json_dict_str.encode('utf-8')
return json_dict_bytes
def utf_decode_json(json_dict_bytes):
json_dict_str = json_dict_bytes.decode('utf-8')
json_dict = json.loads(json_dict_str)
return json_dict
def base64_encode_json_fname(json_fname):
encoded_json_str = None
with open(json_fname, 'r') as fp:
json_dict = json.load(fp)
json_dict_str = json.dumps(json_dict, indent=2)
json_dict_bytes = json_dict_str.encode('utf-8')
encoded_json_bytestr = base64.b64encode(json_dict_bytes)
encoded_json_str = encoded_json_bytestr.decode('utf-8')
return encoded_json_str
def base64_decode_json(encoded_json_str):
|
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--json_fname', help='JSON File Name')
args = parser.parse_args()
# json_fname = 'config.json'
encoded_json_str = base64_encode_json_fname(args.json_fname)
env_file = 'local_env.sh'
with open(env_file, 'w') as fp:
fp.write('echo "Creating environment variables ENCODED_CONFIG_JSON"\n')
fp.write('export ENCODED_CONFIG_JSON=%s\n'%(encoded_json_str))
fp.close()
print('Exported: local_env.sh...')
# print('export ENCODED_CONFIG_JSON=%s'%(encoded_json_str))
# Simply test the inversion process
# json_dict = decode_json(encoded_json_str)
| json_decode_str = base64.b64decode(encoded_json_str)
json_dict = json.loads(json_decode_str)
return json_dict |
Float32Pile.dot.go | // Copyright 2017 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package IsFloat
// This file was generated with dotgo
// DO NOT EDIT - Improve the pattern!
// Note: originally inspired by parts of "cmd/doc/dirs.go"
// Float32Pile is a hybrid container for
// a lazily and concurrently populated growing-only slice
// of items (of type `float32`)
// which may be traversed in parallel to it's growth.
//
// Usage for a pile `p`:
// p := MakeFloat32Pile(128, 32)
//
// Have it grow concurrently using multiple:
// var item float32 = something
// p.Pile(item)
// in as many go routines as You may seem fit.
//
// In parallel, You may either
// traverse `p` in parallel right away:
// for item, ok := p.Iter(); ok; item, ok = p.Next() { ... do sth with item ... }
// Here p.Iter() starts a new transversal with the first item (if any), and
// p.Next() keeps traverses the Float32Pile.
//
// or traverse blocking / awaiting close first:
// for item := range <-p.Done() { ... do sth with item ... }
//
// or use the result when available:
// r, p := <-p.Done(), nil
// Hint: here we get the result in `r` and at the same time discard / deallocate / forget the pile `p` itself.
//
// Note: The traversal is *not* intended to be concurrency safe!
// Thus: You may call `Pile` concurrently to Your traversal, but use of
// either `Done` or `Iter` and `Next` *must* be confined to a single go routine (thread).
//
type Float32Pile struct {
pile chan float32 // channel to receive further items
list []float32 // list of known items
offset int // index for Next()
}
// MakeFloat32Pile returns a (pointer to a) fresh pile
// of items (of type `float32`)
// with size as initial capacity
// and
// with buff as initial leeway, allowing as many Pile's to execute non-blocking before respective Done or Next's.
func MakeFloat32Pile(size, buff int) *Float32Pile {
pile := new(Float32Pile)
pile.list = make([]float32, 0, size)
pile.pile = make(chan float32, buff)
return pile
}
// Pile appends an `float32` item to the Float32Pile.
//
// Note: Pile will block iff buff is exceeded and no Done() or Next()'s are used.
func (d *Float32Pile) Pile(item float32) {
d.pile <- item
}
// Close - call once when everything has been piled.
//
// Close intentionally implements io.Closer
//
// Note: After Close(),
// any Close(...) will panic
// and
// any Pile(...) will panic
// and
// any Done() or Next() will return immediately: no eventual blocking, that is.
func (d *Float32Pile) Close() (err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
panic(r)
}
}
}()
close(d.pile)
return nil
}
// Iter puts the pile iterator back to the beginning
// and returns the first `Next()`, iff any.
// Usage for a pile `p`:
// for item, ok := p.Iter(); ok; item, ok = p.Next() { ... do sth with item ... }
func (d *Float32Pile) Iter() (item float32, ok bool) {
d.offset = 0
return d.Next()
}
// Next returns the next item,
// or false iff the pile is exhausted.
//
// Note: Iff the pile is not closed yet,
// Next may block, awaiting some Pile().
func (d *Float32Pile) Next() (item float32, ok bool) {
if d.offset < len(d.list) | else if item, ok = <-d.pile; ok {
d.list = append(d.list, item)
d.offset++
}
return item, ok
}
// Done returns a channel which emits the result (as slice of Float32) once the pile is closed.
//
// Users of Done() *must not* iterate (via Iter() Next()...) before the done-channel is closed!
//
// Done is a convenience - useful iff You do not like/need to start any traversal before the pile is fully populated.
// Once the pile is closed, Done() will signal in constant time.
//
// Note: Upon signalling, the pile is reset to it's tip,
// so You may traverse it (via Next) right away.
// Usage for a pile `p`:
// Traverse blocking / awaiting close first:
// for item := range <-p.Done() { ... do sth with item ... }
// or use the result when available
// r, p := <-p.Done(), nil
// while discaring the pile itself.
func (d *Float32Pile) Done() (done <-chan []float32) {
cha := make(chan []float32)
go func(cha chan<- []float32, d *Float32Pile) {
defer close(cha)
d.offset = 0
if len(d.list) > d.offset {
// skip what's already known
d.offset = len(d.list) - 1
}
for _, ok := d.Next(); ok; _, ok = d.Next() {
// keep draining
}
d.offset = 0 // reset
cha <- d.list // signal the result, and terminate
}(cha, d)
return cha
}
| {
ok = true
item = d.list[d.offset]
d.offset++
} |
users.ts | import request from '@/utils/request'
const apipath = window.appConf?.api
//console.log(window.appConf)
export const getUserInfo = (data: any) =>
request({
url: apipath.userInfo,
method: 'get',
params:data
})
export const login = (data: any) =>
request({ | })
export const logout = () =>
request({
url: apipath.logout,
method: 'post'
})
export const getUserList = (data: any) =>
request({
url: apipath.userList,
method: 'get',
params:data
}) | url: apipath.login,
method: 'post',
data |
rfc.go | package sockaddr
// ForwardingBlacklist is a faux RFC that includes a list of non-forwardable IP
// blocks.
const (
ForwardingBlacklist = 4294967295
ForwardingBlacklistRFC = "4294967295"
)
// IsRFC tests to see if an SockAddr matches the specified RFC
func IsRFC(rfcNum uint, sa SockAddr) bool |
// KnownRFCs returns an initial set of known RFCs.
//
// NOTE (sean@): As this list evolves over time, please submit patches to keep
// this list current. If something isn't right, inquire, as it may just be a
// bug on my part. Some of the inclusions were based on my judgement as to what
// would be a useful value (e.g. RFC3330).
//
// Useful resources:
//
// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
// * https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml
// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
func KnownRFCs() map[uint]SockAddrs {
// NOTE(sean@): Multiple SockAddrs per RFC lend themselves well to a
// RADIX tree, but `ENOTIME`. Patches welcome.
return map[uint]SockAddrs{
919: {
// [RFC919] Broadcasting Internet Datagrams
MustIPv4Addr("255.255.255.255/32"), // [RFC1122], §7 Broadcast IP Addressing - Proposed Standards
},
1122: {
// [RFC1122] Requirements for Internet Hosts -- Communication Layers
MustIPv4Addr("0.0.0.0/8"), // [RFC1122], §3.2.1.3
MustIPv4Addr("127.0.0.0/8"), // [RFC1122], §3.2.1.3
},
1112: {
// [RFC1112] Host Extensions for IP Multicasting
MustIPv4Addr("224.0.0.0/4"), // [RFC1112], §4 Host Group Addresses
},
1918: {
// [RFC1918] Address Allocation for Private Internets
MustIPv4Addr("10.0.0.0/8"),
MustIPv4Addr("172.16.0.0/12"),
MustIPv4Addr("192.168.0.0/16"),
},
2544: {
// [RFC2544] Benchmarking Methodology for Network
// Interconnect Devices
MustIPv4Addr("198.18.0.0/15"),
},
2765: {
// [RFC2765] Stateless IP/ICMP Translation Algorithm
// (SIIT) (obsoleted by RFCs 6145, which itself was
// later obsoleted by 7915).
// [RFC2765], §2.1 Addresses
MustIPv6Addr("0:0:0:0:0:ffff:0:0/96"),
},
2928: {
// [RFC2928] Initial IPv6 Sub-TLA ID Assignments
MustIPv6Addr("2001::/16"), // Superblock
// MustIPv6Addr("2001:0000::/23"), // IANA
// MustIPv6Addr("2001:0200::/23"), // APNIC
// MustIPv6Addr("2001:0400::/23"), // ARIN
// MustIPv6Addr("2001:0600::/23"), // RIPE NCC
// MustIPv6Addr("2001:0800::/23"), // (future assignment)
// ...
// MustIPv6Addr("2001:FE00::/23"), // (future assignment)
},
3056: { // 6to4 address
// [RFC3056] Connection of IPv6 Domains via IPv4 Clouds
// [RFC3056], §2 IPv6 Prefix Allocation
MustIPv6Addr("2002::/16"),
},
3068: {
// [RFC3068] An Anycast Prefix for 6to4 Relay Routers
// (obsolete by RFC7526)
// [RFC3068], § 6to4 Relay anycast address
MustIPv4Addr("192.88.99.0/24"),
// [RFC3068], §2.5 6to4 IPv6 relay anycast address
//
// NOTE: /120 == 128-(32-24)
MustIPv6Addr("2002:c058:6301::/120"),
},
3171: {
// [RFC3171] IANA Guidelines for IPv4 Multicast Address Assignments
MustIPv4Addr("224.0.0.0/4"),
},
3330: {
// [RFC3330] Special-Use IPv4 Addresses
// Addresses in this block refer to source hosts on
// "this" network. Address 0.0.0.0/32 may be used as a
// source address for this host on this network; other
// addresses within 0.0.0.0/8 may be used to refer to
// specified hosts on this network [RFC1700, page 4].
MustIPv4Addr("0.0.0.0/8"),
// 10.0.0.0/8 - This block is set aside for use in
// private networks. Its intended use is documented in
// [RFC1918]. Addresses within this block should not
// appear on the public Internet.
MustIPv4Addr("10.0.0.0/8"),
// 14.0.0.0/8 - This block is set aside for assignments
// to the international system of Public Data Networks
// [RFC1700, page 181]. The registry of assignments
// within this block can be accessed from the "Public
// Data Network Numbers" link on the web page at
// http://www.iana.org/numbers.html. Addresses within
// this block are assigned to users and should be
// treated as such.
// 24.0.0.0/8 - This block was allocated in early 1996
// for use in provisioning IP service over cable
// television systems. Although the IANA initially was
// involved in making assignments to cable operators,
// this responsibility was transferred to American
// Registry for Internet Numbers (ARIN) in May 2001.
// Addresses within this block are assigned in the
// normal manner and should be treated as such.
// 39.0.0.0/8 - This block was used in the "Class A
// Subnet Experiment" that commenced in May 1995, as
// documented in [RFC1797]. The experiment has been
// completed and this block has been returned to the
// pool of addresses reserved for future allocation or
// assignment. This block therefore no longer has a
// special use and is subject to allocation to a
// Regional Internet Registry for assignment in the
// normal manner.
// 127.0.0.0/8 - This block is assigned for use as the Internet host
// loopback address. A datagram sent by a higher level protocol to an
// address anywhere within this block should loop back inside the host.
// This is ordinarily implemented using only 127.0.0.1/32 for loopback,
// but no addresses within this block should ever appear on any network
// anywhere [RFC1700, page 5].
MustIPv4Addr("127.0.0.0/8"),
// 128.0.0.0/16 - This block, corresponding to the
// numerically lowest of the former Class B addresses,
// was initially and is still reserved by the IANA.
// Given the present classless nature of the IP address
// space, the basis for the reservation no longer
// applies and addresses in this block are subject to
// future allocation to a Regional Internet Registry for
// assignment in the normal manner.
// 169.254.0.0/16 - This is the "link local" block. It
// is allocated for communication between hosts on a
// single link. Hosts obtain these addresses by
// auto-configuration, such as when a DHCP server may
// not be found.
MustIPv4Addr("169.254.0.0/16"),
// 172.16.0.0/12 - This block is set aside for use in
// private networks. Its intended use is documented in
// [RFC1918]. Addresses within this block should not
// appear on the public Internet.
MustIPv4Addr("172.16.0.0/12"),
// 191.255.0.0/16 - This block, corresponding to the numerically highest
// to the former Class B addresses, was initially and is still reserved
// by the IANA. Given the present classless nature of the IP address
// space, the basis for the reservation no longer applies and addresses
// in this block are subject to future allocation to a Regional Internet
// Registry for assignment in the normal manner.
// 192.0.0.0/24 - This block, corresponding to the
// numerically lowest of the former Class C addresses,
// was initially and is still reserved by the IANA.
// Given the present classless nature of the IP address
// space, the basis for the reservation no longer
// applies and addresses in this block are subject to
// future allocation to a Regional Internet Registry for
// assignment in the normal manner.
// 192.0.2.0/24 - This block is assigned as "TEST-NET" for use in
// documentation and example code. It is often used in conjunction with
// domain names example.com or example.net in vendor and protocol
// documentation. Addresses within this block should not appear on the
// public Internet.
MustIPv4Addr("192.0.2.0/24"),
// 192.88.99.0/24 - This block is allocated for use as 6to4 relay
// anycast addresses, according to [RFC3068].
MustIPv4Addr("192.88.99.0/24"),
// 192.168.0.0/16 - This block is set aside for use in private networks.
// Its intended use is documented in [RFC1918]. Addresses within this
// block should not appear on the public Internet.
MustIPv4Addr("192.168.0.0/16"),
// 198.18.0.0/15 - This block has been allocated for use
// in benchmark tests of network interconnect devices.
// Its use is documented in [RFC2544].
MustIPv4Addr("198.18.0.0/15"),
// 223.255.255.0/24 - This block, corresponding to the
// numerically highest of the former Class C addresses,
// was initially and is still reserved by the IANA.
// Given the present classless nature of the IP address
// space, the basis for the reservation no longer
// applies and addresses in this block are subject to
// future allocation to a Regional Internet Registry for
// assignment in the normal manner.
// 224.0.0.0/4 - This block, formerly known as the Class
// D address space, is allocated for use in IPv4
// multicast address assignments. The IANA guidelines
// for assignments from this space are described in
// [RFC3171].
MustIPv4Addr("224.0.0.0/4"),
// 240.0.0.0/4 - This block, formerly known as the Class E address
// space, is reserved. The "limited broadcast" destination address
// 255.255.255.255 should never be forwarded outside the (sub-)net of
// the source. The remainder of this space is reserved
// for future use. [RFC1700, page 4]
MustIPv4Addr("240.0.0.0/4"),
},
3849: {
// [RFC3849] IPv6 Address Prefix Reserved for Documentation
MustIPv6Addr("2001:db8::/32"), // [RFC3849], §4 IANA Considerations
},
3927: {
// [RFC3927] Dynamic Configuration of IPv4 Link-Local Addresses
MustIPv4Addr("169.254.0.0/16"), // [RFC3927], §2.1 Link-Local Address Selection
},
4038: {
// [RFC4038] Application Aspects of IPv6 Transition
// [RFC4038], §4.2. IPv6 Applications in a Dual-Stack Node
MustIPv6Addr("0:0:0:0:0:ffff::/96"),
},
4193: {
// [RFC4193] Unique Local IPv6 Unicast Addresses
MustIPv6Addr("fc00::/7"),
},
4291: {
// [RFC4291] IP Version 6 Addressing Architecture
// [RFC4291], §2.5.2 The Unspecified Address
MustIPv6Addr("::/128"),
// [RFC4291], §2.5.3 The Loopback Address
MustIPv6Addr("::1/128"),
// [RFC4291], §2.5.5.1. IPv4-Compatible IPv6 Address
MustIPv6Addr("::/96"),
// [RFC4291], §2.5.5.2. IPv4-Mapped IPv6 Address
MustIPv6Addr("::ffff:0:0/96"),
// [RFC4291], §2.5.6 Link-Local IPv6 Unicast Addresses
MustIPv6Addr("fe80::/10"),
// [RFC4291], §2.5.7 Site-Local IPv6 Unicast Addresses
// (depreciated)
MustIPv6Addr("fec0::/10"),
// [RFC4291], §2.7 Multicast Addresses
MustIPv6Addr("ff00::/8"),
// IPv6 Multicast Information.
//
// In the following "table" below, `ff0x` is replaced
// with the following values depending on the scope of
// the query:
//
// IPv6 Multicast Scopes:
// * ff00/9 // reserved
// * ff01/9 // interface-local
// * ff02/9 // link-local
// * ff03/9 // realm-local
// * ff04/9 // admin-local
// * ff05/9 // site-local
// * ff08/9 // organization-local
// * ff0e/9 // global
// * ff0f/9 // reserved
//
// IPv6 Multicast Addresses:
// * ff0x::2 // All routers
// * ff02::5 // OSPFIGP
// * ff02::6 // OSPFIGP Designated Routers
// * ff02::9 // RIP Routers
// * ff02::a // EIGRP Routers
// * ff02::d // All PIM Routers
// * ff02::1a // All RPL Routers
// * ff0x::fb // mDNSv6
// * ff0x::101 // All Network Time Protocol (NTP) servers
// * ff02::1:1 // Link Name
// * ff02::1:2 // All-dhcp-agents
// * ff02::1:3 // Link-local Multicast Name Resolution
// * ff05::1:3 // All-dhcp-servers
// * ff02::1:ff00:0/104 // Solicited-node multicast address.
// * ff02::2:ff00:0/104 // Node Information Queries
},
4380: {
// [RFC4380] Teredo: Tunneling IPv6 over UDP through
// Network Address Translations (NATs)
// [RFC4380], §2.6 Global Teredo IPv6 Service Prefix
MustIPv6Addr("2001:0000::/32"),
},
4773: {
// [RFC4773] Administration of the IANA Special Purpose IPv6 Address Block
MustIPv6Addr("2001:0000::/23"), // IANA
},
4843: {
// [RFC4843] An IPv6 Prefix for Overlay Routable Cryptographic Hash Identifiers (ORCHID)
MustIPv6Addr("2001:10::/28"), // [RFC4843], §7 IANA Considerations
},
5180: {
// [RFC5180] IPv6 Benchmarking Methodology for Network Interconnect Devices
MustIPv6Addr("2001:0200::/48"), // [RFC5180], §8 IANA Considerations
},
5735: {
// [RFC5735] Special Use IPv4 Addresses
MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1
MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2
MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3
MustIPv4Addr("198.18.0.0/15"), // Benchmarks
},
5737: {
// [RFC5737] IPv4 Address Blocks Reserved for Documentation
MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1
MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2
MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3
},
6052: {
// [RFC6052] IPv6 Addressing of IPv4/IPv6 Translators
MustIPv6Addr("64:ff9b::/96"), // [RFC6052], §2.1. Well-Known Prefix
},
6333: {
// [RFC6333] Dual-Stack Lite Broadband Deployments Following IPv4 Exhaustion
MustIPv4Addr("192.0.0.0/29"), // [RFC6333], §5.7 Well-Known IPv4 Address
},
6598: {
// [RFC6598] IANA-Reserved IPv4 Prefix for Shared Address Space
MustIPv4Addr("100.64.0.0/10"),
},
6666: {
// [RFC6666] A Discard Prefix for IPv6
MustIPv6Addr("0100::/64"),
},
6890: {
// [RFC6890] Special-Purpose IP Address Registries
// From "RFC6890 §2.2.1 Information Requirements":
/*
The IPv4 and IPv6 Special-Purpose Address Registries maintain the
following information regarding each entry:
o Address Block - A block of IPv4 or IPv6 addresses that has been
registered for a special purpose.
o Name - A descriptive name for the special-purpose address block.
o RFC - The RFC through which the special-purpose address block was
requested.
o Allocation Date - The date upon which the special-purpose address
block was allocated.
o Termination Date - The date upon which the allocation is to be
terminated. This field is applicable for limited-use allocations
only.
o Source - A boolean value indicating whether an address from the
allocated special-purpose address block is valid when used as the
source address of an IP datagram that transits two devices.
o Destination - A boolean value indicating whether an address from
the allocated special-purpose address block is valid when used as
the destination address of an IP datagram that transits two
devices.
o Forwardable - A boolean value indicating whether a router may
forward an IP datagram whose destination address is drawn from the
allocated special-purpose address block between external
interfaces.
o Global - A boolean value indicating whether an IP datagram whose
destination address is drawn from the allocated special-purpose
address block is forwardable beyond a specified administrative
domain.
o Reserved-by-Protocol - A boolean value indicating whether the
special-purpose address block is reserved by IP, itself. This
value is "TRUE" if the RFC that created the special-purpose
address block requires all compliant IP implementations to behave
in a special way when processing packets either to or from
addresses contained by the address block.
If the value of "Destination" is FALSE, the values of "Forwardable"
and "Global" must also be false.
*/
/*+----------------------+----------------------------+
* | Attribute | Value |
* +----------------------+----------------------------+
* | Address Block | 0.0.0.0/8 |
* | Name | "This host on this network"|
* | RFC | [RFC1122], Section 3.2.1.3 |
* | Allocation Date | September 1981 |
* | Termination Date | N/A |
* | Source | True |
* | Destination | False |
* | Forwardable | False |
* | Global | False |
* | Reserved-by-Protocol | True |
* +----------------------+----------------------------+*/
MustIPv4Addr("0.0.0.0/8"),
/*+----------------------+---------------+
* | Attribute | Value |
* +----------------------+---------------+
* | Address Block | 10.0.0.0/8 |
* | Name | Private-Use |
* | RFC | [RFC1918] |
* | Allocation Date | February 1996 |
* | Termination Date | N/A |
* | Source | True |
* | Destination | True |
* | Forwardable | True |
* | Global | False |
* | Reserved-by-Protocol | False |
* +----------------------+---------------+ */
MustIPv4Addr("10.0.0.0/8"),
/*+----------------------+----------------------+
| Attribute | Value |
+----------------------+----------------------+
| Address Block | 100.64.0.0/10 |
| Name | Shared Address Space |
| RFC | [RFC6598] |
| Allocation Date | April 2012 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------+*/
MustIPv4Addr("100.64.0.0/10"),
/*+----------------------+----------------------------+
| Attribute | Value |
+----------------------+----------------------------+
| Address Block | 127.0.0.0/8 |
| Name | Loopback |
| RFC | [RFC1122], Section 3.2.1.3 |
| Allocation Date | September 1981 |
| Termination Date | N/A |
| Source | False [1] |
| Destination | False [1] |
| Forwardable | False [1] |
| Global | False [1] |
| Reserved-by-Protocol | True |
+----------------------+----------------------------+*/
// [1] Several protocols have been granted exceptions to
// this rule. For examples, see [RFC4379] and
// [RFC5884].
MustIPv4Addr("127.0.0.0/8"),
/*+----------------------+----------------+
| Attribute | Value |
+----------------------+----------------+
| Address Block | 169.254.0.0/16 |
| Name | Link Local |
| RFC | [RFC3927] |
| Allocation Date | May 2005 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+----------------+*/
MustIPv4Addr("169.254.0.0/16"),
/*+----------------------+---------------+
| Attribute | Value |
+----------------------+---------------+
| Address Block | 172.16.0.0/12 |
| Name | Private-Use |
| RFC | [RFC1918] |
| Allocation Date | February 1996 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+---------------+*/
MustIPv4Addr("172.16.0.0/12"),
/*+----------------------+---------------------------------+
| Attribute | Value |
+----------------------+---------------------------------+
| Address Block | 192.0.0.0/24 [2] |
| Name | IETF Protocol Assignments |
| RFC | Section 2.1 of this document |
| Allocation Date | January 2010 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+---------------------------------+*/
// [2] Not usable unless by virtue of a more specific
// reservation.
MustIPv4Addr("192.0.0.0/24"),
/*+----------------------+--------------------------------+
| Attribute | Value |
+----------------------+--------------------------------+
| Address Block | 192.0.0.0/29 |
| Name | IPv4 Service Continuity Prefix |
| RFC | [RFC6333], [RFC7335] |
| Allocation Date | June 2011 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+--------------------------------+*/
MustIPv4Addr("192.0.0.0/29"),
/*+----------------------+----------------------------+
| Attribute | Value |
+----------------------+----------------------------+
| Address Block | 192.0.2.0/24 |
| Name | Documentation (TEST-NET-1) |
| RFC | [RFC5737] |
| Allocation Date | January 2010 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------------+*/
MustIPv4Addr("192.0.2.0/24"),
/*+----------------------+--------------------+
| Attribute | Value |
+----------------------+--------------------+
| Address Block | 192.88.99.0/24 |
| Name | 6to4 Relay Anycast |
| RFC | [RFC3068] |
| Allocation Date | June 2001 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | True |
| Reserved-by-Protocol | False |
+----------------------+--------------------+*/
MustIPv4Addr("192.88.99.0/24"),
/*+----------------------+----------------+
| Attribute | Value |
+----------------------+----------------+
| Address Block | 192.168.0.0/16 |
| Name | Private-Use |
| RFC | [RFC1918] |
| Allocation Date | February 1996 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------+*/
MustIPv4Addr("192.168.0.0/16"),
/*+----------------------+---------------+
| Attribute | Value |
+----------------------+---------------+
| Address Block | 198.18.0.0/15 |
| Name | Benchmarking |
| RFC | [RFC2544] |
| Allocation Date | March 1999 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+---------------+*/
MustIPv4Addr("198.18.0.0/15"),
/*+----------------------+----------------------------+
| Attribute | Value |
+----------------------+----------------------------+
| Address Block | 198.51.100.0/24 |
| Name | Documentation (TEST-NET-2) |
| RFC | [RFC5737] |
| Allocation Date | January 2010 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------------+*/
MustIPv4Addr("198.51.100.0/24"),
/*+----------------------+----------------------------+
| Attribute | Value |
+----------------------+----------------------------+
| Address Block | 203.0.113.0/24 |
| Name | Documentation (TEST-NET-3) |
| RFC | [RFC5737] |
| Allocation Date | January 2010 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------------+*/
MustIPv4Addr("203.0.113.0/24"),
/*+----------------------+----------------------+
| Attribute | Value |
+----------------------+----------------------+
| Address Block | 240.0.0.0/4 |
| Name | Reserved |
| RFC | [RFC1112], Section 4 |
| Allocation Date | August 1989 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+----------------------+*/
MustIPv4Addr("240.0.0.0/4"),
/*+----------------------+----------------------+
| Attribute | Value |
+----------------------+----------------------+
| Address Block | 255.255.255.255/32 |
| Name | Limited Broadcast |
| RFC | [RFC0919], Section 7 |
| Allocation Date | October 1984 |
| Termination Date | N/A |
| Source | False |
| Destination | True |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------+*/
MustIPv4Addr("255.255.255.255/32"),
/*+----------------------+------------------+
| Attribute | Value |
+----------------------+------------------+
| Address Block | ::1/128 |
| Name | Loopback Address |
| RFC | [RFC4291] |
| Allocation Date | February 2006 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+------------------+*/
MustIPv6Addr("::1/128"),
/*+----------------------+---------------------+
| Attribute | Value |
+----------------------+---------------------+
| Address Block | ::/128 |
| Name | Unspecified Address |
| RFC | [RFC4291] |
| Allocation Date | February 2006 |
| Termination Date | N/A |
| Source | True |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+---------------------+*/
MustIPv6Addr("::/128"),
/*+----------------------+---------------------+
| Attribute | Value |
+----------------------+---------------------+
| Address Block | 64:ff9b::/96 |
| Name | IPv4-IPv6 Translat. |
| RFC | [RFC6052] |
| Allocation Date | October 2010 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | True |
| Reserved-by-Protocol | False |
+----------------------+---------------------+*/
MustIPv6Addr("64:ff9b::/96"),
/*+----------------------+---------------------+
| Attribute | Value |
+----------------------+---------------------+
| Address Block | ::ffff:0:0/96 |
| Name | IPv4-mapped Address |
| RFC | [RFC4291] |
| Allocation Date | February 2006 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+---------------------+*/
MustIPv6Addr("::ffff:0:0/96"),
/*+----------------------+----------------------------+
| Attribute | Value |
+----------------------+----------------------------+
| Address Block | 100::/64 |
| Name | Discard-Only Address Block |
| RFC | [RFC6666] |
| Allocation Date | June 2012 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------------------+*/
MustIPv6Addr("100::/64"),
/*+----------------------+---------------------------+
| Attribute | Value |
+----------------------+---------------------------+
| Address Block | 2001::/23 |
| Name | IETF Protocol Assignments |
| RFC | [RFC2928] |
| Allocation Date | September 2000 |
| Termination Date | N/A |
| Source | False[1] |
| Destination | False[1] |
| Forwardable | False[1] |
| Global | False[1] |
| Reserved-by-Protocol | False |
+----------------------+---------------------------+*/
// [1] Unless allowed by a more specific allocation.
MustIPv6Addr("2001::/16"),
/*+----------------------+----------------+
| Attribute | Value |
+----------------------+----------------+
| Address Block | 2001::/32 |
| Name | TEREDO |
| RFC | [RFC4380] |
| Allocation Date | January 2006 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------+*/
// Covered by previous entry, included for completeness.
//
// MustIPv6Addr("2001::/16"),
/*+----------------------+----------------+
| Attribute | Value |
+----------------------+----------------+
| Address Block | 2001:2::/48 |
| Name | Benchmarking |
| RFC | [RFC5180] |
| Allocation Date | April 2008 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+----------------+*/
// Covered by previous entry, included for completeness.
//
// MustIPv6Addr("2001:2::/48"),
/*+----------------------+---------------+
| Attribute | Value |
+----------------------+---------------+
| Address Block | 2001:db8::/32 |
| Name | Documentation |
| RFC | [RFC3849] |
| Allocation Date | July 2004 |
| Termination Date | N/A |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+---------------+*/
// Covered by previous entry, included for completeness.
//
// MustIPv6Addr("2001:db8::/32"),
/*+----------------------+--------------+
| Attribute | Value |
+----------------------+--------------+
| Address Block | 2001:10::/28 |
| Name | ORCHID |
| RFC | [RFC4843] |
| Allocation Date | March 2007 |
| Termination Date | March 2014 |
| Source | False |
| Destination | False |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+--------------+*/
// Covered by previous entry, included for completeness.
//
// MustIPv6Addr("2001:10::/28"),
/*+----------------------+---------------+
| Attribute | Value |
+----------------------+---------------+
| Address Block | 2002::/16 [2] |
| Name | 6to4 |
| RFC | [RFC3056] |
| Allocation Date | February 2001 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | N/A [2] |
| Reserved-by-Protocol | False |
+----------------------+---------------+*/
// [2] See [RFC3056] for details.
MustIPv6Addr("2002::/16"),
/*+----------------------+--------------+
| Attribute | Value |
+----------------------+--------------+
| Address Block | fc00::/7 |
| Name | Unique-Local |
| RFC | [RFC4193] |
| Allocation Date | October 2005 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | True |
| Global | False |
| Reserved-by-Protocol | False |
+----------------------+--------------+*/
MustIPv6Addr("fc00::/7"),
/*+----------------------+-----------------------+
| Attribute | Value |
+----------------------+-----------------------+
| Address Block | fe80::/10 |
| Name | Linked-Scoped Unicast |
| RFC | [RFC4291] |
| Allocation Date | February 2006 |
| Termination Date | N/A |
| Source | True |
| Destination | True |
| Forwardable | False |
| Global | False |
| Reserved-by-Protocol | True |
+----------------------+-----------------------+*/
MustIPv6Addr("fe80::/10"),
},
7335: {
// [RFC7335] IPv4 Service Continuity Prefix
MustIPv4Addr("192.0.0.0/29"), // [RFC7335], §6 IANA Considerations
},
ForwardingBlacklist: { // Pseudo-RFC
// Blacklist of non-forwardable IP blocks taken from RFC6890
//
// TODO: the attributes for forwardable should be
// searcahble and embedded in the main list of RFCs
// above.
MustIPv4Addr("0.0.0.0/8"),
MustIPv4Addr("127.0.0.0/8"),
MustIPv4Addr("169.254.0.0/16"),
MustIPv4Addr("192.0.0.0/24"),
MustIPv4Addr("192.0.2.0/24"),
MustIPv4Addr("198.51.100.0/24"),
MustIPv4Addr("203.0.113.0/24"),
MustIPv4Addr("240.0.0.0/4"),
MustIPv4Addr("255.255.255.255/32"),
MustIPv6Addr("::1/128"),
MustIPv6Addr("::/128"),
MustIPv6Addr("::ffff:0:0/96"),
// There is no way of expressing a whitelist per RFC2928
// atm without creating a negative mask, which I don't
// want to do atm.
// MustIPv6Addr("2001::/23"),
MustIPv6Addr("2001:db8::/32"),
MustIPv6Addr("2001:10::/28"),
MustIPv6Addr("fe80::/10"),
},
}
}
// VisitAllRFCs iterates over all known RFCs and calls the visitor
func VisitAllRFCs(fn func(rfcNum uint, sockaddrs SockAddrs)) {
rfcNetMap := KnownRFCs()
// Blacklist of faux-RFCs. Don't show the world that we're abusing the
// RFC system in this library.
rfcBlacklist := map[uint]struct{}{
ForwardingBlacklist: {},
}
for rfcNum, sas := range rfcNetMap {
if _, found := rfcBlacklist[rfcNum]; !found {
fn(rfcNum, sas)
}
}
}
| {
rfcNetMap := KnownRFCs()
rfcNets, ok := rfcNetMap[rfcNum]
if !ok {
return false
}
var contained bool
for _, rfcNet := range rfcNets {
if rfcNet.Contains(sa) {
contained = true
break
}
}
return contained
} |
test_scheduler.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<[email protected]>
# http://binux.me
# Created on 2014-02-08 22:37:13
import os
import time
import shutil
import unittest2 as unittest
import logging
import logging.config
logging.config.fileConfig("pyspider/logging.conf")
from pyspider.scheduler.task_queue import TaskQueue
class TestTaskQueue(unittest.TestCase):
@classmethod
def setUpClass(self):
self.task_queue = TaskQueue()
self.task_queue.rate = 100000
self.task_queue.burst = 100000
self.task_queue.processing_timeout = 0.5
def test_10_put(self):
self.task_queue.put('a3', 0, time.time() + 0.5)
self.task_queue.put('a4', 3, time.time() + 0.2)
self.task_queue.put('a2', 0)
self.task_queue.put('a1', 1)
self.assertEqual(self.task_queue.size(), 4)
def test_20_update(self):
self.task_queue.put('a2', 4)
self.assertEqual(self.task_queue.size(), 4)
self.task_queue.put('a3', 2, 0)
self.assertEqual(self.task_queue.size(), 4)
def test_30_get_from_priority_queue(self):
self.assertEqual(self.task_queue.get(), 'a2')
self.assertEqual(self.task_queue.size(), 4)
def test_40_time_queue_1(self):
self.task_queue.check_update()
self.assertEqual(self.task_queue.get(), 'a3')
self.assertEqual(self.task_queue.size(), 4)
def test_50_time_queue_2(self):
time.sleep(0.3)
self.task_queue.check_update()
self.assertEqual(self.task_queue.get(), 'a4')
self.assertEqual(self.task_queue.get(), 'a1')
self.assertEqual(self.task_queue.size(), 4)
def test_60_processing_queue(self):
time.sleep(0.5)
self.task_queue.check_update()
self.assertEqual(self.task_queue.get(), 'a2')
self.assertEqual(len(self.task_queue), 4)
self.assertEqual(self.task_queue.get(), 'a4')
self.assertEqual(self.task_queue.get(), 'a3')
self.assertEqual(self.task_queue.get(), 'a1')
self.assertEqual(len(self.task_queue), 4)
def test_70_done(self):
self.assertTrue(self.task_queue.done('a2'))
self.assertTrue(self.task_queue.done('a1'))
self.assertEqual(len(self.task_queue), 2)
self.assertTrue(self.task_queue.done('a4'))
self.assertTrue(self.task_queue.done('a3'))
self.assertEqual(len(self.task_queue), 0)
from pyspider.scheduler.token_bucket import Bucket
class TestBucket(unittest.TestCase):
def test_bucket(self):
bucket = Bucket(100, 1000)
self.assertEqual(bucket.get(), 1000)
time.sleep(0.1)
self.assertEqual(bucket.get(), 1000)
bucket.desc(100)
self.assertEqual(bucket.get(), 900)
time.sleep(0.1)
self.assertAlmostEqual(bucket.get(), 910, delta=2)
time.sleep(0.1)
self.assertAlmostEqual(bucket.get(), 920, delta=2)
try:
from six.moves import xmlrpc_client
except ImportError:
import xmlrpclib as xmlrpc_client
from pyspider.scheduler.scheduler import Scheduler
from pyspider.database.sqlite import taskdb, projectdb, resultdb
from pyspider.libs.multiprocessing_queue import Queue
from pyspider.libs.utils import run_in_thread
class TestScheduler(unittest.TestCase):
taskdb_path = './data/tests/task.db'
projectdb_path = './data/tests/project.db'
resultdb_path = './data/tests/result.db' | check_project_time = 1
scheduler_xmlrpc_port = 23333
@classmethod
def setUpClass(self):
shutil.rmtree('./data/tests', ignore_errors=True)
os.makedirs('./data/tests')
def get_taskdb():
return taskdb.TaskDB(self.taskdb_path)
self.taskdb = get_taskdb()
def get_projectdb():
return projectdb.ProjectDB(self.projectdb_path)
self.projectdb = get_projectdb()
def get_resultdb():
return resultdb.ResultDB(self.resultdb_path)
self.resultdb = get_resultdb()
self.newtask_queue = Queue(10)
self.status_queue = Queue(10)
self.scheduler2fetcher = Queue(10)
self.rpc = xmlrpc_client.ServerProxy('http://localhost:%d' % self.scheduler_xmlrpc_port)
def run_scheduler():
scheduler = Scheduler(taskdb=get_taskdb(), projectdb=get_projectdb(),
newtask_queue=self.newtask_queue, status_queue=self.status_queue,
out_queue=self.scheduler2fetcher, data_path="./data/tests/",
resultdb=get_resultdb())
scheduler.UPDATE_PROJECT_INTERVAL = 0.1
scheduler.LOOP_INTERVAL = 0.1
scheduler.INQUEUE_LIMIT = 10
scheduler.DELETE_TIME = 0
scheduler.DEFAULT_RETRY_DELAY = {'': 5}
scheduler._last_tick = int(time.time()) # not dispatch cronjob
run_in_thread(scheduler.xmlrpc_run, port=self.scheduler_xmlrpc_port)
scheduler.run()
self.process = run_in_thread(run_scheduler)
time.sleep(1)
@classmethod
def tearDownClass(self):
if self.process.is_alive():
self.rpc._quit()
self.process.join(5)
assert not self.process.is_alive()
shutil.rmtree('./data/tests', ignore_errors=True)
time.sleep(1)
def test_10_new_task_ignore(self):
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url'
})
self.assertEqual(self.rpc.size(), 0)
self.assertEqual(len(self.rpc.get_active_tasks()), 0)
def test_20_new_project(self):
self.projectdb.insert('test_project', {
'name': 'test_project',
'group': 'group',
'status': 'TODO',
'script': 'import time\nprint(time.time())',
'comments': 'test project',
'rate': 1.0,
'burst': 10,
})
def test_30_update_project(self):
from six.moves import queue as Queue
with self.assertRaises(Queue.Empty):
task = self.scheduler2fetcher.get(timeout=1)
self.projectdb.update('test_project', status="DEBUG")
time.sleep(0.1)
self.rpc.update_project()
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
self.assertEqual(task['url'], 'data:,_on_get_info')
def test_34_new_not_used_project(self):
self.projectdb.insert('test_project_not_started', {
'name': 'test_project_not_started',
'group': 'group',
'status': 'RUNNING',
'script': 'import time\nprint(time.time())',
'comments': 'test project',
'rate': 1.0,
'burst': 10,
})
task = self.scheduler2fetcher.get(timeout=1)
self.assertEqual(task['taskid'], '_on_get_info')
def test_35_new_task(self):
time.sleep(0.2)
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'age': 0,
},
})
time.sleep(0.5)
task = self.scheduler2fetcher.get(timeout=10)
self.assertGreater(len(self.rpc.get_active_tasks()), 0)
self.assertIsNotNone(task)
self.assertEqual(task['project'], 'test_project')
self.assertIn('schedule', task)
self.assertIn('fetch', task)
self.assertIn('process', task)
self.assertIn('track', task)
self.assertEqual(task['fetch']['data'], 'abc')
def test_37_force_update_processing_task(self):
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url_force_update',
'schedule': {
'age': 10,
'force_update': True,
},
})
time.sleep(0.2)
# it should not block next
def test_40_taskdone_error_no_project(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'no_project',
'url': 'url'
})
time.sleep(0.1)
self.assertEqual(self.rpc.size(), 1)
def test_50_taskdone_error_no_track(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url'
})
time.sleep(0.1)
self.assertEqual(self.rpc.size(), 1)
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'track': {}
})
time.sleep(0.1)
self.assertEqual(self.rpc.size(), 1)
def test_60_taskdone_failed_retry(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': False
},
}
})
from six.moves import queue as Queue
with self.assertRaises(Queue.Empty):
task = self.scheduler2fetcher.get(timeout=4)
task = self.scheduler2fetcher.get(timeout=5)
self.assertIsNotNone(task)
def test_70_taskdone_ok(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': True
},
}
})
time.sleep(0.2)
self.assertEqual(self.rpc.size(), 0)
def test_80_newtask_age_ignore(self):
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'age': 30,
},
})
time.sleep(0.1)
self.assertEqual(self.rpc.size(), 0)
def test_82_newtask_via_rpc(self):
self.rpc.newtask({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'age': 30,
},
})
time.sleep(0.1)
self.assertEqual(self.rpc.size(), 0)
def test_90_newtask_with_itag(self):
time.sleep(0.1)
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'itag': "abc",
'retries': 1
},
})
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
self.test_70_taskdone_ok()
def test_a10_newtask_restart_by_age(self):
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'age': 0,
'retries': 1
},
})
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
def test_a20_failed_retry(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': False
},
}
})
task = self.scheduler2fetcher.get(timeout=5)
self.assertIsNotNone(task)
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'track': {
'fetch': {
'ok': False
},
'process': {
'ok': False
},
}
})
from six.moves import queue as Queue
with self.assertRaises(Queue.Empty):
self.scheduler2fetcher.get(timeout=5)
def test_a30_task_verify(self):
self.assertFalse(self.rpc.newtask({
#'taskid': 'taskid#',
'project': 'test_project',
'url': 'url',
}))
self.assertFalse(self.rpc.newtask({
'taskid': 'taskid#',
#'project': 'test_project',
'url': 'url',
}))
self.assertFalse(self.rpc.newtask({
'taskid': 'taskid#',
'project': 'test_project',
#'url': 'url',
}))
self.assertFalse(self.rpc.newtask({
'taskid': 'taskid#',
'project': 'not_exist_project',
'url': 'url',
}))
self.assertTrue(self.rpc.newtask({
'taskid': 'taskid#',
'project': 'test_project',
'url': 'url',
}))
def test_a40_success_recrawl(self):
self.newtask_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'fetch': {
'data': 'abc',
},
'process': {
'data': 'abc',
},
'schedule': {
'age': 0,
'retries': 1,
'auto_recrawl': True,
},
})
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'schedule': {
'age': 0,
'retries': 1,
'auto_recrawl': True,
},
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': True
},
}
})
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
def test_a50_failed_recrawl(self):
for i in range(3):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'schedule': {
'age': 0,
'retries': 1,
'auto_recrawl': True,
},
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': False
},
}
})
task = self.scheduler2fetcher.get(timeout=10)
self.assertIsNotNone(task)
def test_a60_disable_recrawl(self):
self.status_queue.put({
'taskid': 'taskid',
'project': 'test_project',
'url': 'url',
'schedule': {
'age': 0,
'retries': 1,
},
'track': {
'fetch': {
'ok': True
},
'process': {
'ok': True
},
}
})
from six.moves import queue as Queue
with self.assertRaises(Queue.Empty):
self.scheduler2fetcher.get(timeout=5)
def test_x10_inqueue_limit(self):
self.projectdb.insert('test_inqueue_project', {
'name': 'test_inqueue_project',
'group': 'group',
'status': 'DEBUG',
'script': 'import time\nprint(time.time())',
'comments': 'test project',
'rate': 0,
'burst': 0,
})
time.sleep(0.1)
pre_size = self.rpc.size()
for i in range(20):
self.newtask_queue.put({
'taskid': 'taskid%d' % i,
'project': 'test_inqueue_project',
'url': 'url',
'schedule': {
'age': 3000,
'force_update': True,
},
})
time.sleep(1)
self.assertEqual(self.rpc.size() - pre_size, 10)
def test_x20_delete_project(self):
self.assertIsNotNone(self.projectdb.get('test_inqueue_project'))
#self.assertIsNotNone(self.taskdb.get_task('test_inqueue_project', 'taskid1'))
self.projectdb.update('test_inqueue_project', status="STOP", group="lock,delete")
time.sleep(1)
self.assertIsNone(self.projectdb.get('test_inqueue_project'))
self.taskdb._list_project()
self.assertIsNone(self.taskdb.get_task('test_inqueue_project', 'taskid1'))
def test_z10_startup(self):
self.assertTrue(self.process.is_alive())
def test_z20_quit(self):
self.rpc._quit()
time.sleep(0.2)
self.assertFalse(self.process.is_alive())
self.assertEqual(
self.taskdb.get_task('test_project', 'taskid')['status'],
self.taskdb.SUCCESS
)
if __name__ == '__main__':
unittest.main() | |
test_data_context_v013.py | import datetime
import os
import re
import pandas as pd
import pytest
from ruamel.yaml import YAML
from great_expectations import DataContext
from great_expectations.core import ExpectationSuite
from great_expectations.core.batch import Batch, RuntimeBatchRequest
from great_expectations.data_context import BaseDataContext
from great_expectations.data_context.types.base import DataContextConfig
from great_expectations.exceptions import BatchSpecError
from great_expectations.execution_engine.pandas_batch_data import PandasBatchData
from great_expectations.execution_engine.sqlalchemy_batch_data import (
SqlAlchemyBatchData,
)
from great_expectations.validator.validator import Validator
from tests.integration.usage_statistics.test_integration_usage_statistics import (
USAGE_STATISTICS_QA_URL,
)
from tests.test_utils import create_files_in_directory, get_sqlite_temp_table_names
yaml = YAML()
@pytest.fixture
def basic_data_context_v013_config():
return DataContextConfig(
**{
"commented_map": {},
"config_version": 3,
"plugins_directory": "plugins/",
"evaluation_parameter_store_name": "evaluation_parameter_store",
"validations_store_name": "does_not_have_to_be_real",
"expectations_store_name": "expectations_store",
"checkpoint_store_name": "checkpoint_store",
"config_variables_file_path": "uncommitted/config_variables.yml",
"datasources": {},
"stores": {
"expectations_store": {
"class_name": "ExpectationsStore",
"store_backend": {
"class_name": "TupleFilesystemStoreBackend",
"base_directory": "expectations/",
},
},
"evaluation_parameter_store": {
"module_name": "great_expectations.data_context.store",
"class_name": "EvaluationParameterStore",
},
"checkpoint_store": {
"class_name": "CheckpointStore",
"store_backend": {
"class_name": "TupleFilesystemStoreBackend",
"base_directory": "checkpoints/",
},
},
},
"data_docs_sites": {},
"anonymous_usage_statistics": {
"enabled": True,
"data_context_id": "6a52bdfa-e182-455b-a825-e69f076e67d6",
"usage_statistics_url": USAGE_STATISTICS_QA_URL,
},
}
)
def test_ConfigOnlyDataContext_v013__initialization(
tmp_path_factory, basic_data_context_v013_config
):
config_path = str(
tmp_path_factory.mktemp("test_ConfigOnlyDataContext__initialization__dir")
)
context = BaseDataContext(
basic_data_context_v013_config,
config_path,
)
assert len(context.plugins_directory.split("/")[-3:]) == 3
assert "" in context.plugins_directory.split("/")[-3:]
pattern = re.compile(r"test_ConfigOnlyDataContext__initialization__dir\d*")
assert (
len(
list(
filter(
lambda element: element,
sorted(
[
pattern.match(element) is not None
for element in context.plugins_directory.split("/")[-3:]
]
),
)
)
)
== 1
)
def test__normalize_absolute_or_relative_path(
tmp_path_factory, basic_data_context_v013_config
):
config_path = str(
tmp_path_factory.mktemp("test__normalize_absolute_or_relative_path__dir")
)
context = BaseDataContext(
basic_data_context_v013_config,
config_path,
)
pattern_string = os.path.join(
"^.*test__normalize_absolute_or_relative_path__dir\\d*", "yikes$"
)
pattern = re.compile(pattern_string)
assert (
pattern.match(context._normalize_absolute_or_relative_path("yikes")) is not None
)
assert (
"test__normalize_absolute_or_relative_path__dir"
not in context._normalize_absolute_or_relative_path("/yikes")
)
assert "/yikes" == context._normalize_absolute_or_relative_path("/yikes")
def test_load_config_variables_file(
basic_data_context_v013_config, tmp_path_factory, monkeypatch
):
# Setup:
base_path = str(tmp_path_factory.mktemp("test_load_config_variables_file"))
os.makedirs(os.path.join(base_path, "uncommitted"), exist_ok=True)
with open(
os.path.join(base_path, "uncommitted", "dev_variables.yml"), "w"
) as outfile:
yaml.dump({"env": "dev"}, outfile)
with open(
os.path.join(base_path, "uncommitted", "prod_variables.yml"), "w"
) as outfile:
yaml.dump({"env": "prod"}, outfile)
basic_data_context_v013_config[
"config_variables_file_path"
] = "uncommitted/${TEST_CONFIG_FILE_ENV}_variables.yml"
try:
# We should be able to load different files based on an environment variable
monkeypatch.setenv("TEST_CONFIG_FILE_ENV", "dev")
context = BaseDataContext(
basic_data_context_v013_config, context_root_dir=base_path
)
config_vars = context._load_config_variables_file()
assert config_vars["env"] == "dev"
monkeypatch.setenv("TEST_CONFIG_FILE_ENV", "prod")
context = BaseDataContext(
basic_data_context_v013_config, context_root_dir=base_path
)
config_vars = context._load_config_variables_file()
assert config_vars["env"] == "prod"
except Exception:
raise
finally:
# Make sure we unset the environment variable we're using
monkeypatch.delenv("TEST_CONFIG_FILE_ENV")
def test_get_config(empty_data_context):
context = empty_data_context
# We can call get_config in several different modes
assert type(context.get_config()) == DataContextConfig
assert type(context.get_config(mode="typed")) == DataContextConfig
assert type(context.get_config(mode="dict")) == dict
assert type(context.get_config(mode="yaml")) == str
with pytest.raises(ValueError):
context.get_config(mode="foobar")
print(context.get_config(mode="yaml"))
print(context.get_config("dict").keys())
assert set(context.get_config("dict").keys()) == {
"config_version",
"datasources",
"config_variables_file_path",
"plugins_directory",
"stores",
"expectations_store_name",
"validations_store_name",
"evaluation_parameter_store_name",
"checkpoint_store_name",
"data_docs_sites",
"anonymous_usage_statistics",
"notebooks",
}
def test_config_variables(empty_data_context):
context = empty_data_context
assert type(context.config_variables) == dict
assert set(context.config_variables.keys()) == {"instance_id"}
def test_get_batch_of_pipeline_batch_data(empty_data_context, test_df):
context = empty_data_context
yaml_config = f"""
class_name: Datasource
execution_engine:
class_name: PandasExecutionEngine
data_connectors:
my_runtime_data_connector:
module_name: great_expectations.datasource.data_connector
class_name: RuntimeDataConnector
batch_identifiers:
- airflow_run_id
"""
# noinspection PyUnusedLocal
report_object = context.test_yaml_config(
name="my_pipeline_datasource",
yaml_config=yaml_config,
return_mode="report_object",
)
# print(json.dumps(report_object, indent=2))
# print(context.datasources)
my_batch = context.get_batch(
datasource_name="my_pipeline_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
batch_data=test_df,
batch_identifiers={
"airflow_run_id": 1234567890,
},
limit=None,
)
assert my_batch.batch_definition["data_asset_name"] == "IN_MEMORY_DATA_ASSET"
assert my_batch.data.dataframe.equals(test_df)
def test_conveying_splitting_and_sampling_directives_from_data_context_to_pandas_execution_engine(
empty_data_context, test_df, tmp_path_factory
):
base_directory = str(
tmp_path_factory.mktemp(
"test_conveying_splitting_and_sampling_directives_from_data_context_to_pandas_execution_engine"
)
)
create_files_in_directory(
directory=base_directory,
file_name_list=[
"somme_file.csv",
],
file_content_fn=lambda: test_df.to_csv(header=True, index=False),
)
context = empty_data_context
yaml_config = f"""
class_name: Datasource
execution_engine:
class_name: PandasExecutionEngine
data_connectors:
my_filesystem_data_connector:
class_name: ConfiguredAssetFilesystemDataConnector
base_directory: {base_directory}
default_regex:
pattern: (.+)\\.csv
group_names:
- alphanumeric
assets:
A:
"""
# noinspection PyUnusedLocal
report_object = context.test_yaml_config(
name="my_directory_datasource",
yaml_config=yaml_config,
return_mode="report_object",
)
# print(json.dumps(report_object, indent=2))
# print(context.datasources)
my_batch = context.get_batch(
datasource_name="my_directory_datasource",
data_connector_name="my_filesystem_data_connector",
data_asset_name="A",
batch_spec_passthrough={
"sampling_method": "_sample_using_hash",
"sampling_kwargs": {
"column_name": "date",
"hash_function_name": "md5",
"hash_value": "f",
},
},
)
assert my_batch.batch_definition["data_asset_name"] == "A"
df_data = my_batch.data.dataframe
assert df_data.shape == (10, 10)
df_data["date"] = df_data.apply(
lambda row: datetime.datetime.strptime(row["date"], "%Y-%m-%d").date(), axis=1
)
assert (
test_df[
(test_df["date"] == datetime.date(2020, 1, 15))
| (test_df["date"] == datetime.date(2020, 1, 29))
]
.drop("timestamp", axis=1)
.equals(df_data.drop("timestamp", axis=1))
)
my_batch = context.get_batch(
datasource_name="my_directory_datasource",
data_connector_name="my_filesystem_data_connector",
data_asset_name="A",
batch_spec_passthrough={
"splitter_method": "_split_on_multi_column_values",
"splitter_kwargs": {
"column_names": ["y", "m", "d"],
"batch_identifiers": {"y": 2020, "m": 1, "d": 5},
},
},
)
df_data = my_batch.data.dataframe
assert df_data.shape == (4, 10)
df_data["date"] = df_data.apply(
lambda row: datetime.datetime.strptime(row["date"], "%Y-%m-%d").date(), axis=1
)
df_data["belongs_in_split"] = df_data.apply(
lambda row: row["date"] == datetime.date(2020, 1, 5), axis=1
)
df_data = df_data[df_data["belongs_in_split"]]
assert df_data.drop("belongs_in_split", axis=1).shape == (4, 10)
def test_relative_data_connector_default_and_relative_asset_base_directory_paths(
empty_data_context, test_df, tmp_path_factory
):
context = empty_data_context
create_files_in_directory(
directory=context.root_directory,
file_name_list=[
"test_dir_0/A/B/C/logfile_0.csv",
"test_dir_0/A/B/C/bigfile_1.csv",
"test_dir_0/A/filename2.csv",
"test_dir_0/A/filename3.csv",
],
file_content_fn=lambda: test_df.to_csv(header=True, index=False),
)
yaml_config = f"""
class_name: Datasource
execution_engine:
class_name: PandasExecutionEngine
data_connectors:
my_filesystem_data_connector:
class_name: ConfiguredAssetFilesystemDataConnector
base_directory: test_dir_0/A
glob_directive: "*"
default_regex:
pattern: (.+)\\.csv
group_names:
- name
assets:
A:
base_directory: B/C
glob_directive: "log*.csv"
pattern: (.+)_(\\d+)\\.csv
group_names:
- name
- number
"""
my_datasource = context.test_yaml_config(
name="my_directory_datasource",
yaml_config=yaml_config,
)
assert (
my_datasource.data_connectors["my_filesystem_data_connector"].base_directory
== f"{context.root_directory}/test_dir_0/A"
)
assert (
my_datasource.data_connectors[
"my_filesystem_data_connector"
]._get_full_file_path_for_asset(
path="bigfile_1.csv",
asset=my_datasource.data_connectors["my_filesystem_data_connector"].assets[
"A"
],
)
== f"{context.root_directory}/test_dir_0/A/B/C/bigfile_1.csv"
)
my_batch = context.get_batch(
datasource_name="my_directory_datasource",
data_connector_name="my_filesystem_data_connector",
data_asset_name="A",
)
df_data = my_batch.data.dataframe
assert df_data.shape == (120, 10)
def test__get_data_context_version(empty_data_context, titanic_data_context):
context = empty_data_context
assert not context._get_data_context_version("some_datasource_name", **{})
assert not context._get_data_context_version(arg1="some_datasource_name", **{})
yaml_config = f"""
class_name: Datasource
execution_engine:
class_name: PandasExecutionEngine
data_connectors:
general_runtime_data_connector:
module_name: great_expectations.datasource.data_connector
class_name: RuntimeDataConnector
batch_identifiers:
- airflow_run_id
"""
# noinspection PyUnusedLocal
my_datasource = context.test_yaml_config(
name="some_datasource_name",
yaml_config=yaml_config,
)
assert context._get_data_context_version("some_datasource_name", **{}) == "v3"
assert context._get_data_context_version(arg1="some_datasource_name", **{}) == "v3"
context = titanic_data_context
root_dir = context.root_directory
batch_kwargs = {
"datasource": "mydatasource",
"path": f"{root_dir}/../data/Titanic.csv",
}
assert context._get_data_context_version(arg1=batch_kwargs) == "v2"
assert context._get_data_context_version(batch_kwargs) == "v2"
assert (
context._get_data_context_version(
"some_value", **{"batch_kwargs": batch_kwargs}
)
== "v2"
)
def test_in_memory_data_context_configuration(
titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled,
):
project_config_dict: dict = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled.get_config(
mode="dict"
)
project_config_dict["plugins_directory"] = None
project_config_dict["validation_operators"] = {
"action_list_operator": {
"class_name": "ActionListValidationOperator",
"action_list": [
{
"name": "store_validation_result",
"action": {"class_name": "StoreValidationResultAction"},
},
{
"name": "store_evaluation_params",
"action": {"class_name": "StoreEvaluationParametersAction"},
},
{
"name": "update_data_docs",
"action": {"class_name": "UpdateDataDocsAction"},
},
],
}
}
project_config: DataContextConfig = DataContextConfig(**project_config_dict)
data_context = BaseDataContext(
project_config=project_config,
context_root_dir=titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled.root_directory,
)
my_validator: Validator = data_context.get_validator(
datasource_name="my_datasource",
data_connector_name="my_basic_data_connector",
data_asset_name="Titanic_1912",
create_expectation_suite_with_name="my_test_titanic_expectation_suite",
)
assert my_validator.expect_table_row_count_to_equal(1313)["success"]
assert my_validator.expect_table_column_count_to_equal(7)["success"]
def test_get_batch_with_query_in_runtime_parameters_using_runtime_data_connector(
sa,
data_context_with_runtime_sql_datasource_for_testing_get_batch,
sqlite_view_engine,
):
context: DataContext = (
data_context_with_runtime_sql_datasource_for_testing_get_batch
)
batch: Batch
batch = context.get_batch(
batch_request=RuntimeBatchRequest(
datasource_name="my_runtime_sql_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={
"query": "SELECT * FROM table_partitioned_by_date_column__A"
},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
)
assert batch.batch_spec is not None
assert batch.batch_definition["data_asset_name"] == "IN_MEMORY_DATA_ASSET"
assert isinstance(batch.data, SqlAlchemyBatchData)
selectable_table_name = batch.data.selectable.name
selectable_count_sql_str = f"select count(*) from {selectable_table_name}"
sa_engine = batch.data.execution_engine.engine
assert sa_engine.execute(selectable_count_sql_str).scalar() == 120
assert batch.batch_markers.get("ge_load_time") is not None
# since create_temp_table defaults to True, there should be 1 temp table
assert len(get_sqlite_temp_table_names(batch.data.execution_engine.engine)) == 1
# if create_temp_table in batch_spec_passthrough is set to False, no new temp tables should be created
batch = context.get_batch(
batch_request=RuntimeBatchRequest(
datasource_name="my_runtime_sql_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={
"query": "SELECT * FROM table_partitioned_by_date_column__A"
},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
batch_spec_passthrough={"create_temp_table": False},
),
)
assert len(get_sqlite_temp_table_names(batch.data.execution_engine.engine)) == 1
def test_get_validator_with_query_in_runtime_parameters_using_runtime_data_connector(
sa,
data_context_with_runtime_sql_datasource_for_testing_get_batch,
):
context: DataContext = (
data_context_with_runtime_sql_datasource_for_testing_get_batch
)
my_expectation_suite: ExpectationSuite = context.create_expectation_suite(
"my_expectations"
)
validator: Validator
validator = context.get_validator(
batch_request=RuntimeBatchRequest(
datasource_name="my_runtime_sql_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={
"query": "SELECT * FROM table_partitioned_by_date_column__A"
},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
expectation_suite=my_expectation_suite,
)
assert len(validator.batches) == 1
def test_get_batch_with_path_in_runtime_parameters_using_runtime_data_connector(
sa,
titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled,
):
context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled
data_asset_path = os.path.join(
context.root_directory, "..", "data", "titanic", "Titanic_19120414_1313.csv"
)
batch: Batch
batch = context.get_batch(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
)
assert batch.batch_spec is not None
assert batch.batch_definition["data_asset_name"] == "IN_MEMORY_DATA_ASSET"
assert isinstance(batch.data, PandasBatchData)
assert len(batch.data.dataframe.index) == 1313
assert batch.batch_markers.get("ge_load_time") is not None
# using path with no extension
data_asset_path_no_extension = os.path.join(
context.root_directory, "..", "data", "titanic", "Titanic_19120414_1313"
)
# with no reader_method in batch_spec_passthrough
with pytest.raises(BatchSpecError):
context.get_batch(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path_no_extension},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
)
# with reader_method in batch_spec_passthrough
batch = context.get_batch(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path_no_extension},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
batch_spec_passthrough={"reader_method": "read_csv"},
),
)
assert batch.batch_spec is not None
assert batch.batch_definition["data_asset_name"] == "IN_MEMORY_DATA_ASSET"
assert isinstance(batch.data, PandasBatchData)
assert len(batch.data.dataframe.index) == 1313
assert batch.batch_markers.get("ge_load_time") is not None
def | (
sa,
titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled,
):
context: DataContext = titanic_pandas_data_context_with_v013_datasource_with_checkpoints_v1_with_empty_store_stats_enabled
data_asset_path = os.path.join(
context.root_directory, "..", "data", "titanic", "Titanic_19120414_1313.csv"
)
my_expectation_suite: ExpectationSuite = context.create_expectation_suite(
"my_expectations"
)
validator: Validator
validator = context.get_validator(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
expectation_suite=my_expectation_suite,
)
assert len(validator.batches) == 1
# using path with no extension
data_asset_path_no_extension = os.path.join(
context.root_directory, "..", "data", "titanic", "Titanic_19120414_1313"
)
# with no reader_method in batch_spec_passthrough
with pytest.raises(BatchSpecError):
context.get_validator(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path_no_extension},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
),
expectation_suite=my_expectation_suite,
)
# with reader_method in batch_spec_passthrough
validator = context.get_validator(
batch_request=RuntimeBatchRequest(
datasource_name="my_datasource",
data_connector_name="my_runtime_data_connector",
data_asset_name="IN_MEMORY_DATA_ASSET",
runtime_parameters={"path": data_asset_path_no_extension},
batch_identifiers={
"pipeline_stage_name": "core_processing",
"airflow_run_id": 1234567890,
},
batch_spec_passthrough={"reader_method": "read_csv"},
),
expectation_suite=my_expectation_suite,
)
assert len(validator.batches) == 1
| test_get_validator_with_path_in_runtime_parameters_using_runtime_data_connector |
palindrome.js | /***
* Excerpted from "Test-Driving JavaScript Applications",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt. | ***/
module.exports = function(phrase) {
return true;
}; | * We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/vsjavas for more book information. |
test_remongo.py | import os
from django.conf import settings
from main.tests.test_base import MainTestCase
from odk_viewer.models import ParsedInstance
from odk_viewer.management.commands.remongo import Command
from django.core.management import call_command
from common_tags import USERFORM_ID
class TestRemongo(MainTestCase):
def test_remongo_in_batches(self):
self._publish_transportation_form()
# submit 4 instances
self._make_submissions()
self.assertEqual(ParsedInstance.objects.count(), 4)
# clear mongo
settings.MONGO_DB.instances.drop()
c = Command()
c.handle(batchsize=3)
# mongo db should now have 5 records
count = settings.MONGO_DB.instances.count()
self.assertEqual(count, 4)
def test_remongo_with_username_id_string(self):
self._publish_transportation_form()
# submit 1 instances
s = self.surveys[0]
self._make_submission(os.path.join(self.this_directory, 'fixtures',
'transportation', 'instances', s, s + '.xml'))
# publish and submit for a different user
self._logout()
self._create_user_and_login("harry", "harry")
self._publish_transportation_form()
s = self.surveys[1]
self._make_submission(os.path.join(self.this_directory, 'fixtures',
'transportation', 'instances', s, s + '.xml'))
self.assertEqual(ParsedInstance.objects.count(), 2)
# clear mongo
settings.MONGO_DB.instances.drop()
c = Command()
c.handle(batchsize=3, username=self.user.username,
id_string=self.xform.id_string)
# mongo db should now have 2 records
count = settings.MONGO_DB.instances.count()
self.assertEqual(count, 1)
def test_indexes_exist(self):
"""
Make sure the required indexes are set, _userform_id as of now
"""
call_command('remongo')
# if index exists, ensure index returns None
# list of indexes to check for
index_list = [USERFORM_ID]
# get index info
index_info = settings.MONGO_DB.instances.index_information()
# index_info looks like this - {u'_id_': {u'key': [(u'_id', 1)], u'v': 1}, u'_userform_id_1': {u'key': [(u'_userform_id', 1)], u'v': 1}}
# lets make a list of the indexes
existing_indexes = [v['key'][0][0] for v in index_info.itervalues() if v['key'][0][1] == 1]
all_indexes_found = True
for index_item in index_list:
if index_item not in existing_indexes:
all_indexes_found = False
break
self.assertTrue(all_indexes_found)
def test_sync_mongo_with_all_option_deletes_existing_records(self):
self._publish_transportation_form()
userform_id = "%s_%s" % (self.user.username, self.xform.id_string)
initial_mongo_count = settings.MONGO_DB.instances.find(
{USERFORM_ID: userform_id}).count()
for i in range(len(self.surveys)):
self._submit_transport_instance(i)
mongo_count = settings.MONGO_DB.instances.find(
{USERFORM_ID: userform_id}).count()
# check our mongo count
self.assertEqual(mongo_count, initial_mongo_count + len(self.surveys))
# add dummy instance | mongo_count = settings.MONGO_DB.instances.find(
{USERFORM_ID: userform_id}).count()
self.assertEqual(mongo_count,
initial_mongo_count + len(self.surveys) + 1)
# call sync_mongo WITHOUT the all option
call_command("sync_mongo", remongo=True)
mongo_count = settings.MONGO_DB.instances.find(
{USERFORM_ID: userform_id}).count()
self.assertEqual(mongo_count,
initial_mongo_count + len(self.surveys) + 1)
# call sync_mongo WITH the all option
call_command("sync_mongo", remongo=True, update_all=True)
# check that we are back to just the submitted set
mongo_count = settings.MONGO_DB.instances.find(
{USERFORM_ID: userform_id}).count()
self.assertEqual(mongo_count,
initial_mongo_count + len(self.surveys)) | settings.MONGO_DB.instances.save(
{"_id": 12345, "_userform_id": userform_id})
# make sure the dummy is returned as part of the forms mongo instances |
file_status.py | # -*- coding: utf-8 -*-
"""
Display if files or directories exists.
Configuration parameters:
cache_timeout: refresh interval for this module (default 10)
format: display format for this module
(default '\?color=path [\?if=path ●|■]')
format_path: format for paths (default '{basename}')
format_path_separator: show separator if more than one (default ' ')
paths: specify a string or a list of paths to check (default None)
thresholds: specify color thresholds to use
(default [(0, 'bad'), (1, 'good')])
Format placeholders:
{format_path} format for paths
{path} number of paths, eg 1, 2, 3
format_path placeholders:
{basename} basename of pathname
{pathname} pathname
Color options:
color_bad: files or directories does not exist
color_good: files or directories exists
Color thresholds:
format:
path: print a color based on the number of paths
Examples:
# add multiple paths with wildcard or with pathnames
```
file_status {
paths = ['/tmp/test*', '~user/test1', '~/Videos/*.mp4']
}
# colorize basenames
file_status {
paths = ['~/.config/i3/modules/*.py']
format = '{format_path}'
format_path = '\?color=good {basename}'
format_path_separator = ', '
}
```
@author obb, Moritz Lüdecke, Cyril Levis (@cyrinux)
SAMPLE OUTPUT
{'color': '#00FF00', 'full_text': u'\u25cf'}
missing
{'color': '#FF0000', 'full_text': u'\u25a0'}
"""
from glob import glob
from os.path import basename, expanduser
STRING_NO_PATHS = "missing paths"
class Py3status:
"""
"""
# available configuration parameters
cache_timeout = 10
format = u"\?color=path [\?if=path \u25cf|\u25a0]"
format_path = u"{basename}"
format_path_separator = u" "
paths = None
thresholds = [(0, "bad"), (1, "good")]
class Meta:
deprecated = {
"rename": [
{
"param": "format_available",
"new": "icon_available",
"msg": "obsolete parameter use `icon_available`",
},
{
"param": "format_unavailable",
"new": "icon_unavailable",
"msg": "obsolete parameter use `icon_unavailable`",
},
{
"param": "path",
"new": "paths",
"msg": "obsolete parameter use `paths`",
},
],
"rename_placeholder": [
{"placeholder": "paths", "new": "path", "format_strings": ["format"]}
],
}
def post_config_hook(self):
if not self.paths:
raise Exception(STRING_NO_PATHS)
# icon deprecation
on = getattr(self, "icon_available", u"\u25cf")
off = getattr(self, "icon_unavailable", u"\u25a0")
new_icon = u"\?color=path [\?if=path {}|{}]".format(on, off)
self.format = self.format.replace("{icon}", new_icon)
# convert str to list + expand path
if not isinstance(self.paths, list):
self.paths = [self.paths]
self.paths = list(map(expanduser, self.paths))
self.init = {"format_path": []} | # init datas
paths = sorted([files for path in self.paths for files in glob(path)])
count_path = len(paths)
format_path = None
# format paths
if self.init["format_path"]:
new_data = []
format_path_separator = self.py3.safe_format(self.format_path_separator)
for pathname in paths:
path = {}
for key in self.init["format_path"]:
if key == "basename":
value = basename(pathname)
elif key == "pathname":
value = pathname
else:
continue
path[key] = self.py3.safe_format(value)
new_data.append(self.py3.safe_format(self.format_path, path))
format_path = self.py3.composite_join(format_path_separator, new_data)
if self.thresholds:
self.py3.threshold_get_color(count_path, "path")
self.py3.threshold_get_color(count_path, "paths")
return {
"cached_until": self.py3.time_in(self.cache_timeout),
"full_text": self.py3.safe_format(
self.format,
{"path": count_path, "paths": count_path, "format_path": format_path},
),
}
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status) | if self.py3.format_contains(self.format, "format_path"):
self.init["format_path"] = self.py3.get_placeholders_list(self.format_path)
def file_status(self): |
build.rs | fn main() | {
cargo_emit::rerun_if_changed!("migrations",);
} |
|
impls.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use boxed::Box;
use cmp;
use io::{self, SeekFrom, Read, Write, Seek, BufRead, Error, ErrorKind};
use fmt;
use mem;
use slice;
use string::String;
use vec::Vec;
// =============================================================================
// Forwarding implementations
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, R: Read + ?Sized> Read for &'a mut R {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
#[inline]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_to_end(buf)
}
#[inline]
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_to_string(buf)
}
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
(**self).read_exact(buf)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, W: Write + ?Sized> Write for &'a mut W {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
#[inline]
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
(**self).write_all(buf)
}
#[inline]
fn | (&mut self, fmt: fmt::Arguments) -> io::Result<()> {
(**self).write_fmt(fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, S: Seek + ?Sized> Seek for &'a mut S {
#[inline]
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, B: BufRead + ?Sized> BufRead for &'a mut B {
#[inline]
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
#[inline]
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
#[inline]
fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_until(byte, buf)
}
#[inline]
fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_line(buf)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<R: Read + ?Sized> Read for Box<R> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
#[inline]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_to_end(buf)
}
#[inline]
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_to_string(buf)
}
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
(**self).read_exact(buf)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<W: Write + ?Sized> Write for Box<W> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
#[inline]
fn flush(&mut self) -> io::Result<()> { (**self).flush() }
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
(**self).write_all(buf)
}
#[inline]
fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
(**self).write_fmt(fmt)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<S: Seek + ?Sized> Seek for Box<S> {
#[inline]
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<B: BufRead + ?Sized> BufRead for Box<B> {
#[inline]
fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
#[inline]
fn consume(&mut self, amt: usize) { (**self).consume(amt) }
#[inline]
fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
(**self).read_until(byte, buf)
}
#[inline]
fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
(**self).read_line(buf)
}
}
// =============================================================================
// In-memory buffer implementations
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Read for &'a [u8] {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let amt = cmp::min(buf.len(), self.len());
let (a, b) = self.split_at(amt);
slice::bytes::copy_memory(a, buf);
*self = b;
Ok(amt)
}
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
if buf.len() > self.len() {
return Err(Error::new(ErrorKind::UnexpectedEOF, "failed to fill whole buffer"));
}
let (a, b) = self.split_at(buf.len());
slice::bytes::copy_memory(a, buf);
*self = b;
Ok(())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> BufRead for &'a [u8] {
#[inline]
fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) }
#[inline]
fn consume(&mut self, amt: usize) { *self = &self[amt..]; }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Write for &'a mut [u8] {
#[inline]
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let amt = cmp::min(data.len(), self.len());
let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
slice::bytes::copy_memory(&data[..amt], a);
*self = b;
Ok(amt)
}
#[inline]
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
if try!(self.write(data)) == data.len() {
Ok(())
} else {
Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"))
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Write for Vec<u8> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.push_all(buf);
Ok(buf.len())
}
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.push_all(buf);
Ok(())
}
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
#[cfg(test)]
mod tests {
use io::prelude::*;
use vec::Vec;
use test;
#[bench]
fn bench_read_slice(b: &mut test::Bencher) {
let buf = [5; 1024];
let mut dst = [0; 128];
b.iter(|| {
let mut rd = &buf[..];
for _ in (0 .. 8) {
let _ = rd.read(&mut dst);
test::black_box(&dst);
}
})
}
#[bench]
fn bench_write_slice(b: &mut test::Bencher) {
let mut buf = [0; 1024];
let src = [5; 128];
b.iter(|| {
let mut wr = &mut buf[..];
for _ in (0 .. 8) {
let _ = wr.write_all(&src);
test::black_box(&wr);
}
})
}
#[bench]
fn bench_read_vec(b: &mut test::Bencher) {
let buf = vec![5; 1024];
let mut dst = [0; 128];
b.iter(|| {
let mut rd = &buf[..];
for _ in (0 .. 8) {
let _ = rd.read(&mut dst);
test::black_box(&dst);
}
})
}
#[bench]
fn bench_write_vec(b: &mut test::Bencher) {
let mut buf = Vec::with_capacity(1024);
let src = [5; 128];
b.iter(|| {
let mut wr = &mut buf[..];
for _ in (0 .. 8) {
let _ = wr.write_all(&src);
test::black_box(&wr);
}
})
}
}
| write_fmt |
list_tests.py | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import sys
import pytest
class Collector(object):
RUN_INDIVIDUALLY = ['tests/test_pex.py']
def __init__(self):
self._collected = set()
def | (self):
for collected in sorted(self._collected):
yield collected
def pytest_collectreport(self, report):
if report.failed:
raise pytest.UsageError('Errors during collection, aborting!')
def pytest_collection_modifyitems(self, items):
for item in items:
test_file = item.location[0]
if test_file in self.RUN_INDIVIDUALLY:
self._collected.add(item.nodeid)
else:
self._collected.add(test_file)
collector = Collector()
rv = pytest.main(['--collect-only'] + sys.argv[1:], plugins=[collector])
for test_target in collector.iter_collected():
print('RUNNABLE\t"{}"'.format(test_target))
sys.exit(rv)
| iter_collected |
abs.rs | extern crate noise; |
use noise::utils::*;
use noise::{Abs, Perlin};
fn main() {
let perlin = Perlin::new();
let abs = Abs::new(&perlin);
PlaneMapBuilder::new(&abs).build().write_to_file("abs.png");
} | |
respawntype_gen.go | // Code generated by "genenum.exe -typename=RespawnType -packagename=respawntype -basedir=enum"
package respawntype
import "fmt"
type RespawnType uint8
const (
ToHomeFloor RespawnType = iota // respawn to home floor |
RespawnType_Count int = iota
)
var _RespawnType2string = [RespawnType_Count][2]string{
ToHomeFloor: {"ToHomeFloor", "respawn to home floor"},
ToCurrentFloor: {"ToCurrentFloor", "respawn to current floor"},
ToRandomFloor: {"ToRandomFloor", "respawn to random floor in tower"},
}
func (e RespawnType) String() string {
if e >= 0 && e < RespawnType(RespawnType_Count) {
return _RespawnType2string[e][0]
}
return fmt.Sprintf("RespawnType%d", uint8(e))
}
func (e RespawnType) CommentString() string {
if e >= 0 && e < RespawnType(RespawnType_Count) {
return _RespawnType2string[e][1]
}
return ""
}
var _string2RespawnType = map[string]RespawnType{
"ToHomeFloor": ToHomeFloor,
"ToCurrentFloor": ToCurrentFloor,
"ToRandomFloor": ToRandomFloor,
}
func String2RespawnType(s string) (RespawnType, bool) {
v, b := _string2RespawnType[s]
return v, b
} | ToCurrentFloor // respawn to current floor
ToRandomFloor // respawn to random floor in tower
// |
commands.rs | // Copyright 2020. The Tari Project
//
// 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 copyright holder 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
use std::{
fs::File,
io::{LineWriter, Write},
str::FromStr,
time::{Duration, Instant},
};
use chrono::Utc;
use digest::Digest;
use futures::FutureExt;
use log::*;
use sha2::Sha256;
use strum_macros::{Display, EnumIter, EnumString};
use tari_common_types::{array::copy_into_fixed_array, emoji::EmojiId, transaction::TxId, types::PublicKey};
use tari_comms::{
connectivity::{ConnectivityEvent, ConnectivityRequester},
multiaddr::Multiaddr,
types::CommsPublicKey,
};
use tari_comms_dht::{envelope::NodeDestination, DhtDiscoveryRequester};
use tari_core::transactions::{
tari_amount::{uT, MicroTari, Tari},
transaction_components::{TransactionOutput, UnblindedOutput},
};
use tari_crypto::{keys::PublicKey as PublicKeyTrait, ristretto::pedersen::PedersenCommitmentFactory};
use tari_utilities::{hex::Hex, ByteArray, Hashable};
use tari_wallet::{
assets::KEY_MANAGER_ASSET_BRANCH,
error::WalletError,
key_manager_service::KeyManagerInterface,
output_manager_service::handle::OutputManagerHandle,
transaction_service::handle::{TransactionEvent, TransactionServiceHandle},
WalletConfig,
WalletSqlite,
};
use tokio::{
sync::{broadcast, mpsc},
time::{sleep, timeout},
};
use super::error::CommandError;
use crate::{
automation::command_parser::{ParsedArgument, ParsedCommand},
utils::db::{CUSTOM_BASE_NODE_ADDRESS_KEY, CUSTOM_BASE_NODE_PUBLIC_KEY_KEY},
};
pub const LOG_TARGET: &str = "wallet::automation::commands";
/// Enum representing commands used by the wallet
#[derive(Clone, PartialEq, Debug, Display, EnumIter, EnumString)]
#[strum(serialize_all = "kebab_case")]
pub enum WalletCommand {
GetBalance,
SendTari,
SendOneSided,
MakeItRain,
CoinSplit,
DiscoverPeer,
Whois,
ExportUtxos,
ExportSpentUtxos,
CountUtxos,
SetBaseNode,
SetCustomBaseNode,
ClearCustomBaseNode,
InitShaAtomicSwap,
FinaliseShaAtomicSwap,
ClaimShaAtomicSwapRefund,
RegisterAsset,
MintTokens,
CreateInitialCheckpoint,
CreateCommitteeDefinition,
RevalidateWalletDb,
}
#[derive(Debug, EnumString, PartialEq, Clone, Copy)]
pub enum TransactionStage {
Initiated,
DirectSendOrSaf,
Negotiated,
Broadcast,
MinedUnconfirmed,
Mined,
TimedOut,
}
#[derive(Debug)]
pub struct SentTransaction {}
fn get_transaction_parameters(args: Vec<ParsedArgument>) -> Result<(MicroTari, PublicKey, String), CommandError> {
use ParsedArgument::{Amount, PublicKey, Text};
let amount = match args[0].clone() {
Amount(mtari) => Ok(mtari),
_ => Err(CommandError::Argument),
}?;
let dest_pubkey = match args[1].clone() {
PublicKey(key) => Ok(key),
_ => Err(CommandError::Argument),
}?;
let message = match args[2].clone() {
Text(msg) => Ok(msg),
_ => Err(CommandError::Argument),
}?;
Ok((amount, dest_pubkey, message))
}
fn get_init_sha_atomic_swap_parameters(
args: Vec<ParsedArgument>,
) -> Result<(MicroTari, PublicKey, String), CommandError> {
use ParsedArgument::{Amount, PublicKey, Text};
let amount = match args[0].clone() {
Amount(mtari) => Ok(mtari),
_ => Err(CommandError::Argument),
}?;
let dest_pubkey = match args[1].clone() {
PublicKey(key) => Ok(key),
_ => Err(CommandError::Argument),
}?;
let message = match args[2].clone() {
Text(msg) => Ok(msg),
_ => Err(CommandError::Argument),
}?;
Ok((amount, dest_pubkey, message))
}
/// Send a normal negotiated transaction to a recipient
pub async fn send_tari(
mut wallet_transaction_service: TransactionServiceHandle,
fee_per_gram: u64,
args: Vec<ParsedArgument>,
) -> Result<TxId, CommandError> {
let (amount, dest_pubkey, message) = get_transaction_parameters(args)?;
wallet_transaction_service
.send_transaction(dest_pubkey, amount, fee_per_gram * uT, message)
.await
.map_err(CommandError::TransactionServiceError)
}
/// publishes a tari-SHA atomic swap HTLC transaction
pub async fn init_sha_atomic_swap(
mut wallet_transaction_service: TransactionServiceHandle,
fee_per_gram: u64,
args: Vec<ParsedArgument>,
) -> Result<(TxId, PublicKey, TransactionOutput), CommandError> |
/// claims a tari-SHA atomic swap HTLC transaction
pub async fn finalise_sha_atomic_swap(
mut output_service: OutputManagerHandle,
mut transaction_service: TransactionServiceHandle,
args: Vec<ParsedArgument>,
) -> Result<TxId, CommandError> {
use ParsedArgument::{Hash, PublicKey};
let output = match args[0].clone() {
Hash(output) => Ok(output),
_ => Err(CommandError::Argument),
}?;
let pre_image = match args[1].clone() {
PublicKey(key) => Ok(key),
_ => Err(CommandError::Argument),
}?;
let (tx_id, _fee, amount, tx) = output_service
.create_claim_sha_atomic_swap_transaction(output, pre_image, MicroTari(25))
.await?;
transaction_service
.submit_transaction(tx_id, tx, amount, "Claimed HTLC atomic swap".into())
.await?;
Ok(tx_id)
}
/// claims a HTLC refund transaction
pub async fn claim_htlc_refund(
mut output_service: OutputManagerHandle,
mut transaction_service: TransactionServiceHandle,
args: Vec<ParsedArgument>,
) -> Result<TxId, CommandError> {
use ParsedArgument::Hash;
let output = match args[0].clone() {
Hash(output) => Ok(output),
_ => Err(CommandError::Argument),
}?;
let (tx_id, _fee, amount, tx) = output_service
.create_htlc_refund_transaction(output, MicroTari(25))
.await?;
transaction_service
.submit_transaction(tx_id, tx, amount, "Claimed HTLC refund".into())
.await?;
Ok(tx_id)
}
/// Send a one-sided transaction to a recipient
pub async fn send_one_sided(
mut wallet_transaction_service: TransactionServiceHandle,
fee_per_gram: u64,
args: Vec<ParsedArgument>,
) -> Result<TxId, CommandError> {
let (amount, dest_pubkey, message) = get_transaction_parameters(args)?;
wallet_transaction_service
.send_one_sided_transaction(dest_pubkey, amount, fee_per_gram * uT, message)
.await
.map_err(CommandError::TransactionServiceError)
}
pub async fn coin_split(
args: &[ParsedArgument],
output_service: &mut OutputManagerHandle,
transaction_service: &mut TransactionServiceHandle,
) -> Result<TxId, CommandError> {
use ParsedArgument::{Amount, Int};
let amount_per_split = match args[0] {
Amount(s) => Ok(s),
_ => Err(CommandError::Argument),
}?;
let num_splits = match args[1] {
Int(s) => Ok(s),
_ => Err(CommandError::Argument),
}?;
let fee_per_gram = match args[2] {
Amount(s) => Ok(s),
_ => Err(CommandError::Argument),
}?;
let (tx_id, tx, amount) = output_service
.create_coin_split(amount_per_split, num_splits as usize, fee_per_gram, None)
.await?;
transaction_service
.submit_transaction(tx_id, tx, amount, "Coin split".into())
.await?;
Ok(tx_id)
}
async fn wait_for_comms(connectivity_requester: &ConnectivityRequester) -> Result<(), CommandError> {
let mut connectivity = connectivity_requester.get_event_subscription();
print!("Waiting for connectivity... ");
let timeout = sleep(Duration::from_secs(30));
tokio::pin!(timeout);
let mut timeout = timeout.fuse();
loop {
tokio::select! {
// Wait for the first base node connection
Ok(ConnectivityEvent::PeerConnected(conn)) = connectivity.recv() => {
if conn.peer_features().is_node() {
println!("✅");
return Ok(());
}
},
() = &mut timeout => {
println!("❌");
return Err(CommandError::Comms("Timed out".to_string()));
}
}
}
}
async fn set_base_node_peer(
mut wallet: WalletSqlite,
args: &[ParsedArgument],
) -> Result<(CommsPublicKey, Multiaddr), CommandError> {
let public_key = match args[0].clone() {
ParsedArgument::PublicKey(s) => Ok(s),
_ => Err(CommandError::Argument),
}?;
let net_address = match args[1].clone() {
ParsedArgument::Address(a) => Ok(a),
_ => Err(CommandError::Argument),
}?;
println!("Setting base node peer...");
println!("{}::{}", public_key, net_address);
wallet
.set_base_node_peer(public_key.clone(), net_address.clone())
.await?;
Ok((public_key, net_address))
}
pub async fn discover_peer(
mut dht_service: DhtDiscoveryRequester,
args: Vec<ParsedArgument>,
) -> Result<(), CommandError> {
use ParsedArgument::PublicKey;
let dest_public_key = match args[0].clone() {
PublicKey(key) => Ok(key),
_ => Err(CommandError::Argument),
}?;
let start = Instant::now();
println!("🌎 Peer discovery started.");
match dht_service
.discover_peer(
dest_public_key.clone(),
NodeDestination::PublicKey(Box::new(dest_public_key)),
)
.await
{
Ok(peer) => {
println!("⚡️ Discovery succeeded in {}ms.", start.elapsed().as_millis());
println!("{}", peer);
},
Err(err) => {
println!("💀 Discovery failed: '{:?}'", err);
},
}
Ok(())
}
pub async fn make_it_rain(
wallet_transaction_service: TransactionServiceHandle,
fee_per_gram: u64,
args: Vec<ParsedArgument>,
) -> Result<(), CommandError> {
use ParsedArgument::{Amount, Date, Float, Int, Negotiated, PublicKey, Text};
let txps = match args[0].clone() {
Float(r) => Ok(r),
_ => Err(CommandError::Argument),
}?;
let duration = match args[1].clone() {
Int(s) => Ok(s),
_ => Err(CommandError::Argument),
}?;
let start_amount = match args[2].clone() {
Amount(mtari) => Ok(mtari),
_ => Err(CommandError::Argument),
}?;
let inc_amount = match args[3].clone() {
Amount(mtari) => Ok(mtari),
_ => Err(CommandError::Argument),
}?;
let start_time = match args[4].clone() {
Date(dt) => Ok(dt),
_ => Err(CommandError::Argument),
}?;
let public_key = match args[5].clone() {
PublicKey(pk) => Ok(pk),
_ => Err(CommandError::Argument),
}?;
let negotiated = match args[6].clone() {
Negotiated(val) => Ok(val),
_ => Err(CommandError::Argument),
}?;
let message = match args[7].clone() {
Text(m) => Ok(m),
_ => Err(CommandError::Argument),
}?;
// We are spawning this command in parallel, thus not collecting transaction IDs
tokio::task::spawn(async move {
// Wait until specified test start time
let now = Utc::now();
let delay_ms = if start_time > now {
println!(
"`make-it-rain` scheduled to start at {}: msg \"{}\"",
start_time, message
);
(start_time - now).num_milliseconds() as u64
} else {
0
};
debug!(
target: LOG_TARGET,
"make-it-rain delaying for {:?} ms - scheduled to start at {}", delay_ms, start_time
);
sleep(Duration::from_millis(delay_ms)).await;
let num_txs = (txps * duration as f64) as usize;
let started_at = Utc::now();
struct TransactionSendStats {
i: usize,
tx_id: Result<TxId, CommandError>,
delayed_for: Duration,
submit_time: Duration,
}
let transaction_type = if negotiated { "negotiated" } else { "one-sided" };
println!(
"\n`make-it-rain` starting {} {} transactions \"{}\"\n",
num_txs, transaction_type, message
);
let (sender, mut receiver) = mpsc::channel(num_txs);
{
let sender = sender;
for i in 0..num_txs {
debug!(
target: LOG_TARGET,
"make-it-rain starting {} of {} {} transactions",
i + 1,
num_txs,
transaction_type
);
let loop_started_at = Instant::now();
let tx_service = wallet_transaction_service.clone();
// Transaction details
let amount = start_amount + inc_amount * (i as u64);
let send_args = vec![
ParsedArgument::Amount(amount),
ParsedArgument::PublicKey(public_key.clone()),
ParsedArgument::Text(message.clone()),
];
// Manage transaction submission rate
let actual_ms = (Utc::now() - started_at).num_milliseconds();
let target_ms = (i as f64 / (txps / 1000.0)) as i64;
if target_ms - actual_ms > 0 {
// Maximum delay between Txs set to 120 s
sleep(Duration::from_millis((target_ms - actual_ms).min(120_000i64) as u64)).await;
}
let delayed_for = Instant::now();
let sender_clone = sender.clone();
let fee = fee_per_gram;
tokio::task::spawn(async move {
let spawn_start = Instant::now();
// Send transaction
let tx_id = if negotiated {
send_tari(tx_service, fee, send_args).await
} else {
send_one_sided(tx_service, fee, send_args).await
};
let submit_time = Instant::now();
tokio::task::spawn(async move {
print!("{} ", i + 1);
});
if let Err(e) = sender_clone
.send(TransactionSendStats {
i: i + 1,
tx_id,
delayed_for: delayed_for.duration_since(loop_started_at),
submit_time: submit_time.duration_since(spawn_start),
})
.await
{
warn!(
target: LOG_TARGET,
"make-it-rain: Error sending transaction send stats to channel: {}",
e.to_string()
);
}
});
}
}
while let Some(send_stats) = receiver.recv().await {
match send_stats.tx_id {
Ok(tx_id) => {
debug!(
target: LOG_TARGET,
"make-it-rain transaction {} ({}) submitted to queue, tx_id: {}, delayed for ({}ms), submit \
time ({}ms)",
send_stats.i,
transaction_type,
tx_id,
send_stats.delayed_for.as_millis(),
send_stats.submit_time.as_millis()
);
},
Err(e) => {
warn!(
target: LOG_TARGET,
"make-it-rain transaction {} ({}) error: {}",
send_stats.i,
transaction_type,
e.to_string(),
);
},
}
}
debug!(
target: LOG_TARGET,
"make-it-rain concluded {} {} transactions", num_txs, transaction_type
);
println!(
"\n`make-it-rain` concluded {} {} transactions (\"{}\") at {}",
num_txs,
transaction_type,
message,
Utc::now(),
);
});
Ok(())
}
pub async fn monitor_transactions(
transaction_service: TransactionServiceHandle,
tx_ids: Vec<TxId>,
wait_stage: TransactionStage,
) -> Vec<SentTransaction> {
let mut event_stream = transaction_service.get_event_stream();
let mut results = Vec::new();
debug!(target: LOG_TARGET, "monitor transactions wait_stage: {:?}", wait_stage);
println!(
"Monitoring {} sent transactions to {:?} stage...",
tx_ids.len(),
wait_stage
);
loop {
match event_stream.recv().await {
Ok(event) => match &*event {
TransactionEvent::TransactionSendResult(id, status) if tx_ids.contains(id) => {
debug!(target: LOG_TARGET, "tx send event for tx_id: {}, {}", *id, status);
if wait_stage == TransactionStage::DirectSendOrSaf &&
(status.direct_send_result || status.store_and_forward_send_result)
{
results.push(SentTransaction {});
if results.len() == tx_ids.len() {
break;
}
}
},
TransactionEvent::ReceivedTransactionReply(id) if tx_ids.contains(id) => {
debug!(target: LOG_TARGET, "tx reply event for tx_id: {}", *id);
if wait_stage == TransactionStage::Negotiated {
results.push(SentTransaction {});
if results.len() == tx_ids.len() {
break;
}
}
},
TransactionEvent::TransactionBroadcast(id) if tx_ids.contains(id) => {
debug!(target: LOG_TARGET, "tx mempool broadcast event for tx_id: {}", *id);
if wait_stage == TransactionStage::Broadcast {
results.push(SentTransaction {});
if results.len() == tx_ids.len() {
break;
}
}
},
TransactionEvent::TransactionMinedUnconfirmed {
tx_id,
num_confirmations,
is_valid,
} if tx_ids.contains(tx_id) => {
debug!(
target: LOG_TARGET,
"tx mined unconfirmed event for tx_id: {}, confirmations: {}, is_valid: {}",
*tx_id,
num_confirmations,
is_valid
);
if wait_stage == TransactionStage::MinedUnconfirmed {
results.push(SentTransaction {});
if results.len() == tx_ids.len() {
break;
}
}
},
TransactionEvent::TransactionMined { tx_id, is_valid } if tx_ids.contains(tx_id) => {
debug!(
target: LOG_TARGET,
"tx mined confirmed event for tx_id: {}, is_valid:{}", *tx_id, is_valid
);
if wait_stage == TransactionStage::Mined {
results.push(SentTransaction {});
if results.len() == tx_ids.len() {
break;
}
}
},
_ => {},
},
// All event senders have gone (i.e. we take it that the node is shutting down)
Err(broadcast::error::RecvError::Closed) => {
debug!(
target: LOG_TARGET,
"All Transaction event senders have gone. Exiting `monitor_transactions` loop."
);
break;
},
Err(err) => {
warn!(target: LOG_TARGET, "monitor_transactions: {}", err);
},
}
}
results
}
pub async fn command_runner(
config: &WalletConfig,
commands: Vec<ParsedCommand>,
wallet: WalletSqlite,
) -> Result<(), CommandError> {
let wait_stage =
TransactionStage::from_str(&config.command_send_wait_stage).map_err(|e| CommandError::Config(e.to_string()))?;
let mut transaction_service = wallet.transaction_service.clone();
let mut output_service = wallet.output_manager_service.clone();
let dht_service = wallet.dht_service.discovery_service_requester().clone();
let connectivity_requester = wallet.comms.connectivity();
let mut online = false;
let mut tx_ids = Vec::new();
println!("==============");
println!("Command Runner");
println!("==============");
#[allow(clippy::enum_glob_use)]
use WalletCommand::*;
for (idx, parsed) in commands.into_iter().enumerate() {
println!("\n{}. {}\n", idx + 1, parsed);
match parsed.command {
GetBalance => match output_service.clone().get_balance().await {
Ok(balance) => {
println!("{}", balance);
},
Err(e) => eprintln!("GetBalance error! {}", e),
},
DiscoverPeer => {
if !online {
wait_for_comms(&connectivity_requester).await?;
online = true;
}
discover_peer(dht_service.clone(), parsed.args).await?
},
SendTari => {
let tx_id = send_tari(transaction_service.clone(), config.fee_per_gram, parsed.args).await?;
debug!(target: LOG_TARGET, "send-tari tx_id {}", tx_id);
tx_ids.push(tx_id);
},
SendOneSided => {
let tx_id = send_one_sided(transaction_service.clone(), config.fee_per_gram, parsed.args).await?;
debug!(target: LOG_TARGET, "send-one-sided tx_id {}", tx_id);
tx_ids.push(tx_id);
},
MakeItRain => {
make_it_rain(transaction_service.clone(), config.fee_per_gram, parsed.args).await?;
},
CoinSplit => {
let tx_id = coin_split(&parsed.args, &mut output_service, &mut transaction_service.clone()).await?;
tx_ids.push(tx_id);
println!("Coin split succeeded");
},
Whois => {
let public_key = match parsed.args[0].clone() {
ParsedArgument::PublicKey(key) => Ok(Box::new(key)),
_ => Err(CommandError::Argument),
}?;
let emoji_id = EmojiId::from_pubkey(&public_key);
println!("Public Key: {}", public_key.to_hex());
println!("Emoji ID : {}", emoji_id);
},
ExportUtxos => {
let utxos = output_service.get_unspent_outputs().await?;
let count = utxos.len();
let sum: MicroTari = utxos.iter().map(|utxo| utxo.value).sum();
if parsed.args.is_empty() {
for (i, utxo) in utxos.iter().enumerate() {
println!("{}. Value: {} {}", i + 1, utxo.value, utxo.features);
}
} else if let ParsedArgument::CSVFileName(file) = parsed.args[1].clone() {
write_utxos_to_csv_file(utxos, file)?;
} else {
}
println!("Total number of UTXOs: {}", count);
println!("Total value of UTXOs: {}", sum);
},
ExportSpentUtxos => {
let utxos = output_service.get_spent_outputs().await?;
let count = utxos.len();
let sum: MicroTari = utxos.iter().map(|utxo| utxo.value).sum();
if parsed.args.is_empty() {
for (i, utxo) in utxos.iter().enumerate() {
println!("{}. Value: {} {}", i + 1, utxo.value, utxo.features);
}
} else if let ParsedArgument::CSVFileName(file) = parsed.args[1].clone() {
write_utxos_to_csv_file(utxos, file)?;
} else {
}
println!("Total number of UTXOs: {}", count);
println!("Total value of UTXOs: {}", sum);
},
CountUtxos => {
let utxos = output_service.get_unspent_outputs().await?;
let count = utxos.len();
let values: Vec<MicroTari> = utxos.iter().map(|utxo| utxo.value).collect();
let sum: MicroTari = values.iter().sum();
println!("Total number of UTXOs: {}", count);
println!("Total value of UTXOs : {}", sum);
if let Some(min) = values.iter().min() {
println!("Minimum value UTXO : {}", min);
}
if count > 0 {
let average = f64::from(sum) / count as f64;
let average = Tari::from(MicroTari(average.round() as u64));
println!("Average value UTXO : {}", average);
}
if let Some(max) = values.iter().max() {
println!("Maximum value UTXO : {}", max);
}
},
SetBaseNode => {
set_base_node_peer(wallet.clone(), &parsed.args).await?;
},
SetCustomBaseNode => {
let (public_key, net_address) = set_base_node_peer(wallet.clone(), &parsed.args).await?;
wallet
.db
.set_client_key_value(CUSTOM_BASE_NODE_PUBLIC_KEY_KEY.to_string(), public_key.to_string())
.await?;
wallet
.db
.set_client_key_value(CUSTOM_BASE_NODE_ADDRESS_KEY.to_string(), net_address.to_string())
.await?;
println!("Custom base node peer saved in wallet database.");
},
ClearCustomBaseNode => {
wallet
.db
.clear_client_value(CUSTOM_BASE_NODE_PUBLIC_KEY_KEY.to_string())
.await?;
wallet
.db
.clear_client_value(CUSTOM_BASE_NODE_ADDRESS_KEY.to_string())
.await?;
println!("Custom base node peer cleared from wallet database.");
},
InitShaAtomicSwap => {
let (tx_id, pre_image, output) =
init_sha_atomic_swap(transaction_service.clone(), config.fee_per_gram, parsed.clone().args).await?;
debug!(target: LOG_TARGET, "tari HTLC tx_id {}", tx_id);
let hash: [u8; 32] = Sha256::digest(pre_image.as_bytes()).into();
println!("pre_image hex: {}", pre_image.to_hex());
println!("pre_image hash: {}", hash.to_hex());
println!("Output hash: {}", output.hash().to_hex());
tx_ids.push(tx_id);
},
FinaliseShaAtomicSwap => {
let tx_id =
finalise_sha_atomic_swap(output_service.clone(), transaction_service.clone(), parsed.args).await?;
debug!(target: LOG_TARGET, "claiming tari HTLC tx_id {}", tx_id);
tx_ids.push(tx_id);
},
ClaimShaAtomicSwapRefund => {
let tx_id = claim_htlc_refund(output_service.clone(), transaction_service.clone(), parsed.args).await?;
debug!(target: LOG_TARGET, "claiming tari HTLC tx_id {}", tx_id);
tx_ids.push(tx_id);
},
RegisterAsset => {
let name = parsed.args[0].to_string();
let message = format!("Register asset: {}", name);
let mut manager = wallet.asset_manager.clone();
let key_manager = wallet.key_manager_service.clone();
key_manager.add_new_branch(KEY_MANAGER_ASSET_BRANCH).await?;
let result = key_manager.get_next_key(KEY_MANAGER_ASSET_BRANCH).await?;
let public_key = PublicKey::from_secret_key(&result.key);
let public_key_hex = public_key.to_hex();
println!("Registering asset named: {name}");
println!("with public key: {public_key_hex}");
let (tx_id, transaction) = manager
.create_registration_transaction(name, public_key, vec![], None, None, vec![])
.await?;
transaction_service
.submit_transaction(tx_id, transaction, 0.into(), message)
.await?;
println!("Done!");
},
MintTokens => {
println!("Minting tokens for asset");
let public_key = match parsed.args.get(0) {
Some(ParsedArgument::PublicKey(ref key)) => Ok(key.clone()),
_ => Err(CommandError::Argument),
}?;
let unique_ids = parsed.args[1..]
.iter()
.map(|arg| {
let s = arg.to_string();
if let Some(s) = s.strip_prefix("0x") {
Hex::from_hex(s).map_err(|_| CommandError::Argument)
} else {
Ok(s.into_bytes())
}
})
.collect::<Result<Vec<Vec<u8>>, _>>()?;
let mut asset_manager = wallet.asset_manager.clone();
let asset = asset_manager.get_owned_asset_by_pub_key(&public_key).await?;
println!("Asset name: {}", asset.name());
let message = format!("Minting {} tokens for asset {}", unique_ids.len(), asset.name());
let (tx_id, transaction) = asset_manager
.create_minting_transaction(
&public_key,
asset.owner_commitment(),
unique_ids.into_iter().map(|id| (id, None)).collect(),
)
.await?;
transaction_service
.submit_transaction(tx_id, transaction, 0.into(), message)
.await?;
},
CreateInitialCheckpoint => {
println!("Creating Initial Checkpoint for Asset");
let asset_public_key = match parsed.args.get(0) {
Some(ParsedArgument::PublicKey(ref key)) => Ok(key.clone()),
_ => Err(CommandError::Argument),
}?;
let merkle_root = match parsed.args.get(1) {
Some(ParsedArgument::Text(ref root)) => {
let bytes = match &root[0..2] {
"0x" => Vec::<u8>::from_hex(&root[2..]).map_err(|_| CommandError::Argument)?,
_ => Vec::<u8>::from_hex(root).map_err(|_| CommandError::Argument)?,
};
copy_into_fixed_array(&bytes).map_err(|_| CommandError::Argument)?
},
_ => return Err(CommandError::Argument),
};
let message = format!("Initial asset checkpoint for {}", asset_public_key);
let mut asset_manager = wallet.asset_manager.clone();
let (tx_id, transaction) = asset_manager
.create_initial_asset_checkpoint(&asset_public_key, merkle_root)
.await?;
transaction_service
.submit_transaction(tx_id, transaction, 0.into(), message)
.await?;
},
CreateCommitteeDefinition => {
let asset_public_key = match parsed.args.get(0) {
Some(ParsedArgument::PublicKey(ref key)) => Ok(key.clone()),
_ => Err(CommandError::Argument),
}?;
let public_key_hex = asset_public_key.to_hex();
println!("Creating Committee Definition for Asset");
println!("with public key {public_key_hex}");
let committee_public_keys: Vec<PublicKey> = parsed.args[1..]
.iter()
.map(|pk| match pk {
ParsedArgument::PublicKey(ref key) => Ok(key.clone()),
_ => Err(CommandError::Argument),
})
.collect::<Result<_, _>>()?;
let num_members = committee_public_keys.len();
if num_members < 1 {
return Err(CommandError::Config("Committee has no members!".into()));
}
let message = format!(
"Committee definition with {} members for {}",
num_members, asset_public_key
);
println!("with {num_members} committee members");
let mut asset_manager = wallet.asset_manager.clone();
// todo: effective sidechain height...
// todo: updating
let (tx_id, transaction) = asset_manager
.create_committee_definition(&asset_public_key, &committee_public_keys, 0, true)
.await?;
transaction_service
.submit_transaction(tx_id, transaction, 0.into(), message)
.await?;
println!("Done!");
},
RevalidateWalletDb => {
output_service
.revalidate_all_outputs()
.await
.map_err(CommandError::OutputManagerError)?;
transaction_service
.revalidate_all_transactions()
.await
.map_err(CommandError::TransactionServiceError)?;
},
}
}
// listen to event stream
if tx_ids.is_empty() {
trace!(
target: LOG_TARGET,
"Wallet command runner - no transactions to monitor."
);
} else {
let duration = config.command_send_wait_timeout;
debug!(
target: LOG_TARGET,
"wallet monitor_transactions timeout duration {:.2?}", duration
);
match timeout(
duration,
monitor_transactions(transaction_service.clone(), tx_ids, wait_stage),
)
.await
{
Ok(txs) => {
debug!(
target: LOG_TARGET,
"monitor_transactions done to stage {:?} with tx_ids: {:?}", wait_stage, txs
);
println!("Done! All transactions monitored to {:?} stage.", wait_stage);
},
Err(_e) => {
println!(
"The configured timeout ({:#?}) was reached before all transactions reached the {:?} stage. See \
the logs for more info.",
duration, wait_stage
);
},
}
}
Ok(())
}
fn write_utxos_to_csv_file(utxos: Vec<UnblindedOutput>, file_path: String) -> Result<(), CommandError> {
let factory = PedersenCommitmentFactory::default();
let file = File::create(file_path).map_err(|e| CommandError::CSVFile(e.to_string()))?;
let mut csv_file = LineWriter::new(file);
writeln!(
csv_file,
r##""index","value","spending_key","commitment","flags","maturity","script","input_data","script_private_key","sender_offset_public_key","public_nonce","signature_u","signature_v""##
)
.map_err(|e| CommandError::CSVFile(e.to_string()))?;
for (i, utxo) in utxos.iter().enumerate() {
writeln!(
csv_file,
r##""{}","{}","{}","{}","{:?}","{}","{}","{}","{}","{}","{}","{}","{}""##,
i + 1,
utxo.value.0,
utxo.spending_key.to_hex(),
utxo.as_transaction_input(&factory)?
.commitment()
.map_err(|e| CommandError::WalletError(WalletError::TransactionError(e)))?
.to_hex(),
utxo.features.flags,
utxo.features.maturity,
utxo.script.to_hex(),
utxo.input_data.to_hex(),
utxo.script_private_key.to_hex(),
utxo.sender_offset_public_key.to_hex(),
utxo.metadata_signature.public_nonce().to_hex(),
utxo.metadata_signature.u().to_hex(),
utxo.metadata_signature.v().to_hex(),
)
.map_err(|e| CommandError::CSVFile(e.to_string()))?;
}
Ok(())
}
| {
let (amount, dest_pubkey, message) = get_init_sha_atomic_swap_parameters(args)?;
let (tx_id, pre_image, output) = wallet_transaction_service
.send_sha_atomic_swap_transaction(dest_pubkey, amount, fee_per_gram * uT, message)
.await
.map_err(CommandError::TransactionServiceError)?;
Ok((tx_id, pre_image, output))
} |
test_common_test.go | // Copyright 2018 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package frontend
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
"infra/appengine/crosskylabadmin/internal/app/clients"
)
func | (t *testing.T) {
Convey("matching with nil args fails", t, func() {
So((&createTaskArgsMatcher{
DutID: "dut_id",
DutState: "dut_state",
Priority: 10,
CmdSubString: "-b c",
}).Matches(nil), ShouldBeFalse)
})
Convey("with non-nil args", t, func() {
arg := &clients.SwarmingCreateTaskArgs{
Cmd: []string{"a", "-b", "c"},
DutID: "dut_id",
DutState: "dut_state",
ExecutionTimeoutSecs: 20,
Priority: 10,
}
Convey("all fields matching pass", func() {
So((&createTaskArgsMatcher{
DutID: "dut_id",
DutState: "dut_state",
Priority: 10,
CmdSubString: "-b c",
}).Matches(arg), ShouldBeTrue)
})
Convey("missing fields matching pass", func() {
So((&createTaskArgsMatcher{}).Matches(arg), ShouldBeTrue)
})
Convey("mistaching DutID fails", func() {
So((&createTaskArgsMatcher{
DutID: "wrong",
DutState: "dut_state",
Priority: 10,
CmdSubString: "-b c",
}).Matches(arg), ShouldBeFalse)
})
Convey("mistaching DutState fails", func() {
So((&createTaskArgsMatcher{
DutID: "dut_id",
DutState: "wrong",
Priority: 10,
CmdSubString: "-b c",
}).Matches(arg), ShouldBeFalse)
})
Convey("mistaching Priority fails", func() {
So((&createTaskArgsMatcher{
DutID: "dut_id",
DutState: "dut_state",
Priority: 999,
CmdSubString: "-b c",
}).Matches(arg), ShouldBeFalse)
})
Convey("mistaching CmdSubstring fails", func() {
So((&createTaskArgsMatcher{
DutID: "dut_id",
DutState: "dut_state",
Priority: 10,
CmdSubString: "-x z",
}).Matches(arg), ShouldBeFalse)
})
})
}
| TestCreateTaskArgsMatcher |
el_GR_test.go | package el_GR
import (
"testing"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
func TestLocale(t *testing.T) {
trans := New()
expected := "el_GR"
if trans.Locale() != expected {
t.Errorf("Expected '%s' Got '%s'", expected, trans.Locale())
}
}
func TestPluralsRange(t *testing.T) {
trans := New()
tests := []struct {
expected locales.PluralRule
}{
// {
// expected: locales.PluralRuleOther,
// },
}
rules := trans.PluralsRange()
// expected := 1
// if len(rules) != expected {
// t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
// }
for _, tt := range tests {
r := locales.PluralRuleUnknown
for i := 0; i < len(rules); i++ {
if rules[i] == tt.expected {
r = rules[i]
break
}
}
if r == locales.PluralRuleUnknown {
t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
}
}
}
func TestPluralsOrdinal(t *testing.T) {
trans := New()
tests := []struct {
expected locales.PluralRule
}{
// {
// expected: locales.PluralRuleOne,
// },
// {
// expected: locales.PluralRuleTwo,
// },
// {
// expected: locales.PluralRuleFew,
// },
// {
// expected: locales.PluralRuleOther,
// },
}
rules := trans.PluralsOrdinal()
// expected := 4
// if len(rules) != expected {
// t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
// }
for _, tt := range tests {
r := locales.PluralRuleUnknown
for i := 0; i < len(rules); i++ {
if rules[i] == tt.expected {
r = rules[i]
break
}
}
if r == locales.PluralRuleUnknown {
t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
}
}
}
func TestPluralsCardinal(t *testing.T) {
trans := New()
tests := []struct {
expected locales.PluralRule
}{
// {
// expected: locales.PluralRuleOne,
// },
// {
// expected: locales.PluralRuleOther,
// },
}
rules := trans.PluralsCardinal()
// expected := 2
// if len(rules) != expected {
// t.Errorf("Expected '%d' Got '%d'", expected, len(rules))
// }
for _, tt := range tests {
r := locales.PluralRuleUnknown
for i := 0; i < len(rules); i++ {
if rules[i] == tt.expected {
r = rules[i]
break
}
}
if r == locales.PluralRuleUnknown {
t.Errorf("Expected '%s' Got '%s'", tt.expected, r)
}
}
}
func TestRangePlurals(t *testing.T) {
trans := New()
tests := []struct {
num1 float64
v1 uint64
num2 float64
v2 uint64
expected locales.PluralRule
}{
// {
// num1: 1,
// v1: 1,
// num2: 2,
// v2: 2,
// expected: locales.PluralRuleOther,
// },
}
for _, tt := range tests {
rule := trans.RangePluralRule(tt.num1, tt.v1, tt.num2, tt.v2)
if rule != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
}
}
}
func TestOrdinalPlurals(t *testing.T) {
trans := New()
tests := []struct {
num float64
v uint64
expected locales.PluralRule
}{
// {
// num: 1,
// v: 0,
// expected: locales.PluralRuleOne,
// },
// {
// num: 2,
// v: 0,
// expected: locales.PluralRuleTwo,
// },
// {
// num: 3,
// v: 0,
// expected: locales.PluralRuleFew,
// },
// {
// num: 4,
// v: 0,
// expected: locales.PluralRuleOther,
// },
}
for _, tt := range tests {
rule := trans.OrdinalPluralRule(tt.num, tt.v)
if rule != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
}
}
}
func TestCardinalPlurals(t *testing.T) {
trans := New()
tests := []struct {
num float64
v uint64
expected locales.PluralRule
}{
// {
// num: 1,
// v: 0,
// expected: locales.PluralRuleOne,
// },
// {
// num: 4,
// v: 0,
// expected: locales.PluralRuleOther,
// },
}
for _, tt := range tests {
rule := trans.CardinalPluralRule(tt.num, tt.v)
if rule != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, rule)
}
}
}
func TestDaysAbbreviated(t *testing.T) {
trans := New()
days := trans.WeekdaysAbbreviated()
for i, day := range days {
s := trans.WeekdayAbbreviated(time.Weekday(i))
if s != day {
t.Errorf("Expected '%s' Got '%s'", day, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 0,
// expected: "Sun",
// },
// {
// idx: 1,
// expected: "Mon",
// },
// {
// idx: 2,
// expected: "Tue",
// },
// {
// idx: 3,
// expected: "Wed",
// },
// {
// idx: 4,
// expected: "Thu",
// },
// {
// idx: 5,
// expected: "Fri",
// },
// {
// idx: 6,
// expected: "Sat",
// },
}
for _, tt := range tests {
s := trans.WeekdayAbbreviated(time.Weekday(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestDaysNarrow(t *testing.T) {
trans := New()
days := trans.WeekdaysNarrow()
for i, day := range days {
s := trans.WeekdayNarrow(time.Weekday(i))
if s != day {
t.Errorf("Expected '%s' Got '%s'", string(day), s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 0,
// expected: "S",
// },
// {
// idx: 1,
// expected: "M",
// },
// {
// idx: 2,
// expected: "T",
// },
// {
// idx: 3,
// expected: "W",
// },
// {
// idx: 4,
// expected: "T",
// },
// {
// idx: 5,
// expected: "F",
// },
// {
// idx: 6,
// expected: "S",
// },
}
for _, tt := range tests {
s := trans.WeekdayNarrow(time.Weekday(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestDaysShort(t *testing.T) {
trans := New()
days := trans.WeekdaysShort()
for i, day := range days {
s := trans.WeekdayShort(time.Weekday(i))
if s != day {
t.Errorf("Expected '%s' Got '%s'", day, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 0,
// expected: "Su",
// },
// {
// idx: 1,
// expected: "Mo",
// },
// {
// idx: 2,
// expected: "Tu",
// },
// {
// idx: 3,
// expected: "We",
// },
// {
// idx: 4,
// expected: "Th",
// },
// {
// idx: 5,
// expected: "Fr",
// },
// {
// idx: 6,
// expected: "Sa",
// },
}
for _, tt := range tests {
s := trans.WeekdayShort(time.Weekday(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestDaysWide(t *testing.T) {
trans := New()
days := trans.WeekdaysWide()
for i, day := range days {
s := trans.WeekdayWide(time.Weekday(i))
if s != day {
t.Errorf("Expected '%s' Got '%s'", day, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 0,
// expected: "Sunday",
// },
// {
// idx: 1,
// expected: "Monday",
// },
// {
// idx: 2,
// expected: "Tuesday",
// },
// {
// idx: 3,
// expected: "Wednesday",
// },
// {
// idx: 4,
// expected: "Thursday",
// },
// {
// idx: 5,
// expected: "Friday",
// },
// {
// idx: 6,
// expected: "Saturday",
// },
}
for _, tt := range tests {
s := trans.WeekdayWide(time.Weekday(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestMonthsAbbreviated(t *testing.T) {
trans := New()
months := trans.MonthsAbbreviated()
for i, month := range months {
s := trans.MonthAbbreviated(time.Month(i + 1))
if s != month {
t.Errorf("Expected '%s' Got '%s'", month, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 1,
// expected: "Jan",
// },
// {
// idx: 2,
// expected: "Feb",
// },
// {
// idx: 3,
// expected: "Mar",
// },
// {
// idx: 4,
// expected: "Apr",
// },
// {
// idx: 5,
// expected: "May",
// },
// {
// idx: 6,
// expected: "Jun",
// },
// {
// idx: 7,
// expected: "Jul",
// },
// {
// idx: 8,
// expected: "Aug",
// },
// {
// idx: 9,
// expected: "Sep",
// },
// {
// idx: 10,
// expected: "Oct",
// },
// {
// idx: 11,
// expected: "Nov",
// },
// {
// idx: 12,
// expected: "Dec",
// },
}
for _, tt := range tests {
s := trans.MonthAbbreviated(time.Month(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestMonthsNarrow(t *testing.T) {
trans := New()
months := trans.MonthsNarrow()
for i, month := range months {
s := trans.MonthNarrow(time.Month(i + 1))
if s != month {
t.Errorf("Expected '%s' Got '%s'", month, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 1,
// expected: "J",
// },
// {
// idx: 2,
// expected: "F",
// },
// {
// idx: 3,
// expected: "M",
// },
// {
// idx: 4,
// expected: "A",
// },
// {
// idx: 5,
// expected: "M",
// },
// {
// idx: 6,
// expected: "J",
// },
// {
// idx: 7,
// expected: "J",
// },
// {
// idx: 8,
// expected: "A",
// },
// {
// idx: 9,
// expected: "S",
// },
// {
// idx: 10,
// expected: "O",
// },
// {
// idx: 11,
// expected: "N",
// },
// {
// idx: 12,
// expected: "D",
// },
}
for _, tt := range tests {
s := trans.MonthNarrow(time.Month(tt.idx))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestMonthsWide(t *testing.T) {
trans := New()
months := trans.MonthsWide()
for i, month := range months {
s := trans.MonthWide(time.Month(i + 1))
if s != month {
t.Errorf("Expected '%s' Got '%s'", month, s)
}
}
tests := []struct {
idx int
expected string
}{
// {
// idx: 1,
// expected: "January",
// },
// {
// idx: 2,
// expected: "February",
// },
// {
// idx: 3,
// expected: "March",
// },
// {
// idx: 4,
// expected: "April",
// },
// {
// idx: 5,
// expected: "May",
// },
// {
// idx: 6,
// expected: "June",
// },
// {
// idx: 7,
// expected: "July",
// },
// {
// idx: 8,
// expected: "August",
// },
// {
// idx: 9,
// expected: "September",
// },
// {
// idx: 10,
// expected: "October",
// },
// {
// idx: 11,
// expected: "November",
// },
// {
// idx: 12,
// expected: "December",
// },
}
for _, tt := range tests {
s := string(trans.MonthWide(time.Month(tt.idx)))
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtTimeFull(t *testing.T) {
// loc, err := time.LoadLocation("America/Toronto")
// if err != nil {
// t.Errorf("Expected '<nil>' Got '%s'", err)
// }
// fixed := time.FixedZone("OTHER", -4)
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc),
// expected: "9:05:01 am Eastern Standard Time",
// },
// {
// t: time.Date(2016, 02, 03, 20, 5, 1, 0, fixed),
// expected: "8:05:01 pm OTHER",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtTimeFull(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtTimeLong(t *testing.T) {
// loc, err := time.LoadLocation("America/Toronto")
// if err != nil {
// t.Errorf("Expected '<nil>' Got '%s'", err)
// }
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 5, 1, 0, loc),
// expected: "9:05:01 am EST",
// },
// {
// t: time.Date(2016, 02, 03, 20, 5, 1, 0, loc),
// expected: "8:05:01 pm EST",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtTimeLong(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtTimeMedium(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC),
// expected: "9:05:01 am",
// },
// {
// t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC),
// expected: "8:05:01 pm",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtTimeMedium(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtTimeShort(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 5, 1, 0, time.UTC),
// expected: "9:05 am",
// },
// {
// t: time.Date(2016, 02, 03, 20, 5, 1, 0, time.UTC),
// expected: "8:05 pm",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtTimeShort(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtDateFull(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
// expected: "Wednesday, February 3, 2016",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtDateFull(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtDateLong(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
// expected: "February 3, 2016",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtDateLong(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtDateMedium(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
// expected: "Feb 3, 2016",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtDateMedium(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtDateShort(t *testing.T) {
tests := []struct {
t time.Time
expected string
}{
// {
// t: time.Date(2016, 02, 03, 9, 0, 1, 0, time.UTC),
// expected: "2/3/16",
// },
// {
// t: time.Date(-500, 02, 03, 9, 0, 1, 0, time.UTC),
// expected: "2/3/500",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtDateShort(tt.t)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func | (t *testing.T) {
tests := []struct {
num float64
v uint64
expected string
}{
// {
// num: 1123456.5643,
// v: 2,
// expected: "1,123,456.56",
// },
// {
// num: 1123456.5643,
// v: 1,
// expected: "1,123,456.6",
// },
// {
// num: 221123456.5643,
// v: 3,
// expected: "221,123,456.564",
// },
// {
// num: -221123456.5643,
// v: 3,
// expected: "-221,123,456.564",
// },
// {
// num: -221123456.5643,
// v: 3,
// expected: "-221,123,456.564",
// },
// {
// num: 0,
// v: 2,
// expected: "0.00",
// },
// {
// num: -0,
// v: 2,
// expected: "0.00",
// },
// {
// num: -0,
// v: 2,
// expected: "0.00",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtNumber(tt.num, tt.v)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtCurrency(t *testing.T) {
tests := []struct {
num float64
v uint64
currency currency.Type
expected string
}{
// {
// num: 1123456.5643,
// v: 2,
// currency: currency.USD,
// expected: "$1,123,456.56",
// },
// {
// num: 1123456.5643,
// v: 1,
// currency: currency.USD,
// expected: "$1,123,456.60",
// },
// {
// num: 221123456.5643,
// v: 3,
// currency: currency.USD,
// expected: "$221,123,456.564",
// },
// {
// num: -221123456.5643,
// v: 3,
// currency: currency.USD,
// expected: "-$221,123,456.564",
// },
// {
// num: -221123456.5643,
// v: 3,
// currency: currency.CAD,
// expected: "-CAD 221,123,456.564",
// },
// {
// num: 0,
// v: 2,
// currency: currency.USD,
// expected: "$0.00",
// },
// {
// num: -0,
// v: 2,
// currency: currency.USD,
// expected: "$0.00",
// },
// {
// num: -0,
// v: 2,
// currency: currency.CAD,
// expected: "CAD 0.00",
// },
// {
// num: 1.23,
// v: 0,
// currency: currency.USD,
// expected: "$1.00",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtCurrency(tt.num, tt.v, tt.currency)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtAccounting(t *testing.T) {
tests := []struct {
num float64
v uint64
currency currency.Type
expected string
}{
// {
// num: 1123456.5643,
// v: 2,
// currency: currency.USD,
// expected: "$1,123,456.56",
// },
// {
// num: 1123456.5643,
// v: 1,
// currency: currency.USD,
// expected: "$1,123,456.60",
// },
// {
// num: 221123456.5643,
// v: 3,
// currency: currency.USD,
// expected: "$221,123,456.564",
// },
// {
// num: -221123456.5643,
// v: 3,
// currency: currency.USD,
// expected: "($221,123,456.564)",
// },
// {
// num: -221123456.5643,
// v: 3,
// currency: currency.CAD,
// expected: "(CAD 221,123,456.564)",
// },
// {
// num: -0,
// v: 2,
// currency: currency.USD,
// expected: "$0.00",
// },
// {
// num: -0,
// v: 2,
// currency: currency.CAD,
// expected: "CAD 0.00",
// },
// {
// num: 1.23,
// v: 0,
// currency: currency.USD,
// expected: "$1.00",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtAccounting(tt.num, tt.v, tt.currency)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
func TestFmtPercent(t *testing.T) {
tests := []struct {
num float64
v uint64
expected string
}{
// {
// num: 15,
// v: 0,
// expected: "15%",
// },
// {
// num: 15,
// v: 2,
// expected: "15.00%",
// },
// {
// num: 434.45,
// v: 0,
// expected: "434%",
// },
// {
// num: 34.4,
// v: 2,
// expected: "34.40%",
// },
// {
// num: -34,
// v: 0,
// expected: "-34%",
// },
}
trans := New()
for _, tt := range tests {
s := trans.FmtPercent(tt.num, tt.v)
if s != tt.expected {
t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
}
}
}
| TestFmtNumber |
main.py | import itertools
from emoji_chengyu.puzzle import gen_puzzle
def emoji_chengyu():
N = 100
pg = gen_puzzle()
puzzles = list(itertools.islice(pg, N))
puzzles.sort(key=lambda p: sum(p.mask), reverse=True) |
M = 20
for puzzle in puzzles[:M]:
print(''.join(puzzle.puzzle), puzzle.chengyu_item.word) | |
score_definition.rs | use crate::util::{Element, SCError, SCResult};
use super::ScoreDefinitionFragment;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScoreDefinition {
fragments: Vec<ScoreDefinitionFragment>,
}
impl ScoreDefinition {
pub fn new(fragments: impl IntoIterator<Item=ScoreDefinitionFragment>) -> Self {
Self { fragments: fragments.into_iter().collect() }
}
#[inline]
pub fn fragments(&self) -> &Vec<ScoreDefinitionFragment> { &self.fragments }
}
impl TryFrom<&Element> for ScoreDefinition {
type Error = SCError;
fn | (elem: &Element) -> SCResult<Self> {
Ok(ScoreDefinition {
fragments: elem.childs_by_name("fragment").map(ScoreDefinitionFragment::try_from).collect::<SCResult<_>>()?,
})
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use crate::{util::Element, protocol::{ScoreDefinition, ScoreDefinitionFragment, ScoreAggregation}};
#[test]
fn test_parsing() {
assert_eq!(ScoreDefinition::try_from(&Element::from_str(r#"
<definition>
<fragment name="Siegpunkte">
<aggregation>SUM</aggregation>
<relevantForRanking>true</relevantForRanking>
</fragment>
<fragment name="∅ Punkte">
<aggregation>AVERAGE</aggregation>
<relevantForRanking>true</relevantForRanking>
</fragment>
</definition>
"#).unwrap()).unwrap(), ScoreDefinition::new([
ScoreDefinitionFragment::new("Siegpunkte", ScoreAggregation::Sum, true),
ScoreDefinitionFragment::new("∅ Punkte", ScoreAggregation::Average, true),
]));
}
}
| try_from |
validation.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package backendconfig
import (
"fmt"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1"
)
const (
OAuthClientIDKey = "client_id"
OAuthClientSecretKey = "client_secret"
)
var supportedAffinities = map[string]bool{
"NONE": true,
"CLIENT_IP": true,
"GENERATED_COOKIE": true,
}
func | (kubeClient kubernetes.Interface, beConfig *backendconfigv1.BackendConfig) error {
if beConfig == nil {
return nil
}
if err := validateIAP(kubeClient, beConfig); err != nil {
return err
}
if err := validateSessionAffinity(kubeClient, beConfig); err != nil {
return err
}
return nil
}
// TODO(rramkumar): Return errors as constants so that the unit tests can distinguish
// between which error is returned.
func validateIAP(kubeClient kubernetes.Interface, beConfig *backendconfigv1.BackendConfig) error {
// If IAP settings are not found or IAP is not enabled then don't bother continuing.
if beConfig.Spec.Iap == nil || beConfig.Spec.Iap.Enabled == false {
return nil
}
// If necessary, get the OAuth credentials stored in the K8s secret.
if beConfig.Spec.Iap.OAuthClientCredentials != nil && beConfig.Spec.Iap.OAuthClientCredentials.SecretName != "" {
secretName := beConfig.Spec.Iap.OAuthClientCredentials.SecretName
secret, err := kubeClient.CoreV1().Secrets(beConfig.Namespace).Get(secretName, meta_v1.GetOptions{})
if err != nil {
return fmt.Errorf("error retrieving secret %v: %v", secretName, err)
}
clientID, ok := secret.Data[OAuthClientIDKey]
if !ok {
return fmt.Errorf("secret %v missing %v data", secretName, OAuthClientIDKey)
}
clientSecret, ok := secret.Data[OAuthClientSecretKey]
if !ok {
return fmt.Errorf("secret %v missing %v data'", secretName, OAuthClientSecretKey)
}
beConfig.Spec.Iap.OAuthClientCredentials.ClientID = string(clientID)
beConfig.Spec.Iap.OAuthClientCredentials.ClientSecret = string(clientSecret)
}
if beConfig.Spec.Cdn != nil && beConfig.Spec.Cdn.Enabled {
return fmt.Errorf("iap and cdn cannot be enabled at the same time")
}
return nil
}
func validateSessionAffinity(kubeClient kubernetes.Interface, beConfig *backendconfigv1.BackendConfig) error {
if beConfig.Spec.SessionAffinity == nil {
return nil
}
if beConfig.Spec.SessionAffinity.AffinityType != "" {
if _, ok := supportedAffinities[beConfig.Spec.SessionAffinity.AffinityType]; !ok {
return fmt.Errorf("unsupported AffinityType: %s, should be one of NONE, CLIENT_IP, or GENERATED_COOKIE",
beConfig.Spec.SessionAffinity.AffinityType)
}
}
if beConfig.Spec.SessionAffinity.AffinityCookieTtlSec != nil {
if *beConfig.Spec.SessionAffinity.AffinityCookieTtlSec < 0 || *beConfig.Spec.SessionAffinity.AffinityCookieTtlSec > 86400 {
return fmt.Errorf("unsupported AffinityCookieTtlSec: %d, should be between 0 and 86400",
*beConfig.Spec.SessionAffinity.AffinityCookieTtlSec)
}
}
return nil
}
| Validate |
credentials.py | from cliff.lister import Lister | from factioncli.processing.config import get_passwords
class Credentials(Lister):
"Returns a list of the default credentials for this instance of Faction"
def take_action(self, parsed_args):
passwords = get_passwords()
return ("Type", "Username", "Password"), passwords | |
Finish.js | /**
* Copyright (C) 2006-2019 Talend Inc. - www.talend.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { Action, Dialog, Toggle } from '@talend/react-components';
import Help from '../Component/Help';
import Input from '../Component/Input';
import Summary from './Summary';
import { GENERATOR_GITHUB_URL, GENERATOR_ZIP_URL } from '../constants';
import theme from './Finish.scss';
export default class F | extends React.Component {
constructor(props) {
super(props);
const model = this.createModel(this.props);
this.state = {
project: model,
github: {
username: '',
password: '',
organization: '',
repository: model.artifact,
useOrganization: true
}
};
this.initDownloadLink(this.state);
['closeModal', 'notifyProgressDone', 'createModel', 'onGithub', 'showGithub'].forEach(i => this[i] = this[i].bind(this));
}
initDownloadLink(state) {
state.downloadState = btoa(JSON.stringify(state.project));
}
componentWillReceiveProps(nextProps) {
this.setState(state => {
state.project = this.createModel(nextProps);
state.github.repository = state.project.artifact;
this.initDownloadLink(state);
});
}
onClearGithubModal() {
this.setState({ githubError: undefined, current: undefined });
}
createModel(props) {
// we copy the model to compute sources and processors attributes
let lightCopyModel = Object.assign({}, props.project);
const components = props.components();
lightCopyModel.sources = components.filter(c => c.type === 'Input').map(c => {
let source = Object.assign({}, c.source);
source.name = c.configuration.name;
return source;
});
lightCopyModel.processors = components.filter(c => c.type === 'Processor').map(c => {
let processor = Object.assign({}, c.processor);
processor.name = c.configuration.name;
return processor;
});
return lightCopyModel;
}
listenForDone(promise) {
return promise.then(this.notifyProgressDone, this.notifyProgressDone);
}
closeModal() {
this.setState({current: undefined});
}
notifyProgressDone() {
this.setState({progress: undefined});
}
showGithub() {
this.setState({current: 'github'});
}
onGithub() {
if (this.isEmpty(this.state.github.username) || this.isEmpty(this.state.github.password) ||
(this.state.github.useOrganization && this.isEmpty(this.state.github.organization)) || this.isEmpty(this.state.github.repository)) {
this.setState({githubError: 'Please fill the form properly before launching the project creation.'});
return;
}
this.listenForDone(this.doGithub());
}
doGithub(model) {
this.setState({progress: 'github'});
return fetch(`${GENERATOR_GITHUB_URL}`, {
method: 'POST',
body: JSON.stringify({ model: this.state.project, repository: this.state.github }),
headers: new Headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
})
.then(d => {
if (d.status > 299) {
d.json().then(json => {
this.setState({
current: 'message',
modalMessage: (
<div className={theme.error}>
<p>{json.message || JSON.stringify(json)}</p>
</div>
)
});
});
} else {
const link = `https://github.com/${this.state.github.useOrganization ? this.state.github.organization : this.state.github.username}/${this.state.github.repository}`;
this.setState({
current: 'message',
modalMessage: (
<div>
Project <a target="_blank" href={link}>{this.state.github.repository}</a> created with success!
</div>
)
});
}
});
}
isEmpty(str) {
return !str || str.trim().length === 0;
}
render() {
const fieldClasses = ['field', theme.field].join(' ');
return (
<div className={theme.Finish}>
<h2>Project Summary</h2>
<Summary project={this.state.project} />
<div className={theme.bigButton}>
<form id="download-zip-form" novalidate action={GENERATOR_ZIP_URL} method="POST">
<input type="hidden" name="project" value={this.state.downloadState} />
<Action label="Download as ZIP" bsStyle="info" icon="fa-file-archive-o" type="submit"
inProgress={this.state.progress === 'zip'} disabled={!!this.state.progress && this.state.progress !== 'zip'}
className="btn btn-lg" />
</form>
<form novalidate submit={e => e.preventDefault()}>
<Action label="Create on Github" bsStyle="primary" onClick={this.showGithub} icon="fa-github"
inProgress={this.state.progress === 'github'} disabled={!!this.state.progress && this.state.progress !== 'github'}
className="btn btn-lg" />
</form>
</div>
{
this.state.current === 'github' && (
<Dialog header="Github Configuration"
bsDialogProps={{show: true, size: "small", onHide: () => {this.notifyProgressDone(); this.onClearGithubModal(); } }}
action={{label: "Create on Github", onClick: this.onGithub }}>
<form novalidate submit={e => e.preventDefault()} className={theme.modal}>
{!!this.state.githubError && <p className={theme.error}>{this.state.githubError}</p>}
<div className={fieldClasses}>
<label forHtml="githubUser">User</label>
<Help title="Github User" i18nKey="finish_github_user" content={
<span>
<p>The Github username to use to create the project.</p>
</span>
} />
<Input className="form-control" id="githubUser" type="text" placeholder="Enter your Github username..." required
aggregate={this.state.github} accessor="username"/>
</div>
<div className={fieldClasses}>
<label forHtml="githubPassword">Password</label>
<Help title="Github Password" i18nKey="finish_github_password" content={
<span>
<p>The Github password to use to create the project.</p>
</span>
} />
<Input className="form-control" id="githubPassword" type="password" placeholder="Enter your Github password..." required
aggregate={this.state.github} accessor="password"/>
</div>
{
!!this.state.github.useOrganization && (
<div className={fieldClasses}>
<label forHtml="githubOrganization">Organization</label>
<Help title="Github Organization" i18nKey="finish_github_organization" content={
<span>
<p>The Github organization to use to create the project.</p>
</span>
} />
<Input className="form-control" id="githubOrganization" type="text" placeholder="Enter your Github organization..." required
aggregate={this.state.github} accessor="organization"/>
</div>)
}
<div className={fieldClasses}>
<label forHtml="githubRepository">Repository</label>
<Help title="Github Repository" i18nKey="finish_github_repository" content={
<span>
<p>The Github repository to create for the project.</p>
</span>
} />
<Input className="form-control" id="githubRepository" type="text" placeholder="Enter the Github repository to create..." required
aggregate={this.state.github} accessor="repository"/>
</div>
<div className={fieldClasses}>
<label forHtml="githubUseOrganization">Create the repository for an organization</label>
<Help title="Github Use Organization" i18nKey="finish_github_useOrganization" content={
<span>
<p>If checked an organization project will be created instead of a user project.</p>
</span>
} />
<Toggle id="githubUseOrganization" checked={this.state.github.useOrganization}
onChange={() => this.setState(state => state.github.useOrganization = !state.github.useOrganization)} />
</div>
</form>
</Dialog>
)
}
{
this.state.current === 'message' && (
<Dialog header="Result"
bsDialogProps={{show: true, size: "small", onHide: () => {this.notifyProgressDone();this.closeModal();} }}
action={{label: "Close", onClick: () => {this.notifyProgressDone();this.closeModal();} }}>
<p>{this.state.modalMessage}</p>
</Dialog>
)
}
</div>
);
}
}
| inish |
cmd_put.rs | // Copyright 2022 The Engula Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use engula_api::server::v1::ShardPutRequest;
use crate::{
node::engine::{GroupEngine, WriteBatch},
serverpb::v1::{EvalResult, WriteBatchRep},
Error, Result,
};
pub async fn put(group_engine: &GroupEngine, req: &ShardPutRequest) -> Result<EvalResult> | {
let put = req
.put
.as_ref()
.ok_or_else(|| Error::InvalidArgument("ShardPutRequest::put is None".into()))?;
let mut wb = WriteBatch::default();
group_engine.put(&mut wb, req.shard_id, &put.key, &put.value)?;
Ok(EvalResult {
batch: Some(WriteBatchRep {
data: wb.data().to_owned(),
}),
..Default::default()
})
} |
|
models.py |
from django.apps import apps
from django.db import models
from django.conf import settings
from django.utils.crypto import get_random_string
from django.utils.translation import ugettext_lazy as _
from exchange.models import format_printable_price, MultiCurrencyPrice
from delivery.models import DeliveryMethodField
from orders.constants import (
PAYMENT_METHODS,
ORDER_STATUSES,
ORDER_STATUS_NEW,
PAYMENT_METHOD_PRIVAT24
)
def _generate_hash():
return get_random_string(length=10)
class Order(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='orders',
verbose_name=_('Owner'), null=True, blank=True,
on_delete=models.SET_NULL)
status = models.CharField(
_('Status'),
max_length=100,
choices=ORDER_STATUSES,
default=ORDER_STATUS_NEW)
payment_method = models.CharField(
_('Payment method'),
max_length=100,
choices=PAYMENT_METHODS)
delivery = DeliveryMethodField()
first_name = models.CharField(_('First name'), max_length=255)
last_name = models.CharField(_('Last name'), max_length=255)
middle_name = models.CharField(
_('Middle name'), max_length=255, blank=True)
address = models.CharField(_('Address'), max_length=255, blank=True)
mobile = models.CharField(_('Mobile number'), max_length=255)
created = models.DateTimeField(
_('Date created'), auto_now_add=True, editable=False)
comment = models.TextField(_('Comment'), max_length=1000, blank=True)
hash = models.CharField(
max_length=10,
default=_generate_hash,
unique=True)
def __str__(self):
return self.printable_name
@property
def printable_name(self):
return '{} #{}'.format(_('Order'), self.id)
@property
def full_name(self):
return '{} {} {}'.format(
self.last_name, self.first_name, self.middle_name)
@property
def total(self):
return sum([i.subtotal for i in self.items.all()])
@property
def printable_total(self):
return format_printable_price(self.total)
@property
def delivery_method(self):
return self.delivery.name
def is_liqpay_payment(self):
return self.is_paynow_form_visible() and apps.is_installed('liqpay')
def is_paynow_form_visible(self):
return self.payment_method == PAYMENT_METHOD_PRIVAT24
class Meta:
verbose_name = _('Order')
verbose_name_plural = _('Orders')
class OrderedProduct(MultiCurrencyPrice):
| order = models.ForeignKey(
Order,
verbose_name=_('Order'),
related_name='items',
on_delete=models.CASCADE)
product = models.ForeignKey(
'products.Product',
verbose_name=_('Product'),
related_name='order_items',
on_delete=models.CASCADE)
qty = models.PositiveIntegerField(_('Quantity'), default=1)
def __str__(self):
return str(self.product)
@property
def subtotal(self):
return self.price * self.qty
def printable_subtotal(self):
return format_printable_price(self.subtotal)
class Meta:
verbose_name = _('Ordered product')
verbose_name_plural = _('Ordered products') |
|
resources.rs | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![deny(warnings)]
use std::fs::File;
use crate::vmm_config::boot_source::{
BootConfig, BootSourceConfig, BootSourceConfigError, DEFAULT_KERNEL_CMDLINE,
};
use crate::vmm_config::drive::*;
use crate::vmm_config::instance_info::InstanceInfo;
use crate::vmm_config::logger::{init_logger, LoggerConfig, LoggerConfigError};
use crate::vmm_config::machine_config::{VmConfig, VmConfigError};
use crate::vmm_config::metrics::{init_metrics, MetricsConfig, MetricsConfigError};
use crate::vmm_config::mmds::{MmdsConfig, MmdsConfigError};
use crate::vmm_config::net::*;
use crate::vmm_config::vsock::*;
use crate::vstate::vcpu::VcpuConfig;
use mmds::ns::MmdsNetworkStack; | use serde::Deserialize;
type Result<E> = std::result::Result<(), E>;
/// Errors encountered when configuring microVM resources.
#[derive(Debug)]
pub enum Error {
/// JSON is invalid.
InvalidJson,
/// Block device configuration error.
BlockDevice(DriveError),
/// Net device configuration error.
NetDevice(NetworkInterfaceError),
/// Boot source configuration error.
BootSource(BootSourceConfigError),
/// Logger configuration error.
Logger(LoggerConfigError),
/// Metrics system configuration error.
Metrics(MetricsConfigError),
/// microVM vCpus or memory configuration error.
VmConfig(VmConfigError),
/// Vsock device configuration error.
VsockDevice(VsockConfigError),
/// MMDS configuration error.
MmdsConfig(MmdsConfigError),
}
/// Used for configuring a vmm from one single json passed to the Firecracker process.
#[derive(Deserialize)]
pub struct VmmConfig {
#[serde(rename = "boot-source")]
boot_source: BootSourceConfig,
#[serde(rename = "drives")]
block_devices: Vec<BlockDeviceConfig>,
#[serde(rename = "network-interfaces", default)]
net_devices: Vec<NetworkInterfaceConfig>,
#[serde(rename = "logger")]
logger: Option<LoggerConfig>,
#[serde(rename = "machine-config")]
machine_config: Option<VmConfig>,
#[serde(rename = "metrics")]
metrics: Option<MetricsConfig>,
#[serde(rename = "vsock")]
vsock_device: Option<VsockDeviceConfig>,
#[serde(rename = "mmds-config")]
mmds_config: Option<MmdsConfig>,
}
/// A data structure that encapsulates the device configurations
/// held in the Vmm.
#[derive(Default)]
pub struct VmResources {
/// The vCpu and memory configuration for this microVM.
vm_config: VmConfig,
/// The boot configuration for this microVM.
boot_config: Option<BootConfig>,
/// The block devices.
pub block: BlockBuilder,
/// The vsock device.
pub vsock: VsockBuilder,
/// The network devices builder.
pub net_builder: NetBuilder,
/// The configuration for `MmdsNetworkStack`.
pub mmds_config: Option<MmdsConfig>,
/// Whether or not to load boot timer device.
pub boot_timer: bool,
}
impl VmResources {
/// Configures Vmm resources as described by the `config_json` param.
pub fn from_json(
config_json: &str,
instance_info: &InstanceInfo,
) -> std::result::Result<Self, Error> {
let vmm_config: VmmConfig = serde_json::from_slice::<VmmConfig>(config_json.as_bytes())
.map_err(|_| Error::InvalidJson)?;
if let Some(logger) = vmm_config.logger {
init_logger(logger, instance_info).map_err(Error::Logger)?;
}
if let Some(metrics) = vmm_config.metrics {
init_metrics(metrics).map_err(Error::Metrics)?;
}
let mut resources: Self = Self::default();
if let Some(machine_config) = vmm_config.machine_config {
resources
.set_vm_config(&machine_config)
.map_err(Error::VmConfig)?;
}
resources
.set_boot_source(vmm_config.boot_source)
.map_err(Error::BootSource)?;
for drive_config in vmm_config.block_devices.into_iter() {
resources
.set_block_device(drive_config)
.map_err(Error::BlockDevice)?;
}
for net_config in vmm_config.net_devices.into_iter() {
resources
.build_net_device(net_config)
.map_err(Error::NetDevice)?;
}
if let Some(vsock_config) = vmm_config.vsock_device {
resources
.set_vsock_device(vsock_config)
.map_err(Error::VsockDevice)?;
}
if let Some(mmds_config) = vmm_config.mmds_config {
resources
.set_mmds_config(mmds_config)
.map_err(Error::MmdsConfig)?;
}
Ok(resources)
}
/// Returns a VcpuConfig based on the vm config.
pub fn vcpu_config(&self) -> VcpuConfig {
// The unwraps are ok to use because the values are initialized using defaults if not
// supplied by the user.
VcpuConfig {
vcpu_count: self.vm_config().vcpu_count.unwrap(),
ht_enabled: self.vm_config().ht_enabled.unwrap(),
cpu_template: self.vm_config().cpu_template,
}
}
/// Returns whether dirty page tracking is enabled or not.
pub fn track_dirty_pages(&self) -> bool {
self.vm_config().track_dirty_pages
}
/// Returns the VmConfig.
pub fn vm_config(&self) -> &VmConfig {
&self.vm_config
}
/// Set the machine configuration of the microVM.
pub fn set_vm_config(&mut self, machine_config: &VmConfig) -> Result<VmConfigError> {
if machine_config.vcpu_count == Some(0) {
return Err(VmConfigError::InvalidVcpuCount);
}
if machine_config.mem_size_mib == Some(0) {
return Err(VmConfigError::InvalidMemorySize);
}
let ht_enabled = machine_config
.ht_enabled
.unwrap_or_else(|| self.vm_config.ht_enabled.unwrap());
let vcpu_count_value = machine_config
.vcpu_count
.unwrap_or_else(|| self.vm_config.vcpu_count.unwrap());
// If hyperthreading is enabled or is to be enabled in this call
// only allow vcpu count to be 1 or even.
if ht_enabled && vcpu_count_value > 1 && vcpu_count_value % 2 == 1 {
return Err(VmConfigError::InvalidVcpuCount);
}
// Update all the fields that have a new value.
self.vm_config.vcpu_count = Some(vcpu_count_value);
self.vm_config.ht_enabled = Some(ht_enabled);
self.vm_config.track_dirty_pages = machine_config.track_dirty_pages;
if machine_config.mem_size_mib.is_some() {
self.vm_config.mem_size_mib = machine_config.mem_size_mib;
}
if machine_config.cpu_template.is_some() {
self.vm_config.cpu_template = machine_config.cpu_template;
}
Ok(())
}
/// Gets a reference to the boot source configuration.
pub fn boot_source(&self) -> Option<&BootConfig> {
self.boot_config.as_ref()
}
/// Set the guest boot source configuration.
pub fn set_boot_source(
&mut self,
boot_source_cfg: BootSourceConfig,
) -> Result<BootSourceConfigError> {
use self::BootSourceConfigError::{
InvalidInitrdPath, InvalidKernelCommandLine, InvalidKernelPath,
};
// Validate boot source config.
let kernel_file =
File::open(&boot_source_cfg.kernel_image_path).map_err(InvalidKernelPath)?;
let initrd_file: Option<File> = match &boot_source_cfg.initrd_path {
Some(path) => Some(File::open(path).map_err(InvalidInitrdPath)?),
None => None,
};
let mut cmdline = kernel::cmdline::Cmdline::new(arch::CMDLINE_MAX_SIZE);
let boot_args = match boot_source_cfg.boot_args.as_ref() {
None => DEFAULT_KERNEL_CMDLINE,
Some(str) => str.as_str(),
};
cmdline
.insert_str(boot_args)
.map_err(|e| InvalidKernelCommandLine(e.to_string()))?;
self.boot_config = Some(BootConfig {
cmdline,
kernel_file,
initrd_file,
});
Ok(())
}
/// Inserts a block to be attached when the VM starts.
// Only call this function as part of user configuration.
// If the drive_id does not exist, a new Block Device Config is added to the list.
pub fn set_block_device(
&mut self,
block_device_config: BlockDeviceConfig,
) -> Result<DriveError> {
self.block.insert(block_device_config)
}
/// Builds a network device to be attached when the VM starts.
pub fn build_net_device(
&mut self,
body: NetworkInterfaceConfig,
) -> Result<NetworkInterfaceError> {
self.net_builder.build(body).map(|net_device| {
// Update `Net` device `MmdsNetworkStack` IPv4 address.
match &self.mmds_config {
Some(cfg) => cfg.ipv4_addr().map_or((), |ipv4_addr| {
if let Some(mmds_ns) = net_device.lock().expect("Poisoned lock").mmds_ns_mut() {
mmds_ns.set_ipv4_addr(ipv4_addr);
};
}),
None => (),
};
})
}
/// Sets a vsock device to be attached when the VM starts.
pub fn set_vsock_device(&mut self, config: VsockDeviceConfig) -> Result<VsockConfigError> {
self.vsock.insert(config)
}
/// Setter for mmds config.
pub fn set_mmds_config(&mut self, config: MmdsConfig) -> Result<MmdsConfigError> {
// Check IPv4 address validity.
let ipv4_addr = match config.ipv4_addr() {
Some(ipv4_addr) if is_link_local_valid(ipv4_addr) => Ok(ipv4_addr),
None => Ok(MmdsNetworkStack::default_ipv4_addr()),
_ => Err(MmdsConfigError::InvalidIpv4Addr),
}?;
// Update existing built network device `MmdsNetworkStack` IPv4 address.
for net_device in self.net_builder.iter_mut() {
if let Some(mmds_ns) = net_device.lock().expect("Poisoned lock").mmds_ns_mut() {
mmds_ns.set_ipv4_addr(ipv4_addr)
}
}
self.mmds_config = Some(config);
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::os::linux::fs::MetadataExt;
use super::*;
use crate::resources::VmResources;
use crate::vmm_config::boot_source::{BootConfig, BootSourceConfig, DEFAULT_KERNEL_CMDLINE};
use crate::vmm_config::drive::{BlockBuilder, BlockDeviceConfig};
use crate::vmm_config::machine_config::{CpuFeaturesTemplate, VmConfig, VmConfigError};
use crate::vmm_config::net::{NetBuilder, NetworkInterfaceConfig};
use crate::vmm_config::vsock::tests::default_config;
use crate::vmm_config::RateLimiterConfig;
use crate::vstate::vcpu::VcpuConfig;
use dumbo::MacAddr;
use logger::{LevelFilter, LOGGER};
use utils::tempfile::TempFile;
fn default_net_cfg() -> NetworkInterfaceConfig {
NetworkInterfaceConfig {
iface_id: "net_if1".to_string(),
// TempFile::new_with_prefix("") generates a random file name used as random net_if name.
host_dev_name: TempFile::new_with_prefix("")
.unwrap()
.as_path()
.to_str()
.unwrap()
.to_string(),
guest_mac: Some(MacAddr::parse_str("01:23:45:67:89:0a").unwrap()),
rx_rate_limiter: Some(RateLimiterConfig::default()),
tx_rate_limiter: Some(RateLimiterConfig::default()),
allow_mmds_requests: false,
}
}
fn default_net_builder() -> NetBuilder {
let mut net_builder = NetBuilder::new();
net_builder.build(default_net_cfg()).unwrap();
net_builder
}
fn default_block_cfg() -> (BlockDeviceConfig, TempFile) {
let tmp_file = TempFile::new().unwrap();
(
BlockDeviceConfig {
drive_id: "block1".to_string(),
path_on_host: tmp_file.as_path().to_str().unwrap().to_string(),
is_root_device: false,
partuuid: Some("0eaa91a0-01".to_string()),
is_read_only: false,
rate_limiter: Some(RateLimiterConfig::default()),
},
tmp_file,
)
}
fn default_blocks() -> BlockBuilder {
let mut blocks = BlockBuilder::new();
let (cfg, _file) = default_block_cfg();
blocks.insert(cfg).unwrap();
blocks
}
fn default_boot_cfg() -> BootConfig {
let mut kernel_cmdline = kernel::cmdline::Cmdline::new(4096);
kernel_cmdline.insert_str(DEFAULT_KERNEL_CMDLINE).unwrap();
let tmp_file = TempFile::new().unwrap();
BootConfig {
cmdline: kernel_cmdline,
kernel_file: File::open(tmp_file.as_path()).unwrap(),
initrd_file: Some(File::open(tmp_file.as_path()).unwrap()),
}
}
fn default_vm_resources() -> VmResources {
VmResources {
vm_config: VmConfig::default(),
boot_config: Some(default_boot_cfg()),
block: default_blocks(),
vsock: Default::default(),
net_builder: default_net_builder(),
mmds_config: None,
boot_timer: false,
}
}
impl PartialEq for BootConfig {
fn eq(&self, other: &Self) -> bool {
self.cmdline.as_str().eq(other.cmdline.as_str())
&& self.kernel_file.metadata().unwrap().st_ino()
== other.kernel_file.metadata().unwrap().st_ino()
&& self
.initrd_file
.as_ref()
.unwrap()
.metadata()
.unwrap()
.st_ino()
== other
.initrd_file
.as_ref()
.unwrap()
.metadata()
.unwrap()
.st_ino()
}
}
#[test]
fn test_from_json() {
let kernel_file = TempFile::new().unwrap();
let rootfs_file = TempFile::new().unwrap();
let default_instance_info = InstanceInfo {
id: "".to_string(),
started: false,
vmm_version: "SOME_VERSION".to_string(),
app_name: "".to_string(),
};
// We will test different scenarios with invalid resources configuration and
// check the expected errors. We include configuration for the kernel and rootfs
// in every json because they are mandatory fields. If we don't configure
// these resources, it is considered an invalid json and the test will crash.
// Invalid kernel path.
let mut json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "/invalid/path",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
]
}}"#,
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::BootSource(BootSourceConfigError::InvalidKernelPath(_))) => (),
_ => unreachable!(),
}
// Invalid rootfs path.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "/invalid/path",
"is_root_device": true,
"is_read_only": false
}}
]
}}"#,
kernel_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::BlockDevice(DriveError::InvalidBlockDevicePath)) => (),
_ => unreachable!(),
}
// Invalid vCPU number.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"machine-config": {{
"vcpu_count": 0,
"mem_size_mib": 1024,
"ht_enabled": false
}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::VmConfig(VmConfigError::InvalidVcpuCount)) => (),
_ => unreachable!(),
}
// Invalid memory size.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"machine-config": {{
"vcpu_count": 2,
"mem_size_mib": 0,
"ht_enabled": false
}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::VmConfig(VmConfigError::InvalidMemorySize)) => (),
_ => unreachable!(),
}
// Invalid path for logger pipe.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"logger": {{
"log_path": "/invalid/path"
}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::Logger(LoggerConfigError::InitializationFailure { .. })) => (),
_ => unreachable!(),
}
// The previous call enables the logger. We need to disable it.
LOGGER.set_max_level(LevelFilter::Off);
// Invalid path for metrics pipe.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"metrics": {{
"metrics_path": "/invalid/path"
}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::Metrics(MetricsConfigError::InitializationFailure { .. })) => (),
_ => unreachable!(),
}
// Reuse of a host name.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"network-interfaces": [
{{
"iface_id": "netif1",
"host_dev_name": "hostname7"
}},
{{
"iface_id": "netif2",
"host_dev_name": "hostname7"
}}
]
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap()
);
match VmResources::from_json(json.as_str(), &default_instance_info) {
Err(Error::NetDevice(NetworkInterfaceError::CreateNetworkDevice(
devices::virtio::net::Error::TapOpen { .. },
))) => (),
_ => unreachable!(),
}
// Let's try now passing a valid configuration. We won't include any logger
// or metrics configuration because these were already initialized in other
// tests of this module and the reinitialization of them will cause crashing.
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"network-interfaces": [
{{
"iface_id": "netif",
"host_dev_name": "hostname8",
"allow_mmds_requests": true
}}
],
"machine-config": {{
"vcpu_count": 2,
"mem_size_mib": 1024,
"ht_enabled": false
}},
"mmds-config": {{
"ipv4_address": "169.254.170.2"
}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap(),
);
assert!(VmResources::from_json(json.as_str(), &default_instance_info).is_ok());
// Test all configuration, this time trying to configure the MMDS with an
// empty body. It will make it access the code path in which it sets the
// default MMDS configuration.
let kernel_file = TempFile::new().unwrap();
json = format!(
r#"{{
"boot-source": {{
"kernel_image_path": "{}",
"boot_args": "console=ttyS0 reboot=k panic=1 pci=off"
}},
"drives": [
{{
"drive_id": "rootfs",
"path_on_host": "{}",
"is_root_device": true,
"is_read_only": false
}}
],
"network-interfaces": [
{{
"iface_id": "netif",
"host_dev_name": "hostname9",
"allow_mmds_requests": true
}}
],
"machine-config": {{
"vcpu_count": 2,
"mem_size_mib": 1024,
"ht_enabled": false
}},
"mmds-config": {{}}
}}"#,
kernel_file.as_path().to_str().unwrap(),
rootfs_file.as_path().to_str().unwrap(),
);
assert!(VmResources::from_json(json.as_str(), &default_instance_info).is_ok());
}
#[test]
fn test_vcpu_config() {
let vm_resources = default_vm_resources();
let expected_vcpu_config = VcpuConfig {
vcpu_count: vm_resources.vm_config().vcpu_count.unwrap(),
ht_enabled: vm_resources.vm_config().ht_enabled.unwrap(),
cpu_template: vm_resources.vm_config().cpu_template,
};
let vcpu_config = vm_resources.vcpu_config();
assert_eq!(vcpu_config, expected_vcpu_config);
}
#[test]
fn test_vm_config() {
let vm_resources = default_vm_resources();
let expected_vm_cfg = VmConfig::default();
assert_eq!(vm_resources.vm_config(), &expected_vm_cfg);
}
#[test]
fn test_set_vm_config() {
let mut vm_resources = default_vm_resources();
let mut aux_vm_config = VmConfig {
vcpu_count: Some(32),
mem_size_mib: Some(512),
ht_enabled: Some(true),
cpu_template: Some(CpuFeaturesTemplate::T2),
track_dirty_pages: false,
};
assert_ne!(vm_resources.vm_config, aux_vm_config);
vm_resources.set_vm_config(&aux_vm_config).unwrap();
assert_eq!(vm_resources.vm_config, aux_vm_config);
// Invalid vcpu count.
aux_vm_config.vcpu_count = Some(0);
assert_eq!(
vm_resources.set_vm_config(&aux_vm_config),
Err(VmConfigError::InvalidVcpuCount)
);
aux_vm_config.vcpu_count = Some(33);
assert_eq!(
vm_resources.set_vm_config(&aux_vm_config),
Err(VmConfigError::InvalidVcpuCount)
);
aux_vm_config.vcpu_count = Some(32);
// Invalid mem_size_mib.
aux_vm_config.mem_size_mib = Some(0);
assert_eq!(
vm_resources.set_vm_config(&aux_vm_config),
Err(VmConfigError::InvalidMemorySize)
);
}
#[test]
fn test_boot_config() {
let vm_resources = default_vm_resources();
let expected_boot_cfg = vm_resources.boot_config.as_ref().unwrap();
let actual_boot_cfg = vm_resources.boot_source().unwrap();
assert_eq!(actual_boot_cfg, expected_boot_cfg);
}
#[test]
fn test_set_boot_source() {
let tmp_file = TempFile::new().unwrap();
let cmdline = "reboot=k panic=1 pci=off nomodules 8250.nr_uarts=0";
let expected_boot_cfg = BootSourceConfig {
kernel_image_path: String::from(tmp_file.as_path().to_str().unwrap()),
initrd_path: Some(String::from(tmp_file.as_path().to_str().unwrap())),
boot_args: Some(cmdline.to_string()),
};
let mut vm_resources = default_vm_resources();
let boot_cfg = vm_resources.boot_source().unwrap();
let tmp_ino = tmp_file.as_file().metadata().unwrap().st_ino();
assert_ne!(boot_cfg.cmdline.as_str(), cmdline);
assert_ne!(boot_cfg.kernel_file.metadata().unwrap().st_ino(), tmp_ino);
assert_ne!(
boot_cfg
.initrd_file
.as_ref()
.unwrap()
.metadata()
.unwrap()
.st_ino(),
tmp_ino
);
vm_resources.set_boot_source(expected_boot_cfg).unwrap();
let boot_cfg = vm_resources.boot_source().unwrap();
assert_eq!(boot_cfg.cmdline.as_str(), cmdline);
assert_eq!(boot_cfg.kernel_file.metadata().unwrap().st_ino(), tmp_ino);
assert_eq!(
boot_cfg
.initrd_file
.as_ref()
.unwrap()
.metadata()
.unwrap()
.st_ino(),
tmp_ino
);
}
#[test]
fn test_set_block_device() {
let mut vm_resources = default_vm_resources();
let (mut new_block_device_cfg, _file) = default_block_cfg();
let tmp_file = TempFile::new().unwrap();
new_block_device_cfg.drive_id = "block2".to_string();
new_block_device_cfg.path_on_host = tmp_file.as_path().to_str().unwrap().to_string();
assert_eq!(vm_resources.block.list.len(), 1);
vm_resources.set_block_device(new_block_device_cfg).unwrap();
assert_eq!(vm_resources.block.list.len(), 2);
}
#[test]
fn test_set_vsock_device() {
let mut vm_resources = default_vm_resources();
let mut tmp_sock_file = TempFile::new().unwrap();
tmp_sock_file.remove().unwrap();
let new_vsock_cfg = default_config(&tmp_sock_file);
assert!(vm_resources.vsock.get().is_none());
vm_resources
.set_vsock_device(new_vsock_cfg.clone())
.unwrap();
let actual_vsock_cfg = vm_resources.vsock.get().unwrap();
assert_eq!(
actual_vsock_cfg.lock().unwrap().id(),
&new_vsock_cfg.vsock_id
);
}
#[test]
fn test_set_net_device() {
let mut vm_resources = default_vm_resources();
// Clone the existing net config in order to obtain a new one.
let mut new_net_device_cfg = default_net_cfg();
new_net_device_cfg.iface_id = "new_net_if".to_string();
new_net_device_cfg.guest_mac = Some(MacAddr::parse_str("01:23:45:67:89:0c").unwrap());
new_net_device_cfg.host_dev_name = "dummy_path2".to_string();
assert_eq!(vm_resources.net_builder.len(), 1);
vm_resources.build_net_device(new_net_device_cfg).unwrap();
assert_eq!(vm_resources.net_builder.len(), 2);
}
} | use utils::net::ipv4addr::is_link_local_valid;
|
interfacetapconfigurations.go | package network
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// InterfaceTapConfigurationsClient is the network Client
type InterfaceTapConfigurationsClient struct {
BaseClient
}
// NewInterfaceTapConfigurationsClient creates an instance of the InterfaceTapConfigurationsClient client.
func NewInterfaceTapConfigurationsClient(subscriptionID string) InterfaceTapConfigurationsClient {
return NewInterfaceTapConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewInterfaceTapConfigurationsClientWithBaseURI creates an instance of the InterfaceTapConfigurationsClient client
// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign
// clouds, Azure stack). | return InterfaceTapConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a Tap configuration in the specified NetworkInterface.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkInterfaceName - the name of the network interface.
// tapConfigurationName - the name of the tap configuration.
// tapConfigurationParameters - parameters supplied to the create or update tap configuration operation.
func (client InterfaceTapConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (result InterfaceTapConfigurationsCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.CreateOrUpdate")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: tapConfigurationParameters,
Constraints: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}},
}},
{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil},
{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil},
}},
}},
}},
}},
{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}},
}},
{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil},
{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil},
}},
}},
}},
}},
}},
}},
}}}}}); err != nil {
return result, validation.NewError("network.InterfaceTapConfigurationsClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName, tapConfigurationParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client InterfaceTapConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkInterfaceName": autorest.Encode("path", networkInterfaceName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapConfigurationName": autorest.Encode("path", tapConfigurationName),
}
const APIVersion = "2021-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
tapConfigurationParameters.Etag = nil
tapConfigurationParameters.Type = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters),
autorest.WithJSON(tapConfigurationParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client InterfaceTapConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future InterfaceTapConfigurationsCreateOrUpdateFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client InterfaceTapConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified tap configuration from the NetworkInterface.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkInterfaceName - the name of the network interface.
// tapConfigurationName - the name of the tap configuration.
func (client InterfaceTapConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfigurationsDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Delete")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client InterfaceTapConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkInterfaceName": autorest.Encode("path", networkInterfaceName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapConfigurationName": autorest.Encode("path", tapConfigurationName),
}
const APIVersion = "2021-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client InterfaceTapConfigurationsClient) DeleteSender(req *http.Request) (future InterfaceTapConfigurationsDeleteFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client InterfaceTapConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get get the specified tap configuration on a network interface.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkInterfaceName - the name of the network interface.
// tapConfigurationName - the name of the tap configuration.
func (client InterfaceTapConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfiguration, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client InterfaceTapConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkInterfaceName": autorest.Encode("path", networkInterfaceName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"tapConfigurationName": autorest.Encode("path", tapConfigurationName),
}
const APIVersion = "2021-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client InterfaceTapConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client InterfaceTapConfigurationsClient) GetResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List get all Tap configurations in a network interface.
// Parameters:
// resourceGroupName - the name of the resource group.
// networkInterfaceName - the name of the network interface.
func (client InterfaceTapConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List")
defer func() {
sc := -1
if result.itclr.Response.Response != nil {
sc = result.itclr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.itclr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure sending request")
return
}
result.itclr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure responding to request")
return
}
if result.itclr.hasNextLink() && result.itclr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client InterfaceTapConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkInterfaceName": autorest.Encode("path", networkInterfaceName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client InterfaceTapConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client InterfaceTapConfigurationsClient) ListResponder(resp *http.Response) (result InterfaceTapConfigurationListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client InterfaceTapConfigurationsClient) listNextResults(ctx context.Context, lastResults InterfaceTapConfigurationListResult) (result InterfaceTapConfigurationListResult, err error) {
req, err := lastResults.interfaceTapConfigurationListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client InterfaceTapConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName)
return
} | func NewInterfaceTapConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceTapConfigurationsClient { |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { Routes, RouterModule, Router } from '@angular/router';
import { AppComponent } from './app.component';
import { ProjectsComponent } from './projects/projects.component';
import { AddProjectComponent } from './projects/add-project/add-project.component';
import { EditProjectComponent } from './projects/edit-project/edit-project.component';
import { ProjectComponent } from './projects/project/project.component';
import { LoginComponent } from './login/login.component';
import { LessonsComponent } from './lessons/lessons.component';
import { ReportsComponent } from './reports/reports.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthguardService } from './login/authguard.service';
import { AdminComponent } from './admin/admin.component';
import { AdminLoginComponent } from './admin/login/admin-login.component';
import { HomeComponent } from './home/home.component';
import { StudentsComponent } from './students/students.component';
import { AdminReportsComponent } from './admin/reports/admin-reports.component';
import { NotesComponent } from './admin/notes/notes.component';
const routes: Routes = [
{path: 'login', component: LoginComponent},
{path: 'admin-login', component: AdminLoginComponent},
{path: '', component: HomeComponent, canActivate: [AuthguardService], children: [
{path: 'profile', component: ProfileComponent, canActivate: [AuthguardService]},
{path: 'admin', component: AdminComponent},
{path: 'admin-reports', component: AdminReportsComponent},
{path: 'admin-notes', component: NotesComponent},
{path: 'projects', component: ProjectsComponent, canActivate: [AuthguardService], children: [
{path: 'add', component: AddProjectComponent},
{path: 'edit', component : EditProjectComponent},
{path: 'detail', component: ProjectComponent},
]},
{path: 'lessons', canActivate: [AuthguardService], component: LessonsComponent},
{path: 'reports', canActivate: [AuthguardService], component: ReportsComponent},
{path: 'students', canActivate: [AuthguardService], component: StudentsComponent}
]},
];
@NgModule({ | exports: [RouterModule]
})
export class AppRoutingModule { } | imports: [RouterModule.forRoot(routes, {useHash: true}), RouterModule.forChild(routes)], |
pyfile.py | #!/usr/bin/env python
# import required packages
import emcee
import numpy as np
from numpy import exp, log
# import model function from separate file
from mymodel import mymodel
# import post-processing function from theonlinemcmc package
from theonlinemcmc import *
# initialise error code value
errval = 0
# define the log posterior function
def lnprob(theta, x, sigma_gauss, data):
lp = lnprior(theta)
if not np.isfinite(lp):
return -np.inf
return lp + lnlike(theta, x, sigma_gauss, data)
# define the log prior function
def lnprior(theta):
lp = 0.
m,c = theta
if -10 < m < 10:
lp = 0.
else:
return -np.inf
if -10 < c < 10:
lp = 0.
else:
return -np.inf
return lp
# define log likelihood function
def | (theta, x, sigma_gauss, data):
m,c = theta
md = mymodel(m,c,x)
return -0.5*np.sum(((md - data)/sigma_gauss)**2)
# set number of MCMC points
Nmcmc = 1000
Nburnin = 1000
Nens = 100
ndim = 2
# initialise the start ensemble points
try:
mini = -10 + np.random.rand(Nens)*20
cini = -10 + np.random.rand(Nens)*20
pos = np.array([mini, cini]).T
except:
errval = PRIOR_INIT_ERR
# read in the data
if errval == 0:
try:
data = np.loadtxt("data_file.txt")
except:
try:
data = np.loadtxt("data_file.txt", delimiter=",")
except:
errval = DATA_READ_ERR
# read in the abscissa values
if errval == 0:
try:
x = np.loadtxt("abscissa_file.txt")
except:
try:
x = np.loadtxt("abscissa_file.txt", delimiter=",")
except:
errval = ABSCISSA_READ_ERR
# read in sigma (standard deviation) values (there may be nothing here if it not applicable to your likelihood)
# run the MCMC
if errval == 0:
if len(data) != len(x):
errval = DATA_LENGTH_ERR
argslist = (x, 0.65, data)
if errval == 0:
# set up sampler
try:
sampler = emcee.EnsembleSampler(Nens, ndim, lnprob, args=argslist)
except:
errval = MCMC_INIT_ERR
# run sampler
try:
sampler.run_mcmc(pos, Nmcmc+Nburnin)
# remove burn-in and flatten
samples = sampler.chain[:, Nburnin:, :].reshape((-1, ndim))
lnp = np.reshape(sampler.lnprobability[:, Nburnin:].flatten(), (-1,1))
samples = np.hstack((samples, lnp))
except:
errval = MCMC_RUN_ERR
# output the posterior samples, likelihood and variables
try:
np.savetxt('posterior_samples.txt.gz', samples)
fv = open('variables.txt', 'w')
fv.write("m,c")
fv.close()
except:
errval = POST_OUTPUT_ERR
# run post-processing script
try:
postprocessing(samples, "m,c", x, "x", data, "[email protected]", "http://localhost/results/8112a5333cb1bb472ee14fa5342f6422")
except:
errval = POST_PROCESS_ERR
success = True
if errval != 0:
# run different script in case error codes are encountered
errorpage(errval, "[email protected]", "http://localhost/results/8112a5333cb1bb472ee14fa5342f6422")
success = False
| lnlike |
user.rs | #[cfg(test)]
mod tests {
use crate::{
service::endpoints::{graphql, login},
test::init,
};
use actix_web::{
test::{self, TestRequest},
web::post,
App,
};
use serde_json::{self, json};
use std::str::from_utf8;
use crate::test::LoginResponse;
#[actix_rt::test]
async fn test_user() {
let data = init();
let mut app = test::init_service(
App::new()
.data(data.clone())
.route("/login", post().to(login))
.route("/graphql", post().to(graphql)),
)
.await;
let req = TestRequest::post()
.uri("/graphql")
.set_json(&json!({
"query": "mutation Register($username: String!, $password: String!) {
CreateUser(NewUser: { username: $username, password: $password }) {
username
}
}",
"variables": {
"username": "test_user",
"password": "test",
},
}))
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(resp.status().is_success(), "Failed to create user");
assert_eq!(
from_utf8(&test::read_body(resp).await).unwrap(),
"{\"data\":{\"CreateUser\":{\"username\":\"test_user\"}}}"
);
let req = TestRequest::post()
.uri("/login")
.set_json(&json!({
"username": "test_user",
"password": "test",
}))
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(resp.status().is_success(), "Login failed");
let body = test::read_body(resp).await;
let body = from_utf8(&body).unwrap();
let login_response: LoginResponse = serde_json::from_str(&body).unwrap();
let req = TestRequest::post()
.uri("/graphql")
.set_json(&json!({
"query": "mutation UpdateUser($id: Int!, $password: String!) { | username
}
}",
"variables": {
"id": &login_response.user_id,
"password": "changed",
},
}))
.header("Authorization", login_response.token)
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(resp.status().is_success(), "Failed to update user password");
assert_eq!(
from_utf8(&test::read_body(resp).await).unwrap(),
"{\"data\":{\"UpdateUser\":{\"username\":\"test_user\"}}}"
);
let req = TestRequest::post()
.uri("/login")
.set_json(&json!({
"username": "test_user",
"password": "test",
}))
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(
resp.status().is_client_error(),
"Login with old password still works"
);
let req = TestRequest::post()
.uri("/login")
.set_json(&json!({
"username": "test_user",
"password": "changed",
}))
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(resp.status().is_success(), "Login with new password failed");
let body = test::read_body(resp).await;
let body = from_utf8(&body).unwrap();
let login_response: LoginResponse = serde_json::from_str(&body).unwrap();
let req = TestRequest::post()
.uri("/graphql")
.set_json(&json!({
"query": "mutation DeleteUser($id: Int!) {
DeleteUser(DeleteUser: { id: $id }) {
count
}
}",
"variables": {
"id": &login_response.user_id,
},
}))
.header("Authorization", login_response.token)
.to_request();
let resp = test::call_service(&mut app, req).await;
assert!(resp.status().is_success(), "User deletion failed");
assert_eq!(
from_utf8(&test::read_body(resp).await).unwrap(),
"{\"data\":{\"DeleteUser\":{\"count\":1}}}"
);
}
} | UpdateUser(UpdateUser: { id: $id, password: $password }) { |
room.js | /* globals chatMessages, fileUpload , fireGlobalEvent , cordova , readMessage , RoomRoles, popover , device */
import { RocketChatTabBar } from 'meteor/rocketchat:lib';
import _ from 'underscore';
import moment from 'moment';
import mime from 'mime-type/with-db';
import Clipboard from 'clipboard';
import { lazyloadtick } from 'meteor/rocketchat:lazy-load';
window.chatMessages = window.chatMessages || {};
const isSubscribed = _id => ChatSubscription.find({ rid: _id }).count() > 0;
const favoritesEnabled = () => RocketChat.settings.get('Favorite_Rooms');
const userCanDrop = _id => !RocketChat.roomTypes.readOnly(_id, Meteor.user());
const openProfileTab = (e, instance, username) => {
const roomData = Session.get(`roomData${ Session.get('openedRoom') }`);
if (RocketChat.Layout.isEmbedded()) {
fireGlobalEvent('click-user-card-message', { username });
e.preventDefault();
e.stopPropagation();
return;
}
if (RocketChat.roomTypes.roomTypes[roomData.t].enableMembersListProfile()) {
instance.setUserDetail(username);
}
instance.tabBar.setTemplate('membersList');
instance.tabBar.open();
};
const openProfileTabOrOpenDM = (e, instance, username) => {
if (RocketChat.settings.get('UI_Click_Direct_Message')) {
Meteor.call('createDirectMessage', username, (error, result) => {
if (error) {
if (error.isClientSafe) {
openProfileTab(e, instance, username);
} else {
handleError(error);
}
}
if ((result != null ? result.rid : undefined) != null) {
FlowRouter.go('direct', { username }, FlowRouter.current().queryParams);
}
});
} else {
openProfileTab(e, instance, username);
}
};
const mountPopover = (e, i, outerContext) => {
let context = $(e.target).parents('.message').data('context');
if (!context) {
context = 'message';
}
const [, message] = outerContext._arguments;
let menuItems = RocketChat.MessageAction.getButtons(message, context, 'menu').map(item => {
return {
icon: item.icon,
name: t(item.label),
type: 'message-action',
id: item.id,
modifier: item.color
};
});
if (window.matchMedia('(max-width: 500px)').matches) {
const messageItems = RocketChat.MessageAction.getButtons(message, context, 'message').map(item => {
return {
icon: item.icon,
name: t(item.label),
type: 'message-action',
id: item.id,
modifier: item.color
};
});
menuItems = menuItems.concat(messageItems);
}
const [items, deleteItem] = menuItems.reduce((result, value) => (result[value.id === 'delete-message' ? 1 : 0].push(value), result), [[], []]);
const groups = [{ items }];
if (deleteItem.length) {
groups.push({ items: deleteItem });
}
if (typeof device !== 'undefined' && device.platform && device.platform.toLocaleLowerCase() === 'ios') {
groups.push({
items: [
{
icon: 'warning',
name: t('Report_Abuse'),
type: 'message-action',
id: 'report-abuse',
modifier: 'alert'
}
]
});
}
const config = {
columns: [
{
groups
}
],
instance: i,
currentTarget: e.currentTarget,
data: outerContext,
activeElement: $(e.currentTarget).parents('.message')[0],
onRendered: () => new Clipboard('.rc-popover__item')
};
popover.open(config);
};
const wipeFailedUploads = () => {
const uploads = Session.get('uploading');
if (uploads) {
Session.set('uploading', uploads.filter(upload => !upload.error));
}
};
function roomHasGlobalPurge(room) {
if (!RocketChat.settings.get('RetentionPolicy_Enabled')) {
return false;
}
switch (room.t) {
case 'c':
return RocketChat.settings.get('RetentionPolicy_AppliesToChannels');
case 'p':
return RocketChat.settings.get('RetentionPolicy_AppliesToGroups');
case 'd':
return RocketChat.settings.get('RetentionPolicy_AppliesToDMs');
}
return false;
}
function roomHasPurge(room) {
if (!room || !RocketChat.settings.get('RetentionPolicy_Enabled')) {
return false;
}
if (room.retention && room.retention.enabled !== undefined) {
return room.retention.enabled;
}
return roomHasGlobalPurge(room);
}
function roomFilesOnly(room) {
if (!room) {
return false;
}
if (room.retention && room.retention.overrideGlobal) {
return room.retention.filesOnly;
}
return RocketChat.settings.get('RetentionPolicy_FilesOnly');
}
function roomExcludePinned(room) {
if (!room) {
return false;
}
if (room.retention && room.retention.overrideGlobal) {
return room.retention.excludePinned;
}
return RocketChat.settings.get('RetentionPolicy_ExcludePinned');
}
function roomMaxAge(room) {
if (!room) {
return;
}
if (!roomHasPurge(room)) {
return;
}
if (room.retention && room.retention.overrideGlobal) {
return room.retention.maxAge;
}
if (room.t === 'c') {
return RocketChat.settings.get('RetentionPolicy_MaxAge_Channels');
}
if (room.t === 'p') {
return RocketChat.settings.get('RetentionPolicy_MaxAge_Groups');
}
if (room.t === 'd') {
return RocketChat.settings.get('RetentionPolicy_MaxAge_DMs');
}
}
RocketChat.callbacks.add('enter-room', wipeFailedUploads);
Template.room.helpers({
isTranslated() {
const sub = ChatSubscription.findOne({ rid: this._id }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } });
RocketChat.settings.get('AutoTranslate_Enabled') && ((sub != null ? sub.autoTranslate : undefined) === true) && (sub.autoTranslateLanguage != null);
},
embeddedVersion() {
RocketChat.Layout.isEmbedded();
},
subscribed() {
return isSubscribed(this._id);
},
messagesHistory() {
const hideMessagesOfType = [];
RocketChat.settings.collection.find({ _id: /Message_HideType_.+/ }).forEach(function(record) {
let types;
const type = record._id.replace('Message_HideType_', '');
switch (type) {
case 'mute_unmute':
types = ['user-muted', 'user-unmuted'];
break;
default:
types = [type];
}
return types.forEach(function(type) {
const index = hideMessagesOfType.indexOf(type);
if ((record.value === true) && (index === -1)) {
hideMessagesOfType.push(type);
} else if (index > -1) {
hideMessagesOfType.splice(index, 1);
}
});
});
const query =
{ rid: this._id };
if (hideMessagesOfType.length > 0) {
query.t =
{ $nin: hideMessagesOfType };
}
const options = {
sort: {
ts: 1
}
};
return ChatMessage.find(query, options);
},
hasMore() {
return RoomHistoryManager.hasMore(this._id);
},
hasMoreNext() {
return RoomHistoryManager.hasMoreNext(this._id);
},
isLoading() {
return RoomHistoryManager.isLoading(this._id);
},
windowId() {
return `chat-window-${ this._id }`;
},
uploading() {
return Session.get('uploading');
},
roomLeader() {
const roles = RoomRoles.findOne({ rid: this._id, roles: 'leader', 'u._id': { $ne: Meteor.userId() } }); | const leader = RocketChat.models.Users.findOne({ _id: roles.u._id }, { fields: { status: 1 } }) || {};
return {
...roles.u,
name: RocketChat.settings.get('UI_Use_Real_Name') ? (roles.u.name || roles.u.username) : roles.u.username,
status: leader.status || 'offline',
statusDisplay: (status => status.charAt(0).toUpperCase() + status.slice(1))(leader.status || 'offline')
};
}
},
chatNowLink() {
return RocketChat.roomTypes.getRouteLink('d', { name: this.username });
},
showAnnouncement() {
const roomData = Session.get(`roomData${ this._id }`);
if (!roomData) { return false; }
return roomData.announcement != null && roomData.announcement !== '';
},
messageboxData() {
const instance = Template.instance();
return {
_id: this._id,
onResize: () => {
if (instance.sendToBottomIfNecessary) {
instance.sendToBottomIfNecessary();
}
}
};
},
roomAnnouncement() {
const roomData = Session.get(`roomData${ this._id }`);
if (!roomData) { return ''; }
return roomData.announcement;
},
getAnnouncementStyle() {
const roomData = Session.get(`roomData${ this._id }`);
if (!roomData) { return ''; }
return roomData.announcementDetails && roomData.announcementDetails.style !== undefined ? roomData.announcementDetails.style : '';
},
roomIcon() {
const roomData = Session.get(`roomData${ this._id }`);
if (!(roomData != null ? roomData.t : undefined)) { return ''; }
const roomIcon = RocketChat.roomTypes.getIcon(roomData != null ? roomData.t : undefined);
// Remove this 'codegueira' on header redesign
if (!roomIcon) {
return 'at';
}
return roomIcon;
},
tokenAccessChannel() {
return Template.instance().hasTokenpass.get();
},
userStatus() {
const roomData = Session.get(`roomData${ this._id }`);
return RocketChat.roomTypes.getUserStatus(roomData.t, this._id) || 'offline';
},
maxMessageLength() {
return RocketChat.settings.get('Message_MaxAllowedSize');
},
unreadData() {
const data =
{ count: RoomHistoryManager.getRoom(this._id).unreadNotLoaded.get() + Template.instance().unreadCount.get() };
const room = RoomManager.getOpenedRoomByRid(this._id);
if (room != null) {
data.since = room.unreadSince != null ? room.unreadSince.get() : undefined;
}
return data;
},
containerBarsShow(unreadData, uploading) {
const hasUnreadData = unreadData && (unreadData.count && unreadData.since);
const isUploading = uploading && uploading.length;
if (hasUnreadData || isUploading) {
return 'show';
}
},
formatUnreadSince() {
if ((this.since == null)) { return; }
return moment(this.since).calendar(null, { sameDay: 'LT' });
},
flexData() {
const flexData = {
tabBar: Template.instance().tabBar,
data: {
rid: this._id,
userDetail: Template.instance().userDetail.get(),
clearUserDetail: Template.instance().clearUserDetail
}
};
return flexData;
},
adminClass() {
if (RocketChat.authz.hasRole(Meteor.userId(), 'admin')) { return 'admin'; }
},
showToggleFavorite() {
if (isSubscribed(this._id) && favoritesEnabled()) { return true; }
},
messageViewMode() {
const user = Meteor.user();
const viewMode = RocketChat.getUserPreference(user, 'messageViewMode');
const modes = ['', 'cozy', 'compact'];
return modes[viewMode] || modes[0];
},
selectable() {
return Template.instance().selectable.get();
},
hideUsername() {
const user = Meteor.user();
return RocketChat.getUserPreference(user, 'hideUsernames') ? 'hide-usernames' : undefined;
},
hideAvatar() {
const user = Meteor.user();
return RocketChat.getUserPreference(user, 'hideAvatars') ? 'hide-avatars' : undefined;
},
userCanDrop() {
return userCanDrop(this._id);
},
toolbarButtons() {
const toolbar = Session.get('toolbarButtons') || { buttons: {} };
const buttons = Object.keys(toolbar.buttons).map(key => {
return {
id: key,
...toolbar.buttons[key]
};
});
return { buttons };
},
canPreview() {
const room = Session.get(`roomData${ this._id }`);
if (room && room.t !== 'c') {
return true;
}
if (RocketChat.settings.get('Accounts_AllowAnonymousRead') === true) {
return true;
}
if (RocketChat.authz.hasAllPermission('preview-c-room')) {
return true;
}
return (RocketChat.models.Subscriptions.findOne({ rid: this._id }) != null);
},
hideLeaderHeader() {
return Template.instance().hideLeaderHeader.get() ? 'animated-hidden' : '';
},
hasLeader() {
if (RoomRoles.findOne({ rid: this._id, roles: 'leader', 'u._id': { $ne: Meteor.userId() } }, { fields: { _id: 1 } })) {
return 'has-leader';
}
},
hasPurge() {
return roomHasPurge(Session.get(`roomData${ this._id }`));
},
filesOnly() {
return roomFilesOnly(Session.get(`roomData${ this._id }`));
},
excludePinned() {
return roomExcludePinned(Session.get(`roomData${ this._id }`));
},
purgeTimeout() {
moment.relativeTimeThreshold('s', 60);
moment.relativeTimeThreshold('ss', 0);
moment.relativeTimeThreshold('m', 60);
moment.relativeTimeThreshold('h', 24);
moment.relativeTimeThreshold('d', 31);
moment.relativeTimeThreshold('M', 12);
return moment.duration(roomMaxAge(Session.get(`roomData${ this._id }`)) * 1000 * 60 * 60 * 24).humanize();
}
});
let isSocialSharingOpen = false;
let touchMoved = false;
let lastTouchX = null;
let lastTouchY = null;
let lastScrollTop;
Template.room.events({
'click .js-reply-broadcast'() {
const message = this._arguments[1];
RocketChat.roomTypes.openRouteLink('d', {name: this._arguments[1].u.username}, {...FlowRouter.current().queryParams, reply: message._id});
},
'click, touchend'(e, t) {
Meteor.setTimeout(() => t.sendToBottomIfNecessaryDebounced(), 100);
},
'click .messages-container-main'() {
const user = Meteor.user();
if ((Template.instance().tabBar.getState() === 'opened') && RocketChat.getUserPreference(user, 'hideFlexTab')) {
Template.instance().tabBar.close();
}
},
'touchstart .message'(e, t) {
const touches = e.originalEvent.touches;
if (touches && touches.length) {
lastTouchX = touches[0].pageX;
lastTouchY = touches[0].pagey;
}
touchMoved = false;
isSocialSharingOpen = false;
if (e.originalEvent.touches.length !== 1) {
return;
}
if ($(e.currentTarget).hasClass('system')) {
return;
}
if (e.target && (e.target.nodeName === 'AUDIO')) {
return;
}
if (e.target && (e.target.nodeName === 'A') && /^https?:\/\/.+/.test(e.target.getAttribute('href'))) {
e.preventDefault();
e.stopPropagation();
}
const doLongTouch = () => {
console.log('long press');
mountPopover(e, t, this);
};
Meteor.clearTimeout(t.touchtime);
t.touchtime = Meteor.setTimeout(doLongTouch, 500);
},
'click .message img'(e, t) {
Meteor.clearTimeout(t.touchtime);
if ((isSocialSharingOpen === true) || (touchMoved === true)) {
e.preventDefault();
e.stopPropagation();
}
},
'touchend .message'(e, t) {
Meteor.clearTimeout(t.touchtime);
if (isSocialSharingOpen === true) {
e.preventDefault();
e.stopPropagation();
return;
}
if (e.target && (e.target.nodeName === 'A') && /^https?:\/\/.+/.test(e.target.getAttribute('href'))) {
if (touchMoved === true) {
e.preventDefault();
e.stopPropagation();
return;
}
if ((typeof cordova !== 'undefined' && cordova !== null ? cordova.InAppBrowser : undefined) != null) {
cordova.InAppBrowser.open(e.target.href, '_system');
} else {
window.open(e.target.href);
}
}
},
'touchmove .message'(e, t) {
const touches = e.originalEvent.touches;
if (touches && touches.length) {
const deltaX = Math.abs(lastTouchX - touches[0].pageX);
const deltaY = Math.abs(lastTouchY - touches[0].pageY);
if (deltaX > 5 || deltaY > 5) {
touchMoved = true;
}
}
Meteor.clearTimeout(t.touchtime);
},
'touchcancel .message'(e, t) {
Meteor.clearTimeout(t.touchtime);
},
'click .upload-progress-close'(e) {
e.preventDefault();
Session.set(`uploading-cancel-${ this.id }`, true);
},
'click .unread-bar > button.mark-read'() {
readMessage.readNow(true);
},
'click .unread-bar > button.jump-to'(e, t) {
const { _id } = t.data;
const room = RoomHistoryManager.getRoom(_id);
let message = room && room.firstUnread.get();
if (message) {
RoomHistoryManager.getSurroundingMessages(message, 50);
} else {
const subscription = ChatSubscription.findOne({ rid: _id });
message = ChatMessage.find({ rid: _id, ts: { $gt: (subscription != null ? subscription.ls : undefined) } }, { sort: { ts: 1 }, limit: 1 }).fetch()[0];
RoomHistoryManager.getSurroundingMessages(message, 50);
}
},
'click .toggle-favorite'(event) {
event.stopPropagation();
event.preventDefault();
Meteor.call('toggleFavorite', this._id, !$('i', event.currentTarget).hasClass('favorite-room'), function(err) {
if (err) {
handleError(err);
}
});
},
'click .edit-room-title'(event) {
event.preventDefault();
Session.set('editRoomTitle', true);
$('.fixed-title').addClass('visible');
Meteor.setTimeout(() => $('#room-title-field').focus().select(), 10);
},
'click .user-image, click .rc-member-list__user'(e, instance) {
if (!Meteor.userId()) {
return;
}
openProfileTabOrOpenDM(e, instance, this.user.username);
},
'click .user-card-message'(e, instance) {
if (!Meteor.userId() || !this._arguments) {
return;
}
const username = this._arguments[1].u.username;
openProfileTabOrOpenDM(e, instance, username);
},
'scroll .wrapper': _.throttle(function(e, t) {
lazyloadtick();
const $roomLeader = $('.room-leader');
if ($roomLeader.length) {
if (e.target.scrollTop < lastScrollTop) {
t.hideLeaderHeader.set(false);
} else if (t.isAtBottom(100) === false && e.target.scrollTop > $('.room-leader').height()) {
t.hideLeaderHeader.set(true);
}
}
lastScrollTop = e.target.scrollTop;
if (RoomHistoryManager.isLoading(this._id) === false && RoomHistoryManager.hasMore(this._id) === true || RoomHistoryManager.hasMoreNext(this._id) === true) {
if (RoomHistoryManager.hasMore(this._id) === true && e.target.scrollTop === 0) {
RoomHistoryManager.getMore(this._id);
} else if (RoomHistoryManager.hasMoreNext(this._id) === true && e.target.scrollTop >= e.target.scrollHeight - e.target.clientHeight) {
RoomHistoryManager.getMoreNext(this._id);
}
}
}, 200),
'click .new-message'() {
Template.instance().atBottom = true;
chatMessages[RocketChat.openedRoom].input.focus();
},
'click .message-actions__menu'(e, i) {
let context = $(e.target).parents('.message').data('context');
if (!context) {
context = 'message';
}
const [, message] = this._arguments;
const allItems = RocketChat.MessageAction.getButtons(message, context, 'menu').map(item => {
return {
icon: item.icon,
name: t(item.label),
type: 'message-action',
id: item.id,
modifier: item.color
};
});
const [items, deleteItem] = allItems.reduce((result, value) => (result[value.id === 'delete-message' ? 1 : 0].push(value), result), [[], []]);
const groups = [{ items }];
if (deleteItem.length) {
groups.push({ items: deleteItem });
}
const config = {
columns: [
{
groups
}
],
instance: i,
data: this,
currentTarget: e.currentTarget,
activeElement: $(e.currentTarget).parents('.message')[0],
onRendered: () => new Clipboard('.rc-popover__item')
};
popover.open(config);
},
'click .time a'(e) {
e.preventDefault();
const repliedMessageId = this._arguments[1].attachments[0].message_link.split('?msg=')[1];
FlowRouter.go(FlowRouter.current().context.pathname, null, {msg: repliedMessageId, hash: Random.id()});
},
'click .mention-link'(e, instance) {
if (!Meteor.userId()) {
return;
}
const channel = $(e.currentTarget).data('channel');
if (channel != null) {
if (RocketChat.Layout.isEmbedded()) {
fireGlobalEvent('click-mention-link', { path: FlowRouter.path('channel', { name: channel }), channel });
}
FlowRouter.go('channel', { name: channel }, FlowRouter.current().queryParams);
return;
}
const username = $(e.currentTarget).data('username');
openProfileTabOrOpenDM(e, instance, username);
},
'click .image-to-download'(event) {
ChatMessage.update({ _id: this._arguments[1]._id, 'urls.url': $(event.currentTarget).data('url') }, { $set: { 'urls.$.downloadImages': true } });
ChatMessage.update({ _id: this._arguments[1]._id, 'attachments.image_url': $(event.currentTarget).data('url') }, { $set: { 'attachments.$.downloadImages': true } });
},
'click .collapse-switch'(e) {
const index = $(e.currentTarget).data('index');
const collapsed = $(e.currentTarget).data('collapsed');
const id = this._arguments[1]._id;
if ((this._arguments[1] != null ? this._arguments[1].attachments : undefined) != null) {
ChatMessage.update({ _id: id }, { $set: { [`attachments.${ index }.collapsed`]: !collapsed } });
}
if ((this._arguments[1] != null ? this._arguments[1].urls : undefined) != null) {
ChatMessage.update({ _id: id }, { $set: { [`urls.${ index }.collapsed`]: !collapsed } });
}
},
'dragenter .dropzone'(e) {
const types = e.originalEvent && e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.types;
if (types != null && types.length > 0 && _.every(types, type => type.indexOf('text/') === -1 || type.indexOf('text/uri-list') !== -1) && userCanDrop(this._id)) {
e.currentTarget.classList.add('over');
}
},
'dragleave .dropzone-overlay'(e) {
e.currentTarget.parentNode.classList.remove('over');
},
'dragover .dropzone-overlay'(e) {
e = e.originalEvent || e;
if (['move', 'linkMove'].includes(e.dataTransfer.effectAllowed)) {
e.dataTransfer.dropEffect = 'move';
} else {
e.dataTransfer.dropEffect = 'copy';
}
},
'dropped .dropzone-overlay'(event) {
event.currentTarget.parentNode.classList.remove('over');
const e = event.originalEvent || event;
const files = (e.dataTransfer != null ? e.dataTransfer.files : undefined) || [];
const filesToUpload = [];
for (const file of Array.from(files)) {
// `file.type = mime.lookup(file.name)` does not work.
Object.defineProperty(file, 'type', { value: mime.lookup(file.name) });
filesToUpload.push({
file,
name: file.name
});
}
fileUpload(filesToUpload);
},
'load img'(e, template) {
return (typeof template.sendToBottomIfNecessary === 'function' ? template.sendToBottomIfNecessary() : undefined);
},
'click .jump-recent button'(e, template) {
e.preventDefault();
template.atBottom = true;
RoomHistoryManager.clear(template && template.data && template.data._id);
},
'click .message'(e, template) {
if (template.selectable.get()) {
(document.selection != null ? document.selection.empty() : undefined) || (typeof window.getSelection === 'function' ? window.getSelection().removeAllRanges() : undefined);
const data = Blaze.getData(e.currentTarget);
const _id = data && data._arguments && data._arguments[1] && data._arguments[1]._id;
if (!template.selectablePointer) {
template.selectablePointer = _id;
}
if (!e.shiftKey) {
template.selectedMessages = template.getSelectedMessages();
template.selectedRange = [];
template.selectablePointer = _id;
}
template.selectMessages(_id);
const selectedMessages = $('.messages-box .message.selected').map((i, message) => message.id);
const removeClass = _.difference(selectedMessages, template.getSelectedMessages());
const addClass = _.difference(template.getSelectedMessages(), selectedMessages);
removeClass.forEach(message => $(`.messages-box #${ message }`).removeClass('selected'));
addClass.forEach(message => $(`.messages-box #${ message }`).addClass('selected'));
}
},
'click .announcement'() {
const roomData = Session.get(`roomData${ this._id }`);
if (!roomData) { return false; }
if (roomData.announcementDetails != null && roomData.announcementDetails.callback != null) {
return RocketChat.callbacks.run(roomData.announcementDetails.callback, this._id);
} else {
modal.open({
title: t('Announcement'),
text: roomData.announcement,
showConfirmButton: false,
showCancelButton: true,
cancelButtonText: t('Close')
});
}
},
'click .toggle-hidden'(e) {
const id = e.currentTarget.dataset.message;
document.querySelector(`#${ id }`).classList.toggle('message--ignored');
}
});
Template.room.onCreated(function() {
// this.scrollOnBottom = true
// this.typing = new msgTyping this.data._id
lazyloadtick();
this.showUsersOffline = new ReactiveVar(false);
this.atBottom = FlowRouter.getQueryParam('msg') ? false : true;
this.unreadCount = new ReactiveVar(0);
this.selectable = new ReactiveVar(false);
this.selectedMessages = [];
this.selectedRange = [];
this.selectablePointer = null;
this.flexTemplate = new ReactiveVar;
this.userDetail = new ReactiveVar(FlowRouter.getParam('username'));
this.tabBar = new RocketChatTabBar();
this.tabBar.showGroup(FlowRouter.current().route.name);
this.hideLeaderHeader = new ReactiveVar(false);
this.resetSelection = enabled => {
this.selectable.set(enabled);
$('.messages-box .message.selected').removeClass('selected');
this.selectedMessages = [];
this.selectedRange = [];
this.selectablePointer = null;
};
this.selectMessages = to => {
if ((this.selectablePointer === to) && (this.selectedRange.length > 0)) {
this.selectedRange = [];
} else {
const message1 = ChatMessage.findOne(this.selectablePointer);
const message2 = ChatMessage.findOne(to);
const minTs = _.min([message1.ts, message2.ts]);
const maxTs = _.max([message1.ts, message2.ts]);
this.selectedRange = _.pluck(ChatMessage.find({ rid: message1.rid, ts: { $gte: minTs, $lte: maxTs } }).fetch(), '_id');
}
};
this.getSelectedMessages = () => {
let previewMessages;
const messages = this.selectedMessages;
let addMessages = false;
for (const message of Array.from(this.selectedRange)) {
if (messages.indexOf(message) === -1) {
addMessages = true;
break;
}
}
if (addMessages) {
previewMessages = _.compact(_.uniq(this.selectedMessages.concat(this.selectedRange)));
} else {
previewMessages = _.compact(_.difference(this.selectedMessages, this.selectedRange));
}
return previewMessages;
};
this.setUserDetail = username => {
this.userDetail.set(username);
};
this.clearUserDetail = () => {
this.userDetail.set(null);
};
this.hasTokenpass = new ReactiveVar(false);
if (RocketChat.settings.get('API_Tokenpass_URL') !== '') {
Meteor.call('getChannelTokenpass', this.data._id, (error, result) => {
if (!error) {
this.hasTokenpass.set(!!(result && result.tokens && result.tokens.length > 0));
}
});
}
Meteor.call('getRoomRoles', this.data._id, function(error, results) {
if (error) {
handleError(error);
}
return Array.from(results).map((record) => {
delete record._id;
RoomRoles.upsert({ rid: record.rid, 'u._id': record.u._id }, record);
});
});
RoomRoles.find({ rid: this.data._id }).observe({
added: role => {
if (!role.u || !role.u._id) {
return;
}
ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $addToSet: { roles: role._id } }, { multi: true });
}, // Update message to re-render DOM
changed: (role) => {
if (!role.u || !role.u._id) {
return;
}
ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $inc: { rerender: 1 } }, { multi: true });
}, // Update message to re-render DOM
removed: role => {
if (!role.u || !role.u._id) {
return;
}
ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $pull: { roles: role._id } }, { multi: true });
}
});
this.sendToBottomIfNecessary = () => {};
}); // Update message to re-render DOM
Template.room.onDestroyed(function() {
window.removeEventListener('resize', this.onWindowResize);
});
Template.room.onRendered(function() {
// $(this.find('.messages-box .wrapper')).perfectScrollbar();
const rid = Session.get('openedRoom');
if (!window.chatMessages[rid]) {
window.chatMessages[rid] = new ChatMessages;
}
window.chatMessages[rid].init(this.firstNode);
// ScrollListener.init()
const wrapper = this.find('.wrapper');
const wrapperUl = this.find('.wrapper > ul');
const newMessage = this.find('.new-message');
const template = this;
const messageBox = $('.messages-box');
template.isAtBottom = function(scrollThreshold) {
if (scrollThreshold == null) {
scrollThreshold = 0;
}
if (wrapper.scrollTop + scrollThreshold >= wrapper.scrollHeight - wrapper.clientHeight) {
newMessage.className = 'new-message background-primary-action-color color-content-background-color not';
return true;
}
return false;
};
template.sendToBottom = function() {
wrapper.scrollTop = wrapper.scrollHeight - wrapper.clientHeight;
newMessage.className = 'new-message background-primary-action-color color-content-background-color not';
};
template.checkIfScrollIsAtBottom = function() {
template.atBottom = template.isAtBottom(100);
readMessage.enable();
readMessage.read();
};
template.sendToBottomIfNecessary = function() {
if (template.atBottom === true && template.isAtBottom() !== true) {
template.sendToBottom();
}
lazyloadtick();
};
template.sendToBottomIfNecessaryDebounced = _.debounce(template.sendToBottomIfNecessary, 10);
template.sendToBottomIfNecessary();
if ((window.MutationObserver == null)) {
wrapperUl.addEventListener('DOMSubtreeModified', () => template.sendToBottomIfNecessaryDebounced());
} else {
const observer = new MutationObserver((mutations) => mutations.forEach(() => template.sendToBottomIfNecessaryDebounced()));
observer.observe(wrapperUl, { childList: true });
}
// observer.disconnect()
template.onWindowResize = () =>
Meteor.defer(() => template.sendToBottomIfNecessaryDebounced())
;
window.addEventListener('resize', template.onWindowResize);
wrapper.addEventListener('mousewheel', function() {
template.atBottom = false;
Meteor.defer(() => template.checkIfScrollIsAtBottom());
});
wrapper.addEventListener('wheel', function() {
template.atBottom = false;
Meteor.defer(() => template.checkIfScrollIsAtBottom());
});
wrapper.addEventListener('touchstart', () => template.atBottom = false);
wrapper.addEventListener('touchend', function() {
Meteor.defer(() => template.checkIfScrollIsAtBottom());
Meteor.setTimeout(() => template.checkIfScrollIsAtBottom(), 1000);
Meteor.setTimeout(() => template.checkIfScrollIsAtBottom(), 2000);
});
wrapper.addEventListener('scroll', function() {
template.atBottom = false;
Meteor.defer(() => template.checkIfScrollIsAtBottom());
});
$('.flex-tab-bar').on('click', (/*e, t*/) =>
Meteor.setTimeout(() => template.sendToBottomIfNecessaryDebounced(), 50)
);
lastScrollTop = $('.messages-box .wrapper').scrollTop();
const rtl = $('html').hasClass('rtl');
const getElementFromPoint = function(topOffset = 0) {
const messageBoxOffset = messageBox.offset();
let element;
if (rtl) {
element = document.elementFromPoint((messageBoxOffset.left + messageBox.width()) - 1, messageBoxOffset.top + topOffset + 1);
} else {
element = document.elementFromPoint(messageBoxOffset.left + 1, messageBoxOffset.top + topOffset + 1);
}
if (element && element.classList.contains('message')) {
return element;
}
};
const updateUnreadCount = _.throttle(function() {
const lastInvisibleMessageOnScreen = getElementFromPoint(0) || getElementFromPoint(20) || getElementFromPoint(40);
if (lastInvisibleMessageOnScreen == null || lastInvisibleMessageOnScreen.id == null) {
return template.unreadCount.set(0);
}
const lastMessage = ChatMessage.findOne(lastInvisibleMessageOnScreen.id);
if (lastMessage == null) {
return template.unreadCount.set(0);
}
const subscription = ChatSubscription.findOne({ rid: template.data._id }, {reactive: false});
const count = ChatMessage.find({ rid: template.data._id, ts: { $lte: lastMessage.ts, $gt: subscription && subscription.ls } }).count();
template.unreadCount.set(count);
}, 300);
readMessage.onRead(function(rid) {
if (rid === template.data._id) {
template.unreadCount.set(0);
}
});
wrapper.addEventListener('scroll', () => updateUnreadCount());
/* globals WebRTC */
// salva a data da renderização para exibir alertas de novas mensagens
$.data(this.firstNode, 'renderedAt', new Date);
const webrtc = WebRTC.getInstanceByRoomId(template.data._id);
if (webrtc != null) {
Tracker.autorun(() => {
const remoteItems = webrtc.remoteItems.get();
if (remoteItems && remoteItems.length > 0) {
this.tabBar.setTemplate('membersList');
this.tabBar.open();
}
if (webrtc.localUrl.get() != null) {
this.tabBar.setTemplate('membersList');
this.tabBar.open();
}
});
}
RocketChat.callbacks.add('streamMessage', (msg) => {
if (rid !== msg.rid || msg.editedAt) {
return;
}
if (!template.isAtBottom()) {
newMessage.classList.remove('not');
}
});
Tracker.autorun(function() {
const room = RocketChat.models.Rooms.findOne({ _id: template.data._id });
if (!room) {
FlowRouter.go('home');
}
});
}); | if (roles) { |
PlotQueueActions.tsx | import React from 'react';
import { Trans } from '@lingui/macro';
import { useDispatch } from 'react-redux';
import { ConfirmDialog, More } from '@mint/core';
import {
Box,
Divider,
ListItemIcon,
MenuItem,
Typography,
} from '@material-ui/core';
import {
DeleteForever as DeleteForeverIcon,
Info as InfoIcon,
} from '@material-ui/icons';
import useOpenDialog from '../../../hooks/useOpenDialog';
import type PlotQueueItem from '../../../types/PlotQueueItem';
import PlotStatus from '../../../constants/PlotStatus';
import { stopPlotting } from '../../../modules/plotter_messages';
import PlotQueueLogDialog from './PlotQueueLogDialog';
type Props = {
queueItem: PlotQueueItem;
};
export default function PlotQueueAction(props: Props) {
const {
queueItem: { id, state },
} = props;
const dispatch = useDispatch();
const openDialog = useOpenDialog();
const canDelete = state !== PlotStatus.REMOVING;
async function handleDeletePlot() {
if (!canDelete) {
return;
}
const deleteConfirmed = await openDialog(
<ConfirmDialog
title={<Trans>Delete Plot</Trans>}
confirmTitle={<Trans>Delete</Trans>}
confirmColor="danger"
>
<Trans>
Are you sure you want to delete the plot? The plot cannot be
recovered.
</Trans>
</ConfirmDialog>,
);
// @ts-ignore
if (deleteConfirmed) {
dispatch(stopPlotting(id));
}
}
function handleViewLog() {
openDialog(<PlotQueueLogDialog id={id} />);
}
return (
<More> | <Box>
{state === PlotStatus.RUNNING && (
<>
<MenuItem
onClick={() => {
onClose();
handleViewLog();
}}
>
<ListItemIcon>
<InfoIcon fontSize="small" />
</ListItemIcon>
<Typography variant="inherit" noWrap>
<Trans>View Log</Trans>
</Typography>
</MenuItem>
<Divider />
</>
)}
<MenuItem
onClick={() => {
onClose();
handleDeletePlot();
}}
disabled={!canDelete}
>
<ListItemIcon>
<DeleteForeverIcon fontSize="small" />
</ListItemIcon>
<Typography variant="inherit" noWrap>
<Trans>Delete</Trans>
</Typography>
</MenuItem>
</Box>
)}
</More>
);
} | {({ onClose }) => ( |
mit.rs | use crate::items::traits::{Decorate, Builder};
use crate::items::util::{create_file, get_git_name};
static MIT_LICENSE: &'static str = r#"
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.
"#;
pub struct Mit {}
impl Mit {
pub fn new() -> Self {
Mit{}
}
}
impl Decorate for Mit {
fn decorate(&mut self, path: &String) {
let name = path.to_owned() + "/" + "LICENSE-MIT";
let git_user_name = get_git_name().unwrap();
let content_header = " Copyright (c) 2019 ".to_owned() + &git_user_name + "\n";
let content = content_header + MIT_LICENSE;
create_file(&name, &content);
}
}
///Builder
pub struct MitBuilder {}
impl MitBuilder {
pub fn new() -> Self {
MitBuilder{}
}
} | Box::new( Mit::new() )
}
} |
impl Builder for MitBuilder {
type Output = Box<dyn Decorate>;
fn build(&mut self) -> Box<dyn Decorate> { |
glu.go | package gtds
import (
"runtime"
"unsafe"
)
func init() {
runtime.LockOSThread()
}
type WindowStyle int
const (
Borderless WindowStyle = 1 << iota
Titled
Closable
Resizable
Hideable
Fullscreen
)
type Window struct {
ptr unsafe.Pointer
}
type WindowConfig struct { | Width, Height int
Style WindowStyle
}
type windowData struct {
window Window
shouldClose bool
}
func CreateWindow(w WindowConfig) Window {
if w.Width < 0 || w.Height < 0 {
panic("Improper Window Dimensions")
}
return platformCreateWindow(w)
}
func PollEvents() {
platformPollEvents()
}
func (w Window) ShouldClose() bool {
return getData(w).shouldClose
}
func Run(run func() error) error {
platformInit()
return run()
} | Title string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.