file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
serializers.py | from rest_framework import serializers
class DescriptionAssessmentResponseSerializer(serializers.Serializer):
priority = serializers.ListField(child=serializers.CharField())
resolution = serializers.ListField(child=serializers.CharField())
areas_of_testing = serializers.ListField(child=serializers.CharField())
| resolution = serializers.DictField(child=serializers.FloatField())
areas_of_testing = serializers.DictField(child=serializers.FloatField())
time_to_resolve = serializers.DictField(child=serializers.FloatField())
class HighlightingResponseSerializer(serializers.ListSerializer):
child = serializers.CharField()
class PredictorRequestSerializer(serializers.Serializer):
description = serializers.CharField()
class HighlightingRequestSerializer(serializers.Serializer):
metric = serializers.CharField()
value = serializers.CharField() | class PredictorResponseSerializer(serializers.Serializer):
priority = serializers.DictField(child=serializers.FloatField()) |
esse3api.py |
import json, sys, re, urllib, urllib2, socket, json, pydoc, cgi, os, time, inspect
from hashlib import md5
from datetime import datetime
import time
import csv
from scraper import Scraper
from flask import Flask
from flask import Response
from flask import request
from flask import jsonify
from flask import current_app
from flask import make_response
from flask import session
from flask import url_for
from flask import redirect
from flask import render_template
from flask import abort
from flask import g
from flask import flash
from flask import _app_ctx_stack
from flask_restplus import Resource, Api
from flask_restplus import fields
from functools import wraps
from functools import update_wrapper
import logging
import traceback
log = logging.getLogger(__name__)
app = Flask(__name__)
api = Api(app)
app.config.from_object(__name__) # load config from this file , esse3api.py
# Load default config and override config from an environment variable
app.config.update(dict(
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('ESSE3API_SETTINGS', silent=True)
@api.errorhandler
def default_error_handler(e):
message = 'An unhandled exception occurred.'
log.exception(message)
if not settings.FLASK_DEBUG:
return {'message': message}, 500
#### CROSSDOMAIN DECORATOR ####
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
|
#### JSONP DECORATOR ####
def jsonp(func):
""" Wrap json as jsonp """
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
parser = api.parser()
parser.add_argument('username', help='The username', location='form')
parser.add_argument('password', help='The passowrd', location='form')
@api.route('/dati_anagrafici')
class DatiAnagrafici(Resource):
@api.doc(parser=parser)
def post(self):
"""Recuper i dati anagrafici
:param: username: Nome utente
:param: password: Password
:example: /dati_anagrafici
:returns: json -- I dati personali
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
log.info(username)
s = Scraper(username, password)
return jsonify(s.dati_anagrafici())
@api.route('/login')
class Login(Resource):
@api.doc(parser=parser)
def post(self):
"""Permette il login al portale esse3
:param: username: Nome utente
:param: password: Password
:example: /login
:returns: json -- Risultato del login
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.login())
@api.route('/riepilogo_esami')
class RiepilogoEsami(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il riepilogo degli esami effettuati dallo studente
:param: username: Nome utente
:param: password: Password
:example: /riepilogo_esami
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.riepilogo_esami())
@api.route('/residenza')
class Residenza(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce la residenza dello studente
:param: username: Nome utente
:param: password: Password
:example: /residenza
:returns: json -- Residenza dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.residenza())
@api.route('/domicilio')
class Domicilio(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il domicilio dello studente
:param: username: Nome utente
:param: password: Password
:example: /domicilio
:returns: json -- Domicilio dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.domicilio())
@api.route('/libretto')
class Libretto(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il libretto universitario dello studente
:param: username: Nome utente
:param: password: Password
:example: /libretto
:returns: json -- Libretto dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.libretto())
@api.route('/pagamenti')
class Pagamenti(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce i pagamenti effettuati dello studente
:param: username: Nome utente
:param: password: Password
:example: /pagamenti
:returns: json -- Pagamenti effettuati dallo studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pagamenti())
@api.route('/prenotazioni_effettuate')
class PrenotazioniEffettuate(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce le prenotazioni alle sedute d'esame effettuati dello studente
:param: username: Nome utente
:param: password: Password
:example: /prenotazioni_effettuate
:returns: json -- Prenotazioni effettuate dallo studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.prenotazioni_effettuate())
@api.route('/piano')
class Piano(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il piano di studio dello studente
:param: username: Nome utente
:param: password: Password
:example: /piano
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.piano())
@api.route('/pannello')
class Pannello(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il pannello di controllo dello studente
:param: username: Nome utente
:param: password: Password
:example: /pannello
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pannello_di_controllo())
if __name__ == '__main__':
app.debug = True
app.run()
| if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
h['Access-Control-Allow-Credentials'] = 'true'
h['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept, Authorization"
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator |
get_all_product_package_items.py | #!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all product package items.
"""
# Import appropriate modules from the client library. |
def main(client):
# Initialize appropriate service.
product_package_item_service = client.GetService(
'ProductPackageItemService', version='v201805')
# Create a statement to select product package items.
statement = ad_manager.StatementBuilder(version='v201805')
# Retrieve a small amount of product package items at a time, paging
# through until all product package items have been retrieved.
while True:
response = product_package_item_service.getProductPackageItemsByStatement(
statement.ToStatement())
if 'results' in response and len(response['results']):
for product_package_item in response['results']:
# Print out some information for each product package item.
print('Product package item with ID "%d", product id "%d", and product '
'package id "%d" was found.\n' %
(product_package_item['id'], product_package_item['productId'],
product_package_item['productPackageId']))
statement.offset += statement.limit
else:
break
print '\nNumber of results found: %s' % response['totalResultSetSize']
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client) | from googleads import ad_manager |
factory.go | // Copyright The OpenTelemetry 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 groupbytraceprocessor
import (
"context"
"fmt"
"time"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config/configmodels"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/processor/processorhelper"
)
const (
// typeStr is the value of "type" for this processor in the configuration.
typeStr configmodels.Type = "groupbytrace"
)
var (
defaultWaitDuration = time.Second
defaultNumTraces = 1_000_000
defaultDiscardOrphans = false
defaultStoreOnDisk = false
errDiskStorageNotSupported = fmt.Errorf("option 'disk storage' not supported in this release")
errDiscardOrphansNotSupported = fmt.Errorf("option 'discard orphans' not supported in this release")
)
// NewFactory returns a new factory for the Filter processor.
func NewFactory() component.ProcessorFactory {
return processorhelper.NewFactory(
typeStr,
createDefaultConfig,
processorhelper.WithTraces(createTraceProcessor))
}
// createDefaultConfig creates the default configuration for the processor.
func createDefaultConfig() configmodels.Processor {
return &Config{
ProcessorSettings: configmodels.ProcessorSettings{
TypeVal: typeStr,
NameVal: string(typeStr),
},
NumTraces: defaultNumTraces,
WaitDuration: defaultWaitDuration,
// not supported for now
DiscardOrphans: defaultDiscardOrphans,
StoreOnDisk: defaultStoreOnDisk,
}
}
// createTraceProcessor creates a trace processor based on this config.
func createTraceProcessor(
_ context.Context,
params component.ProcessorCreateParams,
cfg configmodels.Processor,
nextConsumer consumer.TraceConsumer) (component.TraceProcessor, error) {
oCfg := cfg.(*Config)
var st storage
if oCfg.StoreOnDisk {
return nil, errDiskStorageNotSupported
}
if oCfg.DiscardOrphans |
// the only supported storage for now
st = newMemoryStorage()
return newGroupByTraceProcessor(params.Logger, st, nextConsumer, *oCfg)
}
| {
return nil, errDiscardOrphansNotSupported
} |
python-startup.py | import sys
import subprocess
def snipe_import_exceptions(exctype, value, traceback):
if exctype == ImportError:
module = str(value).split(" ")[-1:][0]
install_module(module) |
def install_module(module):
print "installing module", module
subprocess.call("sudo pip install %s" %module, shell=True) | else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = snipe_import_exceptions |
conn.go | /*
Copyright 2017 The GoStor Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package iscsit
import (
"io"
"net"
"sort"
"sync"
"github.com/gostor/gotgt/pkg/api"
"github.com/gostor/gotgt/pkg/util"
)
const (
CONN_STATE_FREE = 0
CONN_STATE_SECURITY = 1
CONN_STATE_SECURITY_AUTH = 2
CONN_STATE_SECURITY_DONE = 3
CONN_STATE_SECURITY_LOGIN = 4
CONN_STATE_SECURITY_FULL = 5
CONN_STATE_LOGIN = 6
CONN_STATE_LOGIN_FULL = 7
CONN_STATE_FULL = 8
CONN_STATE_KERNEL = 9
CONN_STATE_CLOSE = 10
CONN_STATE_EXIT = 11
CONN_STATE_SCSI = 12
CONN_STATE_INIT = 13
CONN_STATE_START = 14
CONN_STATE_READY = 15
)
var (
DATAIN byte = 0x01
DATAOUT byte = 0x10
)
type iscsiConnection struct {
ConnNum int
state int
authState int
session *ISCSISession
tid int
cid uint16
rxIOState int
txIOState int
refcount int
conn net.Conn
rxBuffer []byte
txBuffer []byte
req *ISCSICommand
resp *ISCSICommand
loginParam *iscsiLoginParam
// StatSN - the status sequence number on this connection
statSN uint32
// ExpStatSN - the expected status sequence number on this connection
expStatSN uint32
// CmdSN - the command sequence number at the target
cmdSN uint32
// ExpCmdSN - the next expected command sequence number at the target
expCmdSN uint32
// MaxCmdSN - the maximum CmdSN acceptable at the target from this initiator
maxCmdSN uint32
maxRecvDataSegmentLength uint32
maxBurstLength uint32
maxSeqCount uint32
rxTask *iscsiTask
txTask *iscsiTask
readLock *sync.RWMutex
}
type taskState int
const (
taskPending taskState = 0
taskSCSI taskState = 1
)
type iscsiTask struct {
tag uint32
conn *iscsiConnection
cmd *ISCSICommand
scmd *api.SCSICommand
state taskState
expectedDataLength int64
result byte
offset int
r2tCount int
unsolCount int
expR2TSN int
r2tSN uint32
}
func (c *iscsiConnection) init() {
c.state = CONN_STATE_FREE
c.refcount = 1
c.readLock = new(sync.RWMutex)
c.loginParam.sessionParam = []ISCSISessionParam{}
c.loginParam.tgtCSG = LoginOperationalNegotiation
c.loginParam.tgtNSG = LoginOperationalNegotiation
for _, param := range sessionKeys {
c.loginParam.sessionParam = append(c.loginParam.sessionParam,
ISCSISessionParam{idx: param.idx, Value: param.def})
}
sort.Sort(c.loginParam.sessionParam)
}
func (c *iscsiConnection) readData(buf []byte) (int, error) {
length, err := io.ReadFull(c.conn, buf)
if err != nil {
return -1, err
}
return length, nil
}
func (c *iscsiConnection) write(resp []byte) (int, error) {
return c.conn.Write(resp)
}
func (c *iscsiConnection) close() {
c.conn.Close()
}
func (conn *iscsiConnection) ReInstatement(newConn *iscsiConnection) {
conn.close()
conn.conn = newConn.conn
}
func (conn *iscsiConnection) buildRespPackage(oc OpCode, task *iscsiTask) error {
conn.txTask = &iscsiTask{conn: conn, cmd: conn.req, tag: conn.req.TaskTag, scmd: &api.SCSICommand{}}
conn.txIOState = IOSTATE_TX_BHS
conn.statSN += 1
if task == nil {
task = conn.rxTask
}
conn.resp = &ISCSICommand{
StartTime: conn.req.StartTime,
StatSN: conn.req.ExpStatSN,
TaskTag: conn.req.TaskTag,
ExpCmdSN: conn.session.ExpCmdSN,
MaxCmdSN: conn.session.ExpCmdSN + conn.session.MaxQueueCommand,
ExpectedDataLen: conn.req.ExpectedDataLen,
}
switch oc {
case OpReady:
conn.resp.OpCode = OpReady
conn.resp.R2TSN = task.r2tSN
conn.resp.Final = true
conn.resp.BufferOffset = uint32(task.offset)
conn.resp.DesiredLength = uint32(task.r2tCount)
if val := conn.loginParam.sessionParam[ISCSI_PARAM_MAX_BURST].Value; task.r2tCount > int(val) {
conn.resp.DesiredLength = uint32(val)
}
case OpSCSIIn, OpSCSIResp:
conn.resp.OpCode = oc
conn.resp.SCSIOpCode = conn.req.SCSIOpCode
conn.resp.Immediate = true
conn.resp.Final = true
conn.resp.SCSIResponse = 0x00
conn.resp.HasStatus = true
scmd := task.scmd
conn.resp.Status = scmd.Result
if scmd.Result != 0 && scmd.SenseBuffer != nil | else if scmd.Direction == api.SCSIDataRead || scmd.Direction == api.SCSIDataWrite {
if scmd.InSDBBuffer != nil {
conn.resp.Resid = scmd.InSDBBuffer.Resid
if conn.resp.Resid != 0 && conn.resp.Resid < scmd.InSDBBuffer.Length {
conn.resp.RawData = scmd.InSDBBuffer.Buffer[:conn.resp.Resid]
} else {
conn.resp.RawData = scmd.InSDBBuffer.Buffer
}
} else {
conn.resp.RawData = []byte{}
}
}
case OpNoopIn, OpReject:
conn.resp.OpCode = oc
conn.resp.Final = true
conn.resp.NSG = FullFeaturePhase
conn.resp.ExpCmdSN = conn.req.CmdSN + 1
case OpSCSITaskResp:
conn.resp.OpCode = oc
conn.resp.Final = true
conn.resp.NSG = FullFeaturePhase
conn.resp.ExpCmdSN = conn.req.CmdSN + 1
conn.resp.Result = task.result
case OpLoginResp:
conn.resp.OpCode = OpLoginResp
conn.resp.Transit = conn.loginParam.tgtTrans
conn.resp.CSG = conn.req.CSG
conn.resp.NSG = conn.loginParam.tgtNSG
conn.resp.ExpCmdSN = conn.req.CmdSN
conn.resp.MaxCmdSN = conn.req.CmdSN
negoKeys, err := conn.processLoginData()
if err != nil {
return err
}
if !conn.loginParam.keyDeclared {
negoKeys = loginKVDeclare(conn, negoKeys)
conn.loginParam.keyDeclared = true
}
conn.resp.RawData = util.MarshalKVText(negoKeys)
conn.txTask = nil
}
return nil
}
func (conn *iscsiConnection) State() string {
switch conn.state {
case CONN_STATE_FREE:
return "free"
case CONN_STATE_SECURITY:
return "begin security"
case CONN_STATE_SECURITY_AUTH:
return "security auth"
case CONN_STATE_SECURITY_DONE:
return "done security"
case CONN_STATE_SECURITY_LOGIN:
return "security login"
case CONN_STATE_SECURITY_FULL:
return "security full"
case CONN_STATE_LOGIN:
return "begin login"
case CONN_STATE_LOGIN_FULL:
return "done login"
case CONN_STATE_FULL:
return "full feature"
case CONN_STATE_KERNEL:
return "kernel"
case CONN_STATE_CLOSE:
return "close"
case CONN_STATE_EXIT:
return "exit"
case CONN_STATE_SCSI:
return "scsi"
case CONN_STATE_INIT:
return "init"
case CONN_STATE_START:
return "start"
case CONN_STATE_READY:
return "ready"
}
return ""
}
| {
length := util.MarshalUint32(scmd.SenseBuffer.Length)
conn.resp.RawData = append(length[2:4], scmd.SenseBuffer.Buffer...)
} |
root.route.js | import {Outlet} from 'react-router-dom'
function Route() {
return (
<div>
<p>In 'routes/root.route.js'</p>
<p>---------Outlet---------</p>
<Outlet />
</div>
);
} |
export default Route; |
|
sift.py | import os
import cv2
import numpy as np
import multiprocessing
class SiftExtractor:
def __init__(self, feature_data, collection_data):
""" Creates a SiftExtractor.
:param feature_data: Feature data set.
:param collection_data: Collection data set.
"""
self.__feature_data = feature_data
self.__collection_data = collection_data
def | (self, image):
""" Extracts SIFT features for an image and saves the descriptors
and locations to file.
:param image: Image name.
"""
im = cv2.imread(os.path.join(self.__collection_data.path, image), cv2.IMREAD_GRAYSCALE)
if im is None:
# Image is corrupt. Delete the image file.
print 'Removing corrupt image {0}'.format(image)
os.remove(os.path.join(self.__collection_data.path, image))
return
locations, descriptors = extract_sift_features(im, self.__feature_data.config.edge_threshold,
self.__feature_data.config.peak_threshold)
self.__feature_data.save(image, locations, descriptors)
print 'Extracted {0} features for {1}'.format(descriptors.shape[0], image)
def extract(data):
""" Extracts SIFT features for a list of images. Saves the descriptors
and locations to file.
:param data: Data set.
"""
sift_extractor = SiftExtractor(data.feature, data.collection)
if data.collection.config.processes == 1:
for image in data.collection.images():
sift_extractor(image)
else:
pool = multiprocessing.Pool(data.collection.config.processes)
pool.map(sift_extractor, data.collection.images())
print 'Features extracted'
def extract_sift_features(image, edge_threshold=10, peak_threshold=0.01):
""" Process a grayscale image and return the found SIFT feature points
and descriptors.
:param image : A gray scale image represented in a 2-D array.
:param edge_threshold: The edge threshold.
:param peak_threshold: The peak threshold.
:return locations : An array with the row, column, scale and orientation of each feature.
:return descriptors : The descriptors.
"""
detector = cv2.FeatureDetector_create('SIFT')
descriptor = cv2.DescriptorExtractor_create('SIFT')
detector.setDouble('edgeThreshold', edge_threshold)
detector.setDouble("contrastThreshold", peak_threshold)
locations = detector.detect(image)
locations, descriptors = descriptor.compute(image, locations)
locations = np.array([(loc.pt[0], loc.pt[1], loc.size, loc.angle) for loc in locations])
return locations, descriptors | __call__ |
__init__.py | from weldarray import *
from weldnumpy import *
# FIXME: Should this be in weldnump? pytest gives errors when trying to import
# weldarray in weldnumpy...so keeping it here for now.
def array(arr, *args, **kwargs):
''' | '''
return weldarray(np.array(arr, *args, **kwargs)) | Wrapper around weldarray - first create np.array and then convert to
weldarray. |
ConnectHandler.py | #######################################################
#
# ConnectHandler.py
# Python implementation of the Class ConnectHandler
# Generated by Enterprise Architect
# Created on: 29-Dec-2020 8:10:45 AM
# Original author: natha
#
#######################################################
from Catalog.Data.Federation.Handler import Handler
class ConnectHandler(Handler):
# default constructor def __init__(self):
def Handle(object, command): | pass | pass
def setNextHandler(handler): |
test_ZKZ.py | import unittest
import numpy as np
from limix.core.covar.zkz import ZKZCov
from limix.utils.check_grad import mcheck_grad
import scipy as sp
class TestZKZ(unittest.TestCase):
def setUp(self):
np.random.seed()
print '\n\n\n'
print np.random.randn(1)
print '\n\n\n'
self._X = np.random.randn(10, 5)
tmp = np.random.randn(10, 20)
self.Kinship = tmp.dot(tmp.transpose())
self._cov = ZKZCov(self._X, self.Kinship, remove_diag=True)
def test_Kgrad(self):
def | (x, i):
self._cov.scale = x[i]
return self._cov.K()
def grad(x, i):
self._cov.scale = x[i]
return self._cov.K_grad_i(0)
x0 = np.array([self._cov.scale])
err = mcheck_grad(func, grad, x0)
np.testing.assert_almost_equal(err, 0, decimal=5)
def func(x, i):
self._cov.length = x[i]
return self._cov.K()
def grad(x, i):
self._cov.scale = x[i]
return self._cov.K_grad_i(1)
x0 = np.array([self._cov.scale])
err = mcheck_grad(func, grad, x0)
if __name__ == '__main__':
unittest.main()
| func |
positive_tests.go | package checker_test
type reader interface {
Read([]byte) (int, error)
}
type myReader struct{}
func (myReader) Read(_ []byte) (int, error) { return 0, nil }
func | (x interface{}) {
switch x.(type) {
case reader:
/// case myReader must go before the reader case
case myReader:
/// case *myReader must go before the reader case
case *myReader:
default:
}
switch x.(type) {
case interface{}:
/// case reader must go before the interface{} case
case reader:
/// case myReader must go before the interface{} case
case myReader:
/// case *myReader must go before the interface{} case
case *myReader:
default:
}
switch x.(type) {
case reader:
case interface{}:
/// case myReader must go before the reader case
case myReader:
/// case *myReader must go before the reader case
case *myReader:
default:
}
}
| typeSwitches |
gmm2d.py | import torch
import torch.distributions as td
class GMM2D(td.MixtureSameFamily):
def __init__(self, mixture_distribution, component_distribution):
super(GMM2D, self).__init__(mixture_distribution, component_distribution)
def mode_mode(self):
mode_k = torch.argmax(self.mixture_distribution.probs[0, 0]).item()
mode_gaussian = self.component_distribution.mean[:, 0, mode_k, :2]
return mode_gaussian
def position_log_prob(self, x):
# Computing the log probability over only the positions.
|
@property
def pis(self):
return self.mixture_distribution.probs[0, 0]
| component_dist = td.MultivariateNormal(loc=self.component_distribution.mean[..., :2],
scale_tril=self.component_distribution.scale_tril[..., :2, :2])
position_dist = td.MixtureSameFamily(self.mixture_distribution, component_dist)
return position_dist.log_prob(x) |
advent05.rs | use std::collections::HashSet;
use std::io::{BufRead};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
struct Record {
pub row: u32,
pub col: u32,
}
impl Record {
fn from_line(line: &[u8]) -> Self {
let mut row = 0;
let mut col = 0;
for b in line {
match b {
b'F' => { row = row << 1; }
b'B' => { row = (row << 1) | 1; }
b'L' => { col = col << 1; }
b'R' => { col = (col << 1) | 1; }
b'\n' | b'\r' => (),
c => panic!("Unexpected byte {}", c),
}
}
Self {row, col}
}
pub fn ident(&self) -> u32 {
self.col + 8 * self.row
}
}
fn input() -> Vec<Record> {
let mut buf = Vec::with_capacity(8 + 3 + 1);
let mut ret = Vec::new();
let stdin = std::io::stdin();
let mut stdin = stdin.lock();
loop {
let len = stdin.read_until(b'\n', &mut buf).expect("No I/O errors");
if len == 0 {
return ret;
}
ret.push(Record::from_line(&buf));
buf.clear();
}
}
fn part_a(idents: &[u32]) -> u32 {
idents.iter().copied().max().expect("Non-empty input")
}
// Pass in max from part a, save on recomputaiton
fn part_b(idents: &[u32], max: u32) -> u32 {
let min = idents.iter().copied().min().expect("Non-empty input");
let mut seats = HashSet::with_capacity((max - min) as usize);
seats.extend(min..max);
for ident in idents {
seats.remove(ident);
}
seats.remove(&min);
seats.remove(&max);
if seats.len() != 1 |
seats.iter().copied().nth(0).expect("A solution to exist")
}
fn main() {
let data = input();
let idents = data.iter().map(|x| x.ident()).collect::<Vec<u32>>();
let soln_a = part_a(&idents);
println!("Part a: {}", soln_a);
let soln_b = part_b(&idents, soln_a);
println!("Part b: {}", soln_b);
}
| {
panic!("Non-unique seats: {:?}", seats)
} |
ucb.py | import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
def | ():
# create argument parser
parser = argparse.ArgumentParser()
# parameter for problem
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--benchmark_id', type=int, default=0)
parser.add_argument('--rmp', type=float, default=0.3)
# parse args
args = parser.parse_args()
# add other args
return args
ROOT = '../../result'
def load(args):
folder = os.path.join(ROOT, '{}/{}_{}'.format(args.benchmark_id, args.algorithm, args.rmp))
Fitness = []
for name in os.listdir(folder):
path = os.path.join(folder, name)
if 'ucb' in name:
y = np.load(path)
Fitness.append(y)
return np.array(Fitness)
def get_label(args):
return '{}_{}'.format(args.algorithm, args.benchmark_id)
def plot(Fitness, args):
cs = [
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['r', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'r', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'r', 'r', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'r', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
]
label = get_label(args)
Fitness = Fitness[:, :, args.source]
mean_fitness = np.mean(Fitness, axis=0)
i = 0
for target in range(mean_fitness.shape[1]):
if target != args.source:
plt.plot(mean_fitness[:, target], label='T{}'.format(target+1), color=cs[args.source][i], linewidth=0.3)
plt.ylabel('UCB value')
i += 1
def main():
# get args
args = get_args()
# plot each algorithm
args.algorithm = 'MTO'
Fitness = load(args)
for source in range(10):
args.source = source
plot(Fitness, args)
plt.legend()
plt.ylim((0, 2))
plt.savefig('plot/ucb/{}.eps'.format(source + 1), dpi=300)
plt.savefig('plot/ucb/{}.png'.format(source + 1), dpi=300)
plt.clf()
plt.cla()
if __name__ == '__main__':
main()
| get_args |
subtask-drag-and-drop.js | KB.on('dom.ready', function() {
function | (subtaskId, position) {
var url = $(".subtasks-table").data("save-position-url");
$.ajax({
cache: false,
url: url,
contentType: "application/json",
type: "POST",
processData: false,
data: JSON.stringify({
"subtask_id": subtaskId,
"position": position
})
});
}
$(".draggable-row-handle").mouseenter(function() {
$(this).parent().parent().addClass("draggable-item-hover");
}).mouseleave(function() {
$(this).parent().parent().removeClass("draggable-item-hover");
});
$(".subtasks-table tbody").sortable({
forcePlaceholderSize: true,
handle: "td:first i",
helper: function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
},
stop: function(event, ui) {
var subtask = ui.item;
subtask.removeClass("draggable-item-selected");
savePosition(subtask.data("subtask-id"), subtask.index() + 1);
},
start: function(event, ui) {
ui.item.addClass("draggable-item-selected");
}
}).disableSelection();
});
| savePosition |
seek-bar.js | /**
* @file seek-bar.js
*/
import Slider from '../../slider/slider.js';
import Component from '../../component.js';
import {IS_IOS, IS_ANDROID} from '../../utils/browser.js';
import * as Dom from '../../utils/dom.js';
import * as Fn from '../../utils/fn.js';
import formatTime from '../../utils/format-time.js';
import {silencePromise} from '../../utils/promise';
import './load-progress-bar.js';
import './play-progress-bar.js';
import './mouse-time-display.js';
// The number of seconds the `step*` functions move the timeline.
const STEP_SECONDS = 5;
// The interval at which the bar should update as it progresses.
const UPDATE_REFRESH_INTERVAL = 30;
/**
* Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
* as its `bar`.
*
* @extends Slider
*/
class SeekBar extends Slider {
/**
* Creates an instance of this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
constructor(player, options) {
super(player, options);
this.setEventHandlers_();
}
/**
* Sets the event handlers
*
* @private
*/
setEventHandlers_() {
this.update = Fn.throttle(Fn.bind(this, this.update), UPDATE_REFRESH_INTERVAL);
this.on(this.player_, 'timeupdate', this.update);
this.on(this.player_, 'ended', this.handleEnded);
// when playing, let's ensure we smoothly update the play progress bar
// via an interval
this.updateInterval = null;
this.on(this.player_, ['playing'], () => {
this.clearInterval(this.updateInterval);
this.updateInterval = this.setInterval(() =>{
this.requestAnimationFrame(() => {
this.update();
});
}, UPDATE_REFRESH_INTERVAL);
});
this.on(this.player_, ['ended', 'pause', 'waiting'], () => {
this.clearInterval(this.updateInterval);
});
this.on(this.player_, ['timeupdate', 'ended'], this.update);
}
/**
* Create the `Component`'s DOM element
*
* @return {Element}
* The element that was created.
*/
createEl() {
return super.createEl('div', {
className: 'vjs-progress-holder'
}, {
'aria-label': this.localize('Progress Bar')
});
}
/**
* This function updates the play progress bar and accessibility
* attributes to whatever is passed in.
*
* @param {number} currentTime
* The currentTime value that should be used for accessibility
*
* @param {number} percent
* The percentage as a decimal that the bar should be filled from 0-1.
*
* @private
*/
update_(currentTime, percent) {
const duration = this.player_.duration();
// machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
// human readable value of progress bar (time complete)
this.el_.setAttribute('aria-valuetext',
this.localize('progress bar timing: currentTime={1} duration={2}',
[formatTime(currentTime, duration),
formatTime(duration, duration)],
'{1} of {2}'));
// Update the `PlayProgressBar`.
this.bar.update(Dom.getBoundingClientRect(this.el_), percent);
}
/**
* Update the seek bar's UI.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` or `ended` event that caused this to run.
*
* @listens Player#timeupdate
*
* @returns {number}
* The current percent at a number from 0-1
*/
update(event) {
const percent = super.update();
this.update_(this.getCurrentTime_(), percent);
return percent;
}
/**
* Get the value of current time but allows for smooth scrubbing,
* when player can't keep up.
*
* @return {number}
* The current time value to display
*
* @private
*/
getCurrentTime_() {
return (this.player_.scrubbing()) ?
this.player_.getCache().currentTime :
this.player_.currentTime();
}
/**
* We want the seek bar to be full on ended
* no matter what the actual internal values are. so we force it.
*
* @param {EventTarget~Event} [event]
* The `timeupdate` or `ended` event that caused this to run.
*
* @listens Player#ended
*/
handleEnded(event) {
this.update_(this.player_.duration(), 1);
}
/**
* Get the percentage of media played so far.
*
* @return {number}
* The percentage of media played so far (0 to 1).
*/
getPercent() {
const percent = this.getCurrentTime_() / this.player_.duration();
return percent >= 1 ? 1 : percent;
}
/**
* Handle mouse down on seek bar
*
* @param {EventTarget~Event} event
* The `mousedown` event that caused this to run.
*
* @listens mousedown
*/
handleMouseDown(event) {
if (!Dom.isSingleLeftClick(event)) {
return;
}
// Stop event propagation to prevent double fire in progress-control.js
event.stopPropagation();
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
super.handleMouseDown(event);
}
/**
* Handle mouse move on seek bar
*
* @param {EventTarget~Event} event
* The `mousemove` event that caused this to run.
*
* @listens mousemove
*/
handleMouseMove(event) {
if (!Dom.isSingleLeftClick(event)) {
return;
}
let newTime = this.calculateDistance(event) * this.player_.duration();
// Don't let video end while scrubbing.
if (newTime === this.player_.duration()) {
newTime = newTime - 0.1;
}
// Set new time (tell player to seek to new time)
this.player_.currentTime(newTime);
}
enable() {
super.enable();
const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
if (!mouseTimeDisplay) {
return;
}
mouseTimeDisplay.show();
} | const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
if (!mouseTimeDisplay) {
return;
}
mouseTimeDisplay.hide();
}
/**
* Handle mouse up on seek bar
*
* @param {EventTarget~Event} event
* The `mouseup` event that caused this to run.
*
* @listens mouseup
*/
handleMouseUp(event) {
super.handleMouseUp(event);
// Stop event propagation to prevent double fire in progress-control.js
if (event) {
event.stopPropagation();
}
this.player_.scrubbing(false);
/**
* Trigger timeupdate because we're done seeking and the time has changed.
* This is particularly useful for if the player is paused to time the time displays.
*
* @event Tech#timeupdate
* @type {EventTarget~Event}
*/
this.player_.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
if (this.videoWasPlaying) {
silencePromise(this.player_.play());
}
}
/**
* Move more quickly fast forward for keyboard-only users
*/
stepForward() {
this.player_.currentTime(this.player_.currentTime() + STEP_SECONDS);
}
/**
* Move more quickly rewind for keyboard-only users
*/
stepBack() {
this.player_.currentTime(this.player_.currentTime() - STEP_SECONDS);
}
/**
* Toggles the playback state of the player
* This gets called when enter or space is used on the seekbar
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called
*
*/
handleAction(event) {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
}
/**
* Called when this SeekBar has focus and a key gets pressed down. By
* default it will call `this.handleAction` when the key is space or enter.
*
* @param {EventTarget~Event} event
* The `keydown` event that caused this function to be called.
*
* @listens keydown
*/
handleKeyPress(event) {
// Support Space (32) or Enter (13) key operation to fire a click event
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.handleAction(event);
} else if (super.handleKeyPress) {
// Pass keypress handling up for unsupported keys
super.handleKeyPress(event);
}
}
}
/**
* Default options for the `SeekBar`
*
* @type {Object}
* @private
*/
SeekBar.prototype.options_ = {
children: [
'loadProgressBar',
'playProgressBar'
],
barName: 'playProgressBar'
};
// MouseTimeDisplay tooltips should not be added to a player on mobile devices
if (!IS_IOS && !IS_ANDROID) {
SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
}
/**
* Call the update event for this Slider when this event happens on the player.
*
* @type {string}
*/
SeekBar.prototype.playerEvent = 'timeupdate';
Component.registerComponent('SeekBar', SeekBar);
export default SeekBar; |
disable() {
super.disable(); |
options.js | module.exports = { | }; | themeColor: '#B21255',
head: '<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />', |
rpc.rs | //! Serialization for client-server communication.
use std::any::Any;
use std::char;
use std::io::Write;
use std::num::NonZeroU32;
use std::ops::Bound;
use std::str;
pub(super) type Writer = super::buffer::Buffer;
pub(super) trait Encode<S>: Sized {
fn encode(self, w: &mut Writer, s: &mut S);
}
pub(super) type Reader<'a> = &'a [u8];
pub(super) trait Decode<'a, 's, S>: Sized {
fn decode(r: &mut Reader<'a>, s: &'s S) -> Self;
}
pub(super) trait DecodeMut<'a, 's, S>: Sized {
fn decode(r: &mut Reader<'a>, s: &'s mut S) -> Self;
}
macro_rules! rpc_encode_decode {
(le $ty:ty) => {
impl<S> Encode<S> for $ty {
fn encode(self, w: &mut Writer, _: &mut S) {
w.extend_from_array(&self.to_le_bytes());
}
}
impl<S> DecodeMut<'_, '_, S> for $ty {
fn decode(r: &mut Reader<'_>, _: &mut S) -> Self {
const N: usize = ::std::mem::size_of::<$ty>();
let mut bytes = [0; N];
bytes.copy_from_slice(&r[..N]);
*r = &r[N..];
Self::from_le_bytes(bytes)
}
} | $(self.$field.encode(w, s);)*
}
}
impl<S> DecodeMut<'_, '_, S> for $name {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
$name {
$($field: DecodeMut::decode(r, s)),*
}
}
}
};
(enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => {
impl<S, $($($T: Encode<S>),+)?> Encode<S> for $name $(<$($T),+>)? {
fn encode(self, w: &mut Writer, s: &mut S) {
// HACK(eddyb): `Tag` enum duplicated between the
// two impls as there's no other place to stash it.
#[allow(non_upper_case_globals)]
mod tag {
#[repr(u8)] enum Tag { $($variant),* }
$(pub const $variant: u8 = Tag::$variant as u8;)*
}
match self {
$($name::$variant $(($field))* => {
tag::$variant.encode(w, s);
$($field.encode(w, s);)*
})*
}
}
}
impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S>
for $name $(<$($T),+>)?
{
fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
// HACK(eddyb): `Tag` enum duplicated between the
// two impls as there's no other place to stash it.
#[allow(non_upper_case_globals)]
mod tag {
#[repr(u8)] enum Tag { $($variant),* }
$(pub const $variant: u8 = Tag::$variant as u8;)*
}
match u8::decode(r, s) {
$(tag::$variant => {
$(let $field = DecodeMut::decode(r, s);)*
$name::$variant $(($field))*
})*
_ => unreachable!(),
}
}
}
}
}
impl<S> Encode<S> for () {
fn encode(self, _: &mut Writer, _: &mut S) {}
}
impl<S> DecodeMut<'_, '_, S> for () {
fn decode(_: &mut Reader<'_>, _: &mut S) -> Self {}
}
impl<S> Encode<S> for u8 {
fn encode(self, w: &mut Writer, _: &mut S) {
w.push(self);
}
}
impl<S> DecodeMut<'_, '_, S> for u8 {
fn decode(r: &mut Reader<'_>, _: &mut S) -> Self {
let x = r[0];
*r = &r[1..];
x
}
}
rpc_encode_decode!(le u32);
rpc_encode_decode!(le usize);
impl<S> Encode<S> for bool {
fn encode(self, w: &mut Writer, s: &mut S) {
(self as u8).encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for bool {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
match u8::decode(r, s) {
0 => false,
1 => true,
_ => unreachable!(),
}
}
}
impl<S> Encode<S> for char {
fn encode(self, w: &mut Writer, s: &mut S) {
(self as u32).encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for char {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
char::from_u32(u32::decode(r, s)).unwrap()
}
}
impl<S> Encode<S> for NonZeroU32 {
fn encode(self, w: &mut Writer, s: &mut S) {
self.get().encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for NonZeroU32 {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
Self::new(u32::decode(r, s)).unwrap()
}
}
impl<S, A: Encode<S>, B: Encode<S>> Encode<S> for (A, B) {
fn encode(self, w: &mut Writer, s: &mut S) {
self.0.encode(w, s);
self.1.encode(w, s);
}
}
impl<'a, S, A: for<'s> DecodeMut<'a, 's, S>, B: for<'s> DecodeMut<'a, 's, S>> DecodeMut<'a, '_, S>
for (A, B)
{
fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
(DecodeMut::decode(r, s), DecodeMut::decode(r, s))
}
}
rpc_encode_decode!(
enum Bound<T> {
Included(x),
Excluded(x),
Unbounded,
}
);
rpc_encode_decode!(
enum Option<T> {
None,
Some(x),
}
);
rpc_encode_decode!(
enum Result<T, E> {
Ok(x),
Err(e),
}
);
impl<S> Encode<S> for &[u8] {
fn encode(self, w: &mut Writer, s: &mut S) {
self.len().encode(w, s);
w.write_all(self).unwrap();
}
}
impl<'a, S> DecodeMut<'a, '_, S> for &'a [u8] {
fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
let len = usize::decode(r, s);
let xs = &r[..len];
*r = &r[len..];
xs
}
}
impl<S> Encode<S> for &str {
fn encode(self, w: &mut Writer, s: &mut S) {
self.as_bytes().encode(w, s);
}
}
impl<'a, S> DecodeMut<'a, '_, S> for &'a str {
fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
str::from_utf8(<&[u8]>::decode(r, s)).unwrap()
}
}
impl<S> Encode<S> for String {
fn encode(self, w: &mut Writer, s: &mut S) {
self[..].encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for String {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
<&str>::decode(r, s).to_string()
}
}
/// Simplified version of panic payloads, ignoring
/// types other than `&'static str` and `String`.
pub enum PanicMessage {
StaticStr(&'static str),
String(String),
Unknown,
}
impl From<Box<dyn Any + Send>> for PanicMessage {
fn from(payload: Box<dyn Any + Send + 'static>) -> Self {
if let Some(s) = payload.downcast_ref::<&'static str>() {
return PanicMessage::StaticStr(s);
}
if let Ok(s) = payload.downcast::<String>() {
return PanicMessage::String(*s);
}
PanicMessage::Unknown
}
}
impl Into<Box<dyn Any + Send>> for PanicMessage {
fn into(self) -> Box<dyn Any + Send> {
match self {
PanicMessage::StaticStr(s) => Box::new(s),
PanicMessage::String(s) => Box::new(s),
PanicMessage::Unknown => {
struct UnknownPanicMessage;
Box::new(UnknownPanicMessage)
}
}
}
}
impl PanicMessage {
pub fn as_str(&self) -> Option<&str> {
match self {
PanicMessage::StaticStr(s) => Some(s),
PanicMessage::String(s) => Some(s),
PanicMessage::Unknown => None,
}
}
}
impl<S> Encode<S> for PanicMessage {
fn encode(self, w: &mut Writer, s: &mut S) {
self.as_str().encode(w, s);
}
}
impl<S> DecodeMut<'_, '_, S> for PanicMessage {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
match Option::<String>::decode(r, s) {
Some(s) => PanicMessage::String(s),
None => PanicMessage::Unknown,
}
}
} | };
(struct $name:ident { $($field:ident),* $(,)? }) => {
impl<S> Encode<S> for $name {
fn encode(self, w: &mut Writer, s: &mut S) { |
expressrouteserviceproviders.go | package network
// Copyright (c) Microsoft and contributors. 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.
//
// 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"
"net/http"
)
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// ExpressRouteServiceProvidersClient is the network Client
type ExpressRouteServiceProvidersClient struct {
BaseClient
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// NewExpressRouteServiceProvidersClient creates an instance of the ExpressRouteServiceProvidersClient client.
func | (subscriptionID string) ExpressRouteServiceProvidersClient {
return NewExpressRouteServiceProvidersClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// NewExpressRouteServiceProvidersClientWithBaseURI creates an instance of the ExpressRouteServiceProvidersClient
// client.
func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteServiceProvidersClient {
return ExpressRouteServiceProvidersClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// List the List ExpressRouteServiceProvider opertion retrieves all the available ExpressRouteServiceProviders.
func (client ExpressRouteServiceProvidersClient) List(ctx context.Context) (result ExpressRouteServiceProviderListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.ersplr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request")
return
}
result.ersplr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to request")
}
return
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// ListPreparer prepares the List request.
func (client ExpressRouteServiceProvidersClient) ListPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRouteServiceProvidersClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Response) (result ExpressRouteServiceProviderListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
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 ExpressRouteServiceProvidersClient) listNextResults(lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, err error) {
req, err := lastResults.expressRouteServiceProviderListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "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.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// Deprecated: Please use package github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network instead.
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExpressRouteServiceProvidersClient) ListComplete(ctx context.Context) (result ExpressRouteServiceProviderListResultIterator, err error) {
result.page, err = client.List(ctx)
return
}
| NewExpressRouteServiceProvidersClient |
nvic_iser2.rs | #[doc = "Register `NVIC_ISER2` reader"]
pub struct R(crate::R<NVIC_ISER2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<NVIC_ISER2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<NVIC_ISER2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<NVIC_ISER2_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `NVIC_ISER2` writer"]
pub struct W(crate::W<NVIC_ISER2_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<NVIC_ISER2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<NVIC_ISER2_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<NVIC_ISER2_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Interrupt set-enable bits\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum SETENA_A {
#[doc = "0: interrupt disabled"]
VALUE3 = 0,
#[doc = "1: interrupt enabled."]
VALUE4 = 1,
}
impl From<SETENA_A> for u32 {
#[inline(always)]
fn from(variant: SETENA_A) -> Self {
variant as _
}
}
#[doc = "Field `SETENA` reader - Interrupt set-enable bits"]
pub struct SETENA_R(crate::FieldReader<u32, SETENA_A>);
impl SETENA_R {
pub(crate) fn new(bits: u32) -> Self {
SETENA_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SETENA_A> {
match self.bits {
0 => Some(SETENA_A::VALUE3),
1 => Some(SETENA_A::VALUE4),
_ => None,
}
}
#[doc = "Checks if the value of the field is `VALUE3`"]
#[inline(always)]
pub fn is_value3(&self) -> bool {
**self == SETENA_A::VALUE3
}
#[doc = "Checks if the value of the field is `VALUE4`"]
#[inline(always)]
pub fn | (&self) -> bool {
**self == SETENA_A::VALUE4
}
}
impl core::ops::Deref for SETENA_R {
type Target = crate::FieldReader<u32, SETENA_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SETENA` writer - Interrupt set-enable bits"]
pub struct SETENA_W<'a> {
w: &'a mut W,
}
impl<'a> SETENA_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SETENA_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "interrupt disabled"]
#[inline(always)]
pub fn value3(self) -> &'a mut W {
self.variant(SETENA_A::VALUE3)
}
#[doc = "interrupt enabled."]
#[inline(always)]
pub fn value4(self) -> &'a mut W {
self.variant(SETENA_A::VALUE4)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | (value as u32 & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - Interrupt set-enable bits"]
#[inline(always)]
pub fn setena(&self) -> SETENA_R {
SETENA_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - Interrupt set-enable bits"]
#[inline(always)]
pub fn setena(&mut self) -> SETENA_W {
SETENA_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Interrupt Set-enable Register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [nvic_iser2](index.html) module"]
pub struct NVIC_ISER2_SPEC;
impl crate::RegisterSpec for NVIC_ISER2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [nvic_iser2::R](R) reader structure"]
impl crate::Readable for NVIC_ISER2_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [nvic_iser2::W](W) writer structure"]
impl crate::Writable for NVIC_ISER2_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets NVIC_ISER2 to value 0"]
impl crate::Resettable for NVIC_ISER2_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| is_value4 |
component_events_integration_test.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
use {
anyhow::{format_err, Context, Error},
fdio,
fidl::endpoints::DiscoverableService,
fidl_fuchsia_inspect::TreeMarker,
fidl_fuchsia_sys::{
ComponentControllerEvent, EnvironmentControllerEvent, EnvironmentControllerProxy,
EnvironmentMarker, EnvironmentOptions, EnvironmentProxy, LauncherProxy,
ServiceProviderMarker,
},
fidl_fuchsia_sys_internal::{
ComponentEventListenerMarker, ComponentEventListenerRequest,
ComponentEventListenerRequestStream, ComponentEventProviderMarker, SourceIdentity,
},
fuchsia_async::{self as fasync, DurationExt, TimeoutExt},
fuchsia_component::client::{connect_to_service, launch, App},
fuchsia_inspect::{assert_inspect_tree, reader},
fuchsia_zircon::DurationNum,
futures::{
future,
stream::{StreamExt, TryStreamExt},
},
lazy_static::lazy_static,
maplit::hashset,
regex::Regex,
std::collections::HashSet,
};
lazy_static! {
static ref TEST_COMPONENT: String = "test_component.cmx".to_string();
static ref TEST_COMPONENT_WITH_REALM: String = "test_component_with_subrealm.cmx".to_string();
static ref TEST_COMPONENT_URL: String =
"fuchsia-pkg://fuchsia.com/component_events_integration_tests#meta/test_component.cmx"
.to_string();
static ref TEST_COMPONENT_WITH_REALM_URL: String =
"fuchsia-pkg://fuchsia.com/component_events_integration_tests#meta/test_component_with_subrealm.cmx"
.to_string();
static ref SELF_COMPONENT: String = "component_events_integration_test.cmx".to_string();
static ref TEST_COMPONENT_REALM_PATH: Vec<String> = vec!["diagnostics_test".to_string()];
static ref TIMEOUT_SECONDS: i64 = 1;
}
struct ComponentEventsTest {
listener_request_stream: Option<ComponentEventListenerRequestStream>,
diagnostics_test_env: EnvironmentProxy,
_diagnostics_test_env_ctrl: EnvironmentControllerProxy,
}
impl ComponentEventsTest {
pub async fn new(env: &EnvironmentProxy, with_listener: bool) -> Result<Self, Error> |
// Asserts that we receive the expected events about this component itself.
async fn consume_self_events(&mut self) -> Result<(), Error> {
match &mut self.listener_request_stream {
None => {}
Some(listener_request_stream) => {
let self_realm_path = Vec::new();
let request =
listener_request_stream.try_next().await.context("Fetch self start")?;
if let Some(ComponentEventListenerRequest::OnStart { component, .. }) = request {
self.assert_identity(component, &SELF_COMPONENT, &self_realm_path);
} else {
return Err(format_err!("Expected start event for self"));
}
}
}
Ok(())
}
/// Asserts a start event for the test_component.
async fn assert_on_start(&mut self, name: &str, realm_path: &[String]) -> Result<(), Error> {
match &mut self.listener_request_stream {
None => {}
Some(listener_request_stream) => {
let request =
listener_request_stream.try_next().await.context("Fetch test start")?;
if let Some(ComponentEventListenerRequest::OnStart { component, .. }) = request {
self.assert_identity(component, name, realm_path);
} else {
return Err(format_err!("Expected start event. Got: {:?}", request));
}
}
}
Ok(())
}
/// Asserts a stop event for the test_component.
async fn assert_on_stop(&mut self) -> Result<(), Error> {
match &mut self.listener_request_stream {
None => {}
Some(listener_request_stream) => {
let request =
listener_request_stream.try_next().await.context("Fetch test stop")?;
if let Some(ComponentEventListenerRequest::OnStop { component, .. }) = request {
self.assert_identity(component, &*TEST_COMPONENT, &*TEST_COMPONENT_REALM_PATH);
} else {
return Err(format_err!("Expected stop event. Got: {:?}", request));
}
}
}
Ok(())
}
/// Utility function to assert that a `SourceIdentity` is the expected one.
fn assert_identity(
&self,
component: SourceIdentity,
name: &str,
expected_realm_path: &[String],
) {
assert_eq!(component.component_name, Some(name.to_string()));
assert_eq!(
component.component_url,
Some(format!(
"fuchsia-pkg://fuchsia.com/component_events_integration_tests#meta/{}",
name
))
);
let instance_id = component.instance_id.expect("no instance id");
assert!(Regex::new("[0-9]+").unwrap().is_match(&instance_id));
let realm_path = component.realm_path.unwrap();
assert_eq!(realm_path, expected_realm_path);
}
}
async fn create_nested_environment(
parent: &EnvironmentProxy,
label: &str,
) -> Result<(EnvironmentProxy, EnvironmentControllerProxy), Error> {
let (new_env, new_env_server_end) =
fidl::endpoints::create_proxy::<EnvironmentMarker>().context("could not create proxy")?;
let (controller, controller_server_end) =
fidl::endpoints::create_proxy().context("could not create proxy")?;
let mut env_options = EnvironmentOptions {
inherit_parent_services: true,
use_parent_runners: true,
kill_on_oom: true,
delete_storage_on_death: true,
};
parent
.create_nested_environment(
new_env_server_end,
controller_server_end,
label,
None,
&mut env_options,
)
.context("could not create isolated environment")?;
let EnvironmentControllerEvent::OnCreated {} = controller
.take_event_stream()
.next()
.await
.unwrap()
.expect("failed to get env created event");
Ok((new_env, controller))
}
fn listen_for_component_events(
env: &EnvironmentProxy,
) -> Result<ComponentEventListenerRequestStream, Error> {
let (service_provider, server_end) =
fidl::endpoints::create_proxy::<ServiceProviderMarker>().context("create proxy")?;
env.get_services(server_end)?;
let (event_provider, server_end) =
fidl::endpoints::create_proxy::<ComponentEventProviderMarker>().context("create proxy")?;
service_provider.connect_to_service(
ComponentEventProviderMarker::SERVICE_NAME,
server_end.into_channel(),
)?;
let (events_client_end, listener_request_stream) =
fidl::endpoints::create_request_stream::<ComponentEventListenerMarker>()
.context("Create request stream")?;
event_provider.set_listener(events_client_end)?;
Ok(listener_request_stream)
}
fn get_launcher(env: &EnvironmentProxy) -> Result<LauncherProxy, Error> {
let (launcher, launcher_server_end) =
fidl::endpoints::create_proxy().context("could not create proxy")?;
env.get_launcher(launcher_server_end).context("could not get isolated environment launcher")?;
Ok(launcher)
}
// Asserts that we receive the expected events about a component that contains an
// out/diagnostics directory: START, STOP, OUT_DIR_READY.
#[fasync::run_singlethreaded(test)]
async fn test_with_diagnostics() -> Result<(), Error> {
let env = connect_to_service::<EnvironmentMarker>().expect("connect to current environment");
let mut test = ComponentEventsTest::new(&env, true).await?;
let arguments = vec!["with-diagnostics".to_string()];
let launcher = get_launcher(&test.diagnostics_test_env).context("get launcher")?;
let mut app = launch(&launcher, TEST_COMPONENT_URL.to_string(), Some(arguments))
.context("start test component")?;
test.assert_on_start(&*TEST_COMPONENT, &*TEST_COMPONENT_REALM_PATH).await?;
let request = test
.listener_request_stream
.as_mut()
.unwrap()
.try_next()
.await
.context("Fetch test dir ready")?;
if let Some(ComponentEventListenerRequest::OnDiagnosticsDirReady {
component, directory, ..
}) = request
{
test.assert_identity(component, &*TEST_COMPONENT, &*TEST_COMPONENT_REALM_PATH);
let (tree, server_end) =
fidl::endpoints::create_proxy::<TreeMarker>().expect("Create Tree proxy");
fdio::service_connect_at(
directory.channel(),
TreeMarker::SERVICE_NAME,
server_end.into_channel(),
)
.expect("Connect to Tree service");
let hierarchy = reader::read_from_tree(&tree).await.context("Get inspect hierarchy")?;
assert_inspect_tree!(hierarchy, root: {
"fuchsia.inspect.Health": contains {
status: "OK",
}
});
} else {
return Err(format_err!("Expected diagnostics directory ready event. Got: {:?}", request));
}
app.kill().context("Kill app")?;
test.assert_on_stop().await?;
Ok(())
}
// Asserts that we receive the expected events about a component that doesn't contain an
// out/diagnostics directory: START, STOP.
#[fasync::run_singlethreaded(test)]
async fn test_without_diagnostics() -> Result<(), Error> {
let env = connect_to_service::<EnvironmentMarker>().expect("connect to current environment");
let mut test = ComponentEventsTest::new(&env, true).await?;
let launcher = get_launcher(&test.diagnostics_test_env).context("get launcher")?;
let mut app = launch(&launcher, TEST_COMPONENT_URL.to_string(), None)?;
test.assert_on_start(&*TEST_COMPONENT, &*TEST_COMPONENT_REALM_PATH).await?;
let request = test
.listener_request_stream
.as_mut()
.unwrap()
.try_next()
.on_timeout(TIMEOUT_SECONDS.seconds().after_now(), || Ok(None))
.await
.context("Fetch start event on a")?;
if let Some(ComponentEventListenerRequest::OnDiagnosticsDirReady { .. }) = request {
return Err(format_err!(
"Unexpected diagnostics dir ready event for component without diagnostics"
));
}
app.kill().context("Kill app")?;
test.assert_on_stop().await?;
Ok(())
}
async fn launch_app(
env: &EnvironmentProxy,
url: String,
args: Option<Vec<String>>,
) -> Result<App, Error> {
let app = launch(&get_launcher(&env)?, url, args)?;
let event_stream = app.controller().take_event_stream();
event_stream
.try_filter_map(|event| {
let event = match event {
ComponentControllerEvent::OnDirectoryReady {} => Some(event),
_ => None,
};
future::ready(Ok(event))
})
.next()
.await;
Ok(app)
}
// Tests that START events for components that exist before the listener is attached are
// propagated only to the first ancestor realm with a listener attached.
// This test does the following:
// 1. Create a realm hierarchy under the existing "test_env". This hierarchy looks like
// "test_env -> A -> sub -> comp"
// '-> B -> sub -> comp"
// 2. Start a component in A (that listens for events)
// 3. Start a component in B (no event listening)
// 4. Listen for events
// 5. Even though there's a component running under A, we are never notified about it given that
// given that there's already a listener there.
#[fasync::run_singlethreaded(test)]
async fn test_register_listener_in_subrealm() -> Result<(), Error> {
let env = connect_to_service::<EnvironmentMarker>().expect("connect to current environment");
let mut test = ComponentEventsTest::new(&env, false).await?;
let (env_a, _a_ctrl) = create_nested_environment(&env, "a").await?;
let (env_b, _b_ctrl) = create_nested_environment(&env, "b").await?;
// start our test component in environment a
let arguments = vec!["with-event-listener".to_string()];
let _app_a = launch_app(&env_a, TEST_COMPONENT_WITH_REALM_URL.to_string(), Some(arguments))
.await
.context("launch on a")?;
let _app_b = launch_app(&env_b, TEST_COMPONENT_WITH_REALM_URL.to_string(), None)
.await
.context("launch on b")?;
// Listen for start events. Only events expected are for: self, the component under B,
// and the test component under B.
test.listener_request_stream =
Some(listen_for_component_events(&env).context("get component event provider")?);
let mut events = HashSet::new();
for _ in 0..3 {
let request = test
.listener_request_stream
.as_mut()
.unwrap()
.try_next()
.await
.context("Fetch self start")?;
if let Some(ComponentEventListenerRequest::OnStart { component, .. }) = request {
events.insert((component.component_name.unwrap(), component.realm_path.unwrap()));
} else {
panic!("Expected start event. Got: {:?}", request);
}
}
assert_eq!(
events,
hashset! {
(SELF_COMPONENT.to_string(), vec![]),
(TEST_COMPONENT.to_string(), vec!["b".to_string(), "sub".to_string()]),
(TEST_COMPONENT_WITH_REALM.to_string(), vec!["b".to_string()]),
}
);
// Verify the listener on A is not notified about anything given that B already
// is listening for events.
let request = test
.listener_request_stream
.as_mut()
.unwrap()
.try_next()
.on_timeout(TIMEOUT_SECONDS.seconds().after_now(), || Ok(None))
.await
.context("Fetch start event on a")?;
if let Some(ComponentEventListenerRequest::OnStart { .. }) = request {
return Err(format_err!("Unexpected start event for test component on A"));
}
Ok(())
}
| {
let (diagnostics_test_env, ctrl) =
create_nested_environment(&env, "diagnostics_test").await?;
let listener_request_stream = if with_listener {
Some(listen_for_component_events(&env).context("get component event provider")?)
} else {
None
};
let mut test = Self {
listener_request_stream,
diagnostics_test_env,
_diagnostics_test_env_ctrl: ctrl,
};
test.consume_self_events().await.expect("failed to consume self events");
Ok(test)
} |
argon.js | /*!
=========================================================
* Argon Dashboard - v1.0.0
=========================================================
* Product Page: https://www.creative-tim.com/product/argon-dashboard
* Copyright 2018 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard/blob/master/LICENSE.md)
* Coded by www.creative-tim.com
=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
//
// Bootstrap Datepicker
//
'use strict';
var Datepicker = (function() {
// Variables
var $datepicker = $('.datepicker');
// Methods
function init($this) {
var options = {
disableTouchKeyboard: true,
autoclose: false
};
$this.datepicker(options);
}
// Events
if ($datepicker.length) {
$datepicker.each(function() {
init($(this));
});
}
})();
//
// Icon code copy/paste
//
'use strict';
var CopyIcon = (function() {
// Variables
var $element = '.btn-icon-clipboard',
$btn = $($element);
// Methods
function init($this) {
$this.tooltip().on('mouseleave', function() {
// Explicitly hide tooltip, since after clicking it remains
// focused (as it's a button), so tooltip would otherwise
// remain visible until focus is moved away
$this.tooltip('hide');
});
var clipboard = new ClipboardJS($element);
clipboard.on('success', function(e) {
$(e.trigger)
.attr('title', 'Copied!')
.tooltip('_fixTitle')
.tooltip('show')
.attr('title', 'Copy to clipboard')
.tooltip('_fixTitle')
e.clearSelection()
});
}
// Events
if ($btn.length) {
init($btn);
}
})();
//
// Form control
//
'use strict';
var FormControl = (function() {
// Variables
var $input = $('.form-control');
// Methods
function init($this) {
$this.on('focus blur', function(e) {
$(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
}
// Events
if ($input.length) {
init($input);
}
})();
//
// Google maps
//
var $map = $('#map-canvas'),
map,
lat,
lng,
color = "#5e72e4";
function initMap() {
map = document.getElementById('map-canvas');
lat = map.getAttribute('data-lat');
lng = map.getAttribute('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 12,
scrollwheel: false,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":color},{"visibility":"on"}]}]
}
map = new google.maps.Map(map, mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP,
title: 'Hello World!'
});
var contentString = '<div class="info-window-content"><h2>Argon Dashboard</h2>' +
'<p>A beautiful Dashboard for Bootstrap 4. It is Free and Open Source.</p></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
if($map.length) {
google.maps.event.addDomListener(window, 'load', initMap);
}
// //
// // Headroom - show/hide navbar on scroll
// //
//
// 'use strict';
//
// var Headroom = (function() {
//
// // Variables
//
// var $headroom = $('#navbar-main');
//
//
// // Methods
//
// function init($this) {
//
// var headroom = new Headroom(document.querySelector("#navbar-main"), {
// offset: 300,
// tolerance: {
// up: 30,
// down: 30
// },
// });
//
//
//
// // Events
//
// if ($headroom.length) {
// headroom.init();
// }
//
// })();
//
// Navbar
//
'use strict';
var Navbar = (function() {
// Variables
var $nav = $('.navbar-nav, .navbar-nav .nav');
var $collapse = $('.navbar .collapse');
var $dropdown = $('.navbar .dropdown');
// Methods
function accordion($this) {
$this.closest($nav).find($collapse).not($this).collapse('hide');
}
function closeDropdown($this) {
var $dropdownMenu = $this.find('.dropdown-menu');
$dropdownMenu.addClass('close');
setTimeout(function() {
$dropdownMenu.removeClass('close');
}, 200);
}
// Events
$collapse.on({
'show.bs.collapse': function() {
accordion($(this));
}
})
$dropdown.on({
'hide.bs.dropdown': function() {
closeDropdown($(this));
}
})
})();
//
// Navbar collapse
//
var NavbarCollapse = (function() {
// Variables
var $nav = $('.navbar-nav'),
$collapse = $('.navbar .collapse');
// Methods
function hideNavbarCollapse($this) {
$this.addClass('collapsing-out');
}
function hiddenNavbarCollapse($this) {
$this.removeClass('collapsing-out');
}
// Events
if ($collapse.length) {
$collapse.on({
'hide.bs.collapse': function() {
hideNavbarCollapse($collapse);
}
})
$collapse.on({
'hidden.bs.collapse': function() {
hiddenNavbarCollapse($collapse);
}
})
}
})();
//
// Form control
//
'use strict';
var noUiSlider = (function() {
// Variables
// var $sliderContainer = $('.input-slider-container'),
// $slider = $('.input-slider'),
// $sliderId = $slider.attr('id'),
// $sliderMinValue = $slider.data('range-value-min');
// $sliderMaxValue = $slider.data('range-value-max');;
// // Methods
//
// function init($this) {
// $this.on('focus blur', function(e) {
// $this.parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
// }).trigger('blur');
// }
//
//
// // Events
//
// if ($input.length) {
// init($input);
// }
if ($(".input-slider-container")[0]) {
$('.input-slider-container').each(function() {
var slider = $(this).find('.input-slider');
var sliderId = slider.attr('id');
var minValue = slider.data('range-value-min');
var maxValue = slider.data('range-value-max');
var sliderValue = $(this).find('.range-slider-value');
var sliderValueId = sliderValue.attr('id');
var startValue = sliderValue.data('range-value-low');
var c = document.getElementById(sliderId),
d = document.getElementById(sliderValueId);
noUiSlider.create(c, {
start: [parseInt(startValue)],
connect: [true, false],
//step: 1000,
range: {
'min': [parseInt(minValue)],
'max': [parseInt(maxValue)]
}
});
c.noUiSlider.on('update', function(a, b) {
d.textContent = a[b];
});
})
}
if ($("#input-slider-range")[0]) {
var c = document.getElementById("input-slider-range"),
d = document.getElementById("input-slider-range-value-low"),
e = document.getElementById("input-slider-range-value-high"),
f = [d, e];
noUiSlider.create(c, {
start: [parseInt(d.getAttribute('data-range-value-low')), parseInt(e.getAttribute('data-range-value-high'))],
connect: !0,
range: {
min: parseInt(c.getAttribute('data-range-value-min')),
max: parseInt(c.getAttribute('data-range-value-max'))
}
}), c.noUiSlider.on("update", function(a, b) {
f[b].textContent = a[b]
})
}
})();
//
// Popover
//
'use strict';
var Popover = (function() {
// Variables
var $popover = $('[data-toggle="popover"]'),
$popoverClass = '';
// Methods
function init($this) {
if ($this.data('color')) {
$popoverClass = 'popover-' + $this.data('color');
}
var options = {
trigger: 'focus',
template: '<div class="popover ' + $popoverClass + '" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
};
$this.popover(options);
}
// Events
if ($popover.length) {
$popover.each(function() {
init($(this));
});
}
})();
//
// Scroll to (anchor links)
//
'use strict';
var ScrollTo = (function() {
//
// Variables
//
var $scrollTo = $('.scroll-me, [data-scroll-to], .toc-entry a');
//
// Methods
//
function scrollTo($this) {
var $el = $this.attr('href');
var offset = $this.data('scroll-to-offset') ? $this.data('scroll-to-offset') : 0;
var options = {
scrollTop: $($el).offset().top - offset
};
// Animate scroll to the selected section
$('html, body').stop(true, true).animate(options, 600);
event.preventDefault();
}
//
// Events
//
if ($scrollTo.length) {
$scrollTo.on('click', function(event) {
scrollTo($(this));
});
}
})();
//
// Tooltip
//
'use strict';
var Tooltip = (function() {
// Variables
var $tooltip = $('[data-toggle="tooltip"]');
// Methods
function init() {
$tooltip.tooltip();
}
// Events
if ($tooltip.length) {
init();
}
})();
//
// Charts
//
'use strict';
var Charts = (function() {
// Variable
var $toggle = $('[data-toggle="chart"]');
var mode = 'light';//(themeMode) ? themeMode : 'light';
var fonts = {
base: 'Open Sans'
}
// Colors
var colors = {
gray: {
100: '#f6f9fc',
200: '#e9ecef',
300: '#dee2e6',
400: '#ced4da',
500: '#adb5bd',
600: '#8898aa',
700: '#525f7f',
800: '#32325d',
900: '#212529'
},
theme: {
'default': '#172b4d',
'primary': '#5e72e4',
'secondary': '#f4f5f7',
'info': '#11cdef',
'success': '#2dce89',
'danger': '#f5365c',
'warning': '#fb6340'
},
black: '#12263F',
white: '#FFFFFF',
transparent: 'transparent',
};
// Methods
// Chart.js global options
function chartOptions() {
// Options
var options = {
defaults: {
global: {
responsive: true,
maintainAspectRatio: false,
defaultColor: (mode == 'dark') ? colors.gray[700] : colors.gray[600],
defaultFontColor: (mode == 'dark') ? colors.gray[700] : colors.gray[600],
defaultFontFamily: fonts.base,
defaultFontSize: 13,
layout: {
padding: 0
},
legend: {
display: false,
position: 'bottom',
labels: {
usePointStyle: true,
padding: 16
}
},
elements: {
point: {
radius: 0,
backgroundColor: colors.theme['primary']
},
line: {
tension: .4,
borderWidth: 4,
borderColor: colors.theme['primary'],
backgroundColor: colors.transparent,
borderCapStyle: 'rounded'
},
rectangle: {
backgroundColor: colors.theme['warning']
},
arc: {
backgroundColor: colors.theme['primary'],
borderColor: (mode == 'dark') ? colors.gray[800] : colors.white,
borderWidth: 4
}
},
tooltips: {
enabled: false,
mode: 'index',
intersect: false,
custom: function(model) {
// Get tooltip
var $tooltip = $('#chart-tooltip');
// Create tooltip on first render
if (!$tooltip.length) {
$tooltip = $('<div id="chart-tooltip" class="popover bs-popover-top" role="tooltip"></div>');
// Append to body
$('body').append($tooltip);
}
// Hide if no tooltip
if (model.opacity === 0) {
$tooltip.css('display', 'none');
return;
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Fill with content
if (model.body) {
var titleLines = model.title || [];
var bodyLines = model.body.map(getBody);
var html = '';
// Add arrow
html += '<div class="arrow"></div>';
// Add header
titleLines.forEach(function(title) {
html += '<h3 class="popover-header text-center">' + title + '</h3>';
});
// Add body
bodyLines.forEach(function(body, i) {
var colors = model.labelColors[i];
var styles = 'background-color: ' + colors.backgroundColor;
var indicator = '<span class="badge badge-dot"><i class="bg-primary"></i></span>';
var align = (bodyLines.length > 1) ? 'justify-content-left' : 'justify-content-center';
html += '<div class="popover-body d-flex align-items-center ' + align + '">' + indicator + body + '</div>';
});
$tooltip.html(html);
}
// Get tooltip position
var $canvas = $(this._chart.canvas);
var canvasWidth = $canvas.outerWidth();
var canvasHeight = $canvas.outerHeight();
var canvasTop = $canvas.offset().top;
var canvasLeft = $canvas.offset().left;
var tooltipWidth = $tooltip.outerWidth();
var tooltipHeight = $tooltip.outerHeight();
var top = canvasTop + model.caretY - tooltipHeight - 16;
var left = canvasLeft + model.caretX - tooltipWidth / 2;
// Display tooltip
$tooltip.css({
'top': top + 'px',
'left': left + 'px',
'display': 'block',
'z-index': '100'
});
},
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="badge badge-primary mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + yLabel + '</span>' ;
return content;
}
}
}
},
doughnut: {
cutoutPercentage: 83,
tooltips: {
callbacks: {
title: function(item, data) {
var title = data.labels[item[0].index];
return title;
},
label: function(item, data) {
var value = data.datasets[0].data[item.index];
var content = '';
content += '<span class="popover-body-value">' + value + '</span>';
return content;
}
}
},
legendCallback: function(chart) {
var data = chart.data;
var content = '';
data.labels.forEach(function(label, index) {
var bgColor = data.datasets[0].backgroundColor[index];
content += '<span class="chart-legend-item">';
content += '<i class="chart-legend-indicator" style="background-color: ' + bgColor + '"></i>';
content += label;
content += '</span>';
});
return content;
}
}
}
}
// yAxes
Chart.scaleService.updateScaleDefaults('linear', {
gridLines: {
borderDash: [2],
borderDashOffset: [2],
color: (mode == 'dark') ? colors.gray[900] : colors.gray[300],
drawBorder: false, | drawTicks: false,
lineWidth: 0,
zeroLineWidth: 0,
zeroLineColor: (mode == 'dark') ? colors.gray[900] : colors.gray[300],
zeroLineBorderDash: [2],
zeroLineBorderDashOffset: [2]
},
ticks: {
beginAtZero: true,
padding: 10,
callback: function(value) {
if (!(value % 10)) {
return value
}
}
}
});
// xAxes
Chart.scaleService.updateScaleDefaults('category', {
gridLines: {
drawBorder: false,
drawOnChartArea: false,
drawTicks: false
},
ticks: {
padding: 20
},
maxBarThickness: 10
});
return options;
}
// Parse global options
function parseOptions(parent, options) {
for (var item in options) {
if (typeof options[item] !== 'object') {
parent[item] = options[item];
} else {
parseOptions(parent[item], options[item]);
}
}
}
// Push options
function pushOptions(parent, options) {
for (var item in options) {
if (Array.isArray(options[item])) {
options[item].forEach(function(data) {
parent[item].push(data);
});
} else {
pushOptions(parent[item], options[item]);
}
}
}
// Pop options
function popOptions(parent, options) {
for (var item in options) {
if (Array.isArray(options[item])) {
options[item].forEach(function(data) {
parent[item].pop();
});
} else {
popOptions(parent[item], options[item]);
}
}
}
// Toggle options
function toggleOptions(elem) {
var options = elem.data('add');
var $target = $(elem.data('target'));
var $chart = $target.data('chart');
if (elem.is(':checked')) {
// Add options
pushOptions($chart, options);
// Update chart
$chart.update();
} else {
// Remove options
popOptions($chart, options);
// Update chart
$chart.update();
}
}
// Update options
function updateOptions(elem) {
var options = elem.data('update');
var $target = $(elem.data('target'));
var $chart = $target.data('chart');
// Parse options
parseOptions($chart, options);
// Toggle ticks
toggleTicks(elem, $chart);
// Update chart
$chart.update();
}
// Toggle ticks
function toggleTicks(elem, $chart) {
if (elem.data('prefix') !== undefined || elem.data('prefix') !== undefined) {
var prefix = elem.data('prefix') ? elem.data('prefix') : '';
var suffix = elem.data('suffix') ? elem.data('suffix') : '';
// Update ticks
$chart.options.scales.yAxes[0].ticks.callback = function(value) {
if (!(value % 10)) {
return prefix + value + suffix;
}
}
// Update tooltips
$chart.options.tooltips.callbacks.label = function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + prefix + yLabel + suffix + '</span>';
return content;
}
}
}
// Events
// Parse global options
if (window.Chart) {
parseOptions(Chart, chartOptions());
}
// Toggle options
$toggle.on({
'change': function() {
var $this = $(this);
if ($this.is('[data-add]')) {
toggleOptions($this);
}
},
'click': function() {
var $this = $(this);
if ($this.is('[data-update]')) {
updateOptions($this);
}
}
});
// Return
return {
colors: colors,
fonts: fonts,
mode: mode
};
})();
//
// Orders chart
//
var OrdersChart = (function() {
//
// Variables
//
var $chart = $('#chart-orders');
var $ordersSelect = $('[name="ordersSelect"]');
//
// Methods
//
// Init chart
function initChart($chart) {
// Create chart
var ordersChart = new Chart($chart, {
type: 'bar',
options: {
scales: {
yAxes: [{
ticks: {
callback: function(value) {
if (!(value % 10)) {
//return '$' + value + 'k'
return value
}
}
}
}]
},
tooltips: {
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + yLabel + '</span>';
return content;
}
}
}
},
data: {
labels: ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Sales',
data: [25, 20, 30, 22, 17, 29]
}]
}
});
// Save to jQuery object
$chart.data('chart', ordersChart);
}
// Init chart
if ($chart.length) {
initChart($chart);
}
})();
//
// Charts
//
'use strict';
//
// Sales chart
//
var SalesChart = (function() {
// Variables
var $chart = $('#chart-sales');
// Methods
function init($chart) {
var salesChart = new Chart($chart, {
type: 'line',
options: {
scales: {
yAxes: [{
gridLines: {
color: Charts.colors.gray[900],
zeroLineColor: Charts.colors.gray[900]
},
ticks: {
callback: function(value) {
if (!(value % 10)) {
return '$' + value + 'k';
}
}
}
}]
},
tooltips: {
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">$' + yLabel + 'k</span>';
return content;
}
}
}
},
data: {
labels: ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Performance',
data: [0, 20, 10, 30, 15, 40, 20, 60, 60]
}]
}
});
// Save to jQuery object
$chart.data('chart', salesChart);
}
// Events
if ($chart.length) {
init($chart);
}
})(); | |
orbit-common-local-storage.min.js | define("orbit-common/local-storage-source",["orbit/lib/assert","./memory-source","exports"],function(a,b,c){"use strict";var d=a.assert,e=b["default"],f=function(){try{return"localStorage"in window&&null!==window.localStorage}catch(a){return!1}},g=e.extend({init:function(a,b){d("Your browser does not support local storage!",f()),this._super.apply(this,arguments),b=b||{},this.namespace=b.namespace||"orbit",this._autosave=void 0!==b.autosave?b.autosave:!0;var c=void 0!==b.autoload?b.autoload:!0;this._isDirty=!1,this.on("didTransform",function(){this._saveData()},this),c&&this.load()},load:function(){var a=window.localStorage.getItem(this.namespace);a&&this.reset(JSON.parse(a))},enableAutosave:function(){this._autosave||(this._autosave=!0,this._isDirty&&this._saveData())},disableAutosave:function(){this._autosave&&(this._autosave=!1)},_saveData:function(a){return this._autosave||a?(window.localStorage.setItem(this.namespace,JSON.stringify(this.retrieve())),void(this._isDirty=!1)):void(this._isDirty=!0)}});c["default"]=g}),define("orbit-common/local-storage-source",["orbit/lib/assert","./memory-source","exports"],function(a,b,c){"use strict";var d=a.assert,e=b["default"],f=function(){try{return"localStorage"in window&&null!==window.localStorage}catch(a){return!1}},g=e.extend({init:function(a,b){d("Your browser does not support local storage!",f()),this._super.apply(this,arguments),b=b||{},this.namespace=b.namespace||"orbit",this._autosave=void 0!==b.autosave?b.autosave:!0;var c=void 0!==b.autoload?b.autoload:!0;this._isDirty=!1,this.on("didTransform",function(){this._saveData()},this),c&&this.load()},load:function(){var a=window.localStorage.getItem(this.namespace);a&&this.reset(JSON.parse(a))},enableAutosave:function(){this._autosave||(this._autosave=!0,this._isDirty&&this._saveData())},disableAutosave:function(){this._autosave&&(this._autosave=!1)},_saveData:function(a){return this._autosave||a?(window.localStorage.setItem(this.namespace,JSON.stringify(this.retrieve())),void(this._isDirty=!1)):void(this._isDirty=!0)}});c["default"]=g}),function(a){var b=a.Orbit.__defineModule__,c=a.Orbit.__requireModule__;b("orbit-common/local-storage-source",["orbit/lib/assert","./memory-source","exports"],function(a,b,c){"use strict";var d=a.assert,e=b["default"],f=function(){try{return"localStorage"in window&&null!==window.localStorage}catch(a){return!1}},g=e.extend({init:function(a,b){d("Your browser does not support local storage!",f()),this._super.apply(this,arguments),b=b||{},this.namespace=b.namespace||"orbit",this._autosave=void 0!==b.autosave?b.autosave:!0;var c=void 0!==b.autoload?b.autoload:!0;this._isDirty=!1,this.on("didTransform",function(){this._saveData()},this),c&&this.load()},load:function(){var a=window.localStorage.getItem(this.namespace);a&&this.reset(JSON.parse(a))},enableAutosave:function(){this._autosave||(this._autosave=!0,this._isDirty&&this._saveData())},disableAutosave:function(){this._autosave&&(this._autosave=!1)},_saveData:function(a){return this._autosave||a?(window.localStorage.setItem(this.namespace,JSON.stringify(this.retrieve())),void(this._isDirty=!1)):void(this._isDirty=!0)}});c["default"]=g}),a.OC.LocalStorageSource=c("orbit-common/local-storage-source")["default"]}(window); |
||
list.component.ts | import { Component, OnInit, DoCheck } from '@angular/core';
import { LocalDataSource } from 'ng2-smart-table';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { CustomerService } from '../../../services/customer.service';
import { AuthenticationService } from '../../../services/authentication.service';
import { CommonFunction } from '../../../common/common-functions';
import { UserLog } from '../../../models/common-model';
import { CommonService } from '../../../services/common.service';
import { AccountsService } from '../../../services/accounts.service';
@Component({
selector: 'ngx-list-state-customer',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss'],
})
export class CStateListComponent implements OnInit, DoCheck {
defaultRowPerPage = 10;
SerachValue = '';
totalRows = 0;
Swal = require('sweetalert2');
customerStateArr: Array<any> = []; // List of customer States
custid = 0;
source: LocalDataSource = new LocalDataSource();
accessArr: Array<any> = []; // List of menuaccess
settings = {
attr: {
class: 'table',
},
hideSubHeader: true,
mode: 'external',
actions: {
add: false,
edit: false,
delete: false,
custom: [
{ name: 'edit', title: '<i class="nb-edit" title="Edit"></i>' },
{ name: 'delete', title: '<i class="nb-trash" title="Delete"></i>' },
],
position: 'right',
},
pager: {
display: true,
perPage: this.defaultRowPerPage,
},
columns: {
srno: {
title: 'Sr No.',
type: 'number',
valuePrepareFunction: (value, row, cell) => {
return (cell.row.index + 1); // Increment rows
},
},
customerName: {
title: 'Customer',
type: 'string',
filter: false,
},
stateCode: {
title: 'State Code',
type: 'string',
filter: false,
},
gstNo: {
title: 'GST No',
type: 'string',
filter: false,
},
address: {
title: 'Address',
type: 'string',
filter: false,
},
},
};
constructor(private custservice: CustomerService,
private _router: Router,
private _auth: AuthenticationService,
private commonfunction: CommonFunction,
private commservice: CommonService,
private accservice: AccountsService,
) {
}
ngOnInit(): void {
this.custid = this._auth.getCustId();
this.accservice.getGetUserActions(this._auth.getUserId()).subscribe(
(data) => {
if (data['message'] === 'Success') {
this.accessArr = data['payload'];
if (this.accessArr.filter(t => t.actionName === 'List' && t.module === 'Customer State').length > 0) {
this.getCustomerStateData(this.custid);
} else {
const message = '401 Unauthorized page: Customer State List';
this.commonfunction.ErrorLogHdlFunc(message, this._auth.getUserId());
this._router.navigate(['unauthorized']);
}
if (this.accessArr.filter(t => t.actionName === 'Update' && t.module === 'Customer State').length === 0) {
const item = this.settings.actions.custom.findIndex((t => t.name === 'edit'));
this.settings.actions.custom.splice(item, 1);
}
if (this.accessArr.filter(t => t.actionName === 'Delete' && t.module === 'Customer State').length === 0) {
const item2 = this.settings.actions.custom.findIndex((t => t.name === 'delete'));
this.settings.actions.custom.splice(item2, 1);
}
this.settings = Object.assign({}, this.settings);
}
});
}
ngDoCheck() {
this.totalRows = this.source != null ? this.source.count() : null;
}
// Filter Search datatable
onSearch(query: string = '') {
if (query === '') {
this.source.reset();
} else {
this.source.setFilter([
// fields we want to include in the search
{
field: 'customerName',
search: query,
},
{
field: 'stateCode',
search: query,
},
{
field: 'gstNo',
search: query,
},
{
field: 'address',
search: query,
},
], false);
}
}
// Set Datatable pager
setPager() {
this.source.setPaging(1, this.defaultRowPerPage, true);
this.settings = Object.assign({}, this.settings);
}
// Datatable Custom action click
onCustomAction(event) {
switch (event.action) {
case 'edit':
this.onEdit(event.data);
break;
case 'delete':
this.onDelete(event.data);
}
}
public onEdit(formData: any) {
if (this.accessArr.filter(t => t.actionName === 'Update' && t.module === 'Customer State').length === 0) {
this.commonfunction.showToast('danger', 'Failed', 'Access Denied');
} else {
let id: number = 0;
let idstr: string = '';
id = formData['custStId'];
const obj = {
custStId: id,
};
idstr = this._auth.encryptData(obj);
this._router.navigate(['customerStateEdit/' + idstr]);
}
}
public onDelete(formData: any) {
if (this.accessArr.filter(t => t.actionName === 'Delete' && t.module === 'Customer State').length === 0) {
this.commonfunction.showToast('danger', 'Failed', 'Access Denied');
} else {
Swal.fire({
title: 'Are you sure?',
text: 'Once deleted, you will not be able to recover this!',
icon: 'warning',
showCancelButton: true,
}).then((result) => {
if (result.value) {
let id: number = 0;
id = formData['custStId'];
this.custservice.customerStateMasterDel(id).subscribe(
(data) => {
if (data['isError'] === false && data['code'] === 200) {
if (data['message'] === 'Success') {
const objULog: UserLog = new UserLog();
objULog.Action = 'Customer State Delete';
objULog.UserId = this._auth.getUserId();
objULog.PageName = 'customerStateList';
objULog.Notes = 'custStId=' + id;
this.commservice.insertUserLog(objULog).subscribe(data3 => {
// do something, success
}, error => { alert(error); });
this.source.remove(formData);
this.commonfunction.showToast('success', 'Success', 'Record successfully deleted');
} else {
this.commonfunction.showToast('danger', 'Failed', 'Record not deleted');
}
}
},
);
}
});
}
}
onAdd(): void {
if (this.accessArr.filter(t => t.actionName === 'Create' && t.module === 'Customer State').length === 0) {
this.commonfunction.showToast('danger', 'Failed', 'Access Denied');
} else {
this._router.navigate(['customerStateCreate']);
}
}
// Get Customer state Master Data
getCustomerStateData(custid: number) {
this.custservice.getCustomerStateMasterList(0, custid).subscribe(
(data) => {
if (data['isError'] === false && data['code'] === 200) {
this.customerStateArr = data['payload'];
const objULog: UserLog = new UserLog();
objULog.Action = 'Customer State List';
objULog.UserId = this._auth.getUserId();
objULog.PageName = 'customerStateList';
objULog.Notes = 'Customer State List';
this.commservice.insertUserLog(objULog).subscribe(data3 => {
// do something, success
}, error => { alert(error); });
} else {
this.customerStateArr = [];
} | this.source.count();
},
);
}
} | // Bind data to Datatable
this.source.load(this.customerStateArr); |
lib.rs | /// This is just here to make tests the lib is not meant to funciton stand alone
pub mod cli;
pub mod data;
pub mod datawrapper;
pub mod ibm;
pub mod ubidots; | pub mod utils;
pub mod waternsw; | |
get_stats.py | import json
from copy import copy
from stat_utils import *
with open('time_trimmed.json', 'r') as infile:
data = json.loads(infile.read())
subject_stats = {}
inr_fields = [
'inr_im_lborres',
]
chem_fields = [
'alt_im_lborres',
'ast_im_lborres',
'dbil_im_lborres',
'tbil_im_lborres',
]
inr_date = 'inr_im_lbdtc'
chem_date = 'chem_im_lbdtc'
import pdb
for subid, subj in data.items():
forms = ['chem', 'inr']
for form in forms:
fields = chem_fields if form == 'chem' else inr_fields
date_field = chem_date if form == 'chem' else inr_date
recs = copy(subj.get(form)) or []
base = copy(subj.get('baseline_{}'.format(form))) or {}
recs.insert(0, base)
if not subject_stats.get(subid):
subject_stats[subid] = {}
follow_ups = get_follow_up_stats(recs, form)
for key, val in follow_ups.items():
subject_stats[subid][key] = val | field_recs = copy([rec for rec in recs if rec.get(field)])
delta, deltas = get_delta(field_recs, field, date_field)
subject_stats[subid]['{}_{}_baseline'.format(form, field)] = base.get(field)
subject_stats[subid]['{}_{}_mean'.format(form, field)] = get_mean(field_recs, field)
subject_stats[subid]['{}_{}_max'.format(form, field)] = get_max(field_recs, field)
subject_stats[subid]['{}_{}_min'.format(form, field)] = get_min(field_recs, field)
subject_stats[subid]['{}_{}_sigma'.format(form, field)] = get_std_dev(field_recs, field)
subject_stats[subid]['{}_{}_delta'.format(form, field)] = delta
subject_stats[subid]['{}_{}_deltas'.format(form, field)] = deltas
subject_stats[subid]['total_{}_records'.format(form)] = len(recs)
subject_stats[subid]['research_id'] = subj['research_id']
subject_stats[subid]['regimen'] = subj['regimen']
subject_stats[subid]['duration'] = subj['duration']
with open('sub_stats.json', 'w') as outfile:
outfile.write(json.dumps(subject_stats, indent=4, sort_keys=True)) |
for field in fields: |
method-on-generic-struct.rs | // Copyright 2013-2014 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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// STACK BY REF
// gdb-command:print *self
// gdb-check:$1 = {x = {__0 = 8888, __1 = -8888}}
// gdb-command:print arg1
// gdb-check:$2 = -1
// gdb-command:print arg2
// gdb-check:$3 = -2
// gdb-command:continue
// STACK BY VAL
// gdb-command:print self
// gdb-check:$4 = {x = {__0 = 8888, __1 = -8888}}
// gdb-command:print arg1
// gdb-check:$5 = -3
// gdb-command:print arg2
// gdb-check:$6 = -4
// gdb-command:continue
// OWNED BY REF
// gdb-command:print *self
// gdb-check:$7 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$8 = -5
// gdb-command:print arg2
// gdb-check:$9 = -6
// gdb-command:continue
// OWNED BY VAL
// gdb-command:print self
// gdb-check:$10 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$11 = -7
// gdb-command:print arg2
// gdb-check:$12 = -8
// gdb-command:continue
// OWNED MOVED
// gdb-command:print *self
// gdb-check:$13 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$14 = -9
// gdb-command:print arg2
// gdb-check:$15 = -10
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// STACK BY REF
// lldb-command:print *self
// lldb-check:[...]$0 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$1 = -1
// lldb-command:print arg2
// lldb-check:[...]$2 = -2
// lldb-command:continue
// STACK BY VAL
// lldb-command:print self
// lldb-check:[...]$3 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$4 = -3
// lldb-command:print arg2
// lldb-check:[...]$5 = -4
// lldb-command:continue
// OWNED BY REF
// lldb-command:print *self
// lldb-check:[...]$6 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$7 = -5
// lldb-command:print arg2
// lldb-check:[...]$8 = -6
// lldb-command:continue
// OWNED BY VAL
// lldb-command:print self | // lldb-command:print arg2
// lldb-check:[...]$11 = -8
// lldb-command:continue
// OWNED MOVED
// lldb-command:print *self
// lldb-check:[...]$12 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$13 = -9
// lldb-command:print arg2
// lldb-check:[...]$14 = -10
// lldb-command:continue
#![feature(box_syntax)]
#![omit_gdb_pretty_printer_section]
#[derive(Copy, Clone)]
struct Struct<T> {
x: T
}
impl<T> Struct<T> {
fn self_by_ref(&self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_owned(self: Box<Struct<T>>, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned: Box<_> = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() {()} | // lldb-check:[...]$9 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$10 = -7 |
traced.ts | import trace from './trace';
const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const FN_NAME = /^\s*function\s*([^\s\(]*)/m;
const FN_ARGS = /\(([^\)]*)\)/m;
function | (fn: Function) {
return fn.toString().replace(COMMENTS, '');
}
function getFunctionName(fn: Function) {
return getFunctionText(fn).match(FN_NAME)[1];
}
function getFunctionArgNames(fn: Function) {
const args = getFunctionText(fn).match(FN_ARGS)[1].trim();
return args ? args.split(',').map(arg => arg.trim()) : [];
}
function stringify(value: any) {
return JSON.stringify(value, null, '\t');
}
interface ITracedMethodOptions {
return: boolean;
}
const tracedMethod = trace.enabled ? (options?: ITracedMethodOptions): MethodDecorator => {
const skipReturn = options && options.return === false;
return (
target: Object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<Function>
) => {
const methodName = getFunctionName(target.constructor) + '#' + propertyKey.toString();
const method = descriptor.value;
if (typeof method !== 'function') {
throw new TypeError(`@traceMethod: ${methodName} is not a method`);
}
const argNames = getFunctionArgNames(method);
descriptor.value = function (...args: any[]) {
trace('CALL: ' + methodName);
trace.increaseIndent();
for (let i = 0; i < Math.max(argNames.length, args.length); i++) {
trace('ARG ' + argNames[i] + ': ' + stringify(args[i]));
}
try {
const result = method.apply(this, args);
if (!skipReturn) {
trace('RETURN: ' + stringify(result));
}
return result;
} catch (err) {
trace('THROW: ' + stringify(err));
throw err;
} finally {
trace.decreaseIndent();
trace('EXIT: ' + methodName);
}
};
}
} : (): MethodDecorator => () => {};
export {tracedMethod};
| getFunctionText |
exception.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Cinder base exception handling.
Includes decorator for re-raising Cinder-type exceptions.
SHOULD include dedicated exception logging.
"""
from oslo_log import log as logging
from oslo_versionedobjects import exception as obj_exc
import six
import webob.exc
from webob.util import status_generic_reasons
from webob.util import status_reasons
from cinder.i18n import _
LOG = logging.getLogger(__name__)
class ConvertedException(webob.exc.WSGIHTTPException):
def __init__(self, code=500, title="", explanation=""):
self.code = code
# There is a strict rule about constructing status line for HTTP:
# '...Status-Line, consisting of the protocol version followed by a
# numeric status code and its associated textual phrase, with each
# element separated by SP characters'
# (http://www.faqs.org/rfcs/rfc2616.html)
# 'code' and 'title' can not be empty because they correspond
# to numeric status code and its associated text
if title:
self.title = title
else:
try:
self.title = status_reasons[self.code]
except KeyError:
generic_code = self.code // 100
self.title = status_generic_reasons[generic_code]
self.explanation = explanation
super(ConvertedException, self).__init__()
class Error(Exception):
pass
class CinderException(Exception):
"""Base Cinder Exception
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the constructor.
"""
message = _("An unknown exception occurred.")
code = 500
headers = {}
safe = False
def __init__(self, message=None, **kwargs):
self.kwargs = kwargs
self.kwargs['message'] = message
if 'code' not in self.kwargs:
try:
self.kwargs['code'] = self.code
except AttributeError:
pass
for k, v in self.kwargs.items():
if isinstance(v, Exception):
# NOTE(tommylikehu): If this is a cinder exception it will
# return the msg object, so we won't be preventing
# translations.
self.kwargs[k] = six.text_type(v)
if self._should_format():
try:
message = self.message % kwargs
except Exception:
# NOTE(melwitt): This is done in a separate method so it can be
# monkey-patched during testing to make it a hard failure.
self._log_exception()
message = self.message
elif isinstance(message, Exception):
# NOTE(tommylikehu): If this is a cinder exception it will
# return the msg object, so we won't be preventing
# translations.
message = six.text_type(message)
# NOTE(luisg): We put the actual message in 'msg' so that we can access
# it, because if we try to access the message via 'message' it will be
# overshadowed by the class' message attribute
self.msg = message
super(CinderException, self).__init__(message)
# Oslo.messaging use the argument 'message' to rebuild exception
# directly at the rpc client side, therefore we should not use it
# in our keyword arguments, otherwise, the rebuild process will fail
# with duplicate keyword exception.
self.kwargs.pop('message', None)
def _log_exception(self):
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception('Exception in string format operation:')
for name, value in self.kwargs.items():
LOG.error("%(name)s: %(value)s",
{'name': name, 'value': value})
def _should_format(self):
return self.kwargs['message'] is None or '%(message)' in self.message
# NOTE(tommylikehu): self.msg is already an unicode compatible object
# as the __init__ method ensures of it, and we should not be modifying
# it in any way with str(), unicode(), or six.text_type() as we would
# be preventing translations from happening.
def __unicode__(self):
return self.msg
class VolumeBackendAPIException(CinderException):
message = _("Bad or unexpected response from the storage volume "
"backend API: %(data)s")
class VolumeDriverException(CinderException):
message = _("Volume driver reported an error: %(message)s")
class BackupDriverException(CinderException):
message = _("Backup driver reported an error: %(reason)s")
class BackupRestoreCancel(CinderException):
message = _("Canceled backup %(back_id)s restore on volume %(vol_id)s")
class GlanceConnectionFailed(CinderException):
message = _("Connection to glance failed: %(reason)s")
class ProgrammingError(CinderException):
message = _('Programming error in Cinder: %(reason)s')
class NotAuthorized(CinderException):
message = _("Not authorized.")
code = 403
class AdminRequired(NotAuthorized):
message = _("User does not have admin privileges")
class PolicyNotAuthorized(NotAuthorized):
message = _("Policy doesn't allow %(action)s to be performed.")
class ImageNotAuthorized(CinderException):
message = _("Not authorized for image %(image_id)s.")
class DriverNotInitialized(CinderException):
message = _("Volume driver not ready.")
class Invalid(CinderException):
message = _("Unacceptable parameters.")
code = 400
class InvalidSnapshot(Invalid):
message = _("Invalid snapshot: %(reason)s")
class InvalidVolumeAttachMode(Invalid):
message = _("Invalid attaching mode '%(mode)s' for "
"volume %(volume_id)s.")
class VolumeAttached(Invalid):
message = _("Volume %(volume_id)s is still attached, detach volume first.")
class InvalidResults(Invalid):
message = _("The results are invalid.")
class InvalidInput(Invalid):
message = _("Invalid input received: %(reason)s")
class InvalidAvailabilityZone(Invalid):
message = _("Availability zone '%(az)s' is invalid.")
class InvalidTypeAvailabilityZones(Invalid):
message = _("Volume type's availability zones are invalid %(az)s.")
class InvalidVolumeType(Invalid):
message = _("Invalid volume type: %(reason)s")
class InvalidGroupType(Invalid):
message = _("Invalid group type: %(reason)s")
class InvalidVolume(Invalid):
message = _("Invalid volume: %(reason)s")
class InvalidContentType(Invalid):
message = _("Invalid content type %(content_type)s.")
class InvalidHost(Invalid):
message = _("Invalid host: %(reason)s")
# Cannot be templated as the error syntax varies.
# msg needs to be constructed when raised.
class InvalidParameterValue(Invalid):
message = "%(err)s"
class InvalidAuthKey(Invalid):
message = _("Invalid auth key: %(reason)s")
class InvalidConfigurationValue(Invalid):
message = _('Value "%(value)s" is not valid for '
'configuration option "%(option)s"')
class ServiceUnavailable(Invalid):
message = _("Service is unavailable at this time.")
class UnavailableDuringUpgrade(Invalid):
message = _('Cannot perform %(action)s during system upgrade.')
class ImageUnacceptable(Invalid):
message = _("Image %(image_id)s is unacceptable: %(reason)s")
class ImageTooBig(Invalid):
message = _("Image %(image_id)s size exceeded available "
"disk space: %(reason)s")
class DeviceUnavailable(Invalid):
message = _("The device in the path %(path)s is unavailable: %(reason)s")
class SnapshotUnavailable(VolumeBackendAPIException):
message = _("The snapshot is unavailable: %(data)s")
class InvalidUUID(Invalid):
message = _("Expected a UUID but received %(uuid)s.")
class InvalidAPIVersionString(Invalid):
message = _("API Version String %(version)s is of invalid format. Must "
"be of format MajorNum.MinorNum.")
class VersionNotFoundForAPIMethod(Invalid):
message = _("API version %(version)s is not supported on this method.")
class InvalidGlobalAPIVersion(Invalid):
message = _("Version %(req_ver)s is not supported by the API. Minimum "
"is %(min_ver)s and maximum is %(max_ver)s.")
class MissingRequired(Invalid):
message = _("Missing required element '%(element)s' in request body.")
class ValidationError(Invalid):
message = "%(detail)s"
class APIException(CinderException):
message = _("Error while requesting %(service)s API.")
def __init__(self, message=None, **kwargs):
if 'service' not in kwargs:
kwargs['service'] = 'unknown'
super(APIException, self).__init__(message, **kwargs)
class APITimeout(APIException):
message = _("Timeout while requesting %(service)s API.")
class RPCTimeout(CinderException):
message = _("Timeout while requesting capabilities from backend "
"%(service)s.")
code = 502
class Duplicate(CinderException):
pass
class NotFound(CinderException):
message = _("Resource could not be found.")
code = 404
safe = True
class VolumeNotFound(NotFound):
message = _("Volume %(volume_id)s could not be found.")
class MessageNotFound(NotFound):
message = _("Message %(message_id)s could not be found.")
class VolumeAttachmentNotFound(NotFound):
message = _("Volume attachment could not be found with "
"filter: %(filter)s.")
class VolumeMetadataNotFound(NotFound):
message = _("Volume %(volume_id)s has no metadata with "
"key %(metadata_key)s.")
class VolumeAdminMetadataNotFound(NotFound):
message = _("Volume %(volume_id)s has no administration metadata with "
"key %(metadata_key)s.")
class InvalidVolumeMetadata(Invalid):
message = _("Invalid metadata: %(reason)s")
class InvalidVolumeMetadataSize(Invalid):
message = _("Invalid metadata size: %(reason)s")
class SnapshotMetadataNotFound(NotFound):
|
class VolumeTypeNotFound(NotFound):
message = _("Volume type %(volume_type_id)s could not be found.")
class VolumeTypeNotFoundByName(VolumeTypeNotFound):
message = _("Volume type with name %(volume_type_name)s "
"could not be found.")
class VolumeTypeAccessNotFound(NotFound):
message = _("Volume type access not found for %(volume_type_id)s / "
"%(project_id)s combination.")
class VolumeTypeExtraSpecsNotFound(NotFound):
message = _("Volume Type %(volume_type_id)s has no extra specs with "
"key %(extra_specs_key)s.")
class VolumeTypeInUse(CinderException):
message = _("Volume Type %(volume_type_id)s deletion is not allowed with "
"volumes present with the type.")
class GroupTypeNotFound(NotFound):
message = _("Group type %(group_type_id)s could not be found.")
class GroupTypeNotFoundByName(GroupTypeNotFound):
message = _("Group type with name %(group_type_name)s "
"could not be found.")
class GroupTypeAccessNotFound(NotFound):
message = _("Group type access not found for %(group_type_id)s / "
"%(project_id)s combination.")
class GroupTypeSpecsNotFound(NotFound):
message = _("Group Type %(group_type_id)s has no specs with "
"key %(group_specs_key)s.")
class GroupTypeInUse(CinderException):
message = _("Group Type %(group_type_id)s deletion is not allowed with "
"groups present with the type.")
class SnapshotNotFound(NotFound):
message = _("Snapshot %(snapshot_id)s could not be found.")
class ServerNotFound(NotFound):
message = _("Instance %(uuid)s could not be found.")
class VolumeSnapshotNotFound(NotFound):
message = _("No snapshots found for volume %(volume_id)s.")
class VolumeIsBusy(CinderException):
message = _("deleting volume %(volume_name)s that has snapshot")
class SnapshotIsBusy(CinderException):
message = _("deleting snapshot %(snapshot_name)s that has "
"dependent volumes")
class ISCSITargetNotFoundForVolume(NotFound):
message = _("No target id found for volume %(volume_id)s.")
class InvalidImageRef(Invalid):
message = _("Invalid image href %(image_href)s.")
class InvalidSignatureImage(Invalid):
message = _("Signature metadata is incomplete for image: "
"%(image_id)s.")
class ImageSignatureVerificationException(CinderException):
message = _("Failed to verify image signature, reason: %(reason)s.")
class ImageNotFound(NotFound):
message = _("Image %(image_id)s could not be found.")
class ServiceNotFound(NotFound):
def __init__(self, message=None, **kwargs):
if not message:
if kwargs.get('host', None):
self.message = _("Service %(service_id)s could not be "
"found on host %(host)s.")
else:
self.message = _("Service %(service_id)s could not be found.")
super(ServiceNotFound, self).__init__(message, **kwargs)
class ServiceTooOld(Invalid):
message = _("Service is too old to fulfil this request.")
class WorkerNotFound(NotFound):
message = _("Worker with %s could not be found.")
def __init__(self, message=None, **kwargs):
keys_list = ('{0}=%({0})s'.format(key) for key in kwargs)
placeholder = ', '.join(keys_list)
self.message = self.message % placeholder
super(WorkerNotFound, self).__init__(message, **kwargs)
class WorkerExists(Duplicate):
message = _("Worker for %(type)s %(id)s already exists.")
class CleanableInUse(Invalid):
message = _('%(type)s with id %(id)s is already being cleaned up or '
'another host has taken over it.')
class ClusterNotFound(NotFound):
message = _('Cluster %(id)s could not be found.')
class ClusterHasHosts(Invalid):
message = _("Cluster %(id)s still has hosts.")
class ClusterExists(Duplicate):
message = _("Cluster %(name)s already exists.")
class HostNotFound(NotFound):
message = _("Host %(host)s could not be found.")
class SchedulerHostFilterNotFound(NotFound):
message = _("Scheduler Host Filter %(filter_name)s could not be found.")
class SchedulerHostWeigherNotFound(NotFound):
message = _("Scheduler Host Weigher %(weigher_name)s could not be found.")
class InvalidReservationExpiration(Invalid):
message = _("Invalid reservation expiration %(expire)s.")
class InvalidQuotaValue(Invalid):
message = _("Change would make usage less than 0 for the following "
"resources: %(unders)s")
class InvalidNestedQuotaSetup(CinderException):
message = _("Project quotas are not properly setup for nested quotas: "
"%(reason)s.")
class QuotaNotFound(NotFound):
message = _("Quota could not be found")
class QuotaResourceUnknown(QuotaNotFound):
message = _("Unknown quota resources %(unknown)s.")
class ProjectQuotaNotFound(QuotaNotFound):
message = _("Quota for project %(project_id)s could not be found.")
class QuotaClassNotFound(QuotaNotFound):
message = _("Quota class %(class_name)s could not be found.")
class QuotaUsageNotFound(QuotaNotFound):
message = _("Quota usage for project %(project_id)s could not be found.")
class ReservationNotFound(QuotaNotFound):
message = _("Quota reservation %(uuid)s could not be found.")
class OverQuota(CinderException):
message = _("Quota exceeded for resources: %(overs)s")
class FileNotFound(NotFound):
message = _("File %(file_path)s could not be found.")
class VolumeTypeExists(Duplicate):
message = _("Volume Type %(id)s already exists.")
class VolumeTypeAccessExists(Duplicate):
message = _("Volume type access for %(volume_type_id)s / "
"%(project_id)s combination already exists.")
class VolumeTypeEncryptionExists(Invalid):
message = _("Volume type encryption for type %(type_id)s already exists.")
class VolumeTypeEncryptionNotFound(NotFound):
message = _("Volume type encryption for type %(type_id)s does not exist.")
class GroupTypeExists(Duplicate):
message = _("Group Type %(id)s already exists.")
class GroupTypeAccessExists(Duplicate):
message = _("Group type access for %(group_type_id)s / "
"%(project_id)s combination already exists.")
class GroupVolumeTypeMappingExists(Duplicate):
message = _("Group volume type mapping for %(group_id)s / "
"%(volume_type_id)s combination already exists.")
class GroupTypeEncryptionExists(Invalid):
message = _("Group type encryption for type %(type_id)s already exists.")
class GroupTypeEncryptionNotFound(NotFound):
message = _("Group type encryption for type %(type_id)s does not exist.")
class MalformedRequestBody(CinderException):
message = _("Malformed message body: %(reason)s")
class ConfigNotFound(NotFound):
message = _("Could not find config at %(path)s")
class ParameterNotFound(NotFound):
message = _("Could not find parameter %(param)s")
class NoValidBackend(CinderException):
message = _("No valid backend was found. %(reason)s")
class NoMoreTargets(CinderException):
"""No more available targets."""
pass
class QuotaError(CinderException):
message = _("Quota exceeded: code=%(code)s")
code = 413
headers = {'Retry-After': '0'}
safe = True
class VolumeSizeExceedsAvailableQuota(QuotaError):
message = _("Requested volume or snapshot exceeds allowed %(name)s "
"quota. Requested %(requested)sG, quota is %(quota)sG and "
"%(consumed)sG has been consumed.")
def __init__(self, message=None, **kwargs):
kwargs.setdefault('name', 'gigabytes')
super(VolumeSizeExceedsAvailableQuota, self).__init__(
message, **kwargs)
class VolumeSizeExceedsLimit(QuotaError):
message = _("Requested volume size %(size)dG is larger than "
"maximum allowed limit %(limit)dG.")
class VolumeBackupSizeExceedsAvailableQuota(QuotaError):
message = _("Requested backup exceeds allowed Backup gigabytes "
"quota. Requested %(requested)sG, quota is %(quota)sG and "
"%(consumed)sG has been consumed.")
class VolumeLimitExceeded(QuotaError):
message = _("Maximum number of volumes allowed (%(allowed)d) exceeded for "
"quota '%(name)s'.")
def __init__(self, message=None, **kwargs):
kwargs.setdefault('name', 'volumes')
super(VolumeLimitExceeded, self).__init__(message, **kwargs)
class SnapshotLimitExceeded(QuotaError):
message = _("Maximum number of snapshots allowed (%(allowed)d) exceeded")
class UnexpectedOverQuota(QuotaError):
message = _("Unexpected over quota on %(name)s.")
class BackupLimitExceeded(QuotaError):
message = _("Maximum number of backups allowed (%(allowed)d) exceeded")
class ImageLimitExceeded(QuotaError):
message = _("Image quota exceeded")
class DuplicateSfVolumeNames(Duplicate):
message = _("Detected more than one volume with name %(vol_name)s")
class VolumeTypeCreateFailed(CinderException):
message = _("Cannot create volume_type with "
"name %(name)s and specs %(extra_specs)s")
class VolumeTypeUpdateFailed(CinderException):
message = _("Cannot update volume_type %(id)s")
class GroupTypeCreateFailed(CinderException):
message = _("Cannot create group_type with "
"name %(name)s and specs %(group_specs)s")
class GroupTypeUpdateFailed(CinderException):
message = _("Cannot update group_type %(id)s")
class GroupLimitExceeded(QuotaError):
message = _("Maximum number of groups allowed (%(allowed)d) exceeded")
class UnknownCmd(VolumeDriverException):
message = _("Unknown or unsupported command %(cmd)s")
class MalformedResponse(VolumeDriverException):
message = _("Malformed response to command %(cmd)s: %(reason)s")
class FailedCmdWithDump(VolumeDriverException):
message = _("Operation failed with status=%(status)s. Full dump: %(data)s")
class InvalidConnectorException(VolumeDriverException):
message = _("Connector doesn't have required information: %(missing)s")
class GlanceMetadataExists(Invalid):
message = _("Glance metadata cannot be updated, key %(key)s"
" exists for volume id %(volume_id)s")
class GlanceMetadataNotFound(NotFound):
message = _("Glance metadata for volume/snapshot %(id)s cannot be found.")
class ImageDownloadFailed(CinderException):
message = _("Failed to download image %(image_href)s, reason: %(reason)s")
class ExportFailure(Invalid):
message = _("Failed to export for volume: %(reason)s")
class RemoveExportException(VolumeDriverException):
message = _("Failed to remove export for volume %(volume)s: %(reason)s")
class MetadataCreateFailure(Invalid):
message = _("Failed to create metadata for volume: %(reason)s")
class MetadataUpdateFailure(Invalid):
message = _("Failed to update metadata for volume: %(reason)s")
class MetadataCopyFailure(Invalid):
message = _("Failed to copy metadata to volume: %(reason)s")
class InvalidMetadataType(Invalid):
message = _("The type of metadata: %(metadata_type)s for volume/snapshot "
"%(id)s is invalid.")
class ImageCopyFailure(Invalid):
message = _("Failed to copy image to volume: %(reason)s")
class BackupInvalidCephArgs(BackupDriverException):
message = _("Invalid Ceph args provided for backup rbd operation")
class BackupOperationError(Invalid):
message = _("An error has occurred during backup operation")
class BackupMetadataUnsupportedVersion(BackupDriverException):
message = _("Unsupported backup metadata version requested")
class BackupMetadataNotFound(NotFound):
message = _("Backup %(backup_id)s has no metadata with "
"key %(metadata_key)s.")
class BackupVerifyUnsupportedDriver(BackupDriverException):
message = _("Unsupported backup verify driver")
class VolumeMetadataBackupExists(BackupDriverException):
message = _("Metadata backup already exists for this volume")
class BackupRBDOperationFailed(BackupDriverException):
message = _("Backup RBD operation failed")
class EncryptedBackupOperationFailed(BackupDriverException):
message = _("Backup operation of an encrypted volume failed.")
class BackupNotFound(NotFound):
message = _("Backup %(backup_id)s could not be found.")
class BackupFailedToGetVolumeBackend(NotFound):
message = _("Failed to identify volume backend.")
class InvalidBackup(Invalid):
message = _("Invalid backup: %(reason)s")
class SwiftConnectionFailed(BackupDriverException):
message = _("Connection to swift failed: %(reason)s")
class TransferNotFound(NotFound):
message = _("Transfer %(transfer_id)s could not be found.")
class VolumeMigrationFailed(CinderException):
message = _("Volume migration failed: %(reason)s")
class SSHInjectionThreat(CinderException):
message = _("SSH command injection detected: %(command)s")
class QoSSpecsExists(Duplicate):
message = _("QoS Specs %(specs_id)s already exists.")
class QoSSpecsCreateFailed(CinderException):
message = _("Failed to create qos_specs: "
"%(name)s with specs %(qos_specs)s.")
class QoSSpecsUpdateFailed(CinderException):
message = _("Failed to update qos_specs: "
"%(specs_id)s with specs %(qos_specs)s.")
class QoSSpecsNotFound(NotFound):
message = _("No such QoS spec %(specs_id)s.")
class QoSSpecsAssociateFailed(CinderException):
message = _("Failed to associate qos_specs: "
"%(specs_id)s with type %(type_id)s.")
class QoSSpecsDisassociateFailed(CinderException):
message = _("Failed to disassociate qos_specs: "
"%(specs_id)s with type %(type_id)s.")
class QoSSpecsKeyNotFound(NotFound):
message = _("QoS spec %(specs_id)s has no spec with "
"key %(specs_key)s.")
class InvalidQoSSpecs(Invalid):
message = _("Invalid qos specs: %(reason)s")
class QoSSpecsInUse(CinderException):
message = _("QoS Specs %(specs_id)s is still associated with entities.")
class KeyManagerError(CinderException):
message = _("key manager error: %(reason)s")
class ManageExistingInvalidReference(CinderException):
message = _("Manage existing volume failed due to invalid backend "
"reference %(existing_ref)s: %(reason)s")
class ManageExistingAlreadyManaged(CinderException):
message = _("Unable to manage existing volume. "
"Volume %(volume_ref)s already managed.")
class InvalidReplicationTarget(Invalid):
message = _("Invalid Replication Target: %(reason)s")
class UnableToFailOver(CinderException):
message = _("Unable to failover to replication target: %(reason)s).")
class ReplicationError(CinderException):
message = _("Volume %(volume_id)s replication "
"error: %(reason)s")
class ReplicationGroupError(CinderException):
message = _("Group %(group_id)s replication "
"error: %(reason)s.")
class ReplicationNotFound(NotFound):
message = _("Volume replication for %(volume_id)s "
"could not be found.")
class ManageExistingVolumeTypeMismatch(CinderException):
message = _("Manage existing volume failed due to volume type mismatch: "
"%(reason)s")
class ExtendVolumeError(CinderException):
message = _("Error extending volume: %(reason)s")
class EvaluatorParseException(Exception):
message = _("Error during evaluator parsing: %(reason)s")
class LockCreationFailed(CinderException):
message = _('Unable to create lock. Coordination backend not started.')
class LockingFailed(CinderException):
message = _('Lock acquisition failed.')
UnsupportedObjectError = obj_exc.UnsupportedObjectError
OrphanedObjectError = obj_exc.OrphanedObjectError
IncompatibleObjectVersion = obj_exc.IncompatibleObjectVersion
ReadOnlyFieldError = obj_exc.ReadOnlyFieldError
ObjectActionError = obj_exc.ObjectActionError
ObjectFieldInvalid = obj_exc.ObjectFieldInvalid
class CappedVersionUnknown(CinderException):
message = _("Unrecoverable Error: Versioned Objects in DB are capped to "
"unknown version %(version)s. Most likely your environment "
"contains only new services and you're trying to start an "
"older one. Use `cinder-manage service list` to check that "
"and upgrade this service.")
class VolumeGroupNotFound(CinderException):
message = _('Unable to find Volume Group: %(vg_name)s')
class VolumeGroupCreationFailed(CinderException):
message = _('Failed to create Volume Group: %(vg_name)s')
class VolumeNotDeactivated(CinderException):
message = _('Volume %(name)s was not deactivated in time.')
class VolumeDeviceNotFound(CinderException):
message = _('Volume device not found at %(device)s.')
# Driver specific exceptions
# Dell
class DellDriverRetryableException(VolumeBackendAPIException):
message = _("Retryable Dell Exception encountered")
class DellDriverUnknownSpec(VolumeDriverException):
message = _("Dell driver failure: %(reason)s")
# Pure Storage
class PureDriverException(VolumeDriverException):
message = _("Pure Storage Cinder driver failure: %(reason)s")
class PureRetryableException(VolumeBackendAPIException):
message = _("Retryable Pure Storage Exception encountered")
# RBD
class RBDDriverException(VolumeDriverException):
message = _("RBD Cinder driver failure: %(reason)s")
# SolidFire
class SolidFireAPIException(VolumeBackendAPIException):
message = _("Bad response from SolidFire API")
class SolidFireDriverException(VolumeDriverException):
message = _("SolidFire Cinder Driver exception")
class SolidFireAPIDataException(SolidFireAPIException):
message = _("Error in SolidFire API response: data=%(data)s")
class SolidFireAccountNotFound(SolidFireDriverException):
message = _("Unable to locate account %(account_name)s on "
"Solidfire device")
class SolidFireRetryableException(VolumeBackendAPIException):
message = _("Retryable SolidFire Exception encountered")
# HP 3Par
class Invalid3PARDomain(VolumeDriverException):
message = _("Invalid 3PAR Domain: %(err)s")
# RemoteFS drivers
class RemoteFSException(VolumeDriverException):
message = _("Unknown RemoteFS exception")
class RemoteFSConcurrentRequest(RemoteFSException):
message = _("A concurrent, possibly contradictory, request "
"has been made.")
class RemoteFSNoSharesMounted(RemoteFSException):
message = _("No mounted shares found")
class RemoteFSNoSuitableShareFound(RemoteFSException):
message = _("There is no share which can host %(volume_size)sG")
class RemoteFSInvalidBackingFile(VolumeDriverException):
message = _("File %(path)s has invalid backing file %(backing_file)s.")
# NFS driver
class NfsException(RemoteFSException):
message = _("Unknown NFS exception")
class NfsNoSharesMounted(RemoteFSNoSharesMounted):
message = _("No mounted NFS shares found")
class NfsNoSuitableShareFound(RemoteFSNoSuitableShareFound):
message = _("There is no share which can host %(volume_size)sG")
# Smbfs driver
class SmbfsException(RemoteFSException):
message = _("Unknown SMBFS exception.")
class SmbfsNoSharesMounted(RemoteFSNoSharesMounted):
message = _("No mounted SMBFS shares found.")
class SmbfsNoSuitableShareFound(RemoteFSNoSuitableShareFound):
message = _("There is no share which can host %(volume_size)sG.")
# Virtuozzo Storage Driver
class VzStorageException(RemoteFSException):
message = _("Unknown Virtuozzo Storage exception")
class VzStorageNoSharesMounted(RemoteFSNoSharesMounted):
message = _("No mounted Virtuozzo Storage shares found")
class VzStorageNoSuitableShareFound(RemoteFSNoSuitableShareFound):
message = _("There is no share which can host %(volume_size)sG")
# Fibre Channel Zone Manager
class ZoneManagerException(CinderException):
message = _("Fibre Channel connection control failure: %(reason)s")
class FCZoneDriverException(CinderException):
message = _("Fibre Channel Zone operation failed: %(reason)s")
class FCSanLookupServiceException(CinderException):
message = _("Fibre Channel SAN Lookup failure: %(reason)s")
class ZoneManagerNotInitialized(CinderException):
message = _("Fibre Channel Zone Manager not initialized")
class BrocadeZoningCliException(CinderException):
message = _("Brocade Fibre Channel Zoning CLI error: %(reason)s")
class BrocadeZoningHttpException(CinderException):
message = _("Brocade Fibre Channel Zoning HTTP error: %(reason)s")
class BrocadeZoningRestException(CinderException):
message = _("Brocade Fibre Channel Zoning REST error: %(reason)s")
class CiscoZoningCliException(CinderException):
message = _("Cisco Fibre Channel Zoning CLI error: %(reason)s")
class NetAppDriverException(VolumeDriverException):
message = _("NetApp Cinder Driver exception.")
class EMCVnxCLICmdError(VolumeBackendAPIException):
message = _("EMC VNX Cinder Driver CLI exception: %(cmd)s "
"(Return Code: %(rc)s) (Output: %(out)s).")
class EMCSPUnavailableException(EMCVnxCLICmdError):
message = _("EMC VNX Cinder Driver SPUnavailableException: %(cmd)s "
"(Return Code: %(rc)s) (Output: %(out)s).")
# ConsistencyGroup
class ConsistencyGroupNotFound(NotFound):
message = _("ConsistencyGroup %(consistencygroup_id)s could not be found.")
class InvalidConsistencyGroup(Invalid):
message = _("Invalid ConsistencyGroup: %(reason)s")
# Group
class GroupNotFound(NotFound):
message = _("Group %(group_id)s could not be found.")
class InvalidGroup(Invalid):
message = _("Invalid Group: %(reason)s")
class InvalidGroupStatus(Invalid):
message = _("Invalid Group Status: %(reason)s")
# CgSnapshot
class CgSnapshotNotFound(NotFound):
message = _("CgSnapshot %(cgsnapshot_id)s could not be found.")
class InvalidCgSnapshot(Invalid):
message = _("Invalid CgSnapshot: %(reason)s")
# GroupSnapshot
class GroupSnapshotNotFound(NotFound):
message = _("GroupSnapshot %(group_snapshot_id)s could not be found.")
class InvalidGroupSnapshot(Invalid):
message = _("Invalid GroupSnapshot: %(reason)s")
class InvalidGroupSnapshotStatus(Invalid):
message = _("Invalid GroupSnapshot Status: %(reason)s")
# Datera driver
class DateraAPIException(VolumeBackendAPIException):
message = _("Bad response from Datera API")
# Target drivers
class ISCSITargetCreateFailed(CinderException):
message = _("Failed to create iscsi target for volume %(volume_id)s.")
class ISCSITargetRemoveFailed(CinderException):
message = _("Failed to remove iscsi target for volume %(volume_id)s.")
class ISCSITargetAttachFailed(CinderException):
message = _("Failed to attach iSCSI target for volume %(volume_id)s.")
class ISCSITargetDetachFailed(CinderException):
message = _("Failed to detach iSCSI target for volume %(volume_id)s.")
class TargetUpdateFailed(CinderException):
message = _("Failed to update target for volume %(volume_id)s.")
class ISCSITargetHelperCommandFailed(CinderException):
message = "%(error_message)s"
class BadHTTPResponseStatus(VolumeDriverException):
message = _("Bad HTTP response status %(status)s")
class BadResetResourceStatus(CinderException):
message = _("Bad reset resource status : %(reason)s")
# ZADARA STORAGE VPSA driver exception
class ZadaraServerCreateFailure(VolumeDriverException):
message = _("Unable to create server object for initiator %(name)s")
class ZadaraServerNotFound(NotFound):
message = _("Unable to find server object for initiator %(name)s")
class ZadaraVPSANoActiveController(VolumeDriverException):
message = _("Unable to find any active VPSA controller")
class ZadaraAttachmentsNotFound(NotFound):
message = _("Failed to retrieve attachments for volume %(name)s")
class ZadaraInvalidAttachmentInfo(Invalid):
message = _("Invalid attachment info for volume %(name)s: %(reason)s")
class ZadaraVolumeNotFound(VolumeDriverException):
message = "%(reason)s"
# ZFSSA NFS driver exception.
class WebDAVClientError(VolumeDriverException):
message = _("The WebDAV request failed. Reason: %(msg)s, "
"Return code/reason: %(code)s, Source Volume: %(src)s, "
"Destination Volume: %(dst)s, Method: %(method)s.")
# XtremIO Drivers
class XtremIOAlreadyMappedError(VolumeDriverException):
message = _("Volume to Initiator Group mapping already exists")
class XtremIOArrayBusy(VolumeDriverException):
message = _("System is busy, retry operation.")
class XtremIOSnapshotsLimitExceeded(VolumeDriverException):
message = _("Exceeded the limit of snapshots per volume")
# StorPool driver
class StorPoolConfigurationInvalid(CinderException):
message = _("Invalid parameter %(param)s in the %(section)s section "
"of the /etc/storpool.conf file: %(error)s")
# DOTHILL drivers
class DotHillInvalidBackend(VolumeDriverException):
message = _("Backend doesn't exist (%(backend)s)")
class DotHillConnectionError(VolumeDriverException):
message = "%(message)s"
class DotHillAuthenticationError(VolumeDriverException):
message = "%(message)s"
class DotHillNotEnoughSpace(VolumeDriverException):
message = _("Not enough space on backend (%(backend)s)")
class DotHillRequestError(VolumeDriverException):
message = "%(message)s"
class DotHillNotTargetPortal(VolumeDriverException):
message = _("No active iSCSI portals with supplied iSCSI IPs")
class DotHillDriverNotSupported(VolumeDriverException):
message = _("The Dot Hill driver is no longer supported.")
# Sheepdog
class SheepdogError(VolumeBackendAPIException):
message = _("An error has occurred in SheepdogDriver. "
"(Reason: %(reason)s)")
class SheepdogCmdError(SheepdogError):
message = _("(Command: %(cmd)s) "
"(Return Code: %(exit_code)s) "
"(Stdout: %(stdout)s) "
"(Stderr: %(stderr)s)")
class MetadataAbsent(CinderException):
message = _("There is no metadata in DB object.")
class NotSupportedOperation(Invalid):
message = _("Operation not supported: %(operation)s.")
code = 405
# NexentaStor driver exception
class NexentaException(VolumeDriverException):
message = "%(reason)s"
# Google Cloud Storage(GCS) backup driver
class GCSConnectionFailure(BackupDriverException):
message = _("Google Cloud Storage connection failure: %(reason)s")
class GCSApiFailure(BackupDriverException):
message = _("Google Cloud Storage api failure: %(reason)s")
class GCSOAuth2Failure(BackupDriverException):
message = _("Google Cloud Storage oauth2 failure: %(reason)s")
# Kaminario K2
class KaminarioCinderDriverException(VolumeDriverException):
message = _("KaminarioCinderDriver failure: %(reason)s")
class KaminarioRetryableException(VolumeDriverException):
message = _("Kaminario retryable exception: %(reason)s")
# Synology driver
class SynoAPIHTTPError(VolumeDriverException):
message = _("HTTP exit code: [%(code)s]")
class SynoAuthError(VolumeDriverException):
message = _("Synology driver authentication failed: %(reason)s.")
class SynoLUNNotExist(VolumeDriverException):
message = _("LUN not found by UUID: %(uuid)s.")
class AttachmentSpecsNotFound(NotFound):
message = _("Attachment %(attachment_id)s has no "
"key %(specs_key)s.")
class InvalidAttachment(Invalid):
message = _("Invalid attachment: %(reason)s")
# Veritas driver
class UnableToExecuteHyperScaleCmd(VolumeDriverException):
message = _("Failed HyperScale command for '%(command)s'")
class UnableToProcessHyperScaleCmdOutput(VolumeDriverException):
message = _("Failed processing command output '%(cmd_out)s'"
" for HyperScale command")
class ErrorInFetchingConfiguration(VolumeDriverException):
message = _("Error in fetching configuration for '%(persona)s'")
class ErrorInSendingMsg(VolumeDriverException):
message = _("Error in sending message '%(cmd_error)s'")
class ErrorInHyperScaleVersion(VolumeDriverException):
message = _("Error in getting HyperScale version '%(cmd_error)s'")
# GPFS driver
class GPFSDriverUnsupportedOperation(VolumeBackendAPIException):
message = _("GPFS driver unsupported operation: %(msg)s")
class InvalidName(Invalid):
message = _("An invalid 'name' value was provided. %(reason)s")
class ServiceUserTokenNoAuth(CinderException):
message = _("The [service_user] send_service_user_token option was "
"requested, but no service auth could be loaded. Please check "
"the [service_user] configuration section.")
class UnsupportedNVMETProtocol(Invalid):
message = _("An invalid 'target_protocol' "
"value was provided: %(protocol)s")
# NVMET driver
class NVMETTargetAddError(CinderException):
message = "Failed to add subsystem: %(subsystem)s"
class NVMETTargetDeleteError(CinderException):
message = "Failed to delete subsystem: %(subsystem)s"
| message = _("Snapshot %(snapshot_id)s has no metadata with "
"key %(metadata_key)s.") |
main.rs | #![allow(dead_code, mutable_transmutes, non_camel_case_types, non_snake_case,
non_upper_case_globals, unused_assignments, unused_mut)]
use std::{
collections::HashMap,
io,
ffi::OsStr,
mem::forget,
os::unix::{
ffi::OsStrExt,
io::FromRawFd,
},
pin::Pin,
rc::Rc,
};
use smol::{
block_on,
LocalExecutor,
fs::File,
future::{self, Future, FutureExt},
prelude::*,
};
mod spawn;
type LocalBoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
#[repr(C)]
#[derive(Clone, Copy)]
pub enum CommandType {
Exec = 1,
Redir = 2,
Pipe = 3,
List = 4,
Back = 5,
}
extern "C" {
fn dprintf(__fd: libc::c_int, __fmt: *const libc::c_char, _: ...)
-> libc::c_int;
fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong)
-> *mut libc::c_void;
fn strchr(_: *const libc::c_char, _: libc::c_int) -> *mut libc::c_char;
fn strlen(_: *const libc::c_char) -> libc::c_ulong;
fn malloc(_: libc::c_ulong) -> *mut libc::c_void;
fn close(__fd: libc::c_int) -> libc::c_int;
fn pipe(__pipedes: *mut libc::c_int) -> libc::c_int;
fn chdir(__path: *const libc::c_char) -> libc::c_int;
fn open(__file: *const libc::c_char, __oflag: libc::c_int, _: ...)
-> libc::c_int;
}
pub type size_t = libc::c_ulong;
pub type __off_t = libc::c_long;
pub type __off64_t = libc::c_long;
pub type __pid_t = libc::c_int;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct cmd {
pub type_0: CommandType,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct execcmd {
pub type_0: CommandType,
pub argv: [*mut libc::c_char; 10],
pub eargv: [*mut libc::c_char; 10],
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct redircmd {
pub type_0: CommandType,
pub cmd: *mut cmd,
pub file: *mut libc::c_char,
pub efile: *mut libc::c_char,
pub mode: libc::c_int,
pub fd: libc::c_int,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct pipecmd {
pub type_0: CommandType,
pub left: *mut cmd,
pub right: *mut cmd,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct listcmd {
pub type_0: CommandType,
pub left: *mut cmd,
pub right: *mut cmd,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct backcmd {
pub type_0: CommandType,
pub cmd: *mut cmd,
}
// Lifetime is a lie, lives as long as s.
unsafe fn make_osstr(s: *mut i8) -> &'static OsStr {
let len = strlen(s);
let bytes = std::slice::from_raw_parts(s as *mut u8, len as usize);
OsStr::from_bytes(bytes)
}
fn ready<T: 'static>(t: T) -> LocalBoxFuture<'static, T> {
smol::future::ready(t).boxed_local()
}
impl Shell {
// Execute cmd. Conceptually runs a forked shell, returns the forked shells
// exit status.
pub unsafe fn runcmd(&self, mut cmd: *mut cmd) -> LocalBoxFuture<'static, libc::c_int> {
let mut p: [libc::c_int; 2] = [0; 2];
let mut bcmd: *mut backcmd = 0 as *mut backcmd;
let mut ecmd: *mut execcmd = 0 as *mut execcmd;
let mut lcmd: *mut listcmd = 0 as *mut listcmd;
let mut pcmd: *mut pipecmd = 0 as *mut pipecmd;
let mut rcmd: *mut redircmd = 0 as *mut redircmd;
if cmd.is_null() { return ready(1) }
match (*cmd).type_0 {
CommandType::Exec => {
ecmd = cmd as *mut execcmd;
if (*ecmd).argv[0 as libc::c_int as usize].is_null() {
return ready(1);
}
match spawn::spawn((*ecmd).argv.as_ptr() as *const *const i8, &self.fds) {
Ok(fut) => fut.boxed_local(),
Err(e) => ready(e as libc::c_int),
}
}
CommandType::Redir => {
rcmd = cmd as *mut redircmd;
let new_fd = open((*rcmd).file, (*rcmd).mode);
if new_fd < 0 {
dprintf(2 as libc::c_int,
b"open %s failed\n\x00" as *const u8 as
*const libc::c_char, (*rcmd).file);
return ready(1);
}
let mut this = self.clone();
// In most cases including this we could avoid the extraneous clone
// by saving and restoring the old fd from the stack.
// Let's not worry about that yet.
this.fds.insert((*rcmd).fd, Rc::new(File::from_raw_fd(new_fd)));
this.runcmd((*rcmd).cmd).boxed_local()
}
CommandType::List => {
lcmd = cmd as *mut listcmd;
let this = self.clone();
async move {
this.runcmd((*lcmd).left).await;
this.runcmd((*lcmd).right).await
}.boxed_local()
}
CommandType::Pipe => {
pcmd = cmd as *mut pipecmd;
if pipe(p.as_mut_ptr()) < 0 as libc::c_int {
panic(b"pipe\x00" as *const u8 as *const libc::c_char as
*mut libc::c_char);
}
let mut this1 = self.clone();
let fut1 = async move {
this1.fds.insert(1, Rc::new(File::from_raw_fd(p[1])));
let proc = this1.runcmd((*pcmd).left);
// Need to get rid of this1 since it contains the pipe fd.
drop(this1);
proc.await
};
let mut this2 = self.clone();
let fut2 = async move {
this2.fds.insert(0, Rc::new(File::from_raw_fd(p[0])));
this2.runcmd((*pcmd).right).await
};
// What half should this return as anyways? Whatever, first half for now.
async move { future::zip(fut1, fut2).await.0 }.boxed_local()
}
CommandType::Back => {
bcmd = cmd as *mut backcmd;
let this = self.clone();
self.executor.spawn( async move {
this.runcmd((*bcmd).cmd).await
}).detach();
ready(0)
}
}
}
}
// Returns false if we reached EOF. Errors if we fail to read.
pub async fn getcmd(mut input: impl AsyncRead + Unpin, buf: &mut [u8]) -> Result<bool, io::Error> {
eprint!("$ " );
let n = input.read(buf).await?;
buf[n] = 0;
Ok(n != 0)
}
impl Shell {
async unsafe fn exec_string(&self, buf: &mut [i8]) {
// Read and run input commands.
if buf[0 as libc::c_int as usize] as libc::c_int == 'c' as i32 &&
buf[1 as libc::c_int as usize] as libc::c_int == 'd' as i32 &&
buf[2 as libc::c_int as usize] as libc::c_int == ' ' as i32 {
// Chdir must be called by the parent, not the child.
buf[strlen(buf.as_mut_ptr()).wrapping_sub(1 as libc::c_int as
libc::c_ulong) as
usize] = 0 as libc::c_int as libc::c_char; // chop \n
if chdir(buf.as_mut_ptr().offset(3 as libc::c_int as isize)) <
0 as libc::c_int {
dprintf(2 as libc::c_int,
b"cannot cd %s\n\x00" as *const u8 as
*const libc::c_char,
buf.as_mut_ptr().offset(3 as libc::c_int as isize));
}
} else {
match parsecmd(buf.as_mut_ptr()) {
Ok(cmd) => self.runcmd(cmd).await,
Err(e) => { eprintln!("{}", e); 1 },
};
}
}
}
pub unsafe fn panic(mut s: *mut libc::c_char) -> libc::c_int {
dprintf(2 as libc::c_int, b"%s\n\x00" as *const u8 as *const libc::c_char,
s);
return 1 as libc::c_int;
}
//PAGEBREAK!
// Constructors
pub unsafe fn execcmd() -> *mut cmd {
let mut cmd: *mut execcmd = 0 as *mut execcmd;
cmd =
malloc(::std::mem::size_of::<execcmd>() as libc::c_ulong) as
*mut execcmd;
memset(cmd as *mut libc::c_void, 0 as libc::c_int,
::std::mem::size_of::<execcmd>() as libc::c_ulong);
(*cmd).type_0 = CommandType::Exec;
return cmd as *mut cmd;
}
pub unsafe fn redircmd(mut subcmd: *mut cmd,
mut file: *mut libc::c_char,
mut efile: *mut libc::c_char,
mut mode: libc::c_int, mut fd: libc::c_int)
-> *mut cmd {
let mut cmd: *mut redircmd = 0 as *mut redircmd;
cmd =
malloc(::std::mem::size_of::<redircmd>() as libc::c_ulong) as
*mut redircmd;
memset(cmd as *mut libc::c_void, 0 as libc::c_int,
::std::mem::size_of::<redircmd>() as libc::c_ulong);
(*cmd).type_0 = CommandType::Redir;
(*cmd).cmd = subcmd;
(*cmd).file = file;
(*cmd).efile = efile;
(*cmd).mode = mode;
(*cmd).fd = fd;
return cmd as *mut cmd;
}
#[no_mangle]
pub unsafe fn pipecmd(mut left: *mut cmd, mut right: *mut cmd)
-> *mut cmd {
let mut cmd: *mut pipecmd = 0 as *mut pipecmd;
cmd =
malloc(::std::mem::size_of::<pipecmd>() as libc::c_ulong) as
*mut pipecmd;
memset(cmd as *mut libc::c_void, 0 as libc::c_int,
::std::mem::size_of::<pipecmd>() as libc::c_ulong);
(*cmd).type_0 = CommandType::Pipe;
(*cmd).left = left;
(*cmd).right = right;
return cmd as *mut cmd;
}
#[no_mangle]
pub unsafe fn listcmd(mut left: *mut cmd, mut right: *mut cmd)
-> *mut cmd {
let mut cmd: *mut listcmd = 0 as *mut listcmd;
cmd =
malloc(::std::mem::size_of::<listcmd>() as libc::c_ulong) as
*mut listcmd;
memset(cmd as *mut libc::c_void, 0 as libc::c_int,
::std::mem::size_of::<listcmd>() as libc::c_ulong);
(*cmd).type_0 = CommandType::List;
(*cmd).left = left;
(*cmd).right = right;
return cmd as *mut cmd;
}
#[no_mangle]
pub unsafe fn backcmd(mut subcmd: *mut cmd) -> *mut cmd {
let mut cmd: *mut backcmd = 0 as *mut backcmd;
cmd =
malloc(::std::mem::size_of::<backcmd>() as libc::c_ulong) as
*mut backcmd;
memset(cmd as *mut libc::c_void, 0 as libc::c_int,
::std::mem::size_of::<backcmd>() as libc::c_ulong);
(*cmd).type_0 = CommandType::Back;
(*cmd).cmd = subcmd;
return cmd as *mut cmd;
}
//PAGEBREAK!
// Parsing
#[no_mangle]
pub static mut whitespace: [libc::c_char; 6] =
unsafe {
*::std::mem::transmute::<&[u8; 6],
&[libc::c_char; 6]>(b" \t\r\n\x0b\x00")
};
#[no_mangle]
pub static mut symbols: [libc::c_char; 8] =
unsafe {
*::std::mem::transmute::<&[u8; 8], &[libc::c_char; 8]>(b"<|>&;()\x00")
};
#[no_mangle]
pub unsafe fn gettoken(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char,
mut q: *mut *mut libc::c_char,
mut eq: *mut *mut libc::c_char)
-> libc::c_int {
let mut s: *mut libc::c_char = 0 as *mut libc::c_char;
let mut ret: libc::c_int = 0;
s = *ps;
while s < es && !strchr(whitespace.as_ptr(), *s as libc::c_int).is_null()
{
s = s.offset(1)
}
if !q.is_null() { *q = s }
ret = *s as libc::c_int;
match *s as libc::c_int {
0 => { }
124 | 40 | 41 | 59 | 38 | 60 => { s = s.offset(1) }
62 => {
s = s.offset(1);
if *s as libc::c_int == '>' as i32 {
ret = '+' as i32;
s = s.offset(1)
}
}
_ => {
ret = 'a' as i32;
while s < es &&
strchr(whitespace.as_ptr(), *s as libc::c_int).is_null()
&& strchr(symbols.as_ptr(), *s as libc::c_int).is_null()
{
s = s.offset(1)
}
}
}
if !eq.is_null() { *eq = s }
while s < es && !strchr(whitespace.as_ptr(), *s as libc::c_int).is_null()
{
s = s.offset(1)
}
*ps = s;
return ret;
}
#[no_mangle]
pub unsafe fn peek(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char,
mut toks: *mut libc::c_char) -> libc::c_int {
let mut s: *mut libc::c_char = 0 as *mut libc::c_char;
s = *ps;
while s < es && !strchr(whitespace.as_ptr(), *s as libc::c_int).is_null()
{
s = s.offset(1)
}
*ps = s;
return (*s as libc::c_int != 0 &&
!strchr(toks, *s as libc::c_int).is_null()) as libc::c_int;
}
#[no_mangle]
pub unsafe fn parsecmd(mut s: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut es: *mut libc::c_char = 0 as *mut libc::c_char;
let mut cmd: *mut cmd = 0 as *mut cmd;
es = s.offset(strlen(s) as isize);
cmd = parseline(&mut s, es)?;
peek(&mut s, es,
b"\x00" as *const u8 as *const libc::c_char as *mut libc::c_char);
if s != es {
dprintf(2 as libc::c_int,
b"leftovers: %s\n\x00" as *const u8 as *const libc::c_char,
s);
return Err("syntax");
}
nulterminate(cmd);
return Ok(cmd);
}
#[no_mangle]
pub unsafe fn parseline(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut cmd: *mut cmd = 0 as *mut cmd;
cmd = parsepipe(ps, es)?;
while peek(ps, es,
b"&\x00" as *const u8 as *const libc::c_char as
*mut libc::c_char) != 0 {
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
cmd = backcmd(cmd)
}
if peek(ps, es,
b";\x00" as *const u8 as *const libc::c_char as *mut libc::c_char)
!= 0 {
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
cmd = listcmd(cmd, parseline(ps, es)?)
}
return Ok(cmd);
}
#[no_mangle]
pub unsafe fn parsepipe(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut cmd: *mut cmd = 0 as *mut cmd;
cmd = parseexec(ps, es)?;
if peek(ps, es,
b"|\x00" as *const u8 as *const libc::c_char as *mut libc::c_char)
!= 0 {
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
cmd = pipecmd(cmd, parsepipe(ps, es)?)
}
return Ok(cmd);
}
#[no_mangle]
pub unsafe fn parseredirs(mut cmd: *mut cmd,
mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut tok: libc::c_int = 0;
let mut q: *mut libc::c_char = 0 as *mut libc::c_char;
let mut eq: *mut libc::c_char = 0 as *mut libc::c_char;
while peek(ps, es,
b"<>\x00" as *const u8 as *const libc::c_char as
*mut libc::c_char) != 0 {
tok =
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
if gettoken(ps, es, &mut q, &mut eq) != 'a' as i32 {
return Err("missing file for redirection");
}
match tok {
60 => {
cmd = redircmd(cmd, q, eq, 0 as libc::c_int, 0 as libc::c_int)
}
62 => {
cmd =
redircmd(cmd, q, eq,
0o1 as libc::c_int | 0o100 as libc::c_int,
1 as libc::c_int)
}
43 => {
// >>
cmd =
redircmd(cmd, q, eq,
0o1 as libc::c_int | 0o100 as libc::c_int,
1 as libc::c_int)
}
_ => { }
}
}
return Ok(cmd);
}
#[no_mangle]
pub unsafe fn parseblock(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut cmd: *mut cmd = 0 as *mut cmd;
if peek(ps, es,
b"(\x00" as *const u8 as *const libc::c_char as *mut libc::c_char)
== 0 {
return Err("parseblock");
}
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
cmd = parseline(ps, es)?;
if peek(ps, es,
b")\x00" as *const u8 as *const libc::c_char as *mut libc::c_char)
== 0 {
return Err("syntax - missing )");
}
gettoken(ps, es, 0 as *mut *mut libc::c_char,
0 as *mut *mut libc::c_char);
cmd = parseredirs(cmd, ps, es)?;
return Ok(cmd);
}
#[no_mangle]
pub unsafe fn parseexec(mut ps: *mut *mut libc::c_char,
mut es: *mut libc::c_char) -> Result<*mut cmd, &'static str> {
let mut q: *mut libc::c_char = 0 as *mut libc::c_char;
let mut eq: *mut libc::c_char = 0 as *mut libc::c_char;
let mut tok: libc::c_int = 0;
let mut argc: libc::c_int = 0;
let mut cmd: *mut execcmd = 0 as *mut execcmd;
let mut ret: *mut cmd = 0 as *mut cmd;
if peek(ps, es,
b"(\x00" as *const u8 as *const libc::c_char as *mut libc::c_char)
!= 0 {
return parseblock(ps, es)
}
ret = execcmd();
cmd = ret as *mut execcmd;
argc = 0 as libc::c_int;
ret = parseredirs(ret, ps, es)?;
while peek(ps, es,
b"|)&;\x00" as *const u8 as *const libc::c_char as
*mut libc::c_char) == 0 {
tok = gettoken(ps, es, &mut q, &mut eq);
if tok == 0 as libc::c_int { break ; }
if tok != 'a' as i32 {
return Err("syntax");
}
(*cmd).argv[argc as usize] = q;
(*cmd).eargv[argc as usize] = eq;
argc += 1;
if argc >= 10 as libc::c_int {
return Err("too many args");
}
ret = parseredirs(ret, ps, es)?
}
(*cmd).argv[argc as usize] = 0 as *mut libc::c_char;
(*cmd).eargv[argc as usize] = 0 as *mut libc::c_char;
return Ok(ret);
}
// NUL-terminate all the counted strings.
#[no_mangle]
pub unsafe fn nulterminate(mut cmd: *mut cmd) -> *mut cmd {
let mut i: libc::c_int = 0;
let mut bcmd: *mut backcmd = 0 as *mut backcmd;
let mut ecmd: *mut execcmd = 0 as *mut execcmd;
let mut lcmd: *mut listcmd = 0 as *mut listcmd;
let mut pcmd: *mut pipecmd = 0 as *mut pipecmd;
let mut rcmd: *mut redircmd = 0 as *mut redircmd;
if cmd.is_null() { return 0 as *mut cmd }
match (*cmd).type_0 {
CommandType::Exec => {
ecmd = cmd as *mut execcmd;
i = 0 as libc::c_int;
while !(*ecmd).argv[i as usize].is_null() {
*(*ecmd).eargv[i as usize] = 0 as libc::c_int as libc::c_char;
i += 1
}
}
CommandType::Redir => {
rcmd = cmd as *mut redircmd;
nulterminate((*rcmd).cmd);
*(*rcmd).efile = 0 as libc::c_int as libc::c_char
}
CommandType::Pipe => {
pcmd = cmd as *mut pipecmd;
nulterminate((*pcmd).left);
nulterminate((*pcmd).right);
}
CommandType::List => {
lcmd = cmd as *mut listcmd;
nulterminate((*lcmd).left);
nulterminate((*lcmd).right);
}
CommandType::Back => { bcmd = cmd as *mut backcmd; nulterminate((*bcmd).cmd); }
}
return cmd;
}
/* Api */
#[derive(Clone)]
pub struct | {
executor: &'static LocalExecutor<'static>,
// Should really use a VecMap or something more efficient...
// Ideally inline the first 3 or 4 fds instead of always heap allocating...
fds: HashMap<i32, Rc<File>>,
}
impl Shell {
pub fn new() -> Shell {
let mut fds = HashMap::with_capacity(3);
unsafe {
let mut fd: libc::c_int = 0;
loop
// Ensure that three file descriptors are open.
{
fd =
open(b"console\x00" as *const u8 as *const libc::c_char,
0o2 as libc::c_int);
if !(fd >= 0 as libc::c_int) { break ; }
if !(fd >= 3 as libc::c_int) { continue ; }
close(fd);
break ;
}
let stdin_rc = Rc::new(File::from_raw_fd(0));
let stdout_rc = Rc::new(File::from_raw_fd(1));
let stderr_rc = Rc::new(File::from_raw_fd(2));
fds.insert(0, stdin_rc.clone());
fds.insert(1, stdout_rc.clone());
fds.insert(2, stderr_rc.clone());
// Forget the original rc's so that we never drop stdin/out/err.
forget(stdin_rc);
forget(stdout_rc);
forget(stderr_rc);
}
Shell{
executor: Box::leak(Box::new(LocalExecutor::new())),
fds,
}
}
}
fn main() {
let shell: Shell = Shell::new();
let shutdown = event_listener::Event::new();
let fut = async {
let mut stdin = smol::Async::new(std::io::stdin()).unwrap();
let mut buf = [0u8; 100];
while getcmd(&mut stdin, &mut buf).await.unwrap() {
unsafe {
let buf_ptr: &mut [i8; 100] = std::mem::transmute(&mut buf);
shell.exec_string(buf_ptr).await;
}
}
shutdown.notify(usize::MAX);
};
// Not sure why shutdown.listen() is needed to get tasks to spawn...
// Only reason I even realized it is that in more real executors I always
// have something like that anyways.
block_on(shell.executor.run(future::zip(
shutdown.listen(),
fut
)));
} | Shell |
index.ts | import { sub } from 'date-fns';
//
import { role } from './role';
import { email } from './email';
import { boolean } from './boolean';
import { company } from './company';
import { phoneNumber } from './phoneNumber';
import { fullAddress, country } from './address';
import { firstName, lastName, fullName } from './name';
import { title, sentence, description } from './text';
import { price, rating, age, percent } from './number';
// ----------------------------------------------------------------------
const mockData = {
id: (index: number) => `e99f09a7-dd88-49d5-b1c8-1daf80c2d7b${index + 1}`,
email: (index: number) => email[index],
phoneNumber: (index: number) => phoneNumber[index],
time: (index: number) => sub(new Date(), { days: index, hours: index }),
boolean: (index: number) => boolean[index],
role: (index: number) => role[index],
company: (index: number) => company[index],
address: {
fullAddress: (index: number) => fullAddress[index],
country: (index: number) => country[index] | },
name: {
firstName: (index: number) => firstName[index],
lastName: (index: number) => lastName[index],
fullName: (index: number) => fullName[index]
},
text: {
title: (index: number) => title[index],
sentence: (index: number) => sentence[index],
description: (index: number) => description[index]
},
number: {
percent: (index: number) => percent[index],
rating: (index: number) => rating[index],
age: (index: number) => age[index],
price: (index: number) => price[index]
},
image: {
cover: (index: number) => `/static/mock-images/covers/cover_${index + 1}.jpg`,
feed: (index: number) => `/static/mock-images/feeds/feed_${index + 1}.jpg`,
product: (index: number) => `/static/mock-images/products/product_${index + 1}.jpg`,
avatar: (index: number) => `/static/mock-images/avatars/avatar_${index + 1}.jpg`
}
};
export default mockData; | |
mod.rs | // SPDX-License-Identifier: Apache-2.0
#![allow(dead_code)]
use process_control::{ChildExt, Control, Output};
use std::io::{stderr, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::Duration;
pub const CRATE: &str = env!("CARGO_MANIFEST_DIR");
pub const KEEP_BIN: &str = env!("CARGO_BIN_EXE_enarx");
pub const OUT_DIR: &str = env!("OUT_DIR");
pub const TEST_BINS_OUT: &str = "bin";
pub const TIMEOUT_SECS: u64 = 60 * 60;
pub const MAX_ASSERT_ELEMENTS: usize = 100;
pub fn assert_eq_slices(expected_output: &[u8], output: &[u8], what: &str) {
let max_len = usize::min(output.len(), expected_output.len());
let max_len = max_len.min(MAX_ASSERT_ELEMENTS);
assert_eq!(
output[..max_len],
expected_output[..max_len],
"Expected contents of {} differs",
what
);
assert_eq!(
output.len(),
expected_output.len(),
"Expected length of {} differs",
what
);
assert_eq!(
output, expected_output,
"Expected contents of {} differs",
what
);
}
/// Returns a handle to a child process through which output (stdout, stderr) can
/// be accessed.
pub fn keepldr_exec<'a>(bin: impl Into<PathBuf>, input: impl Into<Option<&'a [u8]>>) -> Output {
let bin: PathBuf = bin.into();
let mut child = Command::new(KEEP_BIN)
.current_dir(CRATE)
.arg("exec")
.arg(&bin)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|e| panic!("failed to run `{}`: {:#?}", bin.display(), e));
let input_thread = if let Some(input) = input.into() {
let mut stdin = child.stdin.take().unwrap();
let input = input.to_vec();
Some(std::thread::spawn(move || {
stdin
.write_all(&input)
.expect("failed to write stdin to child");
}))
} else {
None
};
let output = child
.controlled_with_output()
.time_limit(Duration::from_secs(TIMEOUT_SECS))
.terminate_for_timeout()
.wait()
.unwrap_or_else(|e| panic!("failed to run `{}`: {:#?}", bin.display(), e))
.unwrap_or_else(|| panic!("process `{}` timed out", bin.display()));
if let Some(input_thread) = input_thread {
if let Err(_) = input_thread.join() {
let _unused = stderr().write_all(&output.stderr);
panic!("failed to provide input for process `{}`", bin.display())
}
}
assert!(
output.status.code().is_some(),
"process `{}` terminated by signal {:?}",
bin.display(),
output.status.signal()
);
output
}
pub fn check_output<'a>(
output: &Output,
expected_status: i32,
expected_stdout: impl Into<Option<&'a [u8]>>,
expected_stderr: impl Into<Option<&'a [u8]>>,
) {
let expected_stdout = expected_stdout.into();
let expected_stderr = expected_stderr.into();
// Output potential error messages
if expected_stderr.is_none() && !output.stderr.is_empty() {
let _ = std::io::stderr().write_all(&output.stderr);
}
if let Some(expected_stdout) = expected_stdout {
if output.stdout.len() < MAX_ASSERT_ELEMENTS && expected_stdout.len() < MAX_ASSERT_ELEMENTS
{
assert_eq!(
output.stdout, expected_stdout,
"Expected contents of stdout output differs"
);
} else {
assert_eq_slices(expected_stdout, &output.stdout, "stdout output");
}
}
if let Some(expected_stderr) = expected_stderr {
if output.stderr.len() < MAX_ASSERT_ELEMENTS && expected_stderr.len() < MAX_ASSERT_ELEMENTS
{
assert_eq!(
output.stderr, expected_stderr,
"Expected contents of stderr output differs."
);
} else {
assert_eq_slices(expected_stderr, &output.stderr, "stderr output");
}
}
assert_eq!(
output.status.code().unwrap(),
expected_status as i64,
"Expected exit status differs." | }
/// Returns a handle to a child process through which output (stdout, stderr) can
/// be accessed.
pub fn run_test<'a>(
bin: impl Into<PathBuf>,
status: i32,
input: impl Into<Option<&'a [u8]>>,
expected_stdout: impl Into<Option<&'a [u8]>>,
expected_stderr: impl Into<Option<&'a [u8]>>,
) -> Output {
let output = keepldr_exec(bin, input);
check_output(&output, status, expected_stdout, expected_stderr);
output
} | ); |
api.go | package api
import (
routing "github.com/qiangxue/fasthttp-routing"
"github.com/valyala/fasthttp"
"github.com/cyrildever/treee/common/logger"
"github.com/cyrildever/treee/config"
)
// InitHTTPServer ...
func InitHTTPServer(conf *config.Config) | {
log := logger.Init("api", "InitHTTPServer")
router := routing.New()
Routes(router)
address := conf.Host + ":" + conf.HTTPPort
log.Info("API started listening", "address", address)
log.Crit(fasthttp.ListenAndServe(address, router.HandleRequest).Error())
} |
|
Contact.js | import React from "react";
import HeroSection from "../../HeroSection";
import {
contactObjFour,
contactObjOne,
contactObjThree,
contactObjTwo,
} from "./ContactData";
function | () {
return (
<div>
<HeroSection {...contactObjOne} />
<HeroSection {...contactObjTwo} /> <HeroSection {...contactObjThree} />
<HeroSection {...contactObjFour} />
</div>
);
}
export default Contact;
| Contact |
FunctionGraphState.ts | import { observable, computed } from 'mobx';
import mermaid from 'mermaid';
import { buildFunctionDiagramCode } from './az-func-as-a-graph/buildFunctionDiagramCode';
import { FunctionGraphStateBase } from './FunctionGraphStateBase';
// State of FunctionGraph view
export class FunctionGraphState extends FunctionGraphStateBase {
@observable
errorMessage: string = '';
@computed
get inProgress(): boolean { return this._inProgress; };
@computed
get functionsLoaded(): boolean { return !!this._traversalResult; };
@computed
get renderFunctions(): boolean { return this._renderFunctions; };
set renderFunctions(val: boolean) {
this._renderFunctions = val;
this.render();
};
@computed
get renderProxies(): boolean { return this._renderProxies; };
set renderProxies(val: boolean) {
this._renderProxies = val;
this.render();
};
render() {
this._diagramCode = '';
this._diagramSvg = '';
this.errorMessage = '';
if (!this._traversalResult) {
return;
}
this._inProgress = true;
try {
const diagramCode = buildFunctionDiagramCode(this._traversalResult.functions, this._traversalResult.proxies,
{
doNotRenderFunctions: !this._renderFunctions,
doNotRenderProxies: !this._renderProxies
});
if (!diagramCode) {
this._inProgress = false;
return;
}
this._diagramCode = `graph LR\n${diagramCode}`;
mermaid.render('mermaidSvgId', this._diagramCode, (svg) => {
this._diagramSvg = this.applyIcons(svg);
this._inProgress = false; | this._inProgress = false;
}
}
load() {
if (this._inProgress) {
return;
}
// Only doing this on demand, just in case
this.initMermaidWhenNeeded();
this._inProgress = true;
this.errorMessage = '';
this._diagramCode = '';
this._diagramSvg = '';
this._traversalResult = null;
this._backendClient.call('GET', '/function-map').then(response => {
this._traversalResult = response;
this.render();
}, err => {
this._inProgress = false;
this.errorMessage = `Failed to traverse. ${!err.response ? err.message : err.response.data}`;
});
}
@observable
private _inProgress: boolean = false;
} | });
} catch (err) {
this.errorMessage = `Failed to render: ${err.message}`; |
server.py | # Copyright 2016 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
from neutron_lib.api.definitions import portbindings
from neutron_lib.db import api as db_api
from neutron_lib.plugins import directory
from neutron_lib import rpc as n_rpc
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
import oslo_messaging
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks.producer import registry
from neutron.api.rpc.callbacks import resources
from neutron.api.rpc.handlers import resources_rpc
from neutron.objects import trunk as trunk_objects
from neutron.services.trunk import constants as trunk_consts
from neutron.services.trunk import exceptions as trunk_exc |
# This module contains stub (client-side) and skeleton (server-side)
# proxy code that executes in the Neutron server process space. This
# is needed if any of the trunk service plugin drivers has a remote
# component (e.g. agent), that needs to communicate with the Neutron
# Server.
# The Server side exposes the following remote methods:
#
# - lookup method to retrieve trunk details: used by the agent to learn
# about the trunk.
# - update methods for trunk and its subports: used by the agent to
# inform the server about local trunk status changes.
#
# For agent-side stub and skeleton proxy code, please look at agent.py
def trunk_by_port_provider(resource, port_id, context, **kwargs):
"""Provider callback to supply trunk information by parent port."""
return trunk_objects.Trunk.get_object(context, port_id=port_id)
class TrunkSkeleton(object):
"""Skeleton proxy code for agent->server communication."""
# API version history:
# 1.0 Initial version
target = oslo_messaging.Target(version='1.0',
namespace=constants.TRUNK_BASE_NAMESPACE)
_core_plugin = None
def __init__(self):
# Used to provide trunk lookups for the agent.
registry.provide(trunk_by_port_provider, resources.TRUNK)
self._connection = n_rpc.Connection()
self._connection.create_consumer(
constants.TRUNK_BASE_TOPIC, [self], fanout=False)
self._connection.consume_in_threads()
@property
def core_plugin(self):
if not self._core_plugin:
self._core_plugin = directory.get_plugin()
return self._core_plugin
@log_helpers.log_method_call
def update_subport_bindings(self, context, subports):
"""Update subport bindings to match trunk host binding."""
el = context.elevated()
ports_by_trunk_id = collections.defaultdict(list)
updated_ports = collections.defaultdict(list)
for s in subports:
ports_by_trunk_id[s['trunk_id']].append(s['port_id'])
for trunk_id, subport_ids in ports_by_trunk_id.items():
trunk = trunk_objects.Trunk.get_object(el, id=trunk_id)
if not trunk:
LOG.debug("Trunk not found. id: %s", trunk_id)
continue
trunk_updated_ports = self._process_trunk_subport_bindings(
el,
trunk,
subport_ids)
updated_ports[trunk.id].extend(trunk_updated_ports)
return updated_ports
def update_trunk_status(self, context, trunk_id, status):
"""Update the trunk status to reflect outcome of data plane wiring."""
with db_api.autonested_transaction(context.session):
trunk = trunk_objects.Trunk.get_object(context, id=trunk_id)
if trunk:
trunk.update(status=status)
def _process_trunk_subport_bindings(self, context, trunk, port_ids):
"""Process port bindings for subports on the given trunk."""
updated_ports = []
trunk_port_id = trunk.port_id
trunk_port = self.core_plugin.get_port(context, trunk_port_id)
trunk_host = trunk_port.get(portbindings.HOST_ID)
# NOTE(status_police) Set the trunk in BUILD state before processing
# subport bindings. The trunk will stay in BUILD state until an
# attempt has been made to bind all subports passed here and the
# agent acknowledges the operation was successful.
trunk.update(status=trunk_consts.BUILD_STATUS)
for port_id in port_ids:
try:
updated_port = self._handle_port_binding(context, port_id,
trunk, trunk_host)
# NOTE(fitoduarte): consider trimming down the content
# of the port data structure.
updated_ports.append(updated_port)
except trunk_exc.SubPortBindingError as e:
LOG.error("Failed to bind subport: %s", e)
# NOTE(status_police) The subport binding has failed in a
# manner in which we cannot proceed and the user must take
# action to bring the trunk back to a sane state.
trunk.update(status=trunk_consts.ERROR_STATUS)
return []
except Exception as e:
msg = ("Failed to bind subport port %(port)s on trunk "
"%(trunk)s: %(exc)s")
LOG.error(msg, {'port': port_id, 'trunk': trunk.id, 'exc': e})
if len(port_ids) != len(updated_ports):
trunk.update(status=trunk_consts.DEGRADED_STATUS)
return updated_ports
def _handle_port_binding(self, context, port_id, trunk, trunk_host):
"""Bind the given port to the given host.
:param context: The context to use for the operation
:param port_id: The UUID of the port to be bound
:param trunk: The trunk that the given port belongs to
:param trunk_host: The host to bind the given port to
"""
port = self.core_plugin.update_port(
context, port_id,
{'port': {portbindings.HOST_ID: trunk_host,
'device_owner': trunk_consts.TRUNK_SUBPORT_OWNER}})
vif_type = port.get(portbindings.VIF_TYPE)
if vif_type == portbindings.VIF_TYPE_BINDING_FAILED:
raise trunk_exc.SubPortBindingError(port_id=port_id,
trunk_id=trunk.id)
return port
class TrunkStub(object):
"""Stub proxy code for server->agent communication."""
def __init__(self):
self._resource_rpc = resources_rpc.ResourcesPushRpcApi()
@log_helpers.log_method_call
def trunk_created(self, context, trunk):
"""Tell the agent about a trunk being created."""
self._resource_rpc.push(context, [trunk], events.CREATED)
@log_helpers.log_method_call
def trunk_deleted(self, context, trunk):
"""Tell the agent about a trunk being deleted."""
self._resource_rpc.push(context, [trunk], events.DELETED)
@log_helpers.log_method_call
def subports_added(self, context, subports):
"""Tell the agent about new subports to add."""
self._resource_rpc.push(context, subports, events.CREATED)
@log_helpers.log_method_call
def subports_deleted(self, context, subports):
"""Tell the agent about existing subports to remove."""
self._resource_rpc.push(context, subports, events.DELETED) | from neutron.services.trunk.rpc import constants
LOG = logging.getLogger(__name__) |
scopes_test.go | package tests_test
import (
"context"
"testing"
"github.com/raphaelyancey/gorm/gorm"
. "github.com/raphaelyancey/gorm/gorm/utils/tests"
)
func NameIn1And2(d *gorm.DB) *gorm.DB {
return d.Where("name in (?)", []string{"ScopeUser1", "ScopeUser2"})
}
func NameIn2And3(d *gorm.DB) *gorm.DB {
return d.Where("name in (?)", []string{"ScopeUser2", "ScopeUser3"})
}
func | (names []string) func(d *gorm.DB) *gorm.DB {
return func(d *gorm.DB) *gorm.DB {
return d.Where("name in (?)", names)
}
}
func TestScopes(t *testing.T) {
users := []*User{
GetUser("ScopeUser1", Config{}),
GetUser("ScopeUser2", Config{}),
GetUser("ScopeUser3", Config{}),
}
DB.Create(&users)
var users1, users2, users3 []User
DB.Scopes(NameIn1And2).Find(&users1)
if len(users1) != 2 {
t.Errorf("Should found two users's name in 1, 2, but got %v", len(users1))
}
DB.Scopes(NameIn1And2, NameIn2And3).Find(&users2)
if len(users2) != 1 {
t.Errorf("Should found one user's name is 2, but got %v", len(users2))
}
DB.Scopes(NameIn([]string{users[0].Name, users[2].Name})).Find(&users3)
if len(users3) != 2 {
t.Errorf("Should found two users's name in 1, 3, but got %v", len(users3))
}
db := DB.Scopes(func(tx *gorm.DB) *gorm.DB {
return tx.Table("custom_table")
}).Session(&gorm.Session{})
db.AutoMigrate(&User{})
if db.Find(&User{}).Statement.Table != "custom_table" {
t.Errorf("failed to call Scopes")
}
result := DB.Scopes(NameIn1And2, func(tx *gorm.DB) *gorm.DB {
return tx.Session(&gorm.Session{})
}).Find(&users1)
if result.RowsAffected != 2 {
t.Errorf("Should found two users's name in 1, 2, but got %v", result.RowsAffected)
}
var maxId int64
userTable := func(db *gorm.DB) *gorm.DB {
return db.WithContext(context.Background()).Table("users")
}
if err := DB.Scopes(userTable).Select("max(id)").Scan(&maxId).Error; err != nil {
t.Errorf("select max(id)")
}
}
| NameIn |
pytest_doctest.py | import py
class DoctestPlugin:
def pytest_addoption(self, parser):
parser.addoption("--doctest-modules",
action="store_true", default=False,
dest="doctestmodules")
def pytest_collect_file(self, path, parent):
if path.ext == ".py":
if parent.config.getvalue("doctestmodules"):
return DoctestModule(path, parent)
if path.check(fnmatch="test_*.txt"):
return DoctestTextfile(path, parent)
from py.__.code.excinfo import Repr, ReprFileLocation
class ReprFailDoctest(Repr):
def __init__(self, reprlocation, lines):
self.reprlocation = reprlocation
self.lines = lines
def toterminal(self, tw):
for line in self.lines:
tw.line(line)
self.reprlocation.toterminal(tw)
class DoctestItem(py.test.collect.Item):
def __init__(self, path, parent):
name = self.__class__.__name__ + ":" + path.basename
super(DoctestItem, self).__init__(name=name, parent=parent)
self.fspath = path
def repr_failure(self, excinfo, outerr):
if excinfo.errisinstance(py.compat.doctest.DocTestFailure):
doctestfailure = excinfo.value
example = doctestfailure.example
test = doctestfailure.test
filename = test.filename
lineno = example.lineno + 1
message = excinfo.type.__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = py.compat.doctest.OutputChecker()
REPORT_UDIFF = py.compat.doctest.REPORT_UDIFF
filelines = py.path.local(filename).readlines(cr=0)
i = max(0, lineno - 10)
lines = []
for line in filelines[i:lineno]:
lines.append("%03d %s" % (i+1, line))
i += 1
lines += checker.output_difference(example,
doctestfailure.got, REPORT_UDIFF).split("\n")
return ReprFailDoctest(reprlocation, lines)
elif excinfo.errisinstance(py.compat.doctest.UnexpectedException):
excinfo = py.code.ExceptionInfo(excinfo.value.exc_info)
return super(DoctestItem, self).repr_failure(excinfo, outerr)
else:
return super(DoctestItem, self).repr_failure(excinfo, outerr)
class DoctestTextfile(DoctestItem):
def runtest(self):
if not self._deprecated_testexecution():
failed, tot = py.compat.doctest.testfile(
str(self.fspath), module_relative=False,
raise_on_error=True, verbose=0)
class DoctestModule(DoctestItem):
def runtest(self):
module = self.fspath.pyimport()
failed, tot = py.compat.doctest.testmod(
module, raise_on_error=True, verbose=0)
#
# Plugin tests
#
class TestDoctests:
def test_collect_testtextfile(self, testdir):
testdir.plugins.append(DoctestPlugin())
testdir.maketxtfile(whatever="")
checkfile = testdir.maketxtfile(test_something="""
alskdjalsdk
>>> i = 5
>>> i-1
4
""")
for x in (testdir.tmpdir, checkfile):
#print "checking that %s returns custom items" % (x,)
items, events = testdir.inline_genitems(x)
print events.events
assert len(items) == 1
assert isinstance(items[0], DoctestTextfile)
def test_collect_module(self, testdir):
testdir.plugins.append(DoctestPlugin())
path = testdir.makepyfile(whatever="#")
for p in (path, testdir.tmpdir):
items, evrec = testdir.inline_genitems(p, '--doctest-modules')
print evrec.events
assert len(items) == 1
assert isinstance(items[0], DoctestModule)
def test_simple_doctestfile(self, testdir):
testdir.plugins.append(DoctestPlugin())
p = testdir.maketxtfile(test_doc="""
>>> x = 1
>>> x == 1
False
""")
events = testdir.inline_run(p)
ev, = events.getnamed("itemtestreport")
assert ev.failed
def test_doctest_unexpected_exception(self, testdir):
from py.__.test.outcome import Failed
testdir.plugins.append(DoctestPlugin())
p = testdir.maketxtfile("""
>>> i = 0
>>> i = 1
>>> x
2
""")
sorter = testdir.inline_run(p)
events = sorter.getnamed("itemtestreport")
assert len(events) == 1
ev, = events
assert ev.failed
assert ev.longrepr
# XXX
#testitem, = items
#excinfo = py.test.raises(Failed, "testitem.runtest()")
#repr = testitem.repr_failure(excinfo, ("", ""))
#assert repr.reprlocation
def test_doctestmodule(self, testdir):
testdir.plugins.append(DoctestPlugin())
p = testdir.makepyfile("""
'''
>>> x = 1
>>> x == 1
False | ev, = events.getnamed("itemtestreport")
assert ev.failed
def test_txtfile_failing(self, testdir):
testdir.plugins.append('pytest_doctest')
p = testdir.maketxtfile("""
>>> i = 0
>>> i + 1
2
""")
result = testdir.runpytest(p)
result.stdout.fnmatch_lines([
'001 >>> i = 0',
'002 >>> i + 1',
'Expected:',
" 2",
"Got:",
" 1",
"*test_txtfile_failing.txt:2: DocTestFailure"
])
def test_generic(plugintester):
plugintester.apicheck(DoctestPlugin) |
'''
""")
events = testdir.inline_run(p, "--doctest-modules") |
fetch_cast_html.py | from urllib.request import FancyURLopener
from bs4 import BeautifulSoup
from random import choice
import csv
from time import sleep
from urllib.parse import quote,unquote
import json
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9'
]
class MyOpener(FancyURLopener, object):
|
myopener = MyOpener()
def _ids():
with open("meta_final.csv", 'r') as infile:
tv_reader = csv.reader(infile)
next(tv_reader)
return list(map(lambda x : x[-1], tv_reader))
def fetch_cast_data():
for index, _id in enumerate(_ids()):
print (index)
url ='http://www.imdb.com/title/{}/fullcredits?ref_=tt_ql_1'.format(_id)
try:
html = myopener.open(url).read()
except:
html = "error"
with open('data/' + _id + '.html', 'wb') as outfile:
outfile.write(html)
sleep(.5)
fetch_cast_data() | version = choice(user_agents) |
add-post.js | async function | (event) {
event.preventDefault();
const title = document.querySelector('#title').value.trim();
const post_text = document.querySelector('#post_text').value.trim();
const response = await fetch(`/api/posts`, {
method: 'POST',
body: JSON.stringify({
title,
post_text
}),
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
document.location.replace('/');
} else {
alert(response.statusText);
}
}
document.querySelector('.new-post-form').addEventListener('submit', newFormHandler); | newFormHandler |
node.rs | use std::{
ffi::CStr,
fmt,
os::raw::{c_char, c_float, c_long, c_short, c_uchar, c_uint, c_ushort},
slice, str,
};
#[repr(C)]
pub struct Path {
_private: [u8; 0],
}
/// # Safety
/// This struct is UB to have a mutable reference to, because if has self-recursion
#[repr(C)]
pub struct Node<'a> {
// prev: *mut raw_node,
pub prev: Option<&'a Node<'a>>,
// next: *mut raw_node,
pub next: Option<&'a Node<'a>>,
// enext: *mut raw_node,
pub enext: Option<&'a Node<'a>>,
// bnext: *mut raw_node,
pub bnext: Option<&'a Node<'a>>,
rpath: *const Path,
lpath: *const Path,
// invariant: must be a valid pointer to "some bytes"
surface: *const c_char,
feature: *const c_char,
id: c_uint,
length: c_ushort,
rlength: c_ushort,
rcattr: c_ushort,
lcattr: c_ushort,
posid: c_ushort,
char_type: c_uchar,
stat: c_uchar,
isbest: c_uchar,
alpha: c_float,
beta: c_float,
prob: c_float,
wcost: c_short,
cost: c_long,
}
impl<'a> Node<'a> {
/// The visible surface of this node
/// # Panics
/// If the `surface` string isn't a valid UTF-8 string.
pub fn surface(&self) -> &'a str {
// Safety: Library invariant says that this *must* be a valid slice.
let bytes = unsafe { slice::from_raw_parts(self.surface as *const u8, self.length.into()) };
str::from_utf8(bytes).expect("surface was not utf-8")
}
/// The surface of this node, including proceeding whitespace
///
/// # Panics
/// If the `surface` string + the proceeding whitespace isn't a valid UTF-8 string.
pub fn full_surface(&self) -> &'a str {
let offset: usize = (self.rlength - self.length).into();
// Safety: FFI invariant says `rlength - length` gives a prefix, which must be part of the same alloc.
let ptr = unsafe { self.surface.sub(offset) as *const u8 };
// Safety: Library invariant says that this *must* be a valid slice.
// we use rlength here because `-(rlength - length) + rlength = length`
let bytes = unsafe { slice::from_raw_parts(ptr, self.rlength.into()) };
str::from_utf8(bytes).expect("surface was not utf-8")
}
/// The proceeding whitespace to this node's surface.
///
/// # Panics
/// If the proceeding whitespace isn't a valid UTF-8 string.
pub fn whitespace(&self) -> &'a str {
let offset: usize = (self.rlength - self.length).into();
// Safety: FFI invariant says `rlength - length` gives a prefix, which must be part of the same alloc.
let ptr = unsafe { self.surface.sub(offset) as *const u8 };
// Safety: Library invariant says that this *must* be a valid slice.
// we use offsest here because we want the string that *ends* where the `surface` begins.
let bytes = unsafe { slice::from_raw_parts(ptr, offset) };
str::from_utf8(bytes).expect("surface was not utf-8")
}
/// The node's feature string (as a CStr)
#[inline(always)]
pub fn feature_cstr(&self) -> &CStr {
// Safety: self.feature *is* a CStr.
unsafe { CStr::from_ptr(self.feature) }
}
pub fn feature(&self) -> &str {
self.feature_cstr().to_str().expect("feature was not valid UTF-8")
}
#[inline(always)]
pub fn id(&self) -> u32 {
self.id.into()
}
// don't bother exposing `length` and `rlength` (they're visible via various `surface` functions and that's about their only use)
/// note: This doesn't seem to actually be useful, it's exposed because it probably exists for *some reason*
#[inline(always)]
pub fn rcattr(&self) -> u16 {
self.rcattr.into()
}
/// note: This doesn't seem to actually be useful, it's exposed because it probably exists for *some reason*
#[inline(always)]
pub fn lcattr(&self) -> u16 {
self.lcattr.into()
}
/// The ID for the part of speech that this node uses.
/// note: This doesn't seem to actually be useful, it's exposed because it probably exists for *some reason*
pub fn pos_id(&self) -> u16 {
self.posid.into()
}
/// This node's character type.
pub fn char_type(&self) -> u8 {
self.char_type.into()
}
/// status of this `Node`.
pub fn stat(&self) -> NodeStat {
match self.stat {
0 => NodeStat::Normal,
1 => NodeStat::Unknown,
2 => NodeStat::BOS,
3 => NodeStat::EOS,
4 => NodeStat::EON,
_ => panic!("Unknown node stat type"),
}
}
#[inline(always)]
pub fn is_best(&self) -> bool {
self.isbest != 0
}
/// forward accumulative log summation.
/// This value is only available when MECAB_MARGINAL_PROB is passed.
#[inline(always)]
pub fn alpha(&self) -> f32 {
self.alpha
}
/// backward accumulative log summation.
/// This value is only available when MECAB_MARGINAL_PROB is passed.
#[inline(always)]
pub fn beta(&self) -> f32 |
/// marginal probability.
/// This value is only available when MECAB_MARGINAL_PROB is passed.
#[inline(always)]
pub fn prob(&self) -> f32 {
self.prob
}
#[inline(always)]
pub fn word_cost(&self) -> i16 {
self.wcost.into()
}
#[inline(always)]
pub fn cost(&self) -> i64 {
self.cost.into()
}
pub fn iter_prev(&'a self) -> NodeIter<'a> {
NodeIter { current: Some(self), mode: Mode::PREV }
}
pub fn iter_next(&'a self) -> NodeIter<'a> {
NodeIter { current: Some(self), mode: Mode::NEXT }
}
pub fn iter_enext(&'a self) -> NodeIter<'a> {
NodeIter { current: Some(self), mode: Mode::ENEXT }
}
pub fn iter_bnext(&'a self) -> NodeIter<'a> {
NodeIter { current: Some(self), mode: Mode::BNEXT }
}
}
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum NodeStat {
/// Normal node defined in the dictionary.
/// MECAB_NOR_NODE
Normal = 0,
/// Unknown node not defined in the dictionary.
/// MECAB_UNK_NODE
Unknown = 1,
/// Virtual node representing a beginning of the sentence.
/// MECAB_BOS_NODE
BOS = 2,
/// Virtual node representing a end of the sentence.
/// MECAB_EOS_NODE
EOS = 3,
/// Virtual node representing a beginning of the sentence.
/// MECAB_EON_NODE
EON = 4,
}
impl NodeStat {
const fn as_str(self) -> &'static str {
match self {
Self::Normal => "MECAB_NOR_NODE",
Self::Unknown => "MECAB_UNK_NODE",
Self::BOS => "MECAB_BOS_NODE",
Self::EOS => "MECAB_EOS_NODE",
Self::EON => "MECAB_EON_NODE",
}
}
}
impl fmt::Display for NodeStat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
enum Mode {
NEXT,
PREV,
ENEXT,
BNEXT,
}
pub struct NodeIter<'a> {
current: Option<&'a Node<'a>>,
mode: Mode,
}
impl<'a> Iterator for NodeIter<'a> {
type Item = &'a Node<'a>;
fn next(&mut self) -> Option<Self::Item> {
let old = self.current.take()?;
self.current = match self.mode {
Mode::NEXT => old.next,
Mode::PREV => old.prev,
Mode::ENEXT => old.enext,
Mode::BNEXT => old.bnext,
};
Some(old)
}
}
| {
self.beta
} |
html_test.go | package util
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestStripTags(t *testing.T) | {
Convey("测试HTML标签过滤", t, func() {
s := []byte("啊<div class=\"a\">是<span>打</span><!--注释-->发<img src=\"http://asf.jpg\">是<br /></div>")
So(string(KeepTags(s)), ShouldEqual, "啊是打发是")
So(string(KeepTags(s, "br", "div")), ShouldEqual, "啊<div class=\"a\">是打发是<br /></div>")
So(string(StripTags(s)), ShouldEqual, string(s))
So(string(StripTags(s, "br", "div")), ShouldEqual, `啊是<span>打</span><!--注释-->发<img src="http://asf.jpg">是`)
})
}
|
|
applySubstructure_cff.py | import FWCore.ParameterSet.Config as cms
from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask, addToProcessAndTask
def | ( process, postfix="" ) :
task = getPatAlgosToolsTask(process)
from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault
# Configure the RECO jets
from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
from RecoJets.JetProducers.ak8PFJets_cfi import ak8PFJetsPuppi, ak8PFJetsPuppiSoftDrop, ak8PFJetsPuppiConstituents, ak8PFJetsCHSConstituents
from RecoJets.JetProducers.ak8GenJets_cfi import ak8GenJets, ak8GenJetsSoftDrop, ak8GenJetsConstituents
addToProcessAndTask('ak4PFJetsPuppi'+postfix,ak4PFJetsPuppi.clone(), process, task)
addToProcessAndTask('ak8PFJetsPuppi'+postfix,ak8PFJetsPuppi.clone(), process, task)
addToProcessAndTask('ak8PFJetsPuppiConstituents', ak8PFJetsPuppiConstituents.clone(cut = cms.string('pt > 170.0 && abs(rapidity()) < 2.4') ), process, task )
addToProcessAndTask('ak8PFJetsCHSConstituents', ak8PFJetsCHSConstituents.clone(), process, task )
addToProcessAndTask('ak8PFJetsPuppiSoftDrop'+postfix, ak8PFJetsPuppiSoftDrop.clone( src = cms.InputTag('ak8PFJetsPuppiConstituents', 'constituents') ), process, task)
addToProcessAndTask('ak8GenJetsNoNuConstituents'+postfix, ak8GenJetsConstituents.clone(src='ak8GenJetsNoNu'), process, task )
addToProcessAndTask('ak8GenJetsNoNuSoftDrop'+postfix,ak8GenJetsSoftDrop.clone(src=cms.InputTag('ak8GenJetsNoNuConstituents'+postfix, 'constituents')),process,task)
addToProcessAndTask('slimmedGenJetsAK8SoftDropSubJets'+postfix,
cms.EDProducer("PATGenJetSlimmer",
src = cms.InputTag("ak8GenJetsNoNuSoftDrop"+postfix, "SubJets"),
packedGenParticles = cms.InputTag("packedGenParticles"),
cut = cms.string(""),
cutLoose = cms.string(""),
nLoose = cms.uint32(0),
clearDaughters = cms.bool(False), #False means rekeying
dropSpecific = cms.bool(True), # Save space
), process, task )
#add AK8 CHS
addJetCollection(process, postfix=postfix, labelName = 'AK8',
jetSource = cms.InputTag('ak8PFJetsCHS'+postfix),
algo= 'AK', rParam = 0.8,
btagDiscriminators = ['None'],
jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
genJetCollection = cms.InputTag('slimmedGenJetsAK8')
)
getattr(process,"patJetsAK8"+postfix).userData.userFloats.src = [] # start with empty list of user floats
getattr(process,"selectedPatJetsAK8").cut = cms.string("pt > 170")
## add AK8 groomed masses with CHS
from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop
addToProcessAndTask('ak8PFJetsCHSPruned'+postfix, ak8PFJetsCHSPruned.clone(), process, task)
addToProcessAndTask('ak8PFJetsCHSSoftDrop'+postfix, ak8PFJetsCHSSoftDrop.clone(), process, task)
from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSSoftDropMass
addToProcessAndTask('ak8PFJetsCHSPrunedMass'+postfix, ak8PFJetsCHSPrunedMass.clone(), process, task)
addToProcessAndTask('ak8PFJetsCHSTrimmedMass'+postfix, ak8PFJetsCHSTrimmedMass.clone(), process, task)
addToProcessAndTask('ak8PFJetsCHSFilteredMass'+postfix, ak8PFJetsCHSFilteredMass.clone(), process, task)
addToProcessAndTask('ak8PFJetsCHSSoftDropMass'+postfix, ak8PFJetsCHSSoftDropMass.clone(), process, task)
getattr(process,"patJetsAK8").userData.userFloats.src += ['ak8PFJetsCHSPrunedMass'+postfix,'ak8PFJetsCHSSoftDropMass'+postfix]
getattr(process,"patJetsAK8").addTagInfos = cms.bool(False)
# add Njetiness for CHS
process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
task.add(process.Njettiness)
addToProcessAndTask('NjettinessAK8'+postfix, process.Njettiness.clone(), process, task)
getattr(process,"NjettinessAK8").src = cms.InputTag("ak8PFJetsCHS"+postfix)
getattr(process,"NjettinessAK8").cone = cms.double(0.8)
getattr(process,"patJetsAK8").userData.userFloats.src += ['NjettinessAK8'+postfix+':tau1','NjettinessAK8'+postfix+':tau2','NjettinessAK8'+postfix+':tau3','NjettinessAK8'+postfix+':tau4']
# add Njetiness from CHS
addToProcessAndTask('NjettinessAK8Subjets'+postfix, process.Njettiness.clone(), process, task)
getattr(process,"NjettinessAK8Subjets"+postfix).src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")
getattr(process,"NjettinessAK8Subjets").cone = cms.double(0.8)
## PATify CHS soft drop fat jets
addJetCollection(
process,
postfix=postfix,
labelName = 'AK8PFCHSSoftDrop',
jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop'+postfix),
btagDiscriminators = ['None'],
jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
getJetMCFlavour = False # jet flavor disabled
)
#add RECO AK8 from PUPPI and RECO AK8 PUPPI with soft drop... will be needed by ungroomed AK8 jets later
## PATify puppi soft drop fat jets
addJetCollection(
process,
postfix=postfix,
labelName = 'AK8PFPuppiSoftDrop' + postfix,
jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix),
btagDiscriminators = ['None'],
genJetCollection = cms.InputTag('slimmedGenJetsAK8'),
jetCorrections = ('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
getJetMCFlavour = False # jet flavor disabled
)
## PATify soft drop subjets
addJetCollection(
process,
postfix=postfix,
labelName = 'AK8PFPuppiSoftDropSubjets',
jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix,'SubJets'),
algo = 'ak', # needed for subjet flavor clustering
rParam = 0.8, # needed for subjet flavor clustering
btagDiscriminators = ['pfDeepCSVJetTags:probb', 'pfDeepCSVJetTags:probbb', 'pfCombinedInclusiveSecondaryVertexV2BJetTags','pfCombinedMVAV2BJetTags'],
jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
explicitJTA = True, # needed for subjet b tagging
svClustering = True, # needed for subjet b tagging
genJetCollection = cms.InputTag('slimmedGenJetsAK8SoftDropSubJets'),
fatJets=cms.InputTag('ak8PFJetsPuppi'), # needed for subjet flavor clustering
groomedFatJets=cms.InputTag('ak8PFJetsPuppiSoftDrop') # needed for subjet flavor clustering
)
# add groomed ECFs and N-subjettiness to soft dropped pat::Jets for fat jets and subjets
process.load('RecoJets.JetProducers.ECF_cff')
addToProcessAndTask('nb1AK8PuppiSoftDrop'+postfix, process.ecfNbeta1.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix), cuts = cms.vstring('', '', 'pt > 250')), process, task)
addToProcessAndTask('nb2AK8PuppiSoftDrop'+postfix, process.ecfNbeta2.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix), cuts = cms.vstring('', '', 'pt > 250')), process, task)
#too slow now ==> disable
from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018
from Configuration.Eras.Modifier_pp_on_XeXe_2017_cff import pp_on_XeXe_2017
from Configuration.Eras.Modifier_phase2_common_cff import phase2_common
for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
e.toModify(getattr(process,'nb1AK8PuppiSoftDrop'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
e.toModify(getattr(process,'nb2AK8PuppiSoftDrop'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
getattr(process,"patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += ['nb1AK8PuppiSoftDrop'+postfix+':ecfN2','nb1AK8PuppiSoftDrop'+postfix+':ecfN3']
getattr(process,"patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += ['nb2AK8PuppiSoftDrop'+postfix+':ecfN2','nb2AK8PuppiSoftDrop'+postfix+':ecfN3']
addToProcessAndTask('nb1AK8PuppiSoftDropSubjets'+postfix, process.ecfNbeta1.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")), process, task)
addToProcessAndTask('nb2AK8PuppiSoftDropSubjets'+postfix, process.ecfNbeta2.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")), process, task)
getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['nb1AK8PuppiSoftDropSubjets'+postfix+':ecfN2','nb1AK8PuppiSoftDropSubjets'+postfix+':ecfN3']
getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['nb2AK8PuppiSoftDropSubjets'+postfix+':ecfN2','nb2AK8PuppiSoftDropSubjets'+postfix+':ecfN3']
getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['NjettinessAK8Subjets'+postfix+':tau1','NjettinessAK8Subjets'+postfix+':tau2','NjettinessAK8Subjets'+postfix+':tau3','NjettinessAK8Subjets'+postfix+':tau4']
for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
e.toModify(getattr(process,'nb1AK8PuppiSoftDropSubjets'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
e.toModify(getattr(process,'nb2AK8PuppiSoftDropSubjets'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
# rekey the groomed ECF value maps to the ungroomed reco jets, which will then be picked
# up by PAT in the user floats.
addToProcessAndTask("ak8PFJetsPuppiSoftDropValueMap"+postfix,
cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
src = cms.InputTag("ak8PFJetsPuppi"+postfix),
matched = cms.InputTag("patJetsAK8PFPuppiSoftDrop"+postfix),
distMax = cms.double(0.8),
values = cms.vstring([
'userFloat("nb1AK8PuppiSoftDrop'+postfix+':ecfN2")',
'userFloat("nb1AK8PuppiSoftDrop'+postfix+':ecfN3")',
'userFloat("nb2AK8PuppiSoftDrop'+postfix+':ecfN2")',
'userFloat("nb2AK8PuppiSoftDrop'+postfix+':ecfN3")',
]),
valueLabels = cms.vstring( [
'nb1AK8PuppiSoftDropN2',
'nb1AK8PuppiSoftDropN3',
'nb2AK8PuppiSoftDropN2',
'nb2AK8PuppiSoftDropN3',
]) ),
process, task)
# Patify AK8 PF PUPPI
addJetCollection(process, postfix=postfix, labelName = 'AK8Puppi',
jetSource = cms.InputTag('ak8PFJetsPuppi'+postfix),
algo= 'AK', rParam = 0.8,
jetCorrections = ('AK8PFPuppi', cms.vstring(['L2Relative', 'L3Absolute']), 'None'),
btagDiscriminators = ([
'pfCombinedSecondaryVertexV2BJetTags',
'pfCombinedInclusiveSecondaryVertexV2BJetTags',
'pfCombinedMVAV2BJetTags',
'pfDeepCSVJetTags:probb',
'pfDeepCSVJetTags:probc',
'pfDeepCSVJetTags:probudsg',
'pfDeepCSVJetTags:probbb',
'pfBoostedDoubleSecondaryVertexAK8BJetTags']),
genJetCollection = cms.InputTag('slimmedGenJetsAK8')
)
getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src = [] # start with empty list of user floats
getattr(process,"selectedPatJetsAK8Puppi"+postfix).cut = cms.string("pt > 100")
getattr(process,"selectedPatJetsAK8Puppi"+postfix).cutLoose = cms.string("pt > 30")
getattr(process,"selectedPatJetsAK8Puppi"+postfix).nLoose = cms.uint32(3)
from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
addToProcessAndTask('ak8PFJetsPuppiTracksAssociatorAtVertex'+postfix, cms.EDProducer("JetTracksAssociatorAtVertex",
j2tParametersVX.clone( coneSize = cms.double(0.8) ),
jets = cms.InputTag("ak8PFJetsPuppi") ),
process, task)
addToProcessAndTask('patJetAK8PuppiCharge'+postfix, cms.EDProducer("JetChargeProducer",
src = cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
var = cms.string('Pt'),
exp = cms.double(1.0) ),
process, task)
## now add AK8 groomed masses and ECF
from RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi import ak8PFJetsPuppiSoftDropMass
addToProcessAndTask('ak8PFJetsPuppiSoftDropMass'+postfix, ak8PFJetsPuppiSoftDropMass.clone(), process, task)
getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += ['ak8PFJetsPuppiSoftDropMass'+postfix]
getattr(process,"patJetsAK8Puppi"+postfix).addTagInfos = cms.bool(False)
getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += [
cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb1AK8PuppiSoftDropN2'),
cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb1AK8PuppiSoftDropN3'),
cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb2AK8PuppiSoftDropN2'),
cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb2AK8PuppiSoftDropN3'),
]
# add PUPPI Njetiness
addToProcessAndTask('NjettinessAK8Puppi'+postfix, process.Njettiness.clone(), process, task)
getattr(process,"NjettinessAK8Puppi"+postfix).src = cms.InputTag("ak8PFJetsPuppi"+postfix)
getattr(process,"NjettinessAK8Puppi").cone = cms.double(0.8)
getattr(process,"patJetsAK8Puppi").userData.userFloats.src += ['NjettinessAK8Puppi'+postfix+':tau1','NjettinessAK8Puppi'+postfix+':tau2','NjettinessAK8Puppi'+postfix+':tau3','NjettinessAK8Puppi'+postfix+':tau4']
# Now combine the CHS and PUPPI information into the PUPPI jets via delta R value maps
addToProcessAndTask("ak8PFJetsCHSValueMap"+postfix, cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
src = cms.InputTag("ak8PFJetsPuppi"+postfix),
matched = cms.InputTag("patJetsAK8"+postfix),
distMax = cms.double(0.8),
values = cms.vstring([
'userFloat("ak8PFJetsCHSPrunedMass"'+postfix+')',
'userFloat("ak8PFJetsCHSSoftDropMass"'+postfix+')',
'userFloat("NjettinessAK8'+postfix+':tau1")',
'userFloat("NjettinessAK8'+postfix+':tau2")',
'userFloat("NjettinessAK8'+postfix+':tau3")',
'userFloat("NjettinessAK8'+postfix+':tau4")',
'pt','eta','phi','mass', 'jetArea', 'jecFactor(0)'
]),
valueLabels = cms.vstring( [
'ak8PFJetsCHSPrunedMass',
'ak8PFJetsCHSSoftDropMass',
'NjettinessAK8CHSTau1',
'NjettinessAK8CHSTau2',
'NjettinessAK8CHSTau3',
'NjettinessAK8CHSTau4',
'pt','eta','phi','mass', 'jetArea', 'rawFactor'
]) ),
process, task)
# Now set up the user floats
getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += [
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSPrunedMass'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSSoftDropMass'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau1'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau2'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau3'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau4'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'pt'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'eta'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'phi'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'mass'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'jetArea'),
cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'rawFactor'),
]
addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropSubjets"+postfix,
cms.EDProducer("PATJetSlimmer",
src = cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
packedPFCandidates = cms.InputTag("packedPFCandidates"),
dropJetVars = cms.string("1"),
dropDaughters = cms.string("0"),
rekeyDaughters = cms.string("1"),
dropTrackRefs = cms.string("1"),
dropSpecific = cms.string("1"),
dropTagInfos = cms.string("1"),
modifyJets = cms.bool(True),
mixedDaughters = cms.bool(False),
modifierConfig = cms.PSet( modifications = cms.VPSet() )
),
process, task)
## Establish references between PATified fat jets and subjets using the BoostedJetMerger
addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix,
cms.EDProducer("BoostedJetMerger",
jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")
),
process, task )
addToProcessAndTask("packedPatJetsAK8"+postfix, cms.EDProducer("JetSubstructurePacker",
jetSrc = cms.InputTag("selectedPatJetsAK8Puppi"+postfix),
distMax = cms.double(0.8),
algoTags = cms.VInputTag(
cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix)
),
algoLabels = cms.vstring(
'SoftDropPuppi'
),
fixDaughters = cms.bool(True),
packedPFCandidates = cms.InputTag("packedPFCandidates"+postfix),
),
process, task)
# switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
process.slimmedJetsAK8.rekeyDaughters = "0"
# Reconfigure the slimmedAK8 jet information to keep
process.slimmedJetsAK8.dropDaughters = cms.string("pt < 170")
process.slimmedJetsAK8.dropSpecific = cms.string("pt < 170")
process.slimmedJetsAK8.dropTagInfos = cms.string("pt < 170")
| applySubstructure |
transaction.go | package model
import (
"encoding/json"
"fmt"
"github.com/go-playground/validator/v10"
)
type Transaction struct {
ID string `json:"id" validate:"required,uuid4"`
AccountID string `json:"accountId" validate:"required,uuid4"`
Amount float64 `json:"amount" validate:"required,numeric"`
PixKeyTo string `json:"pixKeyTo" validate:"required"`
PixKeyKindTo string `json:"pixKeyKindTo" validate:"required"`
Description string `json:"description" validate:"required"`
Status string `json:"status" validate:"-"`
Error string `json:"error"`
}
func (t *Transaction) isValid() error {
v := validator.New()
err := v.Struct(t)
if err != nil {
fmt.Errorf("Error during Transaction validation: %s", err.Error())
return err
}
return nil
}
func (t *Transaction) ParseJson(data []byte) error {
err := json.Unmarshal(data, t)
if err != nil {
return err
}
err = t.isValid()
if err != nil {
return err
}
return nil
}
func (t *Transaction) ToJson() ([]byte, error) {
err := t.isValid()
if err != nil {
return nil, err
}
result, err := json.Marshal(t)
if err != nil {
return nil, nil
}
return result, nil
}
func | () *Transaction {
return &Transaction{}
}
| NewTransaction |
iterator.rs | // ignore-tidy-filelength
// This file almost exclusively consists of the definition of `Iterator`. We
// can't split that into multiple files.
use crate::cmp::{self, Ordering};
use crate::ops::{ControlFlow, Try};
use super::super::TrustedRandomAccess;
use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
use super::super::{FlatMap, Flatten};
use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip};
use super::super::{
Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
};
fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
/// An interface for dealing with iterators.
///
/// This is the main iterator trait. For more about the concept of iterators
/// generally, please see the [module-level documentation]. In particular, you
/// may want to know how to [implement `Iterator`][impl].
///
/// [module-level documentation]: crate::iter
/// [impl]: crate::iter#implementing-iterator
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented(
on(
_Self = "[std::ops::Range<Idx>; 1]",
label = "if you meant to iterate between two values, remove the square brackets",
note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
without the brackets: `start..end`"
),
on(
_Self = "[std::ops::RangeFrom<Idx>; 1]",
label = "if you meant to iterate from a value onwards, remove the square brackets",
note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
`RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
unbounded iterator will run forever unless you `break` or `return` from within the \
loop"
),
on(
_Self = "[std::ops::RangeTo<Idx>; 1]",
label = "if you meant to iterate until a value, remove the square brackets and add a \
starting value",
note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
`Range` without the brackets: `0..end`"
),
on(
_Self = "[std::ops::RangeInclusive<Idx>; 1]",
label = "if you meant to iterate between two values, remove the square brackets",
note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
`RangeInclusive` without the brackets: `start..=end`"
),
on(
_Self = "[std::ops::RangeToInclusive<Idx>; 1]",
label = "if you meant to iterate until a value (including it), remove the square brackets \
and add a starting value",
note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
bounded `RangeInclusive` without the brackets: `0..=end`"
),
on(
_Self = "std::ops::RangeTo<Idx>",
label = "if you meant to iterate until a value, add a starting value",
note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
bounded `Range`: `0..end`"
),
on(
_Self = "std::ops::RangeToInclusive<Idx>",
label = "if you meant to iterate until a value (including it), add a starting value",
note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
to have a bounded `RangeInclusive`: `0..=end`"
),
on(
_Self = "&str",
label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self = "std::string::String",
label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self = "[]",
label = "arrays do not yet implement `IntoIterator`; try using `std::array::IntoIter::new(arr)`",
note = "see <https://github.com/rust-lang/rust/pull/65819> for more details"
),
on(
_Self = "{integral}",
note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
syntax `start..end` or the inclusive range syntax `start..=end`"
),
label = "`{Self}` is not an iterator",
message = "`{Self}` is not an iterator"
)]
#[cfg_attr(bootstrap, doc(spotlight))]
#[cfg_attr(not(bootstrap), doc(notable_trait))]
#[rustc_diagnostic_item = "Iterator"]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub trait Iterator {
/// The type of the elements being iterated over.
#[stable(feature = "rust1", since = "1.0.0")]
type Item;
/// Advances the iterator and returns the next value.
///
/// Returns [`None`] when iteration is finished. Individual iterator
/// implementations may choose to resume iteration, and so calling `next()`
/// again may or may not eventually start returning [`Some(Item)`] again at some
/// point.
///
/// [`Some(Item)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// // A call to next() returns the next value...
/// assert_eq!(Some(&1), iter.next());
/// assert_eq!(Some(&2), iter.next());
/// assert_eq!(Some(&3), iter.next());
///
/// // ... and then None once it's over.
/// assert_eq!(None, iter.next());
///
/// // More calls may or may not return `None`. Here, they always will.
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next());
/// ```
#[lang = "next"]
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<Self::Item>;
/// Returns the bounds on the remaining length of the iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that an iterator implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns `(0, `[`None`]`)` which is correct for any
/// iterator.
///
/// [`usize`]: type@usize
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let iter = a.iter();
///
/// assert_eq!((3, Some(3)), iter.size_hint());
/// ```
///
/// A more complex example:
///
/// ```
/// // The even numbers from zero to ten.
/// let iter = (0..10).filter(|x| x % 2 == 0);
///
/// // We might iterate from zero to ten times. Knowing that it's five
/// // exactly wouldn't be possible without executing filter().
/// assert_eq!((0, Some(10)), iter.size_hint());
///
/// // Let's add five more numbers with chain()
/// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
///
/// // now both bounds are increased by five
/// assert_eq!((5, Some(15)), iter.size_hint());
/// ```
///
/// Returning `None` for an upper bound:
///
/// ```
/// // an infinite iterator has no upper bound
/// // and the maximum possible lower bound
/// let iter = 0..;
///
/// assert_eq!((usize::MAX, None), iter.size_hint());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
/// Consumes the iterator, counting the number of iterations and returning it.
///
/// This method will call [`next`] repeatedly until [`None`] is encountered,
/// returning the number of times it saw [`Some`]. Note that [`next`] has to be
/// called at least once even if the iterator does not have any elements.
///
/// [`next`]: Iterator::next
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so counting elements of
/// an iterator with more than [`usize::MAX`] elements either produces the
/// wrong result or panics. If debug assertions are enabled, a panic is
/// guaranteed.
///
/// # Panics
///
/// This function might panic if the iterator has more than [`usize::MAX`]
/// elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().count(), 3);
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().count(), 5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn count(self) -> usize
where
Self: Sized,
{
self.fold(
0,
#[rustc_inherit_overflow_checks]
|count, _| count + 1,
)
}
/// Consumes the iterator, returning the last element.
///
/// This method will evaluate the iterator until it returns [`None`]. While
/// doing so, it keeps track of the current element. After [`None`] is
/// returned, `last()` will then return the last element it saw.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().last(), Some(&3));
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().last(), Some(&5));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
#[inline]
fn some<T>(_: Option<T>, x: T) -> Option<T> {
Some(x)
}
self.fold(None, some)
}
/// Advances the iterator by `n` elements.
///
/// This method will eagerly skip `n` elements by calling [`next`] up to `n`
/// times until [`None`] is encountered.
///
/// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
/// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
/// of elements the iterator is advanced by before running out of elements (i.e. the
/// length of the iterator). Note that `k` is always less than `n`.
///
/// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
///
/// [`next`]: Iterator::next
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_advance_by)]
///
/// let a = [1, 2, 3, 4];
/// let mut iter = a.iter();
///
/// assert_eq!(iter.advance_by(2), Ok(()));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.advance_by(0), Ok(()));
/// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
/// ```
#[inline]
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
for i in 0..n {
self.next().ok_or(i)?;
}
Ok(())
}
/// Returns the `n`th element of the iterator.
///
/// Like most indexing operations, the count starts from zero, so `nth(0)`
/// returns the first value, `nth(1)` the second, and so on.
///
/// Note that all preceding elements, as well as the returned element, will be
/// consumed from the iterator. That means that the preceding elements will be
/// discarded, and also that calling `nth(0)` multiple times on the same iterator
/// will return different elements.
///
/// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
/// iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(1), Some(&2));
/// ```
///
/// Calling `nth()` multiple times doesn't rewind the iterator:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.nth(1), Some(&2));
/// assert_eq!(iter.nth(1), None);
/// ```
///
/// Returning `None` if there are less than `n + 1` elements:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(10), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.advance_by(n).ok()?;
self.next()
}
/// Creates an iterator starting at the same point, but stepping by
/// the given amount at each iteration.
///
/// Note 1: The first element of the iterator will always be returned,
/// regardless of the step given.
///
/// Note 2: The time at which ignored elements are pulled is not fixed.
/// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
/// but is also free to behave like the sequence
/// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
/// Which way is used may change for some iterators for performance reasons.
/// The second way will advance the iterator earlier and may consume more items.
///
/// `advance_n_and_return_first` is the equivalent of:
/// ```
/// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
/// where
/// I: Iterator,
/// {
/// let next = iter.next();
/// if total_step > 1 {
/// iter.nth(total_step-2);
/// }
/// next
/// }
/// ```
///
/// # Panics
///
/// The method will panic if the given step is `0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0, 1, 2, 3, 4, 5];
/// let mut iter = a.iter().step_by(2);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "iterator_step_by", since = "1.28.0")]
fn step_by(self, step: usize) -> StepBy<Self>
where
Self: Sized,
{
StepBy::new(self, step)
}
/// Takes two iterators and creates a new iterator over both in sequence.
///
/// `chain()` will return a new iterator which will first iterate over
/// values from the first iterator and then over values from the second
/// iterator.
///
/// In other words, it links two iterators together, in a chain. 🔗
///
/// [`once`] is commonly used to adapt a single value into a chain of
/// other kinds of iteration.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().chain(a2.iter());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `chain()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `chain()` directly:
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().chain(s2);
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
///
/// ```
/// #[cfg(windows)]
/// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
/// use std::os::windows::ffi::OsStrExt;
/// s.encode_wide().chain(std::iter::once(0)).collect()
/// }
/// ```
///
/// [`once`]: crate::iter::once
/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
where
Self: Sized,
U: IntoIterator<Item = Self::Item>,
{
Chain::new(self, other.into_iter())
}
/// 'Zips up' two iterators into a single iterator of pairs.
///
/// `zip()` returns a new iterator that will iterate over two other
/// iterators, returning a tuple where the first element comes from the
/// first iterator, and the second element comes from the second iterator.
///
/// In other words, it zips two iterators together, into a single one.
///
/// If either iterator returns [`None`], [`next`] from the zipped iterator
/// will return [`None`]. If the first iterator returns [`None`], `zip` will
/// short-circuit and `next` will not be called on the second iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().zip(a2.iter());
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `zip()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `zip()` directly:
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().zip(s2);
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `zip()` is often used to zip an infinite iterator to a finite one.
/// This works because the finite iterator will eventually return [`None`],
/// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
///
/// ```
/// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
///
/// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
///
/// assert_eq!((0, 'f'), enumerate[0]);
/// assert_eq!((0, 'f'), zipper[0]);
///
/// assert_eq!((1, 'o'), enumerate[1]);
/// assert_eq!((1, 'o'), zipper[1]);
///
/// assert_eq!((2, 'o'), enumerate[2]);
/// assert_eq!((2, 'o'), zipper[2]);
/// ```
///
/// [`enumerate`]: Iterator::enumerate
/// [`next`]: Iterator::next
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
where
Self: Sized,
U: IntoIterator,
{
Zip::new(self, other.into_iter())
}
/// Creates a new iterator which places a copy of `separator` between adjacent
/// items of the original iterator.
///
/// In case `separator` does not implement [`Clone`] or needs to be
/// computed every time, use [`intersperse_with`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_intersperse)]
///
/// let mut a = [0, 1, 2].iter().intersperse(&100);
/// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
/// assert_eq!(a.next(), Some(&100)); // The separator.
/// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
/// assert_eq!(a.next(), Some(&100)); // The separator.
/// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
/// assert_eq!(a.next(), None); // The iterator is finished.
/// ```
///
/// `intersperse` can be very useful to join an iterator's items using a common element:
/// ```
/// #![feature(iter_intersperse)]
///
/// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
/// assert_eq!(hello, "Hello World !");
/// ```
///
/// [`Clone`]: crate::clone::Clone
/// [`intersperse_with`]: Iterator::intersperse_with
#[inline]
#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
where
Self: Sized,
Self::Item: Clone,
{
Intersperse::new(self, separator)
}
/// Creates a new iterator which places an item generated by `separator`
/// between adjacent items of the original iterator.
///
/// The closure will be called exactly once each time an item is placed
/// between two adjacent items from the underlying iterator; specifically,
/// the closure is not called if the underlying iterator yields less than
/// two items and after the last item is yielded.
///
/// If the iterator's item implements [`Clone`], it may be easier to use
/// [`intersperse`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_intersperse)]
///
/// #[derive(PartialEq, Debug)]
/// struct NotClone(usize);
///
/// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
/// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
///
/// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
/// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
/// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
/// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
/// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
/// assert_eq!(it.next(), None); // The iterator is finished.
/// ```
///
/// `intersperse_with` can be used in situations where the separator needs
/// to be computed:
/// ```
/// #![feature(iter_intersperse)]
///
/// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
///
/// // The closure mutably borrows its context to generate an item.
/// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
/// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
///
/// let result = src.intersperse_with(separator).collect::<String>();
/// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
/// ```
/// [`Clone`]: crate::clone::Clone
/// [`intersperse`]: Iterator::intersperse
#[inline]
#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
where
Self: Sized,
G: FnMut() -> Self::Item,
{
IntersperseWith::new | creates an iterator which calls that closure on each
/// element.
///
/// `map()` transforms one iterator into another, by means of its argument:
/// something that implements [`FnMut`]. It produces a new iterator which
/// calls this closure on each element of the original iterator.
///
/// If you are good at thinking in types, you can think of `map()` like this:
/// If you have an iterator that gives you elements of some type `A`, and
/// you want an iterator of some other type `B`, you can use `map()`,
/// passing a closure that takes an `A` and returns a `B`.
///
/// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
/// lazy, it is best used when you're already working with other iterators.
/// If you're doing some sort of looping for a side effect, it's considered
/// more idiomatic to use [`for`] than `map()`.
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
/// [`FnMut`]: crate::ops::FnMut
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().map(|x| 2 * x);
///
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If you're doing some sort of side effect, prefer [`for`] to `map()`:
///
/// ```
/// # #![allow(unused_must_use)]
/// // don't do this:
/// (0..5).map(|x| println!("{}", x));
///
/// // it won't even execute, as it is lazy. Rust will warn you about this.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn map<B, F>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> B,
{
Map::new(self, f)
}
/// Calls a closure on each element of an iterator.
///
/// This is equivalent to using a [`for`] loop on the iterator, although
/// `break` and `continue` are not possible from a closure. It's generally
/// more idiomatic to use a `for` loop, but `for_each` may be more legible
/// when processing items at the end of longer iterator chains. In some
/// cases `for_each` may also be faster than a loop, because it will use
/// internal iteration on adaptors like `Chain`.
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::sync::mpsc::channel;
///
/// let (tx, rx) = channel();
/// (0..5).map(|x| x * 2 + 1)
/// .for_each(move |x| tx.send(x).unwrap());
///
/// let v: Vec<_> = rx.iter().collect();
/// assert_eq!(v, vec![1, 3, 5, 7, 9]);
/// ```
///
/// For such a small example, a `for` loop may be cleaner, but `for_each`
/// might be preferable to keep a functional style with longer iterators:
///
/// ```
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// ```
#[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")]
fn for_each<F>(self, f: F)
where
Self: Sized,
F: FnMut(Self::Item),
{
#[inline]
fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
move |(), item| f(item)
}
self.fold((), call(f));
}
/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
/// Given an element the closure must return `true` or `false`. The returned
/// iterator will yield only the elements for which the closure returns
/// true.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0i32, 1, 2];
///
/// let mut iter = a.iter().filter(|x| x.is_positive());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `filter()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// It's common to instead use destructuring on the argument to strip away
/// one:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// or both:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// of these layers.
///
/// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
Filter::new(self, predicate)
}
/// Creates an iterator that both filters and maps.
///
/// The returned iterator yields only the `value`s for which the supplied
/// closure returns `Some(value)`.
///
/// `filter_map` can be used to make chains of [`filter`] and [`map`] more
/// concise. The example below shows how a `map().filter().map()` can be
/// shortened to a single call to `filter_map`.
///
/// [`filter`]: Iterator::filter
/// [`map`]: Iterator::map
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = ["1", "two", "NaN", "four", "5"];
///
/// let mut iter = a.iter().filter_map(|s| s.parse().ok());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`filter`] and [`map`]:
///
/// ```
/// let a = ["1", "two", "NaN", "four", "5"];
/// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
{
FilterMap::new(self, f)
}
/// Creates an iterator which gives the current iteration count as well as
/// the next value.
///
/// The iterator returned yields pairs `(i, val)`, where `i` is the
/// current index of iteration and `val` is the value returned by the
/// iterator.
///
/// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
/// different sized integer, the [`zip`] function provides similar
/// functionality.
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so enumerating more than
/// [`usize::MAX`] elements either produces the wrong result or panics. If
/// debug assertions are enabled, a panic is guaranteed.
///
/// # Panics
///
/// The returned iterator might panic if the to-be-returned index would
/// overflow a [`usize`].
///
/// [`usize`]: type@usize
/// [`zip`]: Iterator::zip
///
/// # Examples
///
/// ```
/// let a = ['a', 'b', 'c'];
///
/// let mut iter = a.iter().enumerate();
///
/// assert_eq!(iter.next(), Some((0, &'a')));
/// assert_eq!(iter.next(), Some((1, &'b')));
/// assert_eq!(iter.next(), Some((2, &'c')));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn enumerate(self) -> Enumerate<Self>
where
Self: Sized,
{
Enumerate::new(self)
}
/// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
/// to look at the next element of the iterator without consuming it. See
/// their documentation for more information.
///
/// Note that the underlying iterator is still advanced when [`peek`] or
/// [`peek_mut`] are called for the first time: In order to retrieve the
/// next element, [`next`] is called on the underlying iterator, hence any
/// side effects (i.e. anything other than fetching the next value) of
/// the [`next`] method will occur.
///
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // peek() lets us see into the future
/// assert_eq!(iter.peek(), Some(&&1));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), Some(&2));
///
/// // we can peek() multiple times, the iterator won't advance
/// assert_eq!(iter.peek(), Some(&&3));
/// assert_eq!(iter.peek(), Some(&&3));
///
/// assert_eq!(iter.next(), Some(&3));
///
/// // after the iterator is finished, so is peek()
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
///
/// Using [`peek_mut`] to mutate the next item without advancing the
/// iterator:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // `peek_mut()` lets us see into the future
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.next(), Some(&1));
///
/// if let Some(mut p) = iter.peek_mut() {
/// assert_eq!(*p, &2);
/// // put a value into the iterator
/// *p = &1000;
/// }
///
/// // The value reappears as the iterator continues
/// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
/// ```
/// [`peek`]: Peekable::peek
/// [`peek_mut`]: Peekable::peek_mut
/// [`next`]: Iterator::next
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn peekable(self) -> Peekable<Self>
where
Self: Sized,
{
Peekable::new(self)
}
/// Creates an iterator that [`skip`]s elements based on a predicate.
///
/// [`skip`]: Iterator::skip
///
/// `skip_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and ignore elements
/// until it returns `false`.
///
/// After `false` is returned, `skip_while()`'s job is over, and the
/// rest of the elements are yielded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [-1i32, 0, 1];
///
/// let mut iter = a.iter().skip_while(|x| x.is_negative());
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `skip_while()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure argument is a double reference:
///
/// ```
/// let a = [-1, 0, 1];
///
/// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial `false`:
///
/// ```
/// let a = [-1, 0, 1, -2];
///
/// let mut iter = a.iter().skip_while(|x| **x < 0);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
///
/// // while this would have been false, since we already got a false,
/// // skip_while() isn't used any more
/// assert_eq!(iter.next(), Some(&-2));
///
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
SkipWhile::new(self, predicate)
}
/// Creates an iterator that yields elements based on a predicate.
///
/// `take_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and yield elements
/// while it returns `true`.
///
/// After `false` is returned, `take_while()`'s job is over, and the
/// rest of the elements are ignored.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [-1i32, 0, 1];
///
/// let mut iter = a.iter().take_while(|x| x.is_negative());
///
/// assert_eq!(iter.next(), Some(&-1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `take_while()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [-1, 0, 1];
///
/// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
///
/// assert_eq!(iter.next(), Some(&-1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial `false`:
///
/// ```
/// let a = [-1, 0, 1, -2];
///
/// let mut iter = a.iter().take_while(|x| **x < 0);
///
/// assert_eq!(iter.next(), Some(&-1));
///
/// // We have more elements that are less than zero, but since we already
/// // got a false, take_while() isn't used any more
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because `take_while()` needs to look at the value in order to see if it
/// should be included or not, consuming iterators will see that it is
/// removed:
///
/// ```
/// let a = [1, 2, 3, 4];
/// let mut iter = a.iter();
///
/// let result: Vec<i32> = iter.by_ref()
/// .take_while(|n| **n != 3)
/// .cloned()
/// .collect();
///
/// assert_eq!(result, &[1, 2]);
///
/// let result: Vec<i32> = iter.cloned().collect();
///
/// assert_eq!(result, &[4]);
/// ```
///
/// The `3` is no longer there, because it was consumed in order to see if
/// the iteration should stop, but wasn't placed back into the iterator.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
TakeWhile::new(self, predicate)
}
/// Creates an iterator that both yields elements based on a predicate and maps.
///
/// `map_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and yield elements
/// while it returns [`Some(_)`][`Some`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_map_while)]
/// let a = [-1i32, 4, 0, 1];
///
/// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
///
/// assert_eq!(iter.next(), Some(-16));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`take_while`] and [`map`]:
///
/// [`take_while`]: Iterator::take_while
/// [`map`]: Iterator::map
///
/// ```
/// let a = [-1i32, 4, 0, 1];
///
/// let mut iter = a.iter()
/// .map(|x| 16i32.checked_div(*x))
/// .take_while(|x| x.is_some())
/// .map(|x| x.unwrap());
///
/// assert_eq!(iter.next(), Some(-16));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial [`None`]:
///
/// ```
/// #![feature(iter_map_while)]
/// use std::convert::TryFrom;
///
/// let a = [0, 1, 2, -3, 4, 5, -6];
///
/// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
/// let vec = iter.collect::<Vec<_>>();
///
/// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
/// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
/// assert_eq!(vec, vec![0, 1, 2]);
/// ```
///
/// Because `map_while()` needs to look at the value in order to see if it
/// should be included or not, consuming iterators will see that it is
/// removed:
///
/// ```
/// #![feature(iter_map_while)]
/// use std::convert::TryFrom;
///
/// let a = [1, 2, -3, 4];
/// let mut iter = a.iter();
///
/// let result: Vec<u32> = iter.by_ref()
/// .map_while(|n| u32::try_from(*n).ok())
/// .collect();
///
/// assert_eq!(result, &[1, 2]);
///
/// let result: Vec<i32> = iter.cloned().collect();
///
/// assert_eq!(result, &[4]);
/// ```
///
/// The `-3` is no longer there, because it was consumed in order to see if
/// the iteration should stop, but wasn't placed back into the iterator.
///
/// Note that unlike [`take_while`] this iterator is **not** fused.
/// It is also not specified what this iterator returns after the first [`None`] is returned.
/// If you need fused iterator, use [`fuse`].
///
/// [`fuse`]: Iterator::fuse
#[inline]
#[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
where
Self: Sized,
P: FnMut(Self::Item) -> Option<B>,
{
MapWhile::new(self, predicate)
}
/// Creates an iterator that skips the first `n` elements.
///
/// `skip(n)` skips elements until `n` elements are skipped or the end of the
/// iterator is reached (whichever happens first). After that, all the remaining
/// elements are yielded. In particular, if the original iterator is too short,
/// then the returned iterator is empty.
///
/// Rather than overriding this method directly, instead override the `nth` method.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().skip(2);
///
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip(self, n: usize) -> Skip<Self>
where
Self: Sized,
{
Skip::new(self, n)
}
/// Creates an iterator that yields the first `n` elements, or fewer
/// if the underlying iterator ends sooner.
///
/// `take(n)` yields elements until `n` elements are yielded or the end of
/// the iterator is reached (whichever happens first).
/// The returned iterator is a prefix of length `n` if the original iterator
/// contains at least `n` elements, otherwise it contains all of the
/// (fewer than `n`) elements of the original iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().take(2);
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `take()` is often used with an infinite iterator, to make it finite:
///
/// ```
/// let mut iter = (0..).take(3);
///
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If less than `n` elements are available,
/// `take` will limit itself to the size of the underlying iterator:
///
/// ```
/// let v = vec![1, 2];
/// let mut iter = v.into_iter().take(5);
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take(self, n: usize) -> Take<Self>
where
Self: Sized,
{
Take::new(self, n)
}
/// An iterator adaptor similar to [`fold`] that holds internal state and
/// produces a new iterator.
///
/// [`fold`]: Iterator::fold
///
/// `scan()` takes two arguments: an initial value which seeds the internal
/// state, and a closure with two arguments, the first being a mutable
/// reference to the internal state and the second an iterator element.
/// The closure can assign to the internal state to share state between
/// iterations.
///
/// On iteration, the closure will be applied to each element of the
/// iterator and the return value from the closure, an [`Option`], is
/// yielded by the iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().scan(1, |state, &x| {
/// // each iteration, we'll multiply the state by the element
/// *state = *state * x;
///
/// // then, we'll yield the negation of the state
/// Some(-*state)
/// });
///
/// assert_eq!(iter.next(), Some(-1));
/// assert_eq!(iter.next(), Some(-2));
/// assert_eq!(iter.next(), Some(-6));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where
Self: Sized,
F: FnMut(&mut St, Self::Item) -> Option<B>,
{
Scan::new(self, initial_state, f)
}
/// Creates an iterator that works like map, but flattens nested structure.
///
/// The [`map`] adapter is very useful, but only when the closure
/// argument produces values. If it produces an iterator instead, there's
/// an extra layer of indirection. `flat_map()` will remove this extra layer
/// on its own.
///
/// You can think of `flat_map(f)` as the semantic equivalent
/// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
///
/// Another way of thinking about `flat_map()`: [`map`]'s closure returns
/// one item for each element, and `flat_map()`'s closure returns an
/// iterator for each element.
///
/// [`map`]: Iterator::map
/// [`flatten`]: Iterator::flatten
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .flat_map(|s| s.chars())
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where
Self: Sized,
U: IntoIterator,
F: FnMut(Self::Item) -> U,
{
FlatMap::new(self, f)
}
/// Creates an iterator that flattens nested structure.
///
/// This is useful when you have an iterator of iterators or an iterator of
/// things that can be turned into iterators and you want to remove one
/// level of indirection.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
/// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
/// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
/// ```
///
/// Mapping and then flattening:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .map(|s| s.chars())
/// .flatten()
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
///
/// You can also rewrite this in terms of [`flat_map()`], which is preferable
/// in this case since it conveys intent more clearly:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .flat_map(|s| s.chars())
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
///
/// Flattening only removes one level of nesting at a time:
///
/// ```
/// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
///
/// let d2 = d3.iter().flatten().collect::<Vec<_>>();
/// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
///
/// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
/// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
/// ```
///
/// Here we see that `flatten()` does not perform a "deep" flatten.
/// Instead, only one level of nesting is removed. That is, if you
/// `flatten()` a three-dimensional array, the result will be
/// two-dimensional and not one-dimensional. To get a one-dimensional
/// structure, you have to `flatten()` again.
///
/// [`flat_map()`]: Iterator::flat_map
#[inline]
#[stable(feature = "iterator_flatten", since = "1.29.0")]
fn flatten(self) -> Flatten<Self>
where
Self: Sized,
Self::Item: IntoIterator,
{
Flatten::new(self)
}
/// Creates an iterator which ends after the first [`None`].
///
/// After an iterator returns [`None`], future calls may or may not yield
/// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
/// [`None`] is given, it will always return [`None`] forever.
///
/// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
/// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
/// if the [`FusedIterator`] trait is improperly implemented.
///
/// [`Some(T)`]: Some
/// [`FusedIterator`]: crate::iter::FusedIterator
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// // an iterator which alternates between Some and None
/// struct Alternate {
/// state: i32,
/// }
///
/// impl Iterator for Alternate {
/// type Item = i32;
///
/// fn next(&mut self) -> Option<i32> {
/// let val = self.state;
/// self.state = self.state + 1;
///
/// // if it's even, Some(i32), else None
/// if val % 2 == 0 {
/// Some(val)
/// } else {
/// None
/// }
/// }
/// }
///
/// let mut iter = Alternate { state: 0 };
///
/// // we can see our iterator going back and forth
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
///
/// // however, once we fuse it...
/// let mut iter = iter.fuse();
///
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), None);
///
/// // it will always return `None` after the first time.
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn fuse(self) -> Fuse<Self>
where
Self: Sized,
{
Fuse::new(self)
}
/// Does something with each element of an iterator, passing the value on.
///
/// When using iterators, you'll often chain several of them together.
/// While working on such code, you might want to check out what's
/// happening at various parts in the pipeline. To do that, insert
/// a call to `inspect()`.
///
/// It's more common for `inspect()` to be used as a debugging tool than to
/// exist in your final code, but applications may find it useful in certain
/// situations when errors need to be logged before being discarded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 4, 2, 3];
///
/// // this iterator sequence is complex.
/// let sum = a.iter()
/// .cloned()
/// .filter(|x| x % 2 == 0)
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
///
/// // let's add some inspect() calls to investigate what's happening
/// let sum = a.iter()
/// .cloned()
/// .inspect(|x| println!("about to filter: {}", x))
/// .filter(|x| x % 2 == 0)
/// .inspect(|x| println!("made it through filter: {}", x))
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// ```
///
/// This will print:
///
/// ```text
/// 6
/// about to filter: 1
/// about to filter: 4
/// made it through filter: 4
/// about to filter: 2
/// made it through filter: 2
/// about to filter: 3
/// 6
/// ```
///
/// Logging errors before discarding them:
///
/// ```
/// let lines = ["1", "2", "a"];
///
/// let sum: i32 = lines
/// .iter()
/// .map(|line| line.parse::<i32>())
/// .inspect(|num| {
/// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e);
/// }
/// })
/// .filter_map(Result::ok)
/// .sum();
///
/// println!("Sum: {}", sum);
/// ```
///
/// This will print:
///
/// ```text
/// Parsing error: invalid digit found in string
/// Sum: 3
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn inspect<F>(self, f: F) -> Inspect<Self, F>
where
Self: Sized,
F: FnMut(&Self::Item),
{
Inspect::new(self, f)
}
/// Borrows an iterator, rather than consuming it.
///
/// This is useful to allow applying iterator adaptors while still
/// retaining ownership of the original iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let mut words = vec!["hello", "world", "of", "Rust"].into_iter();
///
/// // Take the first two words.
/// let hello_world: Vec<_> = words.by_ref().take(2).collect();
/// assert_eq!(hello_world, vec!["hello", "world"]);
///
/// // Collect the rest of the words.
/// // We can only do this because we used `by_ref` earlier.
/// let of_rust: Vec<_> = words.collect();
/// assert_eq!(of_rust, vec!["of", "Rust"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn by_ref(&mut self) -> &mut Self
where
Self: Sized,
{
self
}
/// Transforms an iterator into a collection.
///
/// `collect()` can take anything iterable, and turn it into a relevant
/// collection. This is one of the more powerful methods in the standard
/// library, used in a variety of contexts.
///
/// The most basic pattern in which `collect()` is used is to turn one
/// collection into another. You take a collection, call [`iter`] on it,
/// do a bunch of transformations, and then `collect()` at the end.
///
/// `collect()` can also create instances of types that are not typical
/// collections. For example, a [`String`] can be built from [`char`]s,
/// and an iterator of [`Result<T, E>`][`Result`] items can be collected
/// into `Result<Collection<T>, E>`. See the examples below for more.
///
/// Because `collect()` is so general, it can cause problems with type
/// inference. As such, `collect()` is one of the few times you'll see
/// the syntax affectionately known as the 'turbofish': `::<>`. This
/// helps the inference algorithm understand specifically which collection
/// you're trying to collect into.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled: Vec<i32> = a.iter()
/// .map(|&x| x * 2)
/// .collect();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
/// we could collect into, for example, a [`VecDeque<T>`] instead:
///
/// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
///
/// ```
/// use std::collections::VecDeque;
///
/// let a = [1, 2, 3];
///
/// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
///
/// assert_eq!(2, doubled[0]);
/// assert_eq!(4, doubled[1]);
/// assert_eq!(6, doubled[2]);
/// ```
///
/// Using the 'turbofish' instead of annotating `doubled`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Because `collect()` only cares about what you're collecting into, you can
/// still use a partial type hint, `_`, with the turbofish:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Using `collect()` to make a [`String`]:
///
/// ```
/// let chars = ['g', 'd', 'k', 'k', 'n'];
///
/// let hello: String = chars.iter()
/// .map(|&x| x as u8)
/// .map(|x| (x + 1) as char)
/// .collect();
///
/// assert_eq!("hello", hello);
/// ```
///
/// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
/// see if any of them failed:
///
/// ```
/// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
///
/// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
///
/// // gives us the first error
/// assert_eq!(Err("nope"), result);
///
/// let results = [Ok(1), Ok(3)];
///
/// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
///
/// // gives us the list of answers
/// assert_eq!(Ok(vec![1, 3]), result);
/// ```
///
/// [`iter`]: Iterator::next
/// [`String`]: ../../std/string/struct.String.html
/// [`char`]: type@char
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
fn collect<B: FromIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
FromIterator::from_iter(self)
}
/// Consumes an iterator, creating two collections from it.
///
/// The predicate passed to `partition()` can return `true`, or `false`.
/// `partition()` returns a pair, all of the elements for which it returned
/// `true`, and all of the elements for which it returned `false`.
///
/// See also [`is_partitioned()`] and [`partition_in_place()`].
///
/// [`is_partitioned()`]: Iterator::is_partitioned
/// [`partition_in_place()`]: Iterator::partition_in_place
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let (even, odd): (Vec<i32>, Vec<i32>) = a
/// .iter()
/// .partition(|&n| n % 2 == 0);
///
/// assert_eq!(even, vec![2]);
/// assert_eq!(odd, vec![1, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn partition<B, F>(self, f: F) -> (B, B)
where
Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool,
{
#[inline]
fn extend<'a, T, B: Extend<T>>(
mut f: impl FnMut(&T) -> bool + 'a,
left: &'a mut B,
right: &'a mut B,
) -> impl FnMut((), T) + 'a {
move |(), x| {
if f(&x) {
left.extend_one(x);
} else {
right.extend_one(x);
}
}
}
let mut left: B = Default::default();
let mut right: B = Default::default();
self.fold((), extend(f, &mut left, &mut right));
(left, right)
}
/// Reorders the elements of this iterator *in-place* according to the given predicate,
/// such that all those that return `true` precede all those that return `false`.
/// Returns the number of `true` elements found.
///
/// The relative order of partitioned items is not maintained.
///
/// See also [`is_partitioned()`] and [`partition()`].
///
/// [`is_partitioned()`]: Iterator::is_partitioned
/// [`partition()`]: Iterator::partition
///
/// # Examples
///
/// ```
/// #![feature(iter_partition_in_place)]
///
/// let mut a = [1, 2, 3, 4, 5, 6, 7];
///
/// // Partition in-place between evens and odds
/// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
///
/// assert_eq!(i, 3);
/// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
/// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
/// ```
#[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
where
Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
P: FnMut(&T) -> bool,
{
// FIXME: should we worry about the count overflowing? The only way to have more than
// `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
// These closure "factory" functions exist to avoid genericity in `Self`.
#[inline]
fn is_false<'a, T>(
predicate: &'a mut impl FnMut(&T) -> bool,
true_count: &'a mut usize,
) -> impl FnMut(&&mut T) -> bool + 'a {
move |x| {
let p = predicate(&**x);
*true_count += p as usize;
!p
}
}
#[inline]
fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
move |x| predicate(&**x)
}
// Repeatedly find the first `false` and swap it with the last `true`.
let mut true_count = 0;
while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
if let Some(tail) = self.rfind(is_true(predicate)) {
crate::mem::swap(head, tail);
true_count += 1;
} else {
break;
}
}
true_count
}
/// Checks if the elements of this iterator are partitioned according to the given predicate,
/// such that all those that return `true` precede all those that return `false`.
///
/// See also [`partition()`] and [`partition_in_place()`].
///
/// [`partition()`]: Iterator::partition
/// [`partition_in_place()`]: Iterator::partition_in_place
///
/// # Examples
///
/// ```
/// #![feature(iter_is_partitioned)]
///
/// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
/// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
/// ```
#[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
fn is_partitioned<P>(mut self, mut predicate: P) -> bool
where
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
// Either all items test `true`, or the first clause stops at `false`
// and we check that there are no more `true` items after that.
self.all(&mut predicate) || !self.any(predicate)
}
/// An iterator method that applies a function as long as it returns
/// successfully, producing a single, final value.
///
/// `try_fold()` takes two arguments: an initial value, and a closure with
/// two arguments: an 'accumulator', and an element. The closure either
/// returns successfully, with the value that the accumulator should have
/// for the next iteration, or it returns failure, with an error value that
/// is propagated back to the caller immediately (short-circuiting).
///
/// The initial value is the value the accumulator will have on the first
/// call. If applying the closure succeeded against every element of the
/// iterator, `try_fold()` returns the final accumulator as success.
///
/// Folding is useful whenever you have a collection of something, and want
/// to produce a single value from it.
///
/// # Note to Implementors
///
/// Several of the other (forward) methods have default implementations in
/// terms of this one, so try to implement this explicitly if it can
/// do something better than the default `for` loop implementation.
///
/// In particular, try to have this call `try_fold()` on the internal parts
/// from which this iterator is composed. If multiple calls are needed,
/// the `?` operator may be convenient for chaining the accumulator value
/// along, but beware any invariants that need to be upheld before those
/// early returns. This is a `&mut self` method, so iteration needs to be
/// resumable after hitting an error here.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// // the checked sum of all of the elements of the array
/// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
///
/// assert_eq!(sum, Some(6));
/// ```
///
/// Short-circuiting:
///
/// ```
/// let a = [10, 20, 30, 100, 40, 50];
/// let mut it = a.iter();
///
/// // This sum overflows when adding the 100 element
/// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
/// assert_eq!(sum, None);
///
/// // Because it short-circuited, the remaining elements are still
/// // available through the iterator.
/// assert_eq!(it.len(), 2);
/// assert_eq!(it.next(), Some(&40));
/// ```
#[inline]
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
where
Self: Sized,
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
{
let mut accum = init;
while let Some(x) = self.next() {
accum = f(accum, x)?;
}
try { accum }
}
/// An iterator method that applies a fallible function to each item in the
/// iterator, stopping at the first error and returning that error.
///
/// This can also be thought of as the fallible form of [`for_each()`]
/// or as the stateless version of [`try_fold()`].
///
/// [`for_each()`]: Iterator::for_each
/// [`try_fold()`]: Iterator::try_fold
///
/// # Examples
///
/// ```
/// use std::fs::rename;
/// use std::io::{stdout, Write};
/// use std::path::Path;
///
/// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
///
/// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
/// assert!(res.is_ok());
///
/// let mut it = data.iter().cloned();
/// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
/// assert!(res.is_err());
/// // It short-circuited, so the remaining items are still in the iterator:
/// assert_eq!(it.next(), Some("stale_bread.json"));
/// ```
#[inline]
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
fn try_for_each<F, R>(&mut self, f: F) -> R
where
Self: Sized,
F: FnMut(Self::Item) -> R,
R: Try<Ok = ()>,
{
#[inline]
fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
move |(), x| f(x)
}
self.try_fold((), call(f))
}
/// Folds every element into an accumulator by applying an operation,
/// returning the final result.
///
/// `fold()` takes two arguments: an initial value, and a closure with two
/// arguments: an 'accumulator', and an element. The closure returns the value that
/// the accumulator should have for the next iteration.
///
/// The initial value is the value the accumulator will have on the first
/// call.
///
/// After applying this closure to every element of the iterator, `fold()`
/// returns the accumulator.
///
/// This operation is sometimes called 'reduce' or 'inject'.
///
/// Folding is useful whenever you have a collection of something, and want
/// to produce a single value from it.
///
/// Note: `fold()`, and similar methods that traverse the entire iterator,
/// may not terminate for infinite iterators, even on traits for which a
/// result is determinable in finite time.
///
/// Note: [`reduce()`] can be used to use the first element as the initial
/// value, if the accumulator type and item type is the same.
///
/// # Note to Implementors
///
/// Several of the other (forward) methods have default implementations in
/// terms of this one, so try to implement this explicitly if it can
/// do something better than the default `for` loop implementation.
///
/// In particular, try to have this call `fold()` on the internal parts
/// from which this iterator is composed.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// // the sum of all of the elements of the array
/// let sum = a.iter().fold(0, |acc, x| acc + x);
///
/// assert_eq!(sum, 6);
/// ```
///
/// Let's walk through each step of the iteration here:
///
/// | element | acc | x | result |
/// |---------|-----|---|--------|
/// | | 0 | | |
/// | 1 | 0 | 1 | 1 |
/// | 2 | 1 | 2 | 3 |
/// | 3 | 3 | 3 | 6 |
///
/// And so, our final result, `6`.
///
/// It's common for people who haven't used iterators a lot to
/// use a `for` loop with a list of things to build up a result. Those
/// can be turned into `fold()`s:
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
///
/// ```
/// let numbers = [1, 2, 3, 4, 5];
///
/// let mut result = 0;
///
/// // for loop:
/// for i in &numbers {
/// result = result + i;
/// }
///
/// // fold:
/// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
///
/// // they're the same
/// assert_eq!(result, result2);
/// ```
///
/// [`reduce()`]: Iterator::reduce
#[doc(alias = "reduce")]
#[doc(alias = "inject")]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn fold<B, F>(mut self, init: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;
while let Some(x) = self.next() {
accum = f(accum, x);
}
accum
}
/// Reduces the elements to a single one, by repeatedly applying a reducing
/// operation.
///
/// If the iterator is empty, returns [`None`]; otherwise, returns the
/// result of the reduction.
///
/// For iterators with at least one element, this is the same as [`fold()`]
/// with the first element of the iterator as the initial value, folding
/// every subsequent element into it.
///
/// [`fold()`]: Iterator::fold
///
/// # Example
///
/// Find the maximum value:
///
/// ```
/// fn find_max<I>(iter: I) -> Option<I::Item>
/// where I: Iterator,
/// I::Item: Ord,
/// {
/// iter.reduce(|a, b| {
/// if a >= b { a } else { b }
/// })
/// }
/// let a = [10, 20, 5, -23, 0];
/// let b: [u32; 0] = [];
///
/// assert_eq!(find_max(a.iter()), Some(&20));
/// assert_eq!(find_max(b.iter()), None);
/// ```
#[inline]
#[stable(feature = "iterator_fold_self", since = "1.51.0")]
fn reduce<F>(mut self, f: F) -> Option<Self::Item>
where
Self: Sized,
F: FnMut(Self::Item, Self::Item) -> Self::Item,
{
let first = self.next()?;
Some(self.fold(first, f))
}
/// Tests if every element of the iterator matches a predicate.
///
/// `all()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if they all return
/// `true`, then so does `all()`. If any of them return `false`, it
/// returns `false`.
///
/// `all()` is short-circuiting; in other words, it will stop processing
/// as soon as it finds a `false`, given that no matter what else happens,
/// the result will also be `false`.
///
/// An empty iterator returns `true`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert!(a.iter().all(|&x| x > 0));
///
/// assert!(!a.iter().all(|&x| x > 2));
/// ```
///
/// Stopping at the first `false`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert!(!iter.all(|&x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
/// ```
#[doc(alias = "every")]
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn all<F>(&mut self, f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> bool,
{
#[inline]
fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
move |(), x| {
if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK }
}
}
self.try_fold((), check(f)) == ControlFlow::CONTINUE
}
/// Tests if any element of the iterator matches a predicate.
///
/// `any()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if any of them return
/// `true`, then so does `any()`. If they all return `false`, it
/// returns `false`.
///
/// `any()` is short-circuiting; in other words, it will stop processing
/// as soon as it finds a `true`, given that no matter what else happens,
/// the result will also be `true`.
///
/// An empty iterator returns `false`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert!(a.iter().any(|&x| x > 0));
///
/// assert!(!a.iter().any(|&x| x > 5));
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert!(iter.any(|&x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&2));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn any<F>(&mut self, f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> bool,
{
#[inline]
fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
move |(), x| {
if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE }
}
}
self.try_fold((), check(f)) == ControlFlow::BREAK
}
/// Searches for an element of an iterator that satisfies a predicate.
///
/// `find()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if any of them return
/// `true`, then `find()` returns [`Some(element)`]. If they all return
/// `false`, it returns [`None`].
///
/// `find()` is short-circuiting; in other words, it will stop processing
/// as soon as the closure returns `true`.
///
/// Because `find()` takes a reference, and many iterators iterate over
/// references, this leads to a possibly confusing situation where the
/// argument is a double reference. You can see this effect in the
/// examples below, with `&&x`.
///
/// [`Some(element)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
///
/// assert_eq!(a.iter().find(|&&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
/// ```
///
/// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
#[inline]
fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
move |(), x| {
if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE }
}
}
self.try_fold((), check(predicate)).break_value()
}
/// Applies function to the elements of iterator and returns
/// the first non-none result.
///
/// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
///
/// # Examples
///
/// ```
/// let a = ["lol", "NaN", "2", "5"];
///
/// let first_number = a.iter().find_map(|s| s.parse().ok());
///
/// assert_eq!(first_number, Some(2));
/// ```
#[inline]
#[stable(feature = "iterator_find_map", since = "1.30.0")]
fn find_map<B, F>(&mut self, f: F) -> Option<B>
where
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
{
#[inline]
fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
move |(), x| match f(x) {
Some(x) => ControlFlow::Break(x),
None => ControlFlow::CONTINUE,
}
}
self.try_fold((), check(f)).break_value()
}
/// Applies function to the elements of iterator and returns
/// the first true result or the first error.
///
/// # Examples
///
/// ```
/// #![feature(try_find)]
///
/// let a = ["1", "2", "lol", "NaN", "5"];
///
/// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
/// Ok(s.parse::<i32>()? == search)
/// };
///
/// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
/// assert_eq!(result, Ok(Some(&"2")));
///
/// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
/// assert!(result.is_err());
/// ```
#[inline]
#[unstable(feature = "try_find", reason = "new API", issue = "63178")]
fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
where
Self: Sized,
F: FnMut(&Self::Item) -> R,
R: Try<Ok = bool>,
{
#[inline]
fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> ControlFlow<Result<T, R::Error>>
where
F: FnMut(&T) -> R,
R: Try<Ok = bool>,
{
move |(), x| match f(&x).into_result() {
Ok(false) => ControlFlow::CONTINUE,
Ok(true) => ControlFlow::Break(Ok(x)),
Err(x) => ControlFlow::Break(Err(x)),
}
}
self.try_fold((), check(f)).break_value().transpose()
}
/// Searches for an element in an iterator, returning its index.
///
/// `position()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if one of them
/// returns `true`, then `position()` returns [`Some(index)`]. If all of
/// them return `false`, it returns [`None`].
///
/// `position()` is short-circuiting; in other words, it will stop
/// processing as soon as it finds a `true`.
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so if there are more
/// than [`usize::MAX`] non-matching elements, it either produces the wrong
/// result or panics. If debug assertions are enabled, a panic is
/// guaranteed.
///
/// # Panics
///
/// This function might panic if the iterator has more than `usize::MAX`
/// non-matching elements.
///
/// [`Some(index)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
///
/// assert_eq!(a.iter().position(|&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3, 4];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.position(|&x| x >= 2), Some(1));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
///
/// // The returned index depends on iterator state
/// assert_eq!(iter.position(|&x| x == 4), Some(0));
///
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn position<P>(&mut self, predicate: P) -> Option<usize>
where
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
#[inline]
fn check<T>(
mut predicate: impl FnMut(T) -> bool,
) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
#[rustc_inherit_overflow_checks]
move |i, x| {
if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) }
}
}
self.try_fold(0, check(predicate)).break_value()
}
/// Searches for an element in an iterator from the right, returning its
/// index.
///
/// `rposition()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, starting from the end,
/// and if one of them returns `true`, then `rposition()` returns
/// [`Some(index)`]. If all of them return `false`, it returns [`None`].
///
/// `rposition()` is short-circuiting; in other words, it will stop
/// processing as soon as it finds a `true`.
///
/// [`Some(index)`]: Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
///
/// assert_eq!(a.iter().rposition(|&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&1));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn rposition<P>(&mut self, predicate: P) -> Option<usize>
where
P: FnMut(Self::Item) -> bool,
Self: Sized + ExactSizeIterator + DoubleEndedIterator,
{
// No need for an overflow check here, because `ExactSizeIterator`
// implies that the number of elements fits into a `usize`.
#[inline]
fn check<T>(
mut predicate: impl FnMut(T) -> bool,
) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
move |i, x| {
let i = i - 1;
if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
}
}
let n = self.len();
self.try_rfold(n, check(predicate)).break_value()
}
/// Returns the maximum element of an iterator.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let b: Vec<u32> = Vec::new();
///
/// assert_eq!(a.iter().max(), Some(&3));
/// assert_eq!(b.iter().max(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn max(self) -> Option<Self::Item>
where
Self: Sized,
Self::Item: Ord,
{
self.max_by(Ord::cmp)
}
/// Returns the minimum element of an iterator.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let b: Vec<u32> = Vec::new();
///
/// assert_eq!(a.iter().min(), Some(&1));
/// assert_eq!(b.iter().min(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn min(self) -> Option<Self::Item>
where
Self: Sized,
Self::Item: Ord,
{
self.min_by(Ord::cmp)
}
/// Returns the element that gives the maximum value from the
/// specified function.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
/// ```
#[inline]
#[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
where
Self: Sized,
F: FnMut(&Self::Item) -> B,
{
#[inline]
fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
move |x| (f(&x), x)
}
#[inline]
fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
x_p.cmp(y_p)
}
let (_, x) = self.map(key(f)).max_by(compare)?;
Some(x)
}
/// Returns the element that gives the maximum value with respect to the
/// specified comparison function.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
/// ```
#[inline]
#[stable(feature = "iter_max_by", since = "1.15.0")]
fn max_by<F>(self, compare: F) -> Option<Self::Item>
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
#[inline]
fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
move |x, y| cmp::max_by(x, y, &mut compare)
}
self.reduce(fold(compare))
}
/// Returns the element that gives the minimum value from the
/// specified function.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
/// ```
#[inline]
#[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
where
Self: Sized,
F: FnMut(&Self::Item) -> B,
{
#[inline]
fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
move |x| (f(&x), x)
}
#[inline]
fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
x_p.cmp(y_p)
}
let (_, x) = self.map(key(f)).min_by(compare)?;
Some(x)
}
/// Returns the element that gives the minimum value with respect to the
/// specified comparison function.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
/// ```
#[inline]
#[stable(feature = "iter_min_by", since = "1.15.0")]
fn min_by<F>(self, compare: F) -> Option<Self::Item>
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
#[inline]
fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
move |x, y| cmp::min_by(x, y, &mut compare)
}
self.reduce(fold(compare))
}
/// Reverses an iterator's direction.
///
/// Usually, iterators iterate from left to right. After using `rev()`,
/// an iterator will instead iterate from right to left.
///
/// This is only possible if the iterator has an end, so `rev()` only
/// works on [`DoubleEndedIterator`]s.
///
/// # Examples
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().rev();
///
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[doc(alias = "reverse")]
#[stable(feature = "rust1", since = "1.0.0")]
fn rev(self) -> Rev<Self>
where
Self: Sized + DoubleEndedIterator,
{
Rev::new(self)
}
/// Converts an iterator of pairs into a pair of containers.
///
/// `unzip()` consumes an entire iterator of pairs, producing two
/// collections: one from the left elements of the pairs, and one
/// from the right elements.
///
/// This function is, in some sense, the opposite of [`zip`].
///
/// [`zip`]: Iterator::zip
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [(1, 2), (3, 4)];
///
/// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
///
/// assert_eq!(left, [1, 3]);
/// assert_eq!(right, [2, 4]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Sized + Iterator<Item = (A, B)>,
{
fn extend<'a, A, B>(
ts: &'a mut impl Extend<A>,
us: &'a mut impl Extend<B>,
) -> impl FnMut((), (A, B)) + 'a {
move |(), (t, u)| {
ts.extend_one(t);
us.extend_one(u);
}
}
let mut ts: FromA = Default::default();
let mut us: FromB = Default::default();
let (lower_bound, _) = self.size_hint();
if lower_bound > 0 {
ts.extend_reserve(lower_bound);
us.extend_reserve(lower_bound);
}
self.fold((), extend(&mut ts, &mut us));
(ts, us)
}
/// Creates an iterator which copies all of its elements.
///
/// This is useful when you have an iterator over `&T`, but you need an
/// iterator over `T`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let v_copied: Vec<_> = a.iter().copied().collect();
///
/// // copied is the same as .map(|&x| x)
/// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
///
/// assert_eq!(v_copied, vec![1, 2, 3]);
/// assert_eq!(v_map, vec![1, 2, 3]);
/// ```
#[stable(feature = "iter_copied", since = "1.36.0")]
fn copied<'a, T: 'a>(self) -> Copied<Self>
where
Self: Sized + Iterator<Item = &'a T>,
T: Copy,
{
Copied::new(self)
}
/// Creates an iterator which [`clone`]s all of its elements.
///
/// This is useful when you have an iterator over `&T`, but you need an
/// iterator over `T`.
///
/// [`clone`]: Clone::clone
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let v_cloned: Vec<_> = a.iter().cloned().collect();
///
/// // cloned is the same as .map(|&x| x), for integers
/// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
///
/// assert_eq!(v_cloned, vec![1, 2, 3]);
/// assert_eq!(v_map, vec![1, 2, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn cloned<'a, T: 'a>(self) -> Cloned<Self>
where
Self: Sized + Iterator<Item = &'a T>,
T: Clone,
{
Cloned::new(self)
}
/// Repeats an iterator endlessly.
///
/// Instead of stopping at [`None`], the iterator will instead start again,
/// from the beginning. After iterating again, it will start at the
/// beginning again. And again. And again. Forever.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut it = a.iter().cycle();
///
/// assert_eq!(it.next(), Some(&1));
/// assert_eq!(it.next(), Some(&2));
/// assert_eq!(it.next(), Some(&3));
/// assert_eq!(it.next(), Some(&1));
/// assert_eq!(it.next(), Some(&2));
/// assert_eq!(it.next(), Some(&3));
/// assert_eq!(it.next(), Some(&1));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn cycle(self) -> Cycle<Self>
where
Self: Sized + Clone,
{
Cycle::new(self)
}
/// Sums the elements of an iterator.
///
/// Takes each element, adds them together, and returns the result.
///
/// An empty iterator returns the zero value of the type.
///
/// # Panics
///
/// When calling `sum()` and a primitive integer type is being returned, this
/// method will panic if the computation overflows and debug assertions are
/// enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let sum: i32 = a.iter().sum();
///
/// assert_eq!(sum, 6);
/// ```
#[stable(feature = "iter_arith", since = "1.11.0")]
fn sum<S>(self) -> S
where
Self: Sized,
S: Sum<Self::Item>,
{
Sum::sum(self)
}
/// Iterates over the entire iterator, multiplying all the elements
///
/// An empty iterator returns the one value of the type.
///
/// # Panics
///
/// When calling `product()` and a primitive integer type is being returned,
/// method will panic if the computation overflows and debug assertions are
/// enabled.
///
/// # Examples
///
/// ```
/// fn factorial(n: u32) -> u32 {
/// (1..=n).product()
/// }
/// assert_eq!(factorial(0), 1);
/// assert_eq!(factorial(1), 1);
/// assert_eq!(factorial(5), 120);
/// ```
#[stable(feature = "iter_arith", since = "1.11.0")]
fn product<P>(self) -> P
where
Self: Sized,
P: Product<Self::Item>,
{
Product::product(self)
}
/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
/// of another.
///
/// # Examples
///
/// ```
/// use std::cmp::Ordering;
///
/// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
/// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
/// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn cmp<I>(self, other: I) -> Ordering
where
I: IntoIterator<Item = Self::Item>,
Self::Item: Ord,
Self: Sized,
{
self.cmp_by(other, |x, y| x.cmp(&y))
}
/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
/// of another with respect to the specified comparison function.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_order_by)]
///
/// use std::cmp::Ordering;
///
/// let xs = [1, 2, 3, 4];
/// let ys = [1, 4, 9, 16];
///
/// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
/// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
/// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
/// ```
#[unstable(feature = "iter_order_by", issue = "64295")]
fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, I::Item) -> Ordering,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => {
if other.next().is_none() {
return Ordering::Equal;
} else {
return Ordering::Less;
}
}
Some(val) => val,
};
let y = match other.next() {
None => return Ordering::Greater,
Some(val) => val,
};
match cmp(x, y) {
Ordering::Equal => (),
non_eq => return non_eq,
}
}
}
/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
/// of another.
///
/// # Examples
///
/// ```
/// use std::cmp::Ordering;
///
/// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
/// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
/// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
///
/// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn partial_cmp<I>(self, other: I) -> Option<Ordering>
where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
}
/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
/// of another with respect to the specified comparison function.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_order_by)]
///
/// use std::cmp::Ordering;
///
/// let xs = [1.0, 2.0, 3.0, 4.0];
/// let ys = [1.0, 4.0, 9.0, 16.0];
///
/// assert_eq!(
/// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
/// Some(Ordering::Less)
/// );
/// assert_eq!(
/// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
/// Some(Ordering::Equal)
/// );
/// assert_eq!(
/// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
/// Some(Ordering::Greater)
/// );
/// ```
#[unstable(feature = "iter_order_by", issue = "64295")]
fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => {
if other.next().is_none() {
return Some(Ordering::Equal);
} else {
return Some(Ordering::Less);
}
}
Some(val) => val,
};
let y = match other.next() {
None => return Some(Ordering::Greater),
Some(val) => val,
};
match partial_cmp(x, y) {
Some(Ordering::Equal) => (),
non_eq => return non_eq,
}
}
}
/// Determines if the elements of this [`Iterator`] are equal to those of
/// another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().eq([1].iter()), true);
/// assert_eq!([1].iter().eq([1, 2].iter()), false);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn eq<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialEq<I::Item>,
Self: Sized,
{
self.eq_by(other, |x, y| x == y)
}
/// Determines if the elements of this [`Iterator`] are equal to those of
/// another with respect to the specified equality function.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_order_by)]
///
/// let xs = [1, 2, 3, 4];
/// let ys = [1, 4, 9, 16];
///
/// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
/// ```
#[unstable(feature = "iter_order_by", issue = "64295")]
fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, I::Item) -> bool,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => return other.next().is_none(),
Some(val) => val,
};
let y = match other.next() {
None => return false,
Some(val) => val,
};
if !eq(x, y) {
return false;
}
}
}
/// Determines if the elements of this [`Iterator`] are unequal to those of
/// another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().ne([1].iter()), false);
/// assert_eq!([1].iter().ne([1, 2].iter()), true);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn ne<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialEq<I::Item>,
Self: Sized,
{
!self.eq(other)
}
/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
/// less than those of another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().lt([1].iter()), false);
/// assert_eq!([1].iter().lt([1, 2].iter()), true);
/// assert_eq!([1, 2].iter().lt([1].iter()), false);
/// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn lt<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
self.partial_cmp(other) == Some(Ordering::Less)
}
/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
/// less or equal to those of another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().le([1].iter()), true);
/// assert_eq!([1].iter().le([1, 2].iter()), true);
/// assert_eq!([1, 2].iter().le([1].iter()), false);
/// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn le<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
}
/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
/// greater than those of another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().gt([1].iter()), false);
/// assert_eq!([1].iter().gt([1, 2].iter()), false);
/// assert_eq!([1, 2].iter().gt([1].iter()), true);
/// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn gt<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
self.partial_cmp(other) == Some(Ordering::Greater)
}
/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
/// greater than or equal to those of another.
///
/// # Examples
///
/// ```
/// assert_eq!([1].iter().ge([1].iter()), true);
/// assert_eq!([1].iter().ge([1, 2].iter()), false);
/// assert_eq!([1, 2].iter().ge([1].iter()), true);
/// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
/// ```
#[stable(feature = "iter_order", since = "1.5.0")]
fn ge<I>(self, other: I) -> bool
where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
}
/// Checks if the elements of this iterator are sorted.
///
/// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
/// iterator yields exactly zero or one element, `true` is returned.
///
/// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
/// implies that this function returns `false` if any two consecutive items are not
/// comparable.
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!([1, 2, 2, 9].iter().is_sorted());
/// assert!(![1, 3, 2, 4].iter().is_sorted());
/// assert!([0].iter().is_sorted());
/// assert!(std::iter::empty::<i32>().is_sorted());
/// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted(self) -> bool
where
Self: Sized,
Self::Item: PartialOrd,
{
self.is_sorted_by(PartialOrd::partial_cmp)
}
/// Checks if the elements of this iterator are sorted using the given comparator function.
///
/// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
/// function to determine the ordering of two elements. Apart from that, it's equivalent to
/// [`is_sorted`]; see its documentation for more information.
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
/// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
/// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
/// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
/// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
/// ```
///
/// [`is_sorted`]: Iterator::is_sorted
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted_by<F>(mut self, compare: F) -> bool
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
{
#[inline]
fn check<'a, T>(
last: &'a mut T,
mut compare: impl FnMut(&T, &T) -> Option<Ordering> + 'a,
) -> impl FnMut(T) -> bool + 'a {
move |curr| {
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
return false;
}
*last = curr;
true
}
}
let mut last = match self.next() {
Some(e) => e,
None => return true,
};
self.all(check(&mut last, compare))
}
/// Checks if the elements of this iterator are sorted using the given key extraction
/// function.
///
/// Instead of comparing the iterator's elements directly, this function compares the keys of
/// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
/// its documentation for more information.
///
/// [`is_sorted`]: Iterator::is_sorted
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
/// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted_by_key<F, K>(self, f: F) -> bool
where
Self: Sized,
F: FnMut(Self::Item) -> K,
K: PartialOrd,
{
self.map(f).is_sorted()
}
/// See [TrustedRandomAccess]
// The unusual name is to avoid name collisions in method resolution
// see #76479.
#[inline]
#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
where
Self: TrustedRandomAccess,
{
unreachable!("Always specialized");
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for &mut I {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
(**self).next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
(**self).advance_by(n)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
(**self).nth(n)
}
}
| (self, separator)
}
/// Takes a closure and |
stylist.rs | use egui_stylist::StylistState;
use gdnative::api::FileDialog;
use gdnative::prelude::*;
use godot_egui::GodotEgui;
#[derive(NativeClass)]
#[inherit(Control)]
pub struct GodotEguiStylist {
style: StylistState,
godot_egui: Option<Instance<GodotEgui, Shared>>,
file_dialog: Option<Ref<FileDialog, Shared>>,
}
#[methods]
impl GodotEguiStylist {
fn new(_: &Control) -> Self {
Self { style: StylistState::default(), godot_egui: None, file_dialog: None }
}
/// Updates egui from the `_gui_input` callback
#[export]
pub fn _gui_input(&mut self, owner: TRef<Control>, event: Ref<InputEvent>) {
let gui = unsafe { self.godot_egui.as_ref().expect("GUI initialized").assume_safe() };
gui.map_mut(|gui, instance| {
gui.handle_godot_input(instance, event, true);
if gui.mouse_was_captured(instance) {
owner.accept_event();
}
})
.expect("map_mut should succeed");
}
#[export]
fn _ready(&mut self, owner: TRef<Control>) {
let gui = owner
.get_node("godot_egui")
.and_then(|godot_egui| unsafe { godot_egui.assume_safe() }.cast::<Control>())
.and_then(|godot_egui| godot_egui.cast_instance::<GodotEgui>())
.expect("Expected a `GodotEgui` child with the GodotEgui nativescript class.");
let file_dialog = owner
.get_node("file_dialog")
.and_then(|fd| unsafe { fd.assume_safe() }.cast::<FileDialog>())
.expect("Expected a `FileDialog` to be present as a child with name 'file_dialog'");
file_dialog.set_access(FileDialog::ACCESS_RESOURCES);
file_dialog
.connect(
"file_selected",
owner,
"on_file_selected",
VariantArray::new_shared(),
Object::CONNECT_DEFERRED,
)
.expect("this should work");
file_dialog
.connect(
"popup_hide",
owner,
"on_file_dialog_closed",
VariantArray::new_shared(),
Object::CONNECT_DEFERRED,
)
.expect("this should work");
self.godot_egui = Some(gui.claim());
self.file_dialog = Some(file_dialog.claim());
}
#[export]
fn _process(&mut self, owner: TRef<Control>, _: f32) {
let egui = unsafe { self.godot_egui.as_ref().expect("this must be initialized").assume_safe() };
egui.map_mut(|gui, gui_owner| {
gui.update_ctx(gui_owner, |ctx| {
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| self.menu_bar(owner, gui_owner, ui));
egui::CentralPanel::default().show(ctx, |ui| self.style.ui(ui));
});
})
.expect("this should work");
}
#[export]
fn on_file_dialog_closed(&mut self, _: &Control) {
godot_print!("on_file_dialog_closed");
// owner.set_process(true);
unsafe { self.godot_egui.as_ref().expect("should be initialized").assume_safe() }
.map_mut(|_, o| {
godot_print!("reenable input on `GodotEgui`");
o.set_process_input(true);
})
.expect("this should work");
}
#[export]
fn on_file_selected(&mut self, _: TRef<Control>, path: GodotString) {
godot_print!("on_file_selected");
// Do the saving or loading
let fd = unsafe { self.file_dialog.expect("file dialog should be initialized").assume_safe() };
if fd.mode().0 == FileDialog::MODE_OPEN_FILE {
// TODO: Load the file
self.style.import_theme(load_theme(path));
} else if fd.mode().0 == FileDialog::MODE_SAVE_FILE {
save_theme(path, self.style.export_theme());
} else {
godot_error!("file_dialog mode should only be MODE_SAVE_FILE or MODE_OPEN_FILE")
}
unsafe { self.godot_egui.as_ref().expect("should be initialized").assume_safe() }
.map_mut(|_egui, o| {
godot_print!("reenable input on `GodotEgui`");
o.set_process_input(true);
})
.expect("this should work");
fd.hide();
// self.disconnect_signals(owner);
}
/// This creates the main menu bar that will be used by godot.
fn menu_bar(&mut self, _: TRef<Control>, gui_owner: TRef<Control>, ui: &mut egui::Ui) {
egui::menu::bar(ui, |ui| {
egui::menu::menu(ui, "File", |ui| {
// TODO: Make a generic FileDialog Modal
if ui.button("Load").clicked() {
let fd = unsafe { self.file_dialog.expect("file dialog should be initialized").assume_safe() };
fd.set_mode(FileDialog::MODE_OPEN_FILE);
fd.popup_centered(Vector2::new(500.0, 500.0));
// Push the file filters to the file dialog
let mut filters = StringArray::new();
filters.push("*.ron; Ron format".into());
filters.push("*.eguitheme; egui theme format".into());
fd.set_filters(filters);
godot_print!("disable input on `GodotEgui`");
gui_owner.set_process_input(false);
}
if ui.button("Save").clicked() {
// Option a popup to save the file to a given directory
let fd = unsafe { self.file_dialog.expect("file dialog should be initialized").assume_safe() };
fd.set_mode(FileDialog::MODE_SAVE_FILE);
fd.popup_centered(Vector2::new(500.0, 500.0));
// Push the file filters to the file dialog
let mut filters = StringArray::new();
filters.push("*.eguitheme; egui theme format".into());
fd.set_filters(filters);
godot_print!("disable input on `GodotEgui`");
gui_owner.set_process_input(false);
}
});
egui::menu::menu(ui, "Options", |ui| {
if ui.button("Set current theme as app theme").clicked() {
let ctx = ui.ctx();
let theme = self.style.export_theme();
let (style, font_definitions, ..) = theme.extract();
ctx.set_style(style);
ctx.set_fonts(font_definitions);
}
if ui.button("Clear settings").clicked() {
self.style = StylistState::default();
let ctx = ui.ctx();
ctx.set_fonts(egui::FontDefinitions::default());
}
if ui.button("Reset App Theme Theme").clicked() {
let ctx = ui.ctx(); | });
});
}
}
fn read_file(filepath: &str) -> String {
use gdnative::api::File;
let file = File::new();
file.open(filepath, File::READ).unwrap_or_else(|_| panic!("{} must exist", &filepath));
file.get_as_text().to_string()
}
pub fn load_theme(path: GodotString) -> egui_theme::EguiTheme {
// Load the GodotEguiTheme via the ResourceLoader and then extract the EguiTheme
let file_path = path.to_string();
let file = read_file(&file_path);
ron::from_str(&file).expect("this should load")
}
pub fn save_theme(path: GodotString, theme: egui_theme::EguiTheme) {
use gdnative::api::File;
// First serialize the theme into ron again
let serialized_theme = ron::to_string(&theme).expect("this should work");
// Save it to a file
let path = path.to_string();
let file = File::new();
file.open(&path, File::WRITE).unwrap_or_else(|_| panic!("{} must exist", &path));
file.store_string(serialized_theme);
} | ctx.set_style(egui::Style::default());
} |
primitive_types5.rs | fn main() {
let cat = ("Furry McFurson", 3.5);
let (name, age) = cat; |
println!("{} is {} years old.", name, age);
} |
|
unlink.rs | #![crate_name = "uu_unlink"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Colin Warren <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: unlink (GNU coreutils) 8.21 */
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use getopts::Options;
use libc::{S_IFMT, S_IFLNK, S_IFREG};
use libc::{lstat, unlink, c_char, stat};
use std::io::{Error, ErrorKind, Write};
use std::mem::uninitialized;
static NAME: &'static str = "unlink";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub fn | (args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "invalid options\n{}", f)
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [FILE]... [OPTION]...", NAME);
println!("");
println!("{}", opts.usage("Unlink the file at [FILE]."));
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.len() == 0 {
crash!(1, "missing operand\nTry '{0} --help' for more information.", NAME);
} else if matches.free.len() > 1 {
crash!(1, "extra operand: '{1}'\nTry '{0} --help' for more information.", NAME, matches.free[1]);
}
let st_mode = {
let mut buf: stat = unsafe { uninitialized() };
let result = unsafe { lstat(matches.free[0].as_ptr() as *const c_char, &mut buf as *mut stat) };
if result < 0 {
crash!(1, "Cannot stat '{}': {}", matches.free[0], Error::last_os_error());
}
buf.st_mode & S_IFMT
};
let result = if st_mode != S_IFREG && st_mode != S_IFLNK {
Err(Error::new(ErrorKind::Other, "Not a regular file or symlink"))
} else {
let result = unsafe { unlink(matches.free[0].as_ptr() as *const c_char) };
if result < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
};
match result {
Ok(_) => (),
Err(e) => {
crash!(1, "cannot unlink '{0}': {1}", matches.free[0], e);
}
}
0
}
| uumain |
UseHandlerRatherThanWhenChangedRule.py | # Copyright (c) 2016 Will Thames <[email protected]>
#
# 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.
from ansiblelint.rules import AnsibleLintRule
def _changed_in_when(item):
if not isinstance(item, str):
return False
return any(changed in item for changed in
['.changed', '|changed', '["changed"]', "['changed']"])
| description = (
'If a task has a ``when: result.changed`` setting, it is effectively '
'acting as a handler'
)
severity = 'MEDIUM'
tags = ['task', 'behaviour']
version_added = 'historic'
def matchtask(self, file, task):
if task["__ansible_action_type__"] != 'task':
return False
when = task.get('when')
if isinstance(when, list):
for item in when:
return _changed_in_when(item)
else:
return _changed_in_when(when) |
class UseHandlerRatherThanWhenChangedRule(AnsibleLintRule):
id = '503'
shortdesc = 'Tasks that run when changed should likely be handlers' |
hitbtc.py | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TRUNCATE
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise
class hitbtc(Exchange):
def describe(self):
return self.deep_extend(super(hitbtc, self).describe(), {
'id': 'hitbtc',
'name': 'HitBTC',
'countries': ['HK'],
# 300 requests per second => 1000ms / 300 = 3.333ms between requests on average(Trading)
# 100 requests per second =>( 1000ms / rateLimit ) / 100 => cost = 3.0003(Market Data)
# 20 requests per second =>( 1000ms / rateLimit ) / 20 => cost = 15.0015(Other Requests)
'rateLimit': 3.333,
'version': '2',
'pro': True,
'has': {
'CORS': None,
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'addMargin': False,
'cancelOrder': True,
'createDepositAddress': True,
'createOrder': True,
'createReduceOnlyOrder': False,
'editOrder': True,
'fetchBalance': True,
'fetchBorrowRate': False,
'fetchBorrowRateHistories': False,
'fetchBorrowRateHistory': False,
'fetchBorrowRates': False,
'fetchBorrowRatesPerSymbol': False,
'fetchClosedOrders': True,
'fetchCurrencies': True,
'fetchDepositAddress': True,
'fetchDeposits': None,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchLeverage': False,
'fetchLeverageTiers': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenInterestHistory': False,
'fetchOpenOrder': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': None,
'fetchOrderTrades': True,
'fetchPosition': False,
'fetchPositions': False,
'fetchPositionsRisk': False,
'fetchPremiumIndexOHLCV': False,
'fetchTicker': True,
'fetchTickers': True,
'fetchTrades': True,
'fetchTradingFee': True,
'fetchTradingFees': False,
'fetchTransactions': True,
'fetchWithdrawals': None,
'reduceMargin': False,
'setLeverage': False,
'setMarginMode': False,
'setPositionMode': False,
'transfer': True,
'withdraw': True,
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', # default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'test': {
'public': 'https://api.demo.hitbtc.com',
'private': 'https://api.demo.hitbtc.com',
},
'api': {
'public': 'https://api.hitbtc.com',
'private': 'https://api.hitbtc.com',
},
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com/v2',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': {
'currency': 3, # Available Currencies
'currency/{currency}': 3, # Get currency info
'symbol': 3, # Available Currency Symbols
'symbol/{symbol}': 3, # Get symbol info
'ticker': 3, # Ticker list for all symbols
'ticker/{symbol}': 3, # Ticker for symbol
'trades': 3,
'trades/{symbol}': 3, # Trades
'orderbook': 3,
'orderbook/{symbol}': 3, # Orderbook
'candles': 3,
'candles/{symbol}': 3, # Candles
},
},
'private': {
'get': {
'trading/balance': 15.0015, # Get trading balance
'order': 15.0015, # List your current open orders
'order/{clientOrderId}': 15.0015, # Get a single order by clientOrderId
'trading/fee/all': 15.0015, # Get trading fee rate
'trading/fee/{symbol}': 15.0015, # Get trading fee rate
'margin/account': 15.0015,
'margin/account/{symbol}': 15.0015,
'margin/position': 15.0015,
'margin/position/{symbol}': 15.0015,
'margin/order': 15.0015,
'margin/order/{clientOrderId}': 15.0015,
'history/order': 15.0015, # Get historical orders
'history/trades': 15.0015, # Get historical trades
'history/order/{orderId}/trades': 15.0015, # Get historical trades by specified order
'account/balance': 15.0015, # Get main acccount balance
'account/crypto/address/{currency}': 15.0015, # Get current address
'account/crypto/addresses/{currency}': 15.0015, # Get last 10 deposit addresses for currency
'account/crypto/used-addresses/{currency}': 15.0015, # Get last 10 unique addresses used for withdraw by currency
'account/crypto/estimate-withdraw': 15.0015,
'account/crypto/is-mine/{address}': 15.0015,
'account/transactions': 15.0015, # Get account transactions
'account/transactions/{id}': 15.0015, # Get account transaction by id
'sub-acc': 15.0015,
'sub-acc/acl': 15.0015,
'sub-acc/balance/{subAccountUserID}': 15.0015,
'sub-acc/deposit-address/{subAccountUserId}/{currency}': 15.0015,
},
'post': {
'order': 1, # Create new order
'margin/order': 1,
'account/crypto/address/{currency}': 1, # Create new crypto deposit address
'account/crypto/withdraw': 1, # Withdraw crypto
'account/crypto/transfer-convert': 1,
'account/transfer': 1, # Transfer amount to trading account or to main account
'account/transfer/internal': 1,
'sub-acc/freeze': 1,
'sub-acc/activate': 1,
'sub-acc/transfer': 1,
},
'put': {
'order/{clientOrderId}': 1, # Create new order
'margin/account/{symbol}': 1,
'margin/order/{clientOrderId}': 1,
'account/crypto/withdraw/{id}': 1, # Commit crypto withdrawal
'sub-acc/acl/{subAccountUserId}': 1,
},
'delete': {
'order': 1, # Cancel all open orders
'order/{clientOrderId}': 1, # Cancel order
'margin/account': 1,
'margin/account/{symbol}': 1,
'margin/position': 1,
'margin/position/{symbol}': 1,
'margin/order': 1,
'margin/order/{clientOrderId}': 1,
'account/crypto/withdraw/{id}': 1, # Rollback crypto withdrawal
},
# outdated?
'patch': {
'order/{clientOrderId}': 1, # Cancel Replace order
},
},
},
'precisionMode': TICK_SIZE,
'fees': {
'trading': {
'tierBased': False,
'percentage': True,
'maker': 0.1 / 100,
'taker': 0.2 / 100,
},
},
'options': {
'networks': {
'ETH': 'T20',
'ERC20': 'T20',
'TRX': 'TTRX',
'TRC20': 'TTRX',
'OMNI': '',
},
'defaultTimeInForce': 'FOK',
'accountsByType': {
'funding': 'bank',
'spot': 'exchange',
},
'fetchBalanceMethod': {
'account': 'account',
'bank': 'account',
'main': 'account',
'funding': 'account',
'exchange': 'trading',
'spot': 'trading',
'trade': 'trading',
'trading': 'trading',
},
},
'commonCurrencies': {
'AUTO': 'Cube',
'BCC': 'BCC', # initial symbol for Bitcoin Cash, now inactive
'BDP': 'BidiPass',
'BET': 'DAO.Casino',
'BIT': 'BitRewards',
'BOX': 'BOX Token',
'CPT': 'Cryptaur', # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081
'GET': 'Themis',
'GMT': 'GMT Token',
'HSR': 'HC',
'IQ': 'IQ.Cash',
'LNC': 'LinkerCoin',
'PLA': 'PlayChip',
'PNT': 'Penta',
'SBTC': 'Super Bitcoin',
'STEPN': 'GMT',
'STX': 'STOX',
'TV': 'Tokenville',
'USD': 'USDT',
'XMT': 'MTL',
'XPNT': 'PNT',
},
'exceptions': {
'504': RequestTimeout, # {"error":{"code":504,"message":"Gateway Timeout"}}
'1002': AuthenticationError, # {"error":{"code":1002,"message":"Authorization failed","description":""}}
'1003': PermissionDenied, # "Action is forbidden for self API key"
'2010': InvalidOrder, # "Quantity not a valid number"
'2001': BadSymbol, # "Symbol not found"
'2011': InvalidOrder, # "Quantity too low"
'2020': InvalidOrder, # "Price not a valid number"
'20002': OrderNotFound, # canceling non-existent order
'20001': InsufficientFunds, # {"error":{"code":20001,"message":"Insufficient funds","description":"Check that the funds are sufficient, given commissions"}}
'20010': BadSymbol, # {"error":{"code":20010,"message":"Exchange temporary closed","description":"Exchange market for self symbol is temporary closed"}}
'20045': InvalidOrder, # {"error":{"code":20045,"message":"Fat finger limit exceeded"}}
},
})
def fee_to_precision(self, symbol, fee):
|
async def fetch_markets(self, params={}):
"""
retrieves data on all markets for hitbtc
:param dict params: extra parameters specific to the exchange api endpoint
:returns [dict]: an array of objects representing market data
"""
response = await self.publicGetSymbol(params)
#
# [
# {
# "id":"BCNBTC",
# "baseCurrency":"BCN",
# "quoteCurrency":"BTC",
# "quantityIncrement":"100",
# "tickSize":"0.00000000001",
# "takeLiquidityRate":"0.002",
# "provideLiquidityRate":"0.001",
# "feeCurrency":"BTC"
# }
# ]
#
result = []
for i in range(0, len(response)):
market = response[i]
id = self.safe_string(market, 'id')
baseId = self.safe_string(market, 'baseCurrency')
quoteId = self.safe_string(market, 'quoteCurrency')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
# bequant fix
symbol = base + '/' + quote
if id.find('_') >= 0:
symbol = id
lotString = self.safe_string(market, 'quantityIncrement')
stepString = self.safe_string(market, 'tickSize')
lot = self.parse_number(lotString)
step = self.parse_number(stepString)
feeCurrencyId = self.safe_string(market, 'feeCurrency')
result.append(self.extend(self.fees['trading'], {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'active': True,
'contract': False,
'linear': None,
'inverse': None,
'taker': self.safe_number(market, 'takeLiquidityRate'),
'maker': self.safe_number(market, 'provideLiquidityRate'),
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'feeCurrency': self.safe_currency_code(feeCurrencyId),
'precision': {
'amount': lot,
'price': step,
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': lot,
'max': None,
},
'price': {
'min': step,
'max': None,
},
'cost': {
'min': self.parse_number(Precise.string_mul(lotString, stepString)),
'max': None,
},
},
'info': market,
}))
return result
async def transfer(self, code, amount, fromAccount, toAccount, params={}):
"""
transfer currency internally between wallets on the same account
:param str code: unified currency code
:param float amount: amount to transfer
:param str fromAccount: account to transfer from
:param str toAccount: account to transfer to
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
"""
# account can be "exchange" or "bank", with aliases "main" or "trading" respectively
await self.load_markets()
currency = self.currency(code)
requestAmount = self.currency_to_precision(code, amount)
request = {
'currency': currency['id'],
'amount': requestAmount,
}
type = self.safe_string(params, 'type')
if type is None:
accountsByType = self.safe_value(self.options, 'accountsByType', {})
fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
toId = self.safe_string(accountsByType, toAccount, toAccount)
if fromId == toId:
raise ExchangeError(self.id + ' transfer() from and to cannot be the same account')
type = fromId + 'To' + self.capitalize(toId)
request['type'] = type
response = await self.privatePostAccountTransfer(self.extend(request, params))
#
# {
# 'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
# }
#
transfer = self.parse_transfer(response, currency)
return self.extend(transfer, {
'fromAccount': fromAccount,
'toAccount': toAccount,
'amount': self.parse_number(requestAmount),
})
def parse_transfer(self, transfer, currency=None):
#
# {
# 'id': '2db6ebab-fb26-4537-9ef8-1a689472d236'
# }
#
timestamp = self.milliseconds()
return {
'id': self.safe_string(transfer, 'id'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'currency': self.safe_currency_code(None, currency),
'amount': None,
'fromAccount': None,
'toAccount': None,
'status': None,
'info': transfer,
}
async def fetch_currencies(self, params={}):
"""
fetches all available currencies on an exchange
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an associative dictionary of currencies
"""
response = await self.publicGetCurrency(params)
#
# [
# {
# "id":"XPNT",
# "fullName":"pToken",
# "crypto":true,
# "payinEnabled":true,
# "payinPaymentId":false,
# "payinConfirmations":9,
# "payoutEnabled":true,
# "payoutIsPaymentId":false,
# "transferEnabled":true,
# "delisted":false,
# "payoutFee":"26.510000000000",
# "precisionPayout":18,
# "precisionTransfer":8
# }
# ]
#
result = {}
for i in range(0, len(response)):
currency = response[i]
id = self.safe_string(currency, 'id')
# todo: will need to rethink the fees
# to add support for multiple withdrawal/deposit methods and
# differentiated fees for each particular method
precision = self.safe_string(currency, 'precisionTransfer', '8')
decimals = self.parse_number(precision)
code = self.safe_currency_code(id)
payin = self.safe_value(currency, 'payinEnabled')
payout = self.safe_value(currency, 'payoutEnabled')
transfer = self.safe_value(currency, 'transferEnabled')
active = payin and payout and transfer
if 'disabled' in currency:
if currency['disabled']:
active = False
type = 'fiat'
if ('crypto' in currency) and currency['crypto']:
type = 'crypto'
name = self.safe_string(currency, 'fullName')
result[code] = {
'id': id,
'code': code,
'type': type,
'payin': payin,
'payout': payout,
'transfer': transfer,
'info': currency,
'name': name,
'active': active,
'deposit': payin,
'withdraw': payout,
'fee': self.safe_number(currency, 'payoutFee'), # todo: redesign
'precision': self.parse_number(self.parse_precision(precision)),
'limits': {
'amount': {
'min': 1 / math.pow(10, decimals),
'max': None,
},
'withdraw': {
'min': None,
'max': None,
},
},
}
return result
def parse_trading_fee(self, fee, market=None):
#
#
# {
# takeLiquidityRate: '0.001',
# provideLiquidityRate: '-0.0001'
# }
#
return {
'info': fee,
'symbol': self.safe_symbol(None, market),
'maker': self.safe_number(fee, 'provideLiquidityRate'),
'taker': self.safe_number(fee, 'takeLiquidityRate'),
'percentage': True,
'tierBased': True,
}
async def fetch_trading_fee(self, symbol, params={}):
"""
fetch the trading fees for a market
:param str symbol: unified market symbol
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>`
"""
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = await self.privateGetTradingFeeSymbol(request)
#
# {
# takeLiquidityRate: '0.001',
# provideLiquidityRate: '-0.0001'
# }
#
return self.parse_trading_fee(response, market)
def parse_balance(self, response):
result = {
'info': response,
'timestamp': None,
'datetime': None,
}
for i in range(0, len(response)):
balance = response[i]
currencyId = self.safe_string(balance, 'currency')
code = self.safe_currency_code(currencyId)
account = self.account()
account['free'] = self.safe_string(balance, 'available')
account['used'] = self.safe_string(balance, 'reserved')
result[code] = account
return self.safe_balance(result)
async def fetch_balance(self, params={}):
"""
query for balance and get the amount of funds available for trading or funds locked in orders
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
"""
await self.load_markets()
type = self.safe_string(params, 'type', 'trading')
fetchBalanceAccounts = self.safe_value(self.options, 'fetchBalanceMethod', {})
typeId = self.safe_string(fetchBalanceAccounts, type)
if typeId is None:
raise ExchangeError(self.id + ' fetchBalance() account type must be either main or trading')
method = 'privateGet' + self.capitalize(typeId) + 'Balance'
query = self.omit(params, 'type')
response = await getattr(self, method)(query)
#
# [
# {"currency":"SPI","available":"0","reserved":"0"},
# {"currency":"GRPH","available":"0","reserved":"0"},
# {"currency":"DGTX","available":"0","reserved":"0"},
# ]
#
return self.parse_balance(response)
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# "timestamp":"2015-08-20T19:01:00.000Z",
# "open":"0.006",
# "close":"0.006",
# "min":"0.006",
# "max":"0.006",
# "volume":"0.003",
# "volumeQuote":"0.000018"
# }
#
return [
self.parse8601(self.safe_string(ohlcv, 'timestamp')),
self.safe_number(ohlcv, 'open'),
self.safe_number(ohlcv, 'max'),
self.safe_number(ohlcv, 'min'),
self.safe_number(ohlcv, 'close'),
self.safe_number(ohlcv, 'volume'),
]
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
"""
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int|None since: timestamp in ms of the earliest candle to fetch
:param int|None limit: the maximum amount of candles to fetch
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
"""
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'period': self.timeframes[timeframe],
}
if since is not None:
request['from'] = self.iso8601(since)
if limit is not None:
request['limit'] = limit
response = await self.publicGetCandlesSymbol(self.extend(request, params))
#
# [
# {"timestamp":"2015-08-20T19:01:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.003","volumeQuote":"0.000018"},
# {"timestamp":"2015-08-20T19:03:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.013","volumeQuote":"0.000078"},
# {"timestamp":"2015-08-20T19:06:00.000Z","open":"0.0055","close":"0.005","min":"0.005","max":"0.0055","volume":"0.003","volumeQuote":"0.0000155"},
# ]
#
return self.parse_ohlcvs(response, market, timeframe, since, limit)
async def fetch_order_book(self, symbol, limit=None, params={}):
"""
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
:param str symbol: unified symbol of the market to fetch the order book for
:param int|None limit: the maximum amount of order book entries to return
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
"""
await self.load_markets()
request = {
'symbol': self.market_id(symbol),
}
if limit is not None:
request['limit'] = limit # default = 100, 0 = unlimited
response = await self.publicGetOrderbookSymbol(self.extend(request, params))
return self.parse_order_book(response, symbol, None, 'bid', 'ask', 'price', 'size')
def parse_ticker(self, ticker, market=None):
timestamp = self.parse8601(ticker['timestamp'])
symbol = self.safe_symbol(None, market)
baseVolume = self.safe_string(ticker, 'volume')
quoteVolume = self.safe_string(ticker, 'volumeQuote')
open = self.safe_string(ticker, 'open')
last = self.safe_string(ticker, 'last')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_string(ticker, 'high'),
'low': self.safe_string(ticker, 'low'),
'bid': self.safe_string(ticker, 'bid'),
'bidVolume': None,
'ask': self.safe_string(ticker, 'ask'),
'askVolume': None,
'vwap': None,
'open': open,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market)
async def fetch_tickers(self, symbols=None, params={}):
"""
fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
:param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
"""
await self.load_markets()
response = await self.publicGetTicker(params)
result = {}
for i in range(0, len(response)):
ticker = response[i]
marketId = self.safe_string(ticker, 'symbol')
market = self.safe_market(marketId)
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return self.filter_by_array(result, 'symbol', symbols)
async def fetch_ticker(self, symbol, params={}):
"""
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
"""
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = await self.publicGetTickerSymbol(self.extend(request, params))
if 'message' in response:
raise ExchangeError(self.id + ' ' + response['message'])
return self.parse_ticker(response, market)
def parse_trade(self, trade, market=None):
# createMarketOrder
#
# { fee: "0.0004644",
# id: 386394956,
# price: "0.4644",
# quantity: "1",
# timestamp: "2018-10-25T16:41:44.780Z"}
#
# fetchTrades
#
# {id: 974786185,
# price: '0.032462',
# quantity: '0.3673',
# side: 'buy',
# timestamp: '2020-10-16T12:57:39.846Z'}
#
# fetchMyTrades
#
# {id: 277210397,
# clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
# orderId: 28102855393,
# symbol: 'ETHBTC',
# side: 'sell',
# quantity: '0.002',
# price: '0.073365',
# fee: '0.000000147',
# timestamp: '2018-04-28T18:39:55.345Z'}
#
# {
# "id":1568938909,
# "orderId":793293348428,
# "clientOrderId":"fbc5c5b753e8476cb14697458cb928ef",
# "symbol":"DOGEUSD",
# "side":"sell",
# "quantity":"100",
# "price":"0.03904191",
# "fee":"0.009760477500",
# "timestamp":"2022-01-25T15:15:41.353Z",
# "taker":true
# }
#
timestamp = self.parse8601(trade['timestamp'])
marketId = self.safe_string(trade, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['symbol']
fee = None
feeCostString = self.safe_string(trade, 'fee')
if feeCostString is not None:
feeCurrencyCode = market['feeCurrency'] if market else None
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
}
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
orderId = self.safe_string(trade, 'clientOrderId')
priceString = self.safe_string(trade, 'price')
amountString = self.safe_string(trade, 'quantity')
side = self.safe_string(trade, 'side')
id = self.safe_string(trade, 'id')
return self.safe_trade({
'info': trade,
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': None,
'side': side,
'takerOrMaker': None,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': fee,
}, market)
async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
"""
fetch history of deposits and withdrawals
:param str|None code: unified currency code for the currency of the transactions, default is None
:param int|None since: timestamp in ms of the earliest transaction, default is None
:param int|None limit: max number of transactions to return, default is None
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a list of `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
"""
await self.load_markets()
currency = None
request = {}
if code is not None:
currency = self.currency(code)
request['asset'] = currency['id']
if since is not None:
request['startTime'] = since
response = await self.privateGetAccountTransactions(self.extend(request, params))
return self.parse_transactions(response, currency, since, limit)
def parse_transaction(self, transaction, currency=None):
#
# transactions
#
# {
# id: 'd53ee9df-89bf-4d09-886e-849f8be64647',
# index: 1044718371,
# type: 'payout', # payout, payin
# status: 'success',
# currency: 'ETH',
# amount: '4.522683200000000000000000',
# createdAt: '2018-06-07T00:43:32.426Z',
# updatedAt: '2018-06-07T00:45:36.447Z',
# hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f',
# address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c',
# fee: '0.00958',
# },
# {
# id: 'e6c63331-467e-4922-9edc-019e75d20ba3',
# index: 1044714672,
# type: 'exchangeToBank', # exchangeToBank, bankToExchange, withdraw
# status: 'success',
# currency: 'ETH',
# amount: '4.532263200000000000',
# createdAt: '2018-06-07T00:42:39.543Z',
# updatedAt: '2018-06-07T00:42:39.683Z',
# },
#
# withdraw
#
# {
# "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
# }
#
id = self.safe_string(transaction, 'id')
timestamp = self.parse8601(self.safe_string(transaction, 'createdAt'))
updated = self.parse8601(self.safe_string(transaction, 'updatedAt'))
currencyId = self.safe_string(transaction, 'currency')
code = self.safe_currency_code(currencyId, currency)
status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
amount = self.safe_number(transaction, 'amount')
address = self.safe_string(transaction, 'address')
txid = self.safe_string(transaction, 'hash')
fee = None
feeCost = self.safe_number(transaction, 'fee')
if feeCost is not None:
fee = {
'cost': feeCost,
'currency': code,
}
type = self.parse_transaction_type(self.safe_string(transaction, 'type'))
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'network': None,
'address': address,
'addressTo': None,
'addressFrom': None,
'tag': None,
'tagTo': None,
'tagFrom': None,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
}
def parse_transaction_status(self, status):
statuses = {
'pending': 'pending',
'failed': 'failed',
'success': 'ok',
}
return self.safe_string(statuses, status, status)
def parse_transaction_type(self, type):
types = {
'payin': 'deposit',
'payout': 'withdrawal',
'withdraw': 'withdrawal',
}
return self.safe_string(types, type, type)
async def fetch_trades(self, symbol, since=None, limit=None, params={}):
"""
get the list of most recent trades for a particular symbol
:param str symbol: unified symbol of the market to fetch trades for
:param int|None since: timestamp in ms of the earliest trade to fetch
:param int|None limit: the maximum amount of trades to fetch
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
"""
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['limit'] = limit
if since is not None:
request['sort'] = 'ASC'
request['from'] = self.iso8601(since)
response = await self.publicGetTradesSymbol(self.extend(request, params))
return self.parse_trades(response, market, since, limit)
async def create_order(self, symbol, type, side, amount, price=None, params={}):
"""
create a trade order
:param str symbol: unified symbol of the market to create an order in
:param str type: 'market' or 'limit'
:param str side: 'buy' or 'sell'
:param float amount: how much of currency you want to trade in units of base currency
:param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
"""
await self.load_markets()
market = self.market(symbol)
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
# their max accepted length is 32 characters
uuid = self.uuid()
parts = uuid.split('-')
clientOrderId = ''.join(parts)
clientOrderId = clientOrderId[0:32]
amount = float(amount)
request = {
'clientOrderId': clientOrderId,
'symbol': market['id'],
'side': side,
'quantity': self.amount_to_precision(symbol, amount),
'type': type,
}
if type == 'limit':
request['price'] = self.price_to_precision(symbol, price)
else:
request['timeInForce'] = self.options['defaultTimeInForce']
response = await self.privatePostOrder(self.extend(request, params))
order = self.parse_order(response)
if order['status'] == 'rejected':
raise InvalidOrder(self.id + ' order was rejected by the exchange ' + self.json(order))
return order
async def edit_order(self, id, symbol, type, side, amount=None, price=None, params={}):
await self.load_markets()
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
# their max accepted length is 32 characters
uuid = self.uuid()
parts = uuid.split('-')
requestClientId = ''.join(parts)
requestClientId = requestClientId[0:32]
request = {
'clientOrderId': id,
'requestClientId': requestClientId,
}
if amount is not None:
request['quantity'] = self.amount_to_precision(symbol, amount)
if price is not None:
request['price'] = self.price_to_precision(symbol, price)
response = await self.privatePatchOrderClientOrderId(self.extend(request, params))
return self.parse_order(response)
async def cancel_order(self, id, symbol=None, params={}):
"""
cancels an open order
:param str id: order id
:param str|None symbol: unified symbol of the market the order was made in
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
"""
await self.load_markets()
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
request = {
'clientOrderId': id,
}
response = await self.privateDeleteOrderClientOrderId(self.extend(request, params))
return self.parse_order(response)
def parse_order_status(self, status):
statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
}
return self.safe_string(statuses, status, status)
def parse_order(self, order, market=None):
#
# createMarketOrder
#
# {
# clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0",
# createdAt: "2018-10-25T16:41:44.780Z",
# cumQuantity: "1",
# id: "66799540063",
# quantity: "1",
# side: "sell",
# status: "filled",
# symbol: "XRPUSDT",
# timeInForce: "FOK",
# tradesReport: [
# {
# fee: "0.0004644",
# id: 386394956,
# price: "0.4644",
# quantity: "1",
# timestamp: "2018-10-25T16:41:44.780Z"
# }
# ],
# type: "market",
# updatedAt: "2018-10-25T16:41:44.780Z"
# }
#
# {
# "id": 119499457455,
# "clientOrderId": "87baab109d58401b9202fa0749cb8288",
# "symbol": "ETHUSD",
# "side": "buy",
# "status": "filled",
# "type": "market",
# "timeInForce": "FOK",
# "quantity": "0.0007",
# "price": "181.487",
# "avgPrice": "164.989",
# "cumQuantity": "0.0007",
# "createdAt": "2019-04-17T13:27:38.062Z",
# "updatedAt": "2019-04-17T13:27:38.062Z"
# }
#
created = self.parse8601(self.safe_string(order, 'createdAt'))
updated = self.parse8601(self.safe_string(order, 'updatedAt'))
marketId = self.safe_string(order, 'symbol')
market = self.safe_market(marketId, market)
symbol = market['symbol']
amount = self.safe_string(order, 'quantity')
filled = self.safe_string(order, 'cumQuantity')
status = self.parse_order_status(self.safe_string(order, 'status'))
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
id = self.safe_string(order, 'clientOrderId')
clientOrderId = id
price = self.safe_string(order, 'price')
type = self.safe_string(order, 'type')
side = self.safe_string(order, 'side')
trades = self.safe_value(order, 'tradesReport')
fee = None
average = self.safe_string(order, 'avgPrice')
timeInForce = self.safe_string(order, 'timeInForce')
return self.safe_order({
'id': id,
'clientOrderId': clientOrderId, # https://github.com/ccxt/ccxt/issues/5674
'timestamp': created,
'datetime': self.iso8601(created),
'lastTradeTimestamp': updated,
'status': status,
'symbol': symbol,
'type': type,
'timeInForce': timeInForce,
'side': side,
'price': price,
'stopPrice': None,
'average': average,
'amount': amount,
'cost': None,
'filled': filled,
'remaining': None,
'fee': fee,
'trades': trades,
'info': order,
}, market)
async def fetch_order(self, id, symbol=None, params={}):
"""
fetches information on an order made by the user
:param str|None symbol: not used by hitbtc fetchOrder
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
"""
await self.load_markets()
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
request = {
'clientOrderId': id,
}
response = await self.privateGetHistoryOrder(self.extend(request, params))
numOrders = len(response)
if numOrders > 0:
return self.parse_order(response[0])
raise OrderNotFound(self.id + ' order ' + id + ' not found')
async def fetch_open_order(self, id, symbol=None, params={}):
"""
fetch an open order by it's id
:param str id: order id
:param str|None symbol: not used by hitbtc fetchOpenOrder()
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
"""
await self.load_markets()
# we use clientOrderId as the order id with self exchange intentionally
# because most of their endpoints will require clientOrderId
# explained here: https://github.com/ccxt/ccxt/issues/5674
request = {
'clientOrderId': id,
}
response = await self.privateGetOrderClientOrderId(self.extend(request, params))
return self.parse_order(response)
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
"""
fetch all unfilled currently open orders
:param str|None symbol: unified market symbol
:param int|None since: the earliest time in ms to fetch open orders for
:param int|None limit: the maximum number of open orders structures to retrieve
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
"""
await self.load_markets()
market = None
request = {}
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
response = await self.privateGetOrder(self.extend(request, params))
return self.parse_orders(response, market, since, limit)
async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
"""
fetches information on multiple closed orders made by the user
:param str|None symbol: unified market symbol of the market orders were made in
:param int|None since: the earliest time in ms to fetch orders for
:param int|None limit: the maximum number of orde structures to retrieve
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [dict]: a list of [order structures]{@link https://docs.ccxt.com/en/latest/manual.html#order-structure
"""
await self.load_markets()
market = None
request = {}
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
if limit is not None:
request['limit'] = limit
if since is not None:
request['from'] = self.iso8601(since)
response = await self.privateGetHistoryOrder(self.extend(request, params))
parsedOrders = self.parse_orders(response, market)
orders = []
for i in range(0, len(parsedOrders)):
order = parsedOrders[i]
status = order['status']
if (status == 'closed') or (status == 'canceled'):
orders.append(order)
return self.filter_by_since_limit(orders, since, limit)
async def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
"""
fetch all trades made by the user
:param str|None symbol: unified market symbol
:param int|None since: the earliest time in ms to fetch trades for
:param int|None limit: the maximum number of trades structures to retrieve
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
"""
await self.load_markets()
request = {
# 'symbol': 'BTC/USD', # optional
# 'sort': 'DESC', # or 'ASC'
# 'by': 'timestamp', # or 'id' str timestamp by default, or id
# 'from': 'Datetime or Number', # ISO 8601
# 'till': 'Datetime or Number',
# 'limit': 100,
# 'offset': 0,
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
if since is not None:
request['from'] = self.iso8601(since)
if limit is not None:
request['limit'] = limit
response = await self.privateGetHistoryTrades(self.extend(request, params))
#
# [
# {
# "id": 9535486,
# "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454",
# "orderId": 816088377,
# "symbol": "ETHBTC",
# "side": "sell",
# "quantity": "0.061",
# "price": "0.045487",
# "fee": "0.000002775",
# "timestamp": "2017-05-17T12:32:57.848Z"
# },
# {
# "id": 9535437,
# "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6",
# "orderId": 816088021,
# "symbol": "ETHBTC",
# "side": "buy",
# "quantity": "0.038",
# "price": "0.046000",
# "fee": "-0.000000174",
# "timestamp": "2017-05-17T12:30:57.848Z"
# }
# ]
#
return self.parse_trades(response, market, since, limit)
async def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
"""
fetch all the trades made from a single order
:param str id: order id
:param str|None symbol: unified market symbol
:param int|None since: the earliest time in ms to fetch trades for
:param int|None limit: the maximum number of trades to retrieve
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
"""
# The id needed here is the exchange's id, and not the clientOrderID,
# which is the id that is stored in the unified order id
# To get the exchange's id you need to grab it from order['info']['id']
await self.load_markets()
market = None
if symbol is not None:
market = self.market(symbol)
request = {
'orderId': id,
}
response = await self.privateGetHistoryOrderOrderIdTrades(self.extend(request, params))
numOrders = len(response)
if numOrders > 0:
return self.parse_trades(response, market, since, limit)
raise OrderNotFound(self.id + ' order ' + id + ' not found, ' + self.id + '.fetchOrderTrades() requires an exchange-specific order id, you need to grab it from order["info"]["id"]')
async def create_deposit_address(self, code, params={}):
"""
create a currency deposit address
:param str code: unified currency code of the currency for the deposit address
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
"""
await self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = await self.privatePostAccountCryptoAddressCurrency(self.extend(request, params))
address = self.safe_string(response, 'address')
self.check_address(address)
tag = self.safe_string(response, 'paymentId')
return {
'currency': currency,
'address': address,
'tag': tag,
'info': response,
}
async def fetch_deposit_address(self, code, params={}):
"""
fetch the deposit address for a currency associated with self account
:param str code: unified currency code
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
"""
await self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
network = self.safe_string(params, 'network')
if network is not None:
params = self.omit(params, 'network')
networks = self.safe_value(self.options, 'networks')
endpart = self.safe_string(networks, network, network)
request['currency'] += endpart
response = await self.privateGetAccountCryptoAddressCurrency(self.extend(request, params))
address = self.safe_string(response, 'address')
self.check_address(address)
tag = self.safe_string(response, 'paymentId')
return {
'currency': currency['code'],
'address': address,
'tag': tag,
'network': None,
'info': response,
}
async def convert_currency_network(self, code, amount, fromNetwork, toNetwork, params):
await self.load_markets()
currency = self.currency(code)
networks = self.safe_value(self.options, 'networks', {})
fromNetwork = self.safe_string(networks, fromNetwork, fromNetwork) # handle ETH>ERC20 alias
toNetwork = self.safe_string(networks, toNetwork, toNetwork) # handle ETH>ERC20 alias
if fromNetwork == toNetwork:
raise ExchangeError(self.id + ' convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork')
request = {
'fromCurrency': currency['id'] + fromNetwork,
'toCurrency': currency['id'] + toNetwork,
'amount': float(self.currency_to_precision(code, amount)),
}
response = await self.privatePostAccountCryptoTransferConvert(self.extend(request, params))
return {
'info': response,
}
async def withdraw(self, code, amount, address, tag=None, params={}):
"""
make a withdrawal
:param str code: unified currency code
:param float amount: the amount to withdraw
:param str address: the address to withdraw to
:param str|None tag:
:param dict params: extra parameters specific to the hitbtc api endpoint
:returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
"""
tag, params = self.handle_withdraw_tag_and_params(tag, params)
await self.load_markets()
self.check_address(address)
currency = self.currency(code)
request = {
'currency': currency['id'],
'amount': float(amount),
'address': address,
}
if tag:
request['paymentId'] = tag
networks = self.safe_value(self.options, 'networks', {})
network = self.safe_string_upper(params, 'network') # self line allows the user to specify either ERC20 or ETH
network = self.safe_string(networks, network, network) # handle ERC20>ETH alias
if network is not None:
request['currency'] += network # when network the currency need to be changed to currency + network
params = self.omit(params, 'network')
response = await self.privatePostAccountCryptoWithdraw(self.extend(request, params))
#
# {
# "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b"
# }
#
return self.parse_transaction(response, currency)
def nonce(self):
return self.milliseconds()
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/api/' + self.version + '/'
query = self.omit(params, self.extract_params(path))
if api == 'public':
url += api + '/' + self.implode_params(path, params)
if query:
url += '?' + self.urlencode(query)
else:
self.check_required_credentials()
url += self.implode_params(path, params)
if method == 'GET':
if query:
url += '?' + self.urlencode(query)
elif query:
body = self.json(query)
payload = self.encode(self.apiKey + ':' + self.secret)
auth = self.string_to_base64(payload)
headers = {
'Authorization': 'Basic ' + self.decode(auth),
'Content-Type': 'application/json',
}
url = self.urls['api'][api] + url
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
if response is None:
return
if code >= 400:
feedback = self.id + ' ' + body
# {"code":504,"message":"Gateway Timeout","description":""}
if (code == 503) or (code == 504):
raise ExchangeNotAvailable(feedback)
# fallback to default error handler on rate limit errors
# {"code":429,"message":"Too many requests","description":"Too many requests"}
if code == 429:
return
# {"error":{"code":20002,"message":"Order not found","description":""}}
if body[0] == '{':
if 'error' in response:
errorCode = self.safe_string(response['error'], 'code')
self.throw_exactly_matched_exception(self.exceptions, errorCode, feedback)
message = self.safe_string(response['error'], 'message')
if message == 'Duplicate clientOrderId':
raise InvalidOrder(feedback)
raise ExchangeError(feedback)
| return self.decimal_to_precision(fee, TRUNCATE, 0.00000001, TICK_SIZE) |
test_parser.py | # -*- coding: utf-8 -*-
################################################################################
# Copyright (c), AiiDA team and individual contributors. #
# All rights reserved. #
# This file is part of the AiiDA-wannier90 code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-wannier90 #
# For further information on the license, see the LICENSE.txt file #
################################################################################
import pytest
from aiida import orm
ENTRY_POINT_CALC_JOB = 'wannier90.wannier90'
ENTRY_POINT_PARSER = 'wannier90.wannier90'
@pytest.mark.parametrize("seedname", ("aiida", "wannier"))
def test_wannier_default(#pylint: disable=too-many-arguments
fixture_localhost, generate_calc_job_node, generate_parser,
generate_win_params_gaas, data_regression, seedname
):
"""Basic check of parsing a Wannier90 calculation."""
node = generate_calc_job_node(
entry_point_name=ENTRY_POINT_CALC_JOB,
computer=fixture_localhost,
test_name='gaas/seedname_{}'.format(seedname),
inputs=generate_win_params_gaas(),
seedname=seedname
)
parser = generate_parser(ENTRY_POINT_PARSER)
results, calcfunction = parser.parse_from_node(
node, store_provenance=False
)
assert calcfunction.is_finished, calcfunction.exception
assert calcfunction.is_finished_ok, calcfunction.exit_message
assert not orm.Log.objects.get_logs_for(node)
assert 'output_parameters' in results
data_regression.check({
'output_parameters':
results['output_parameters'].get_dict(),
})
def test_no_kpoint_path(
fixture_localhost,
generate_calc_job_node,
generate_parser,
generate_win_params_gaas,
data_regression,
):
"""Check that parsing still works if the 'kpoint_path' is not set."""
inputs = generate_win_params_gaas()
del inputs['kpoint_path']
node = generate_calc_job_node(
entry_point_name=ENTRY_POINT_CALC_JOB,
computer=fixture_localhost,
test_name='gaas/seedname_aiida',
inputs=inputs,
)
parser = generate_parser(ENTRY_POINT_PARSER)
results, calcfunction = parser.parse_from_node(
node, store_provenance=False
)
assert calcfunction.is_finished, calcfunction.exception
assert calcfunction.is_finished_ok, calcfunction.exit_message
assert not orm.Log.objects.get_logs_for(node)
assert 'output_parameters' in results
data_regression.check({
'output_parameters':
results['output_parameters'].get_dict(),
})
@pytest.mark.parametrize("band_parser", ("new", "legacy"))
def test_band_parser(#pylint: disable=too-many-arguments
fixture_localhost, generate_calc_job_node, generate_parser,
generate_win_params_o2sr, data_regression, band_parser
):
"""Check that band parser returns correct dimension and labels."""
inputs = generate_win_params_o2sr()
node = generate_calc_job_node(
entry_point_name=ENTRY_POINT_CALC_JOB,
computer=fixture_localhost,
test_name='o2sr/band_{}'.format(band_parser),
inputs=inputs
)
parser = generate_parser(ENTRY_POINT_PARSER)
results, calcfunction = parser.parse_from_node(
node, store_provenance=False
)
assert calcfunction.is_finished, calcfunction.exception
assert calcfunction.is_finished_ok, calcfunction.exit_message
assert not orm.Log.objects.get_logs_for(node)
assert 'output_parameters' in results
data_regression.check({
'output_parameters':
results['output_parameters'].get_dict(),
})
bands = results['interpolated_bands']
if band_parser == "new":
assert bands.get_kpoints().shape == (607, 3)
assert bands.get_bands().shape == (607, 21) | (505, 'X'), (533, 'R'), (534, 'G'), (606, 'M')]
elif band_parser == "legacy":
assert bands.get_kpoints().shape == (604, 3)
assert bands.get_bands().shape == (604, 21)
assert bands.labels == [(0, 'GAMMA'), (100, 'X'), (137, 'P'),
(208, 'N'), (288, 'GAMMA'), (362, 'M'),
(412, 'S'), (413, 'S_0'), (502, 'GAMMA'),
(503, 'X'), (530, 'R'), (531, 'G'), (603, 'M')] | assert bands.labels == [(0, 'GAMMA'), (100, 'X'), (137, 'P'),
(208, 'N'), (288, 'GAMMA'), (362, 'M'),
(413, 'S'), (414, 'S_0'), (504, 'GAMMA'), |
tst_dataset.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 17:32:08 2020
@author: apramanik
"""
import numpy as np
import SimpleITK as sitk
import torch
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
#%% Functions
def normalize_img(img):
img = img.copy().astype(np.float32)
img -= np.mean(img)
img /= np.std(img)
return img
def crop_img(img):
sizex = 144
sizey = 144
sizez = 8
img = img.copy()
sh = img.shape
midptx = int(sh[2]/2)
midpty = int(sh[3]/2)
if sh[1]<8:
residue=8-sh[1]
a=np.zeros((sh[0],int(residue),144,144),dtype=np.float32)
img=img[:,:,midptx-int(sizex/2):midptx+int(sizex/2),midpty-int(sizey/2):midpty+int(sizey/2)]
img=np.concatenate((img,a),axis=1)
else:
midptz = int(sh[1]/2)
img = img[:,midptz-int(sizez/2):midptz+int(sizez/2),midptx-int(sizex/2):midptx+int(sizex/2),midpty-int(sizey/2):midpty+int(sizey/2)]
return img
def crop_label(img):
sizex = 144
sizey = 144
sizez = 8
img = img.copy()
sh = img.shape
midptx = int(sh[1]/2)
midpty = int(sh[2]/2)
if sh[0]<8:
residue=8-sh[0]
a=np.zeros((int(residue),144,144),dtype=np.float32)
img=img[:,midptx-int(sizex/2):midptx+int(sizex/2),midpty-int(sizey/2):midpty+int(sizey/2)]
img=np.concatenate((img,a),axis=0)
else:
midptz = int(sh[0]/2)
img = img[midptz-int(sizez/2):midptz+int(sizez/2),midptx-int(sizex/2):midptx+int(sizex/2),midpty-int(sizey/2):midpty+int(sizey/2)]
return img
def crop_img_paper(img):
sizez = 8
img = img.copy()
sh = img.shape
if sh[1]<8:
residue=8-sh[1]
a=np.zeros((sh[0],int(residue),sh[2],sh[3]),dtype=np.float32)
img=np.concatenate((img,a),axis=1)
else:
midptz = int(sh[1]/2)
img = img[:,midptz-int(sizez/2):midptz+int(sizez/2),:,:]
return img
def crop_label_paper(img):
sizez = 8
img = img.copy()
sh = img.shape
if sh[0]<8:
residue=8-sh[0]
a=np.zeros((int(residue),sh[1],sh[2]),dtype=np.float32)
img=np.concatenate((img,a),axis=0)
else:
midptz = int(sh[0]/2)
img = img[midptz-int(sizez/2):midptz+int(sizez/2),:,:]
return img
#%%paths
#%%dataset preparation
class cardiacdata_old(Dataset):
def __init__(self, img_dir = "./Datasets/patient005/patient005_4d.nii.gz", label_dir = r'./Datasets/patient005/patient005_frame01_gt.nii.gz'):
IMG_DIR = "./Datasets"
ptnum=str(5).zfill(3)
img_dir = IMG_DIR + '/patient'+ptnum+'/patient'+ptnum+'_4d.nii.gz'
dummy_img = sitk.GetArrayFromImage(sitk.ReadImage(img_dir))
dummy_img = crop_img(dummy_img)
file = open(IMG_DIR + '/patient'+ptnum+'/'+"Info.cfg","r")
es=int(file.read().split("\n")[1].split(":")[1])
es_str=str(es).zfill(2)
gt_dir_es = IMG_DIR + '/patient'+ptnum+'/patient'+ptnum+'_frame'+es_str+'_gt.nii.gz'
es_label = sitk.GetArrayFromImage(sitk.ReadImage(gt_dir_es))
es_label = crop_label(es_label)
file = open(IMG_DIR + '/patient'+ptnum+'/'+"Info.cfg","r")
ed=int(file.read().split("\n")[0].split(":")[1])
ed_str=str(ed).zfill(2)
gt_dir_ed = IMG_DIR + '/patient'+ptnum+'/patient'+ptnum+'_frame'+ed_str+'_gt.nii.gz'
ed_label = sitk.GetArrayFromImage(sitk.ReadImage(gt_dir_ed))
ed_label = crop_label(ed_label)
a = dummy_img[ed-1:ed]
b = dummy_img[es-1:es]
dummy_img = np.concatenate((a,b),axis=0)
dummy_img = normalize_img(dummy_img)
ed_label = np.expand_dims(ed_label,axis=0)
es_label = np.expand_dims(es_label,axis=0)
dummy_gt = np.concatenate((ed_label,es_label),axis=0)
self.img = np.expand_dims(np.reshape(dummy_img,[dummy_img.shape[0]*dummy_img.shape[1],dummy_img.shape[2],dummy_img.shape[3]]),axis=0)
self.gt = np.expand_dims(np.reshape(dummy_gt,[dummy_gt.shape[0]*dummy_gt.shape[1],dummy_gt.shape[2],dummy_gt.shape[3]]),axis=0)
self.len = self.img.shape[0]
return
def __len__(self):
return self.len
def __getitem__(self, i):
img = self.img[i]
gt = self.gt[i]
img = torch.from_numpy(img.astype(np.float32)).unsqueeze(0)
gt = torch.from_numpy(gt.astype(np.float32)).long()
return img,gt
class cardiacdata(Dataset):
def __init__(self, img_dir = "./Datasets/patient005/patient005_4d.nii.gz", label_dir = r'./Datasets/patient005/patient005_frame01_gt.nii.gz'):
|
def __len__(self):
return self.len
def __getitem__(self, i):
img = self.img[i]
gt = self.gt[i]
img = torch.from_numpy(img.astype(np.float32)).unsqueeze(0)
gt = torch.from_numpy(gt.astype(np.float32)).long()
return img,gt
if __name__ == "__main__":
dataset = cardiacdata()
loader = DataLoader(dataset, shuffle=False, batch_size=1)
count=0
for step, (img, gt) in enumerate(loader):
count=count+1
print('img shape is:', img.shape)
print('gt shape is:', gt.shape)
fig, axes = plt.subplots(1,2)
pos = axes[0].imshow(img[0,0,2,])
pos = axes[1].imshow(gt[0,2,])
plt.show()
#break
| dummy_img = sitk.GetArrayFromImage(sitk.ReadImage(img_dir))
dummy_img = np.squeeze(dummy_img)
# print(dummy_img.shape)
dummy_img = crop_img(dummy_img)
# print(dummy_img.shape)
dummy_img = normalize_img(dummy_img)
if not label_dir is None:
dummy_gt = sitk.GetArrayFromImage(sitk.ReadImage(label_dir))
# print(dummy_gt.shape)
dummy_gt = np.squeeze(dummy_gt)
dummy_gt = crop_img(dummy_gt)
self.img = np.expand_dims(np.reshape(dummy_img,[dummy_img.shape[0]*dummy_img.shape[1],dummy_img.shape[2],dummy_img.shape[3]]),axis=0)
if not label_dir is None:
self.gt = np.expand_dims(np.reshape(dummy_gt,[dummy_gt.shape[0]*dummy_gt.shape[1],dummy_gt.shape[2],dummy_gt.shape[3]]),axis=0)
else:
self.gt = np.zeros(self.img.shape)
self.len = self.img.shape[0]
return |
main.py | import time
from os import getenv
from flask import jsonify, abort
from google.cloud import firestore
from google.oauth2 import id_token
from google.auth.transport import requests as g_requests
from api import (
process_ok_exam_upload,
is_admin,
clear_collection,
get_announcements,
get_email_from_secret,
generate_audio,
)
# this can be public
CLIENT_ID = "713452892775-59gliacuhbfho8qvn4ctngtp3858fgf9.apps.googleusercontent.com"
DEV_EMAIL = getenv("DEV_EMAIL", "[email protected]")
def update_cache():
global main_html, main_js
with open("static/index.html") as f:
main_html = f.read()
with open("static/main.js") as f:
main_js = f.read()
update_cache()
def get_email(request):
if getenv("ENV") == "dev":
return DEV_EMAIL
token = request.json["token"]
# validate token
id_info = id_token.verify_oauth2_token(token, g_requests.Request(), CLIENT_ID)
if id_info["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
raise ValueError("Wrong issuer.")
return id_info["email"]
def index(request):
try:
if getenv("ENV") == "dev":
update_cache()
db = firestore.Client()
if request.path.endswith("main.js"):
return main_js
if request.path.endswith("list_exams"):
return jsonify(
db.collection("exam-alerts")
.document("all")
.get()
.to_dict()["exam-list"]
)
if request.path == "/" or request.json is None:
return main_html
if request.path.endswith("upload_ok_exam"):
process_ok_exam_upload(db, request.json["data"], request.json["secret"])
return jsonify({"success": True})
exam = request.json["exam"]
course = exam.split("-")[0]
if request.path.endswith("fetch_data"):
received_audio = request.json.get("receivedAudio")
email = get_email(request)
student_data = (
db.collection("exam-alerts")
.document(exam)
.collection("students")
.document(email)
.get()
.to_dict()
)
announcements = list(
db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.stream()
)
return jsonify(
{
"success": True,
"exam_type": "ok-exam",
"questions": [],
"startTime": student_data["start_time"],
"endTime": student_data["end_time"],
# "questions": [
# {
# "questionName": question["student_question_name"],
# "startTime": question["start_time"],
# "endTime": question["end_time"],
# }
# for question in student_data["questions"]
# ],
"announcements": get_announcements(
student_data,
announcements,
received_audio,
lambda x: (
db.collection("exam-alerts")
.document(exam)
.collection("announcement_audio")
.document(x)
.get()
.to_dict()
or {}
).get("audio"),
),
}
)
# only staff endpoints from here onwards
email = (
get_email_from_secret(request.json["secret"])
if "secret" in request.json
else get_email(request)
)
if not is_admin(email, course):
abort(401)
if request.path.endswith("fetch_staff_data"):
pass
elif request.path.endswith("add_announcement"):
announcement = request.json["announcement"]
announcement["timestamp"] = time.time()
ref = (
db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.document()
)
ref.set(announcement)
spoken_message = announcement.get("spoken_message", announcement["message"])
if spoken_message:
audio = generate_audio(spoken_message)
db.collection("exam-alerts").document(exam).collection(
"announcement_audio"
).document(ref.id).set({"audio": audio})
elif request.path.endswith("clear_announcements"):
clear_collection(
db,
db.collection("exam-alerts").document(exam).collection("announcements"),
)
clear_collection(
db,
db.collection("exam-alerts")
.document(exam)
.collection("announcement_audio"),
)
elif request.path.endswith("delete_announcement"):
target = request.json["id"]
db.collection("exam-alerts").document(exam).collection(
"announcements"
).document(target).delete()
else:
abort(404)
# all staff endpoints return an updated state
exam_data = db.collection("exam-alerts").document(exam).get().to_dict()
announcements = sorted(
(
{"id": announcement.id, **announcement.to_dict()}
for announcement in db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.stream()
),
key=lambda announcement: announcement["timestamp"],
reverse=True,
)
return jsonify(
{"success": True, "exam": exam_data, "announcements": announcements}
)
| print(e)
print(dict(request.json))
return jsonify({"success": False}) | except Exception as e:
if getenv("ENV") == "dev":
raise |
account.js | module.exports = function (RED) {
function | (config) {
const {Account, PublicAccount} = require('tsjs-xpx-chain-sdk');
const validator = require('../utils/validator');
RED.nodes.createNode(this, config);
this.privateKey = config.privateKey;
this.publicKey = config.publicKey;
this.creationType = config.creationType;
this.network = RED.nodes.getNode(config.network).network;
let node = this;
node.on('input', function (msg) {
try {
if (typeof msg.proximax === "undefined") {
msg.proximax = {};
}
const network = node.network || msg.proximax.network;
switch (node.creationType) {
case "From private key": {
const privateKey = node.privateKey || msg.proximax.privateKey;
if (validator.privateKeyValidate(privateKey)) {
const account = Account.createFromPrivateKey(privateKey, network);
msg.proximax.address = account.address.address;
msg.proximax.privateKey = account.privateKey;
msg.proximax.publicKey = account.publicKey;
node.status({text: account.address.pretty()});
node.send(msg);
} else if (privateKey) {
node.error("Private key is incorrect", msg);
} else {
node.error("Private key is empty", msg);
}
break;
}
case "From public key": {
const publicKey = node.publicKey || msg.proximax.publicKey;
if (validator.publicKeyValidate(publicKey)) {
const publicAccount = PublicAccount.createFromPublicKey(publicKey, network);
msg.proximax.address = publicAccount.address.address;
msg.proximax.publicKey = publicAccount.publicKey;
node.status({text: publicAccount.address.pretty()});
node.send(msg);
} else if (publzicKey) {
node.error("Public key is incorrect", msg);
} else {
node.error("Public key is empty", msg);
}
break;
}
default: {
const account = Account.generateNewAccount(network);
msg.proximax.address = account.address.address;
msg.proximax.privateKey = account.privateKey;
msg.proximax.publicKey = account.publicKey;
node.status({text: account.address.pretty()});
node.send(msg);
}
}
} catch (error) {
node.error(error, msg);
}
});
node.on('close', function () {
node.status({});
});
}
RED.nodes.registerType("account", account);
}; | account |
header.rs | mod builder;
pub use self::builder::Builder;
use crate::num::{Itf8, Ltf8};
use super::ReferenceSequenceId;
// § 9 End of file container (2020-06-22)
const EOF_LEN: i32 = 15;
const EOF_START_POSITION: Itf8 = 4_542_278;
const EOF_BLOCK_COUNT: Itf8 = 1;
const EOF_CRC32: u32 = 0x4f_d9_bd_05;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Header {
length: i32,
reference_sequence_id: ReferenceSequenceId,
start_position: Itf8,
alignment_span: Itf8,
record_count: Itf8,
record_counter: Ltf8,
base_count: Ltf8,
block_count: Itf8,
landmarks: Vec<Itf8>,
crc32: u32,
}
#[allow(clippy::len_without_is_empty)]
impl Header {
pub fn builder() -> Builder {
Builder::default()
}
/// Creates a container header used in the EOF container.
pub fn eof() -> Self { |
pub fn len(&self) -> i32 {
self.length
}
pub fn reference_sequence_id(&self) -> ReferenceSequenceId {
self.reference_sequence_id
}
pub fn start_position(&self) -> Itf8 {
self.start_position
}
pub fn alignment_span(&self) -> Itf8 {
self.alignment_span
}
pub fn record_count(&self) -> Itf8 {
self.record_count
}
pub fn record_counter(&self) -> Ltf8 {
self.record_counter
}
pub fn base_count(&self) -> Ltf8 {
self.base_count
}
pub fn block_count(&self) -> Itf8 {
self.block_count
}
pub fn landmarks(&self) -> &[Itf8] {
&self.landmarks
}
pub fn is_eof(&self) -> bool {
self.length == EOF_LEN
&& self.reference_sequence_id.is_none()
&& self.start_position == EOF_START_POSITION
&& self.alignment_span == 0
&& self.record_count == 0
&& self.record_counter == 0
&& self.base_count == 0
&& self.block_count == EOF_BLOCK_COUNT
&& self.landmarks.is_empty()
&& self.crc32 == EOF_CRC32
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_eof() {
let header = Header::eof();
assert!(header.is_eof());
}
}
|
Self {
length: EOF_LEN,
start_position: EOF_START_POSITION,
block_count: EOF_BLOCK_COUNT,
crc32: EOF_CRC32,
..Default::default()
}
}
|
BACnetConstructedDataAnalogOutputMaxPresValue.go | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.
*/
package model
import (
"github.com/apache/plc4x/plc4go/internal/spi/utils"
"github.com/pkg/errors"
)
// Code generated by code-generation. DO NOT EDIT.
// BACnetConstructedDataAnalogOutputMaxPresValue is the corresponding interface of BACnetConstructedDataAnalogOutputMaxPresValue
type BACnetConstructedDataAnalogOutputMaxPresValue interface {
BACnetConstructedData
// GetMaxPresValue returns MaxPresValue (property field)
GetMaxPresValue() BACnetApplicationTagReal
// GetActualValue returns ActualValue (virtual field)
GetActualValue() BACnetApplicationTagReal
// GetLengthInBytes returns the length in bytes
GetLengthInBytes() uint16
// GetLengthInBits returns the length in bits
GetLengthInBits() uint16
// Serialize serializes this type
Serialize(writeBuffer utils.WriteBuffer) error
}
// _BACnetConstructedDataAnalogOutputMaxPresValue is the data-structure of this message
type _BACnetConstructedDataAnalogOutputMaxPresValue struct {
*_BACnetConstructedData
MaxPresValue BACnetApplicationTagReal
// Arguments.
TagNumber uint8
ArrayIndexArgument BACnetTagPayloadUnsignedInteger
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for discriminator values.
///////////////////////
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetObjectTypeArgument() BACnetObjectType {
return BACnetObjectType_ANALOG_OUTPUT
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetPropertyIdentifierArgument() BACnetPropertyIdentifier {
return BACnetPropertyIdentifier_MAX_PRES_VALUE
}
| ///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) InitializeParent(parent BACnetConstructedData, openingTag BACnetOpeningTag, peekedTagHeader BACnetTagHeader, closingTag BACnetClosingTag) {
m.OpeningTag = openingTag
m.PeekedTagHeader = peekedTagHeader
m.ClosingTag = closingTag
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetParent() BACnetConstructedData {
return m._BACnetConstructedData
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for property fields.
///////////////////////
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetMaxPresValue() BACnetApplicationTagReal {
return m.MaxPresValue
}
///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for virtual fields.
///////////////////////
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetActualValue() BACnetApplicationTagReal {
return CastBACnetApplicationTagReal(m.GetMaxPresValue())
}
///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// NewBACnetConstructedDataAnalogOutputMaxPresValue factory function for _BACnetConstructedDataAnalogOutputMaxPresValue
func NewBACnetConstructedDataAnalogOutputMaxPresValue(maxPresValue BACnetApplicationTagReal, openingTag BACnetOpeningTag, peekedTagHeader BACnetTagHeader, closingTag BACnetClosingTag, tagNumber uint8, arrayIndexArgument BACnetTagPayloadUnsignedInteger) *_BACnetConstructedDataAnalogOutputMaxPresValue {
_result := &_BACnetConstructedDataAnalogOutputMaxPresValue{
MaxPresValue: maxPresValue,
_BACnetConstructedData: NewBACnetConstructedData(openingTag, peekedTagHeader, closingTag, tagNumber, arrayIndexArgument),
}
_result._BACnetConstructedData._BACnetConstructedDataChildRequirements = _result
return _result
}
// Deprecated: use the interface for direct cast
func CastBACnetConstructedDataAnalogOutputMaxPresValue(structType interface{}) BACnetConstructedDataAnalogOutputMaxPresValue {
if casted, ok := structType.(BACnetConstructedDataAnalogOutputMaxPresValue); ok {
return casted
}
if casted, ok := structType.(*BACnetConstructedDataAnalogOutputMaxPresValue); ok {
return *casted
}
return nil
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetTypeName() string {
return "BACnetConstructedDataAnalogOutputMaxPresValue"
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetLengthInBits() uint16 {
return m.GetLengthInBitsConditional(false)
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetLengthInBitsConditional(lastItem bool) uint16 {
lengthInBits := uint16(m.GetParentLengthInBits())
// Simple field (maxPresValue)
lengthInBits += m.MaxPresValue.GetLengthInBits()
// A virtual field doesn't have any in- or output.
return lengthInBits
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) GetLengthInBytes() uint16 {
return m.GetLengthInBits() / 8
}
func BACnetConstructedDataAnalogOutputMaxPresValueParse(readBuffer utils.ReadBuffer, tagNumber uint8, objectTypeArgument BACnetObjectType, propertyIdentifierArgument BACnetPropertyIdentifier, arrayIndexArgument BACnetTagPayloadUnsignedInteger) (BACnetConstructedDataAnalogOutputMaxPresValue, error) {
positionAware := readBuffer
_ = positionAware
if pullErr := readBuffer.PullContext("BACnetConstructedDataAnalogOutputMaxPresValue"); pullErr != nil {
return nil, errors.Wrap(pullErr, "Error pulling for BACnetConstructedDataAnalogOutputMaxPresValue")
}
currentPos := positionAware.GetPos()
_ = currentPos
// Simple Field (maxPresValue)
if pullErr := readBuffer.PullContext("maxPresValue"); pullErr != nil {
return nil, errors.Wrap(pullErr, "Error pulling for maxPresValue")
}
_maxPresValue, _maxPresValueErr := BACnetApplicationTagParse(readBuffer)
if _maxPresValueErr != nil {
return nil, errors.Wrap(_maxPresValueErr, "Error parsing 'maxPresValue' field")
}
maxPresValue := _maxPresValue.(BACnetApplicationTagReal)
if closeErr := readBuffer.CloseContext("maxPresValue"); closeErr != nil {
return nil, errors.Wrap(closeErr, "Error closing for maxPresValue")
}
// Virtual field
_actualValue := maxPresValue
actualValue := _actualValue.(BACnetApplicationTagReal)
_ = actualValue
if closeErr := readBuffer.CloseContext("BACnetConstructedDataAnalogOutputMaxPresValue"); closeErr != nil {
return nil, errors.Wrap(closeErr, "Error closing for BACnetConstructedDataAnalogOutputMaxPresValue")
}
// Create a partially initialized instance
_child := &_BACnetConstructedDataAnalogOutputMaxPresValue{
MaxPresValue: maxPresValue,
_BACnetConstructedData: &_BACnetConstructedData{},
}
_child._BACnetConstructedData._BACnetConstructedDataChildRequirements = _child
return _child, nil
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) Serialize(writeBuffer utils.WriteBuffer) error {
positionAware := writeBuffer
_ = positionAware
ser := func() error {
if pushErr := writeBuffer.PushContext("BACnetConstructedDataAnalogOutputMaxPresValue"); pushErr != nil {
return errors.Wrap(pushErr, "Error pushing for BACnetConstructedDataAnalogOutputMaxPresValue")
}
// Simple Field (maxPresValue)
if pushErr := writeBuffer.PushContext("maxPresValue"); pushErr != nil {
return errors.Wrap(pushErr, "Error pushing for maxPresValue")
}
_maxPresValueErr := writeBuffer.WriteSerializable(m.GetMaxPresValue())
if popErr := writeBuffer.PopContext("maxPresValue"); popErr != nil {
return errors.Wrap(popErr, "Error popping for maxPresValue")
}
if _maxPresValueErr != nil {
return errors.Wrap(_maxPresValueErr, "Error serializing 'maxPresValue' field")
}
// Virtual field
if _actualValueErr := writeBuffer.WriteVirtual("actualValue", m.GetActualValue()); _actualValueErr != nil {
return errors.Wrap(_actualValueErr, "Error serializing 'actualValue' field")
}
if popErr := writeBuffer.PopContext("BACnetConstructedDataAnalogOutputMaxPresValue"); popErr != nil {
return errors.Wrap(popErr, "Error popping for BACnetConstructedDataAnalogOutputMaxPresValue")
}
return nil
}
return m.SerializeParent(writeBuffer, m, ser)
}
func (m *_BACnetConstructedDataAnalogOutputMaxPresValue) String() string {
if m == nil {
return "<nil>"
}
writeBuffer := utils.NewBoxedWriteBufferWithOptions(true, true)
if err := writeBuffer.WriteSerializable(m); err != nil {
return err.Error()
}
return writeBuffer.GetBox().String()
} | /////////////////////// |
tablet.go | /*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package topoproto contains utility functions to deal with the proto3
// structures defined in proto/topodata.
package topoproto
import (
"fmt"
"net"
"sort"
"strconv"
"strings"
"github.com/golang/protobuf/proto"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)
// This file contains the topodata.Tablet utility functions.
const (
// Default name for databases is the prefix plus keyspace
vtDbPrefix = "vt_"
)
// cache the conversion from tablet type enum to lower case string.
var tabletTypeLowerName map[int32]string
func init() {
tabletTypeLowerName = make(map[int32]string, len(topodatapb.TabletType_name))
for k, v := range topodatapb.TabletType_name {
tabletTypeLowerName[k] = strings.ToLower(v)
}
}
// TabletAliasIsZero returns true iff cell and uid are empty
func TabletAliasIsZero(ta *topodatapb.TabletAlias) bool {
return ta == nil || (ta.Cell == "" && ta.Uid == 0)
}
// TabletAliasEqual returns true if two TabletAlias match
func TabletAliasEqual(left, right *topodatapb.TabletAlias) bool {
return proto.Equal(left, right)
}
// TabletAliasString formats a TabletAlias
func TabletAliasString(ta *topodatapb.TabletAlias) string {
if ta == nil {
return "<nil>"
}
return fmt.Sprintf("%v-%010d", ta.Cell, ta.Uid)
}
// TabletAliasUIDStr returns a string version of the uid
func TabletAliasUIDStr(ta *topodatapb.TabletAlias) string |
// ParseTabletAlias returns a TabletAlias for the input string,
// of the form <cell>-<uid>
func ParseTabletAlias(aliasStr string) (*topodatapb.TabletAlias, error) {
nameParts := strings.Split(aliasStr, "-")
if len(nameParts) != 2 {
return nil, fmt.Errorf("invalid tablet alias: %v", aliasStr)
}
uid, err := ParseUID(nameParts[1])
if err != nil {
return nil, fmt.Errorf("invalid tablet uid %v: %v", aliasStr, err)
}
return &topodatapb.TabletAlias{
Cell: nameParts[0],
Uid: uid,
}, nil
}
// ParseUID parses just the uid (a number)
func ParseUID(value string) (uint32, error) {
uid, err := strconv.ParseUint(value, 10, 32)
if err != nil {
return 0, fmt.Errorf("bad tablet uid %v", err)
}
return uint32(uid), nil
}
// TabletAliasList is used mainly for sorting
type TabletAliasList []*topodatapb.TabletAlias
// Len is part of sort.Interface
func (tal TabletAliasList) Len() int {
return len(tal)
}
// Less is part of sort.Interface
func (tal TabletAliasList) Less(i, j int) bool {
if tal[i].Cell < tal[j].Cell {
return true
} else if tal[i].Cell > tal[j].Cell {
return false
}
return tal[i].Uid < tal[j].Uid
}
// Swap is part of sort.Interface
func (tal TabletAliasList) Swap(i, j int) {
tal[i], tal[j] = tal[j], tal[i]
}
// AllTabletTypes lists all the possible tablet types
var AllTabletTypes = []topodatapb.TabletType{
topodatapb.TabletType_MASTER,
topodatapb.TabletType_REPLICA,
topodatapb.TabletType_RDONLY,
topodatapb.TabletType_BATCH,
topodatapb.TabletType_SPARE,
topodatapb.TabletType_EXPERIMENTAL,
topodatapb.TabletType_BACKUP,
topodatapb.TabletType_RESTORE,
topodatapb.TabletType_DRAINED,
}
// SlaveTabletTypes contains all the tablet type that can have replication
// enabled.
var SlaveTabletTypes = []topodatapb.TabletType{
topodatapb.TabletType_REPLICA,
topodatapb.TabletType_RDONLY,
topodatapb.TabletType_BATCH,
topodatapb.TabletType_SPARE,
topodatapb.TabletType_EXPERIMENTAL,
topodatapb.TabletType_BACKUP,
topodatapb.TabletType_RESTORE,
topodatapb.TabletType_DRAINED,
}
// ParseTabletType parses the tablet type into the enum.
func ParseTabletType(param string) (topodatapb.TabletType, error) {
value, ok := topodatapb.TabletType_value[strings.ToUpper(param)]
if !ok {
return topodatapb.TabletType_UNKNOWN, fmt.Errorf("unknown TabletType %v", param)
}
return topodatapb.TabletType(value), nil
}
// ParseTabletTypes parses a comma separated list of tablet types and returns a slice with the respective enums.
func ParseTabletTypes(param string) ([]topodatapb.TabletType, error) {
var tabletTypes []topodatapb.TabletType
for _, typeStr := range strings.Split(param, ",") {
t, err := ParseTabletType(typeStr)
if err != nil {
return nil, err
}
tabletTypes = append(tabletTypes, t)
}
return tabletTypes, nil
}
// TabletTypeLString returns a lower case version of the tablet type,
// or "unknown" if not known.
func TabletTypeLString(tabletType topodatapb.TabletType) string {
value, ok := tabletTypeLowerName[int32(tabletType)]
if !ok {
return "unknown"
}
return value
}
// IsTypeInList returns true if the given type is in the list.
// Use it with AllTabletType and SlaveTabletType for instance.
func IsTypeInList(tabletType topodatapb.TabletType, types []topodatapb.TabletType) bool {
for _, t := range types {
if tabletType == t {
return true
}
}
return false
}
// MakeStringTypeList returns a list of strings that match the input list.
func MakeStringTypeList(types []topodatapb.TabletType) []string {
strs := make([]string, len(types))
for i, t := range types {
strs[i] = strings.ToLower(t.String())
}
sort.Strings(strs)
return strs
}
// SetMysqlPort sets the mysql port for tablet. This function
// also handles legacy by setting the port in PortMap.
// TODO(sougou); deprecate this function after 3.0.
func SetMysqlPort(tablet *topodatapb.Tablet, port int32) {
if tablet.MysqlHostname == "" || tablet.MysqlHostname == tablet.Hostname {
tablet.PortMap["mysql"] = port
}
// If it's the legacy form, preserve old behavior to prevent
// confusion between new and old code.
if tablet.MysqlHostname != "" {
tablet.MysqlPort = port
}
}
// MysqlAddr returns the host:port of the mysql server.
func MysqlAddr(tablet *topodatapb.Tablet) string {
return fmt.Sprintf("%v:%v", MysqlHostname(tablet), MysqlPort(tablet))
}
// MysqlHostname returns the mysql host name. This function
// also handles legacy behavior: it uses the tablet's hostname
// if MysqlHostname is not specified.
// TODO(sougou); deprecate this function after 3.0.
func MysqlHostname(tablet *topodatapb.Tablet) string {
if tablet.MysqlHostname == "" {
return tablet.Hostname
}
return tablet.MysqlHostname
}
// MysqlPort returns the mysql port. This function
// also handles legacy behavior: it uses the tablet's port map
// if MysqlHostname is not specified.
// TODO(sougou); deprecate this function after 3.0.
func MysqlPort(tablet *topodatapb.Tablet) int32 {
if tablet.MysqlHostname == "" {
return tablet.PortMap["mysql"]
}
return tablet.MysqlPort
}
// MySQLIP returns the MySQL server's IP by resolvign the host name.
func MySQLIP(tablet *topodatapb.Tablet) (string, error) {
ipAddrs, err := net.LookupHost(MysqlHostname(tablet))
if err != nil {
return "", err
}
return ipAddrs[0], nil
}
// TabletDbName is usually implied by keyspace. Having the shard
// information in the database name complicates mysql replication.
func TabletDbName(tablet *topodatapb.Tablet) string {
if tablet.DbNameOverride != "" {
return tablet.DbNameOverride
}
if tablet.Keyspace == "" {
return ""
}
return vtDbPrefix + tablet.Keyspace
}
// TabletIsAssigned returns if this tablet is assigned to a keyspace and shard.
// A "scrap" node will show up as assigned even though its data cannot be used
// for serving.
func TabletIsAssigned(tablet *topodatapb.Tablet) bool {
return tablet != nil && tablet.Keyspace != "" && tablet.Shard != ""
}
| {
return fmt.Sprintf("%010d", ta.Uid)
} |
reachable.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.
// Finds items that are externally reachable, to determine which items
// need to have their metadata (and possibly their AST) serialized.
// All items that can be referred to through an exported name are
// reachable, and when a reachable thing is inline or generic, it
// makes all other generics or inline functions that it references
// reachable as well.
use middle::ty;
use middle::typeck;
use std::hashmap::HashSet;
use syntax::ast::*;
use syntax::ast_map;
use syntax::ast_util::def_id_of_def;
use syntax::attr;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
// Returns true if the given set of attributes contains the `#[inline]`
// attribute.
fn attributes_specify_inlining(attrs: &[Attribute]) -> bool {
attr::contains_name(attrs, "inline")
}
// Returns true if the given set of generics implies that the item it's
// associated with must be inlined.
fn generics_require_inlining(generics: &Generics) -> bool {
!generics.ty_params.is_empty()
}
// Returns true if the given item must be inlined because it may be
// monomorphized or it was marked with `#[inline]`. This will only return
// true for functions.
fn item_might_be_inlined(item: @item) -> bool {
if attributes_specify_inlining(item.attrs) {
return true
}
match item.node {
item_fn(_, _, _, ref generics, _) => {
generics_require_inlining(generics)
}
_ => false,
}
}
// Returns true if the given type method must be inlined because it may be
// monomorphized or it was marked with `#[inline]`.
fn ty_method_might_be_inlined(ty_method: &TypeMethod) -> bool {
attributes_specify_inlining(ty_method.attrs) ||
generics_require_inlining(&ty_method.generics)
}
// Returns true if the given trait method must be inlined because it may be
// monomorphized or it was marked with `#[inline]`.
fn trait_method_might_be_inlined(trait_method: &trait_method) -> bool {
match *trait_method {
required(ref ty_method) => ty_method_might_be_inlined(ty_method),
provided(_) => true
}
}
// The context we're in. If we're in a public context, then public symbols are
// marked reachable. If we're in a private context, then only trait
// implementations are marked reachable.
#[deriving(Clone, Eq)]
enum PrivacyContext {
PublicContext,
PrivateContext,
}
// Information needed while computing reachability.
struct ReachableContext {
// The type context.
tcx: ty::ctxt,
// The method map, which links node IDs of method call expressions to the
// methods they've been resolved to.
method_map: typeck::method_map,
// The set of items which must be exported in the linkage sense.
reachable_symbols: @mut HashSet<NodeId>,
// A worklist of item IDs. Each item ID in this worklist will be inlined
// and will be scanned for further references.
worklist: @mut ~[NodeId],
}
struct ReachableVisitor {
reachable_symbols: @mut HashSet<NodeId>,
worklist: @mut ~[NodeId],
}
impl Visitor<PrivacyContext> for ReachableVisitor {
fn visit_item(&mut self, item:@item, privacy_context:PrivacyContext) {
match item.node {
item_fn(*) => {
if privacy_context == PublicContext {
self.reachable_symbols.insert(item.id);
}
if item_might_be_inlined(item) {
self.worklist.push(item.id)
}
}
item_struct(ref struct_def, _) => {
match struct_def.ctor_id {
Some(ctor_id) if
privacy_context == PublicContext => {
self.reachable_symbols.insert(ctor_id);
}
Some(_) | None => {}
}
}
item_enum(ref enum_def, _) => {
if privacy_context == PublicContext {
for variant in enum_def.variants.iter() {
self.reachable_symbols.insert(variant.node.id);
}
}
}
item_impl(ref generics, ref trait_ref, _, ref methods) => {
// XXX(pcwalton): We conservatively assume any methods
// on a trait implementation are reachable, when this
// is not the case. We could be more precise by only
// treating implementations of reachable or cross-
// crate traits as reachable.
let should_be_considered_public = |method: @method| {
(method.vis == public &&
privacy_context == PublicContext) ||
trait_ref.is_some()
};
// Mark all public methods as reachable.
for &method in methods.iter() {
if should_be_considered_public(method) {
self.reachable_symbols.insert(method.id);
}
}
if generics_require_inlining(generics) {
// If the impl itself has generics, add all public
// symbols to the worklist.
for &method in methods.iter() {
if should_be_considered_public(method) {
self.worklist.push(method.id)
}
}
} else {
// Otherwise, add only public methods that have
// generics to the worklist.
for method in methods.iter() {
let generics = &method.generics;
let attrs = &method.attrs;
if generics_require_inlining(generics) ||
attributes_specify_inlining(*attrs) ||
should_be_considered_public(*method) {
self.worklist.push(method.id)
}
}
}
}
item_trait(_, _, ref trait_methods) => {
// Mark all provided methods as reachable.
if privacy_context == PublicContext {
for trait_method in trait_methods.iter() {
match *trait_method {
provided(method) => {
self.reachable_symbols.insert(method.id);
self.worklist.push(method.id)
}
required(_) => {}
}
}
}
}
_ => {}
}
if item.vis == public && privacy_context == PublicContext {
visit::walk_item(self, item, PublicContext)
} else {
visit::walk_item(self, item, PrivateContext)
}
}
}
struct | {
worklist: @mut ~[NodeId],
method_map: typeck::method_map,
tcx: ty::ctxt,
reachable_symbols: @mut HashSet<NodeId>,
}
impl Visitor<()> for MarkSymbolVisitor {
fn visit_expr(&mut self, expr:@Expr, _:()) {
match expr.node {
ExprPath(_) => {
let def = match self.tcx.def_map.find(&expr.id) {
Some(&def) => def,
None => {
self.tcx.sess.span_bug(expr.span,
"def ID not in def map?!")
}
};
let def_id = def_id_of_def(def);
if ReachableContext::
def_id_represents_local_inlined_item(self.tcx,
def_id) {
self.worklist.push(def_id.node)
}
self.reachable_symbols.insert(def_id.node);
}
ExprMethodCall(*) => {
match self.method_map.find(&expr.id) {
Some(&typeck::method_map_entry {
origin: typeck::method_static(def_id),
_
}) => {
if ReachableContext::
def_id_represents_local_inlined_item(
self.tcx,
def_id) {
self.worklist.push(def_id.node)
}
self.reachable_symbols.insert(def_id.node);
}
Some(_) => {}
None => {
self.tcx.sess.span_bug(expr.span,
"method call expression \
not in method map?!")
}
}
}
_ => {}
}
visit::walk_expr(self, expr, ())
}
}
impl ReachableContext {
// Creates a new reachability computation context.
fn new(tcx: ty::ctxt, method_map: typeck::method_map)
-> ReachableContext {
ReachableContext {
tcx: tcx,
method_map: method_map,
reachable_symbols: @mut HashSet::new(),
worklist: @mut ~[],
}
}
// Step 1: Mark all public symbols, and add all public symbols that might
// be inlined to a worklist.
fn mark_public_symbols(&self, crate: &Crate) {
let reachable_symbols = self.reachable_symbols;
let worklist = self.worklist;
let mut visitor = ReachableVisitor {
reachable_symbols: reachable_symbols,
worklist: worklist,
};
visit::walk_crate(&mut visitor, crate, PublicContext);
}
// Returns true if the given def ID represents a local item that is
// eligible for inlining and false otherwise.
fn def_id_represents_local_inlined_item(tcx: ty::ctxt, def_id: DefId)
-> bool {
if def_id.crate != LOCAL_CRATE {
return false
}
let node_id = def_id.node;
match tcx.items.find(&node_id) {
Some(&ast_map::node_item(item, _)) => {
match item.node {
item_fn(*) => item_might_be_inlined(item),
_ => false,
}
}
Some(&ast_map::node_trait_method(trait_method, _, _)) => {
match *trait_method {
required(_) => false,
provided(_) => true,
}
}
Some(&ast_map::node_method(method, impl_did, _)) => {
if generics_require_inlining(&method.generics) ||
attributes_specify_inlining(method.attrs) {
true
} else {
// Check the impl. If the generics on the self type of the
// impl require inlining, this method does too.
assert!(impl_did.crate == LOCAL_CRATE);
match tcx.items.find(&impl_did.node) {
Some(&ast_map::node_item(item, _)) => {
match item.node {
item_impl(ref generics, _, _, _) => {
generics_require_inlining(generics)
}
_ => false
}
}
Some(_) => {
tcx.sess.span_bug(method.span,
"method is not inside an \
impl?!")
}
None => {
tcx.sess.span_bug(method.span,
"the impl that this method is \
supposedly inside of doesn't \
exist in the AST map?!")
}
}
}
}
Some(_) => false,
None => false // This will happen for default methods.
}
}
// Helper function to set up a visitor for `propagate()` below.
fn init_visitor(&self) -> MarkSymbolVisitor {
let (worklist, method_map) = (self.worklist, self.method_map);
let (tcx, reachable_symbols) = (self.tcx, self.reachable_symbols);
MarkSymbolVisitor {
worklist: worklist,
method_map: method_map,
tcx: tcx,
reachable_symbols: reachable_symbols,
}
}
// Step 2: Mark all symbols that the symbols on the worklist touch.
fn propagate(&self) {
let mut visitor = self.init_visitor();
let mut scanned = HashSet::new();
while self.worklist.len() > 0 {
let search_item = self.worklist.pop();
if scanned.contains(&search_item) {
continue
}
scanned.insert(search_item);
self.reachable_symbols.insert(search_item);
// Find the AST block corresponding to the item and visit it,
// marking all path expressions that resolve to something
// interesting.
match self.tcx.items.find(&search_item) {
Some(&ast_map::node_item(item, _)) => {
match item.node {
item_fn(_, _, _, _, ref search_block) => {
visit::walk_block(&mut visitor, search_block, ())
}
_ => {
self.tcx.sess.span_bug(item.span,
"found non-function item \
in worklist?!")
}
}
}
Some(&ast_map::node_trait_method(trait_method, _, _)) => {
match *trait_method {
required(ref ty_method) => {
self.tcx.sess.span_bug(ty_method.span,
"found required method in \
worklist?!")
}
provided(ref method) => {
visit::walk_block(&mut visitor, &method.body, ())
}
}
}
Some(&ast_map::node_method(ref method, _, _)) => {
visit::walk_block(&mut visitor, &method.body, ())
}
Some(_) => {
let ident_interner = token::get_ident_interner();
let desc = ast_map::node_id_to_str(self.tcx.items,
search_item,
ident_interner);
self.tcx.sess.bug(format!("found unexpected thingy in \
worklist: {}",
desc))
}
None => {
self.tcx.sess.bug(format!("found unmapped ID in worklist: \
{}",
search_item))
}
}
}
}
// Step 3: Mark all destructors as reachable.
//
// XXX(pcwalton): This is a conservative overapproximation, but fixing
// this properly would result in the necessity of computing *type*
// reachability, which might result in a compile time loss.
fn mark_destructors_reachable(&self) {
for (_, destructor_def_id) in self.tcx.destructor_for_type.iter() {
if destructor_def_id.crate == LOCAL_CRATE {
self.reachable_symbols.insert(destructor_def_id.node);
}
}
}
}
pub fn find_reachable(tcx: ty::ctxt,
method_map: typeck::method_map,
crate: &Crate)
-> @mut HashSet<NodeId> {
// XXX(pcwalton): We only need to mark symbols that are exported. But this
// is more complicated than just looking at whether the symbol is `pub`,
// because it might be the target of a `pub use` somewhere. For now, I
// think we are fine, because you can't `pub use` something that wasn't
// exported due to the bug whereby `use` only looks through public
// modules even if you're inside the module the `use` appears in. When
// this bug is fixed, however, this code will need to be updated. Probably
// the easiest way to fix this (although a conservative overapproximation)
// is to have the name resolution pass mark all targets of a `pub use` as
// "must be reachable".
let reachable_context = ReachableContext::new(tcx, method_map);
// Step 1: Mark all public symbols, and add all public symbols that might
// be inlined to a worklist.
reachable_context.mark_public_symbols(crate);
// Step 2: Mark all symbols that the symbols on the worklist touch.
reachable_context.propagate();
// Step 3: Mark all destructors as reachable.
reachable_context.mark_destructors_reachable();
// Return the set of reachable symbols.
reachable_context.reachable_symbols
}
| MarkSymbolVisitor |
grid.ts | import { def } from "@cardsgame/utils"
import { canBeChild } from "../annotations/canBeChild"
import { containsChildren } from "../annotations/containsChildren"
import { type } from "../annotations/type"
import type { State } from "../state"
import { ChildTrait } from "../traits/child"
import { applyTraitsMixins, Entity } from "../traits/entity"
import { IdentityTrait } from "../traits/identity"
import { LabelTrait } from "../traits/label"
import { LocationTrait } from "../traits/location"
import { OwnershipTrait } from "../traits/ownership"
import { ParentMapTrait } from "../traits/parentMap"
import { SelectableChildrenTrait } from "../traits/selectableChildren"
export function isGrid(entity: unknown): entity is Grid {
return typeof entity === "object" && "columns" in entity && "rows" in entity
}
/**
* Two dimensional container of items of set spots.
* May also be used as one-dimensional "line" of limited child items.
*/
@canBeChild
@containsChildren()
@applyTraitsMixins([
IdentityTrait,
LocationTrait,
ChildTrait,
ParentMapTrait,
LabelTrait,
OwnershipTrait,
SelectableChildrenTrait,
])
export class Grid extends Entity<GridOptions> {
/** | * @memberof Grid
*/
@type("uint8") rows: number
// @type("number") cellSpacing: number
/**
* @memberof Grid
*/
@type("string") justify: GridJustify
/**
* @memberof Grid
*/
@type("string") justifyItems: GridJustifyItems
/**
* @memberof Grid
*/
@type("string") alignItems: GridAlignItems
/**
* Grid comment at grid file
* @memberof Grid
*/
itemAngle: number
hijacksInteractionTarget = false
create(state: State, options: GridOptions = {}): void {
this.name = def(options.name, "Grid")
this.type = def(options.type, "grid")
this.columns = Math.max(1, def(options.columns, 1))
this.rows = Math.max(1, def(options.rows, 1))
this.maxChildren = this.columns * this.rows
this.justify = options.justify
this.justifyItems = options.justifyItems
this.alignItems = options.alignItems
// this.cellSpacing = def(options.cellSpacing, 0)
this.itemAngle = def(options.itemAngle, 0)
}
addChildAt(entity: ChildTrait, column: number, row: number): void {
this.addChild(entity, column + row * this.columns)
}
getChildAt<T extends ChildTrait>(column: number, row: number): T {
return this.getChildren<T>().find(
(child) => child.idx === column + row * this.columns
)
}
}
type GridJustify =
| "start"
| "end"
| "center"
| "stretch"
| "space-around"
| "space-between"
type GridJustifyItems = "start" | "end" | "center" | "stretch"
type GridAlignItems = "start" | "end" | "center" | "stretch"
interface Mixin
extends IdentityTrait,
LocationTrait,
ChildTrait,
ParentMapTrait,
LabelTrait,
OwnershipTrait,
SelectableChildrenTrait {}
type GridOptions = Partial<
NonFunctionProperties<Mixin> & {
columns: number
rows: number
cellSpacing: number
justify: GridJustify
justifyItems: GridJustifyItems
alignItems: GridAlignItems
itemAngle: number
}
>
export interface Grid extends Mixin {} | * @memberof Grid
*/
@type("uint8") columns: number
/** |
replicated.go | package upstream
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
kotsv1beta1 "github.com/replicatedhq/kots/kotskinds/apis/kots/v1beta1"
reportingtypes "github.com/replicatedhq/kots/pkg/api/reporting/types"
"github.com/replicatedhq/kots/pkg/buildversion"
"github.com/replicatedhq/kots/pkg/crypto"
kotslicense "github.com/replicatedhq/kots/pkg/license"
reporting "github.com/replicatedhq/kots/pkg/reporting"
"github.com/replicatedhq/kots/pkg/template"
"github.com/replicatedhq/kots/pkg/upstream/types"
"github.com/replicatedhq/kots/pkg/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
)
const DefaultMetadata = `apiVersion: kots.io/v1beta1
kind: Application
metadata:
name: "default-application"
spec:
title: "the application"
icon: https://cdn2.iconfinder.com/data/icons/mixd/512/16_kubernetes-512.png
releaseNotes: |
release notes`
type ReplicatedUpstream struct {
Channel *string
AppSlug string
VersionLabel *string
Sequence *int
}
type ReplicatedCursor struct {
ChannelID string
ChannelName string
Cursor string
}
type App struct {
Name string
}
type Release struct {
UpdateCursor ReplicatedCursor
VersionLabel string
ReleaseNotes string
ReleasedAt *time.Time
Manifests map[string][]byte
}
type ChannelRelease struct {
ChannelSequence int `json:"channelSequence"`
ReleaseSequence int `json:"releaseSequence"`
VersionLabel string `json:"versionLabel"`
}
func (this ReplicatedCursor) Equal(other ReplicatedCursor) bool {
if this.ChannelID != "" && other.ChannelID != "" {
return this.ChannelID == other.ChannelID && this.Cursor == other.Cursor
}
return this.ChannelName == other.ChannelName && this.Cursor == other.Cursor
}
func getUpdatesReplicated(u *url.URL, localPath string, currentCursor ReplicatedCursor, currentVersionLabel string, license *kotsv1beta1.License, reportingInfo *reportingtypes.ReportingInfo) ([]Update, error) {
if localPath != "" {
parsedLocalRelease, err := readReplicatedAppFromLocalPath(localPath, currentCursor, currentVersionLabel)
if err != nil {
return nil, errors.Wrap(err, "failed to read replicated app from local path")
}
return []Update{{Cursor: parsedLocalRelease.UpdateCursor.Cursor, VersionLabel: currentVersionLabel}}, nil
}
// A license file is required to be set for this to succeed
if license == nil {
return nil, errors.New("No license was provided")
}
replicatedUpstream, err := parseReplicatedURL(u)
if err != nil {
return nil, errors.Wrap(err, "failed to parse replicated upstream")
}
if err := getSuccessfulHeadResponse(replicatedUpstream, license); err != nil {
return nil, errors.Wrap(err, "failed to get successful head response")
}
pendingReleases, err := listPendingChannelReleases(replicatedUpstream, license, currentCursor, reportingInfo)
if err != nil {
return nil, errors.Wrap(err, "failed to list replicated app releases")
}
updates := []Update{}
for _, pendingRelease := range pendingReleases {
updates = append(updates, Update{
Cursor: strconv.Itoa(pendingRelease.ChannelSequence),
VersionLabel: pendingRelease.VersionLabel,
})
}
return updates, nil
}
func downloadReplicated(
u *url.URL,
localPath string,
rootDir string,
useAppDir bool,
license *kotsv1beta1.License,
existingConfigValues *kotsv1beta1.ConfigValues,
existingIdentityConfig *kotsv1beta1.IdentityConfig,
updateCursor ReplicatedCursor,
versionLabel string,
cipher *crypto.AESCipher,
appSlug string,
appSequence int64,
isAirgap bool,
airgapMetadata *kotsv1beta1.Airgap,
registry types.LocalRegistry,
reportingInfo *reportingtypes.ReportingInfo,
) (*types.Upstream, error) {
var release *Release
if localPath != "" {
parsedLocalRelease, err := readReplicatedAppFromLocalPath(localPath, updateCursor, versionLabel)
if err != nil {
return nil, errors.Wrap(err, "failed to read replicated app from local path")
}
// airgapMetadata is nil when saving initial config
if airgapMetadata != nil {
parsedLocalRelease.ReleaseNotes = airgapMetadata.Spec.ReleaseNotes
}
release = parsedLocalRelease
} else {
// A license file is required to be set for this to succeed
if license == nil {
return nil, errors.New("No license was provided")
}
replicatedUpstream, err := parseReplicatedURL(u)
if err != nil {
return nil, errors.Wrap(err, "failed to parse replicated upstream")
}
if err := getSuccessfulHeadResponse(replicatedUpstream, license); err != nil {
return nil, errors.Wrap(err, "failed to get successful head response")
}
downloadedRelease, err := downloadReplicatedApp(replicatedUpstream, license, updateCursor, reportingInfo)
if err != nil {
return nil, errors.Wrap(err, "failed to download replicated app")
}
licenseData, err := kotslicense.GetLatestLicense(license)
if err != nil {
return nil, errors.Wrap(err, "failed to get latest license")
}
license = licenseData.License
release = downloadedRelease
}
// Find the config in the upstream and write out default values
application := findAppInRelease(release) // this function never returns nil
// NOTE: this currently comes from the application spec and not the channel release meta
if release.ReleaseNotes == "" {
release.ReleaseNotes = application.Spec.ReleaseNotes
}
// get channel name from license, if one was provided
channelID, channelName := "", ""
if license != nil {
channelID = license.Spec.ChannelID
channelName = license.Spec.ChannelName
}
if existingIdentityConfig == nil {
var prevIdentityConfigFile string
if useAppDir {
prevIdentityConfigFile = filepath.Join(rootDir, application.Name, "upstream", "userdata", "identityconfig.yaml")
} else {
prevIdentityConfigFile = filepath.Join(rootDir, "upstream", "userdata", "identityconfig.yaml")
}
var err error
existingIdentityConfig, err = findIdentityConfigInFile(prevIdentityConfigFile)
if err != nil {
return nil, errors.Wrap(err, "failed to load existing identity config")
}
}
if existingIdentityConfig != nil {
release.Manifests["userdata/identityconfig.yaml"] = mustMarshalIdentityConfig(existingIdentityConfig)
}
if existingConfigValues == nil {
var prevConfigFile string
if useAppDir {
prevConfigFile = filepath.Join(rootDir, application.Name, "upstream", "userdata", "config.yaml")
} else {
prevConfigFile = filepath.Join(rootDir, "upstream", "userdata", "config.yaml")
}
var err error
existingConfigValues, err = findConfigValuesInFile(prevConfigFile)
if err != nil {
return nil, errors.Wrap(err, "failed to load existing config values")
}
}
config, _, _, _, _, err := findTemplateContextDataInRelease(release)
if err != nil {
return nil, errors.Wrap(err, "failed to find config in release")
}
if config != nil || existingConfigValues != nil {
appInfo := template.ApplicationInfo{
Slug: appSlug,
}
versionInfo := template.VersionInfo{
Sequence: appSequence,
Cursor: updateCursor.Cursor,
ChannelName: channelName,
VersionLabel: release.VersionLabel,
ReleaseNotes: release.ReleaseNotes,
IsAirgap: isAirgap,
}
localRegistry := template.LocalRegistry{
Host: registry.Host,
Namespace: registry.Namespace,
Username: registry.Username,
Password: registry.Password,
}
// If config existed and was removed from the app,
// values will be carried over to the new version anyway.
configValues, err := createConfigValues(application.Name, config, existingConfigValues, cipher, license, application, &appInfo, &versionInfo, localRegistry, existingIdentityConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to create empty config values")
}
release.Manifests["userdata/config.yaml"] = mustMarshalConfigValues(configValues)
}
// Add the license to the upstream, if one was provided
if license != nil {
release.Manifests["userdata/license.yaml"] = MustMarshalLicense(license)
}
files, err := releaseToFiles(release)
if err != nil {
return nil, errors.Wrap(err, "failed to get files from release")
}
upstream := &types.Upstream{
URI: u.RequestURI(),
Name: application.Name,
Files: files,
Type: "replicated",
UpdateCursor: release.UpdateCursor.Cursor,
ChannelID: channelID,
ChannelName: channelName,
VersionLabel: release.VersionLabel,
ReleaseNotes: release.ReleaseNotes,
ReleasedAt: release.ReleasedAt,
EncryptionKey: cipher.ToString(),
}
return upstream, nil
}
func (r *ReplicatedUpstream) getRequest(method string, license *kotsv1beta1.License, cursor ReplicatedCursor) (*http.Request, error) {
u, err := url.Parse(license.Spec.Endpoint)
if err != nil {
return nil, errors.Wrap(err, "failed to parse endpoint from license")
}
hostname := u.Hostname()
if u.Port() != "" {
hostname = fmt.Sprintf("%s:%s", u.Hostname(), u.Port())
}
urlPath := path.Join(hostname, "release", license.Spec.AppSlug)
if r.Channel != nil {
urlPath = path.Join(urlPath, *r.Channel)
}
urlValues := url.Values{}
urlValues.Set("channelSequence", cursor.Cursor)
urlValues.Add("licenseSequence", fmt.Sprintf("%d", license.Spec.LicenseSequence))
url := fmt.Sprintf("%s://%s?%s", u.Scheme, urlPath, urlValues.Encode())
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to call newrequest")
}
req.Header.Add("User-Agent", fmt.Sprintf("KOTS/%s", buildversion.Version()))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", license.Spec.LicenseID, license.Spec.LicenseID)))))
return req, nil
}
func parseReplicatedURL(u *url.URL) (*ReplicatedUpstream, error) {
replicatedUpstream := ReplicatedUpstream{}
if u.User != nil {
if u.User.Username() != "" {
replicatedUpstream.AppSlug = u.User.Username()
versionLabel := u.Hostname()
replicatedUpstream.VersionLabel = &versionLabel
}
}
if replicatedUpstream.AppSlug == "" {
replicatedUpstream.AppSlug = u.Hostname()
if u.Path != "" {
channel := strings.TrimPrefix(u.Path, "/")
replicatedUpstream.Channel = &channel
}
}
return &replicatedUpstream, nil
}
func getSuccessfulHeadResponse(replicatedUpstream *ReplicatedUpstream, license *kotsv1beta1.License) error {
headReq, err := replicatedUpstream.getRequest("HEAD", license, ReplicatedCursor{})
if err != nil {
return errors.Wrap(err, "failed to create http request")
}
headResp, err := http.DefaultClient.Do(headReq)
if err != nil {
return errors.Wrap(err, "failed to execute head request")
}
defer headResp.Body.Close()
if headResp.StatusCode == 401 {
return errors.New("license was not accepted")
}
if headResp.StatusCode == 403 {
return util.ActionableError{Message: "License is expired"}
}
if headResp.StatusCode >= 400 {
return errors.Errorf("unexpected result from head request: %d", headResp.StatusCode)
}
return nil
}
func readReplicatedAppFromLocalPath(localPath string, localCursor ReplicatedCursor, versionLabel string) (*Release, error) {
release := Release{
Manifests: make(map[string][]byte),
UpdateCursor: localCursor,
VersionLabel: versionLabel,
}
err := filepath.Walk(localPath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return err
}
// remove localpath prefix
appPath := strings.TrimPrefix(path, localPath)
appPath = strings.TrimLeft(appPath, string(os.PathSeparator))
release.Manifests[appPath] = contents
return nil
})
if err != nil {
return nil, errors.Wrap(err, "failed to walk local path")
}
return &release, nil
}
func downloadReplicatedApp(replicatedUpstream *ReplicatedUpstream, license *kotsv1beta1.License, cursor ReplicatedCursor, reportingInfo *reportingtypes.ReportingInfo) (*Release, error) {
getReq, err := replicatedUpstream.getRequest("GET", license, cursor)
if err != nil {
return nil, errors.Wrap(err, "failed to create http request")
}
reporting.InjectReportingInfoHeaders(getReq, reportingInfo)
getResp, err := http.DefaultClient.Do(getReq)
if err != nil {
return nil, errors.Wrap(err, "failed to execute get request")
}
defer getResp.Body.Close()
if getResp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(getResp.Body)
if len(body) > 0 {
return nil, util.ActionableError{Message: string(body)}
}
return nil, errors.Errorf("unexpected result from get request: %d", getResp.StatusCode)
}
updateSequence := getResp.Header.Get("X-Replicated-ChannelSequence")
updateChannelID := getResp.Header.Get("X-Replicated-ChannelID")
updateChannelName := getResp.Header.Get("X-Replicated-ChannelName")
versionLabel := getResp.Header.Get("X-Replicated-VersionLabel")
releasedAtStr := getResp.Header.Get("X-Replicated-ReleasedAt")
var releasedAt *time.Time
r, err := time.Parse(time.RFC3339, releasedAtStr)
if err == nil {
releasedAt = &r
}
gzf, err := gzip.NewReader(getResp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to create new gzip reader")
}
release := Release{
Manifests: make(map[string][]byte),
UpdateCursor: ReplicatedCursor{
ChannelID: updateChannelID,
ChannelName: updateChannelName,
Cursor: updateSequence,
},
VersionLabel: versionLabel,
ReleasedAt: releasedAt,
// NOTE: release notes come from Application spec
}
tarReader := tar.NewReader(gzf)
i := 0
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, errors.Wrap(err, "failed to get next file from reader")
}
name := header.Name
switch header.Typeflag {
case tar.TypeDir:
continue
case tar.TypeReg:
content, err := ioutil.ReadAll(tarReader)
if err != nil {
return nil, errors.Wrap(err, "failed to read file from tar")
}
release.Manifests[name] = content
}
i++
}
return &release, nil
}
func listPendingChannelReleases(replicatedUpstream *ReplicatedUpstream, license *kotsv1beta1.License, currentCursor ReplicatedCursor, reportingInfo *reportingtypes.ReportingInfo) ([]ChannelRelease, error) {
u, err := url.Parse(license.Spec.Endpoint)
if err != nil {
return nil, errors.Wrap(err, "failed to parse endpoint from license")
}
hostname := u.Hostname()
if u.Port() != "" {
hostname = fmt.Sprintf("%s:%s", u.Hostname(), u.Port())
}
sequence := currentCursor.Cursor
if license.Spec.ChannelID != "" && currentCursor.ChannelID != "" && license.Spec.ChannelID != currentCursor.ChannelID {
sequence = ""
} else if license.Spec.ChannelName != currentCursor.ChannelName {
sequence = ""
}
urlValues := url.Values{}
urlValues.Set("channelSequence", sequence)
urlValues.Add("licenseSequence", fmt.Sprintf("%d", license.Spec.LicenseSequence))
url := fmt.Sprintf("%s://%s/release/%s/pending?%s", u.Scheme, hostname, license.Spec.AppSlug, urlValues.Encode())
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to call newrequest")
}
reporting.InjectReportingInfoHeaders(req, reportingInfo)
req.Header.Add("User-Agent", fmt.Sprintf("KOTS/%s", buildversion.Version()))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", license.Spec.LicenseID, license.Spec.LicenseID)))))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "failed to execute get request")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
}
if resp.StatusCode >= 400 {
if len(body) > 0 {
return nil, util.ActionableError{Message: string(body)}
}
return nil, errors.Errorf("unexpected result from get request: %d", resp.StatusCode)
}
var channelReleases struct {
ChannelReleases []ChannelRelease `json:"channelReleases"`
}
if err := json.Unmarshal(body, &channelReleases); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal response")
}
| s := serializer.NewYAMLSerializer(serializer.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
var b bytes.Buffer
if err := s.Encode(license, &b); err != nil {
panic(err)
}
return b.Bytes()
}
func mustMarshalConfigValues(configValues *kotsv1beta1.ConfigValues) []byte {
s := serializer.NewYAMLSerializer(serializer.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
var b bytes.Buffer
if err := s.Encode(configValues, &b); err != nil {
panic(err)
}
return b.Bytes()
}
func createConfigValues(applicationName string, config *kotsv1beta1.Config, existingConfigValues *kotsv1beta1.ConfigValues, cipher *crypto.AESCipher, license *kotsv1beta1.License, app *kotsv1beta1.Application, appInfo *template.ApplicationInfo, versionInfo *template.VersionInfo, localRegistry template.LocalRegistry, identityConfig *kotsv1beta1.IdentityConfig) (*kotsv1beta1.ConfigValues, error) {
templateContextValues := make(map[string]template.ItemValue)
var newValues kotsv1beta1.ConfigValuesSpec
if existingConfigValues != nil {
for k, v := range existingConfigValues.Spec.Values {
value := v.Value
if value == "" {
value = v.ValuePlaintext
}
templateContextValues[k] = template.ItemValue{
Value: value,
Default: v.Default,
Filename: v.Filename,
}
}
newValues = kotsv1beta1.ConfigValuesSpec{
Values: existingConfigValues.Spec.Values,
}
} else {
newValues = kotsv1beta1.ConfigValuesSpec{
Values: map[string]kotsv1beta1.ConfigValue{},
}
}
if config == nil {
return &kotsv1beta1.ConfigValues{
TypeMeta: metav1.TypeMeta{
APIVersion: "kots.io/v1beta1",
Kind: "ConfigValues",
},
ObjectMeta: metav1.ObjectMeta{
Name: applicationName,
},
Spec: newValues,
}, nil
}
builderOptions := template.BuilderOptions{
ConfigGroups: config.Spec.Groups,
ExistingValues: templateContextValues,
LocalRegistry: localRegistry,
Cipher: cipher,
License: license,
Application: app,
ApplicationInfo: appInfo,
VersionInfo: versionInfo,
IdentityConfig: identityConfig,
}
builder, _, err := template.NewBuilder(builderOptions)
if err != nil {
return nil, errors.Wrap(err, "failed to create config context")
}
for _, group := range config.Spec.Groups {
for _, item := range group.Items {
var foundValue, foundValuePlaintext, foundFilename string
prevValue, ok := newValues.Values[item.Name]
if ok {
foundValue = prevValue.Value
foundValuePlaintext = prevValue.ValuePlaintext
foundFilename = prevValue.Filename
}
renderedValue, err := builder.RenderTemplate(item.Name, item.Value.String())
if err != nil {
return nil, errors.Wrap(err, "failed to render config item value")
}
renderedDefault, err := builder.RenderTemplate(item.Name, item.Default.String())
if err != nil {
return nil, errors.Wrap(err, "failed to render config item default")
}
if foundValue != "" || foundValuePlaintext != "" {
newValues.Values[item.Name] = kotsv1beta1.ConfigValue{
Value: foundValue,
ValuePlaintext: foundValuePlaintext,
Default: renderedDefault,
Filename: foundFilename,
}
} else {
newValues.Values[item.Name] = kotsv1beta1.ConfigValue{
Value: renderedValue,
Default: renderedDefault,
Filename: foundFilename,
}
builderOptions.ExistingValues[item.Name] = template.ItemValue{
Value: renderedValue,
Default: renderedDefault,
Filename: foundFilename,
}
}
}
}
configValues := kotsv1beta1.ConfigValues{
TypeMeta: metav1.TypeMeta{
APIVersion: "kots.io/v1beta1",
Kind: "ConfigValues",
},
ObjectMeta: metav1.ObjectMeta{
Name: applicationName,
},
Spec: newValues,
}
return &configValues, nil
}
func findConfigValuesInFile(filename string) (*kotsv1beta1.ConfigValues, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to open file")
}
return contentToConfigValues(content), nil
}
func contentToConfigValues(content []byte) *kotsv1beta1.ConfigValues {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(content, nil, nil)
if err != nil {
return nil
}
if gvk.Group == "kots.io" && gvk.Version == "v1beta1" && gvk.Kind == "ConfigValues" {
return obj.(*kotsv1beta1.ConfigValues)
}
return nil
}
func mustMarshalIdentityConfig(identityConfig *kotsv1beta1.IdentityConfig) []byte {
s := serializer.NewYAMLSerializer(serializer.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
var b bytes.Buffer
if err := s.Encode(identityConfig, &b); err != nil {
panic(err)
}
return b.Bytes()
}
func findIdentityConfigInFile(filename string) (*kotsv1beta1.IdentityConfig, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to open file")
}
return contentToIdentityConfig(content), nil
}
func contentToIdentityConfig(content []byte) *kotsv1beta1.IdentityConfig {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(content, nil, nil)
if err != nil {
return nil
}
if gvk.Group == "kots.io" && gvk.Version == "v1beta1" && gvk.Kind == "IdentityConfig" {
return obj.(*kotsv1beta1.IdentityConfig)
}
return nil
}
func findTemplateContextDataInRelease(release *Release) (*kotsv1beta1.Config, *kotsv1beta1.ConfigValues, *kotsv1beta1.License, *kotsv1beta1.Installation, *kotsv1beta1.IdentityConfig, error) {
var config *kotsv1beta1.Config
var values *kotsv1beta1.ConfigValues
var license *kotsv1beta1.License
var installation *kotsv1beta1.Installation
var identityConfig *kotsv1beta1.IdentityConfig
for _, content := range release.Manifests {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(content, nil, nil)
if err != nil {
continue
}
if gvk.Group == "kots.io" {
if gvk.Version == "v1beta1" {
if gvk.Kind == "Config" {
config = obj.(*kotsv1beta1.Config)
} else if gvk.Kind == "ConfigValues" {
values = obj.(*kotsv1beta1.ConfigValues)
} else if gvk.Kind == "License" {
license = obj.(*kotsv1beta1.License)
} else if gvk.Kind == "Installation" {
installation = obj.(*kotsv1beta1.Installation)
} else if gvk.Kind == "IdentityConfig" {
identityConfig = obj.(*kotsv1beta1.IdentityConfig)
}
}
}
}
return config, values, license, installation, identityConfig, nil
}
func findAppInRelease(release *Release) *kotsv1beta1.Application {
for _, content := range release.Manifests {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(content, nil, nil)
if err != nil {
continue
}
if gvk.Group == "kots.io" {
if gvk.Version == "v1beta1" {
if gvk.Kind == "Application" {
return obj.(*kotsv1beta1.Application)
}
}
}
}
// Using Ship apps for now, so let's create an app manifest on the fly
app := &kotsv1beta1.Application{
TypeMeta: metav1.TypeMeta{
APIVersion: "kots.io/v1beta1",
Kind: "Application",
},
ObjectMeta: metav1.ObjectMeta{
Name: "replicated-kots-app",
},
Spec: kotsv1beta1.ApplicationSpec{
Title: "Replicated KOTS App",
Icon: "",
},
}
return app
}
func releaseToFiles(release *Release) ([]types.UpstreamFile, error) {
upstreamFiles := []types.UpstreamFile{}
for filename, content := range release.Manifests {
upstreamFile := types.UpstreamFile{
Path: filename,
Content: content,
}
upstreamFiles = append(upstreamFiles, upstreamFile)
}
// Stash the user data for this search (we will readd at the end)
userdataFiles := []types.UpstreamFile{}
withoutUserdataFiles := []types.UpstreamFile{}
for _, file := range upstreamFiles {
d, _ := path.Split(file.Path)
dirs := strings.Split(d, string(os.PathSeparator))
if dirs[0] == "userdata" {
userdataFiles = append(userdataFiles, file)
} else {
withoutUserdataFiles = append(withoutUserdataFiles, file)
}
}
// remove any common prefix from all files
if len(withoutUserdataFiles) > 0 {
firstFileDir, _ := path.Split(withoutUserdataFiles[0].Path)
commonPrefix := strings.Split(firstFileDir, string(os.PathSeparator))
for _, file := range withoutUserdataFiles {
d, _ := path.Split(file.Path)
dirs := strings.Split(d, string(os.PathSeparator))
commonPrefix = util.CommonSlicePrefix(commonPrefix, dirs)
}
cleanedUpstreamFiles := []types.UpstreamFile{}
for _, file := range withoutUserdataFiles {
d, f := path.Split(file.Path)
d2 := strings.Split(d, string(os.PathSeparator))
cleanedUpstreamFile := file
d2 = d2[len(commonPrefix):]
cleanedUpstreamFile.Path = path.Join(path.Join(d2...), f)
cleanedUpstreamFiles = append(cleanedUpstreamFiles, cleanedUpstreamFile)
}
upstreamFiles = cleanedUpstreamFiles
}
upstreamFiles = append(upstreamFiles, userdataFiles...)
return upstreamFiles, nil
}
// GetApplicationMetadata will return any available application yaml from
// the upstream. If there is no application.yaml, it will return
// a placeholder one
func GetApplicationMetadata(upstream *url.URL) ([]byte, error) {
metadata, err := getApplicationMetadataFromHost("replicated.app", upstream)
if err != nil {
return nil, errors.Wrap(err, "failed to get metadata from replicated.app")
}
if len(metadata) == 0 {
metadata = []byte(DefaultMetadata)
}
return metadata, nil
}
func getApplicationMetadataFromHost(host string, upstream *url.URL) ([]byte, error) {
r, err := parseReplicatedURL(upstream)
if err != nil {
return nil, errors.Wrap(err, "failed to parse replicated upstream")
}
url := fmt.Sprintf("https://%s/metadata/%s", host, r.AppSlug)
if r.Channel != nil {
url = fmt.Sprintf("%s/%s", url, *r.Channel)
}
getReq, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to call newrequest")
}
getReq.Header.Add("User-Agent", fmt.Sprintf("KOTS/%s", buildversion.Version()))
getResp, err := http.DefaultClient.Do(getReq)
if err != nil {
return nil, errors.Wrap(err, "failed to execute get request")
}
defer getResp.Body.Close()
if getResp.StatusCode == 404 {
// no metadata is not an error
return nil, nil
}
if getResp.StatusCode >= 400 {
return nil, errors.Errorf("unexpected result from get request: %d", getResp.StatusCode)
}
respBody, err := ioutil.ReadAll(getResp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
}
return respBody, nil
} | return channelReleases.ChannelReleases, nil
}
func MustMarshalLicense(license *kotsv1beta1.License) []byte { |
http.go | package protocol
import (
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"net/url"
"time"
)
type HttpProtocol struct {
timeout time.Duration
client *fasthttp.Client
}
func NewHttpProtocol(timeout time.Duration, maxConnsPerHost int) *HttpProtocol {
client := &fasthttp.Client{
ReadTimeout: timeout,
MaxConnsPerHost: maxConnsPerHost,
}
return &HttpProtocol{timeout, client}
}
func (http *HttpProtocol) Name() string {
return "http"
}
func (http *HttpProtocol) Read(uri *url.URL) ([]byte, error) {
request := fasthttp.AcquireRequest()
request.SetRequestURI(uri.String())
response := fasthttp.AcquireResponse()
if err := http.client.DoTimeout(request, response, http.timeout); err != nil {
return nil, errors.Wrap(err, "failed to estabilish HTTP connection")
}
if response.Header.StatusCode() == 404 {
return nil, ErrNotFound
}
return response.Body(), nil | }
type HttpsProtocol struct {
HttpProtocol
}
func NewHttpsProtocol(timeout time.Duration, maxConnsPerHost int) *HttpsProtocol {
return &HttpsProtocol{HttpProtocol: *NewHttpProtocol(timeout, maxConnsPerHost)}
}
func (https *HttpsProtocol) Name() string {
return "https"
} | |
server.py | #!/bin/python3 -*- coding: utf-8 -*-
"""
@Author : Jessy JOSE -- Pierre VAUDRY
IPSA Aero1 - Prim2
Release date: 09/12/2020
[other information]
Licence: MIT
[Description]
SMC is a security message communication.
This program is the part of server program.
The server uses the socket module to work.
To improve communication between the client and the server, we use the select module to select a specific socket.
The datetime, os and platform modules are used to make the server fully functional. These modules are used to date
operations, and to clean the console if necessary depending on the platform used.
[Functions]:
Clean() -- clear console
documentation() -- make native documentation and basic screen interface
log() -- log all data receive on server
log_connection() -- log all connection make with server
process_server() -- interprets the data received and exploits it
list_log() -- conversion of data inside text file to list
str_log(data) -- conversion of a list to str
consoleCommand() -- make a native console after communication to see log.txt
connection_server() -- main process of the server
run() -- run and launch server
[Global variable]:
{int variable}
PORT
{str variable}
HOST
affichage_logo
{dict variable}
server_data
{list variable}
client_connected
[Other variable]:
Many other constants and variable may be defined; these may be used in calls to
the process_server(), list_log(), str_log(data), consoleCommand() and connection_server() functions
"""
# ---------------------------------------------Import module section-------------------------------------------------- #
import datetime
import select
import socket
import os
import platform
# ------------------------------------------------Global variable----------------------------------------------------- #
# Definition of local server variable
# Host is local adress for binding the server
HOST = '127.0.0.1'
# Port is the gate than the client take to discuss with the client
PORT = 50100
# Initialisation of list to make a stockage of connected client on the server
client_connected = []
# server_data is a dict. It's use to make a count of client
server_data = {
'count': 0
}
# ------------------------------------------------Functions & process------------------------------------------------- #
def Clean():
"""
[description]
clean is a process to clean main console
:return: none
"""
if platform.system() == "Windows":
os.system("cls")
elif platform.system() == "Linux":
os.system("clear")
def documentation():
"""
[Description]
This process return a native and basic documentation to the administrator of the serverS with a great ascii art
screen
:return: none
"""
affichage_logo = '\033[36m' + """
___ _ _ __ __ _____ _ _ _
/ ____| (_) | | \/ | / ____| (_) | | (_)
| (___ ___ ___ _ _ _ __ _| |_ _ _ | \ / | ___ ___ ___ __ _ __ _ ___ | | ___ _ __ ___ _ __ ___ _ _ _ __ _ ___ __ _| |_ _ ___ _ __
\___ \ / _ \/ __| | | | '__| | __| | | | | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \ | | / _ \| '_ ` _ \| '_ ` _ \| | | | '_ \| |/ __/ _` | __| |/ _ \| '_ \
____) | __/ (__| |_| | | | | |_| |_| | | | | | __/\__ \__ \ (_| | (_| | __/ | |___| (_) | | | | | | | | | | | |_| | | | | | (_| (_| | |_| | (_) | | | |
|_____/ \___|\___|\__,_|_| |_|\__|\__, | |_| |_|\___||___/___/\__,_|\__, |\___| \_____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|_|\___\__,_|\__|_|\___/|_| |_|
__/ | __/ |
|___/ |___/
/%&@@@@@&%/
@@@@@@@@&&(((((&&@@@@@@@@.
@@@@@,,,,,,,,,,,,,,,,,,,,,,,@@@@@
@@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@@
&@@@,,,,,,,,,,,,,,%@*,,%/%@%***@,,,,,,,&@@&
@@@(@@@@@@@@@@@*,,,,*,,,,,,,,,,,,,,,,,,,,,@@@
&@@@@@@@&,,,.....%@@@@@@@@*,,,,,,,,,,,,,,,,,,,,@@@
(@@@@&(#((***,,,,....,.......@@@@@,,,,,,,,,,,,,,,,,@@@
@@@@*,#*((/(/(/,,,,,,,,...,.... ,@@@&,,,,,,,,,,,,,,@@@
@@@,,/,,(*,/%/(((*,,,,.,....,.,.. ,..,@@@%,,,,,,,,,,,&@@
@@@./. ..*(((/#//***,*,,,,*,,*.. ..,, . @@@,,,,,,,,,@@@
@@@#,/**..*@@@#(//***#@@&,*,.,,.&@@#. ,,.. .@@%,,,,,,@@@#
@@(*%(,,/@@@(@@@%/*#@@@/@@@**.@@@/&@@(.. . @@@,,/@@@@
@@@#.,(/,@@@@@@@(..*@@@@@@@(..@@@@@@@ @@@@@@@
,@@(/((*#**#/(/, .*, ..&*////(,, @@@
@@@ */*(/*/. ..... . ... /*(.,.,, .@@@
%@@@. . . .., ., . . *,**.*, #@@@
@@@@(. .., ,. ,. .@@@
%@@@@@@(,.. ,. .. . .&@@@ , &@@
%@@@@@@@@@@@@@@@* @@@. (@@
@@@.@@.
@@@@.
@@.
""" + '\033[39m'
print(affichage_logo)
print('\t\t\t\t\t\t\t\t\t\t\t\t#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#')
print('\t\t\t\t\t\t\t\t\t\t\t\t# ' + '\033[31m' + 'Welcome in SMC server' + '\033[39m' +
' #')
print('\t\t\t\t\t\t\t\t\t\t\t\t#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#')
print('Reste de la doc à venir °°°')
def log(data):
"""
[description]
log is a process to make a history file of all conversation between client in the server.
He use a str value given by client and save it in a texte file.
:param data: str value given by client to the server
:return: none
"""
# Open file text as lmsg and write data with return line, after close the file in use
with open("log.txt", "a") as lmsg:
lmsg.write(data + "\n")
lmsg.close()
def log_connection(client_connected):
"""
[description]
log_connection is a process to make a history file of all connection client in the server.
He use a type value given by module socket and save it in a texte file..
:param client_connected: type value given by socket module
:return: none
"""
# Open file text as lc and write in file the date time of server, the client information in str
# After close the file
with open("log_connection.txt", "a") as lc:
lc.write(datetime.datetime.isoformat(datetime.datetime.now()) +
"> {} connected on server \n".format(client_connected))
lc.close()
def process_server(data):
"""
[description]
process_server is a function that processes data given by client.
It's a part of server to use client data.
He use a str value given by client and use it in process.
:param data: str value given by client in main bool of server in the part where data are receive
:return: response a str but this variable is not use in the rest of program (because we have not make yet a
functionnaly than use this var)
"""
# Rename data as response and use it in log process
response = data
if response != '/stop':
log(response)
else:
pass
return response
def list_log():
"""
[description]
list_log() is a function to change text file to list.
He open and take all data in log.txt.
He take all ligne and append in output list named dlog
:return: llog list created to use data in file txt
"""
# Open file text as lg and create a list named dlog.
# for line in lg, in variable named lastL, make a str variable named s and split the line with separator '@'
# After append variable l in list dlog and close
with open('log.txt', 'r') as lg:
llog = []
for line in lg:
s = line.strip("\n")
lastL = s.split("@")
llog.append(lastL)
lg.close()
return llog
def str_log(data):
"""
[description]
str_log is a function to change a list to str data.
He split element of list and join all element to make a str data.
But only the last line is returned and use
:param data: list of all data exchange between client2server and server2client
:return: list of all data exchange between client2server and server2client
"""
# Create a empty local variable named str_l
# for i in the range of len data, for j in range of len of all data element, join the last element in variable str_l
str_l = ''
for i in range(len(data)):
for j in range(len(data[i])):
str_l = ','.join(data[i - 1])
return str_l
def consoleCommand(event):
"""
[description]
:param event:
:return:
"""
if event == '/log.txt':
log = open("./log.txt", "r")
contenu = log.read()
print(contenu)
else:
exit()
# This process is named connection_server because client connextion's are logged and used by server.
# connection_server is a inspired of send() process but the code is not the same.
def conn | """
[description]
connection_server is a main process in the server program.
He use socket module to create a server.
It's the main part of server.
He take global value of the program like HOST and PORT, to bind and launch the server and listen all connection in
socket
Create a connection, wait to receive data, process it with the
process_request function.
AF_INET represents the IPv4 address family.
SOCK_STREAM represents the TCP protocol.
:return: none
"""
# Creating a socket, by creating a socket object named s.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Allows to reuse the same address
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# s.bind (address,port) binds an address and a port to socket s.
# The address parameter is a tuple consisting of the IP address of the
# server and a port number.
# s.bind((data_server['HOST'], data_server['PORT']))
s.bind((HOST, PORT))
# s.listen () makes the server ready to accept connections.
s.listen(5)
print('{serverver-status}:', '\033[32m', 'Online', '\033[1m')
print(s)
# Variable that starts the while loop
server_ready = True
turn = server_data['count']
while server_ready:
# wait_connections is variable with client waiting for connection and dialogue with server
# Select allows the first client in wait client to connect with the server every 0,05 second
wait_connections, wlist, xlist = select.select([s], [], [], 0.05)
select.select([s], [], [], 0.05)
# for connection in wait connections, accept the first client who wants to connect with server
# and append this client in list of connected_client, print connection_client in the console and log this
# connection with the process log_connection
for connection in wait_connections:
connection_client, info_connection = connection.accept()
client_connected.append(connection_client)
print("Prosition : ", turn , " | Client : ", connection_client)
turn = turn + 1
log_connection(connection_client)
####################################################################################################################
# Create a empty list read_client
read_client = []
# Part of the program that passes the possible errors in order to run the rest program
try:
read_client, wlist, xlist = select.select(client_connected, [], [], 0.05)
except select.error:
pass
else:
# for client in read_client, receive message of this client, and use process_server to record the message
for client in read_client:
msg_recv = client.recv(1024)
msg_recv = msg_recv.decode()
process_server(msg_recv)
print('\033[39m', '[', '\033[31m', 'SERVER@', '\033[36m', HOST, '\033[33m', '-p ', str(PORT),
'\033[39m', ']: Client send a message. Go to ./log.txt to see more.')
if msg_recv == "/stop":
server_ready = False
break
###############################################
# Function or process to open last message and convert him
d_l = list_log()
c2c = str_log(d_l)
p_server = c2c
###############################################
# encode the message give by server
byte_data = p_server.encode()
# send message to the client
client.sendall(byte_data)
####################################################################################################################
#console = input("[" + datetime.datetime.isoformat(datetime.datetime.now()) + "](/log.txt to see log in server)>")
#consoleCommand(console) # This line, give to the administrator the console to oppen and see log
print("Close all connections")
# For client in client_connected, disconnect all client
for client in client_connected:
client.close()
# close the server after executing while bool
s.close()
Clean()
def run():
"""
[description]
Run process
:return: none
"""
print('[' + '\033[31m' + 'SERVER@' + '\033[36m' + HOST + ' ' + '\033[33m' + '-p ' + str(PORT) + '\033[39m' + ']:\n')
while True:
connection_server()
# -------------------------------------------Run & Start server program----------------------------------------------- #
if __name__ == '__main__':
# Give basic and native documentation in console
documentation()
# Run the program
run()
| ection_server():
|
api_op_CreateMeeting.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package chime
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/chime/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Creates a new Amazon Chime SDK meeting in the specified media Region with no
// initial attendees. For more information about specifying media Regions, see
// Amazon Chime SDK Media Regions
// (https://docs.aws.amazon.com/chime/latest/dg/chime-sdk-meetings-regions.html) in
// the Amazon Chime Developer Guide . For more information about the Amazon Chime
// SDK, see Using the Amazon Chime SDK
// (https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the Amazon
// Chime Developer Guide .
func (c *Client) CreateMeeting(ctx context.Context, params *CreateMeetingInput, optFns ...func(*Options)) (*CreateMeetingOutput, error) {
if params == nil {
params = &CreateMeetingInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateMeeting", params, optFns, c.addOperationCreateMeetingMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateMeetingOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateMeetingInput struct {
// The unique identifier for the client request. Use a different token for
// different meetings.
//
// This member is required.
ClientRequestToken *string
// The external meeting ID.
ExternalMeetingId *string
// The Region in which to create the meeting. Default: us-east-1. Available values:
// af-south-1 , ap-northeast-1 , ap-northeast-2 , ap-south-1 , ap-southeast-1 ,
// ap-southeast-2 , ca-central-1 , eu-central-1 , eu-north-1 , eu-south-1 ,
// eu-west-1 , eu-west-2 , eu-west-3 , sa-east-1 , us-east-1 , us-east-2 ,
// us-west-1 , us-west-2 .
MediaRegion *string
// Reserved.
MeetingHostId *string
// The configuration for resource targets to receive notifications when meeting and
// attendee events occur.
NotificationsConfiguration *types.MeetingNotificationConfiguration
// The tag key-value pairs.
Tags []types.Tag
noSmithyDocumentSerde
}
type CreateMeetingOutput struct {
// The meeting information, including the meeting ID and MediaPlacement .
Meeting *types.Meeting
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateMeetingMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateMeeting{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateMeeting{}, middleware.After)
if err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addIdempotencyToken_opCreateMeetingMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateMeetingValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateMeeting(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateMeeting struct {
tokenProvider IdempotencyTokenProvider | return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateMeeting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateMeetingInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateMeetingInput ")
}
if input.ClientRequestToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.ClientRequestToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateMeetingMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateMeeting{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateMeeting(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "chime",
OperationName: "CreateMeeting",
}
} | }
func (*idempotencyToken_initializeOpCreateMeeting) ID() string { |
index.js | import { InstantBinConfirmSettings } from './settings-entry';
import { InstantBinConfirm } from './instant-bin-confirm';
export {
InstantBinConfirmSettings,
};
| new InstantBinConfirm(); // eslint-disable-line no-new |
|
group_steps.py | import random
from pytest_bdd import given, when, then # пометки
from model.group import Group
# STEPS FOR ADD GROUP
# предусловие
@given('a group list', target_fixture="group_list") # эти штуки представляют собой фикстуры, а их можно передавать в кач-ве параметра, что мы сделали в ф-ции verify_group_added
def group_list(db):
return db.get_group_list()
# предусловие
@given('a group with <name>, <header> and <footer>', target_fixture="new_group")
def new_group(name, header, footer):
return Group(group_name=name, group_header=header, group_footer=footer)
# действие
@when('I add the group to the list') # это тоже фикстура
def add_new_group(app, new_group):
app.group.create(new_group)
# постусловие
@then('the new group list is equal to the old list with the added group') # и это тоже фикстура
def verify_group_added(db, group_list, new_group):
old_groups_list = group_list
new_groups_list = db.get_group_list()
old_groups_list += [new_group]
assert sorted(old_groups_list, key=Group.id_or_max) == sorted(new_groups_list, key=Group.id_or_max)
# STEPS FOR DELETE GROUP
@given('non empty group list', target_fixture="non_empty_group_list") # эти штуки представляют собой фикстуры, а их можно передавать в кач-ве параметра, что мы сделали в ф-ции verify_group_added
def non_empty_group_list(app, db):
if len(db.get_group_list()) == 0:
app.group.create(Group(group_name="name", group_header="header", group_footer="footer"))
return db.get_group_list()
@given('a random group from non empty group list', target_fixture="random_group")
def random_group(non_empty_group_list):
return random.choice(non_empty_group_list)
@when('I delete the group from the list') # это тоже фикстура
def del_some_group(app, random_group):
app.group.delete_group_by_id(random_group.id)
@then('the new group list is equal to the old list without deleted group') # и это тоже фикстура
def verify_group_deleted(db, non_empty_group_list, random_group):
old_groups_list = non_empty_group_list
new_groups_list = db.get_group_list()
old_groups_list.remove(random_group)
assert sorted(old_groups_list, key=Group.id_or_max) == sorted(new_groups_list, key=Group.id_or_max)
# STEPS FOR MODIFY GROUP
@given('a new group with <new_name>, <new_header> and <new_footer>', target_fixture="new_group_for_modify")
def new_group_for_modify(new_name, new_header, new_footer):
return Group(group_name=new_name, group_header=new_header, group_footer=new_footer)
@when('I modify the group from the list') # это тоже фикстура
def modify_some_group(app, random_group, new_group_for_modify):
app.group.modify_group_by_id(random_group.id, new_group_for_modify)
@then('the new group list is equal to the old list with modify group') # и это тоже фикстура
def verify_group_modify(db, non_empty_group_list, random_group, new_group_for_modify):
old_groups_list = non_empty_group_list
new_groups_list = db.get_group_list()
res_old_groups = []
for i in range(len(old_groups_list)):
if str(old_groups_list[i].id) != str(random_group.id):
res_old_groups += [old_groups_list[i]]
if str(old_groups_list[i].id) == str(random_group.id):
res_old_groups += [new_group_for_modify]
assert res_old_groups == sorted(new_groups_list, key=Group.id_or_max)
| ||
main.go | package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func (n *TreeNode) String() string {
if n == nil {
return ""
}
return fmt.Sprintf("(%v,%v,%v)", n.Val, n.Left, n.Right)
}
// Time: O(n)
// Space: O(n) max width of tree + all nodes anyway (for result)
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
result := [][]int{}
curLevelNodes := []*TreeNode{root}
for len(curLevelNodes) > 0 {
levelVals := []int{}
nextLevelNodes := []*TreeNode{}
// For the current level's nodes, save all
// values on _levelVals_ and all next level
// nodes (i.e. _.Left_ and _.Right_) on
// _nextLevelNodes_.
for _, node := range curLevelNodes {
levelVals = append(levelVals, node.Val)
if node.Left != nil {
nextLevelNodes = append(nextLevelNodes, node.Left)
}
if node.Right != nil {
nextLevelNodes = append(nextLevelNodes, node.Right)
}
}
result = append(result, levelVals)
curLevelNodes = nextLevelNodes
}
return result
}
func | () {
fmt.Println(levelOrder(&TreeNode{3, &TreeNode{9, nil, nil}, &TreeNode{20, &TreeNode{15, nil, nil}, &TreeNode{7, nil, nil}}}))
// ts := []struct {
// input *TreeNode
// expected [][]int
// }{
// {
// input: ,
// expected: [][]int{{3}, {9, 20}, {15, 7}},
// },
// }
// for _, tc := range ts {
// actual := levelOrder(tc.input)
// if !reflect.DeepEqual(tc.expected, actual) {
// fmt.Printf("For %v expected %v but got %v\n", tc.input, tc.expected, actual)
// }
// }
}
| main |
fs.rs | use crate::os::unix::prelude::*;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io::{self, Error, IoSlice, IoSliceMut, SeekFrom};
use crate::mem;
use crate::path::{Path, PathBuf};
use crate::ptr;
use crate::sync::Arc;
use crate::sys::fd::FileDesc;
use crate::sys::time::SystemTime;
use crate::sys::{cvt, cvt_r};
use crate::sys_common::{AsInner, FromInner};
use libc::{c_int, mode_t};
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
use libc::dirfd;
#[cfg(any(target_os = "linux", target_os = "emscripten"))]
use libc::fstatat64;
#[cfg(not(any(
target_os = "linux",
target_os = "emscripten",
target_os = "solaris",
target_os = "illumos",
target_os = "l4re",
target_os = "fuchsia",
target_os = "redox"
)))]
use libc::readdir_r as readdir64_r;
#[cfg(target_os = "android")]
use libc::{
dirent as dirent64, fstat as fstat64, fstatat as fstatat64, lseek64, lstat as lstat64,
open as open64, stat as stat64,
};
#[cfg(not(any(
target_os = "linux",
target_os = "emscripten",
target_os = "l4re",
target_os = "android"
)))]
use libc::{
dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
};
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
use libc::{
dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, readdir64_r, stat64,
};
pub use crate::sys_common::fs::{remove_dir_all, try_exists};
pub struct File(FileDesc);
// FIXME: This should be available on Linux with all `target_env`.
// But currently only glibc exposes `statx` fn and structs.
// We don't want to import unverified raw C structs here directly.
// https://github.com/rust-lang/rust/pull/67774
macro_rules! cfg_has_statx {
({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
cfg_if::cfg_if! {
if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
$($then_tt)*
} else {
$($else_tt)*
}
}
};
($($block_inner:tt)*) => {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
$($block_inner)*
}
};
}
cfg_has_statx! {{
#[derive(Clone)]
pub struct FileAttr {
stat: stat64,
statx_extra_fields: Option<StatxExtraFields>,
}
#[derive(Clone)]
struct StatxExtraFields {
// This is needed to check if btime is supported by the filesystem.
stx_mask: u32,
stx_btime: libc::statx_timestamp,
}
// We prefer `statx` on Linux if available, which contains file creation time.
// Default `stat64` contains no creation time.
unsafe fn try_statx(
fd: c_int,
path: *const libc::c_char,
flags: i32,
mask: u32,
) -> Option<io::Result<FileAttr>> {
use crate::sync::atomic::{AtomicU8, Ordering};
// Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
// We store the availability in global to avoid unnecessary syscalls.
// 0: Unknown
// 1: Not available
// 2: Available
static STATX_STATE: AtomicU8 = AtomicU8::new(0);
syscall! {
fn statx(
fd: c_int,
pathname: *const libc::c_char,
flags: c_int,
mask: libc::c_uint,
statxbuf: *mut libc::statx
) -> c_int
}
match STATX_STATE.load(Ordering::Relaxed) {
0 => {
// It is a trick to call `statx` with null pointers to check if the syscall
// is available. According to the manual, it is expected to fail with EFAULT.
// We do this mainly for performance, since it is nearly hundreds times
// faster than a normal successful call.
let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
.err()
.and_then(|e| e.raw_os_error());
// We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
// and returns `EPERM`. Listing all possible errors seems not a good idea.
// See: https://github.com/rust-lang/rust/issues/65662
if err != Some(libc::EFAULT) {
STATX_STATE.store(1, Ordering::Relaxed);
return None;
}
STATX_STATE.store(2, Ordering::Relaxed);
}
1 => return None,
_ => {}
}
let mut buf: libc::statx = mem::zeroed();
if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
return Some(Err(err));
}
// We cannot fill `stat64` exhaustively because of private padding fields.
let mut stat: stat64 = mem::zeroed();
// `c_ulong` on gnu-mips, `dev_t` otherwise
stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
stat.st_ino = buf.stx_ino as libc::ino64_t;
stat.st_nlink = buf.stx_nlink as libc::nlink_t;
stat.st_mode = buf.stx_mode as libc::mode_t;
stat.st_uid = buf.stx_uid as libc::uid_t;
stat.st_gid = buf.stx_gid as libc::gid_t;
stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
stat.st_size = buf.stx_size as off64_t;
stat.st_blksize = buf.stx_blksize as libc::blksize_t;
stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
// `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
let extra = StatxExtraFields {
stx_mask: buf.stx_mask,
stx_btime: buf.stx_btime,
};
Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
}
} else {
#[derive(Clone)]
pub struct FileAttr {
stat: stat64,
}
}}
// all DirEntry's will have a reference to this struct
struct InnerReadDir {
dirp: Dir,
root: PathBuf,
}
pub struct ReadDir {
inner: Arc<InnerReadDir>,
#[cfg(not(any(
target_os = "solaris",
target_os = "illumos",
target_os = "fuchsia",
target_os = "redox",
)))]
end_of_stream: bool,
}
struct Dir(*mut libc::DIR);
unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}
pub struct DirEntry {
entry: dirent64,
dir: Arc<InnerReadDir>,
// We need to store an owned copy of the entry name
// on Solaris and Fuchsia because a) it uses a zero-length
// array to store the name, b) its lifetime between readdir
// calls is not guaranteed.
#[cfg(any(
target_os = "solaris",
target_os = "illumos",
target_os = "fuchsia",
target_os = "redox"
))]
name: Box<[u8]>,
}
#[derive(Clone, Debug)]
pub struct OpenOptions {
// generic
read: bool,
write: bool,
append: bool,
truncate: bool,
create: bool,
create_new: bool,
// system-specific
custom_flags: i32,
mode: mode_t,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions {
mode: mode_t,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct FileType {
mode: mode_t,
}
#[derive(Debug)]
pub struct DirBuilder {
mode: mode_t,
}
cfg_has_statx! {{
impl FileAttr {
fn from_stat64(stat: stat64) -> Self {
Self { stat, statx_extra_fields: None }
}
}
} else {
impl FileAttr {
fn from_stat64(stat: stat64) -> Self {
Self { stat }
}
}
}}
impl FileAttr {
pub fn size(&self) -> u64 {
self.stat.st_size as u64
}
pub fn perm(&self) -> FilePermissions {
FilePermissions { mode: (self.stat.st_mode as mode_t) }
}
pub fn file_type(&self) -> FileType {
FileType { mode: self.stat.st_mode as mode_t }
}
}
#[cfg(target_os = "netbsd")]
impl FileAttr {
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_mtime as libc::time_t,
tv_nsec: self.stat.st_mtimensec as libc::c_long,
}))
}
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_atime as libc::time_t,
tv_nsec: self.stat.st_atimensec as libc::c_long,
}))
}
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_birthtime as libc::time_t,
tv_nsec: self.stat.st_birthtimensec as libc::c_long,
}))
}
}
#[cfg(not(target_os = "netbsd"))]
impl FileAttr {
#[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_mtime as libc::time_t,
tv_nsec: self.stat.st_mtime_nsec as _,
}))
}
#[cfg(any(target_os = "vxworks", target_os = "espidf"))]
pub fn modified(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_mtime as libc::time_t,
tv_nsec: 0,
}))
}
#[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_atime as libc::time_t,
tv_nsec: self.stat.st_atime_nsec as _,
}))
}
#[cfg(any(target_os = "vxworks", target_os = "espidf"))]
pub fn accessed(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_atime as libc::time_t,
tv_nsec: 0,
}))
}
#[cfg(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "macos",
target_os = "ios"
))]
pub fn created(&self) -> io::Result<SystemTime> {
Ok(SystemTime::from(libc::timespec {
tv_sec: self.stat.st_birthtime as libc::time_t,
tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
}))
}
#[cfg(not(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "macos",
target_os = "ios"
)))]
pub fn created(&self) -> io::Result<SystemTime> {
cfg_has_statx! {
if let Some(ext) = &self.statx_extra_fields {
return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
Ok(SystemTime::from(libc::timespec {
tv_sec: ext.stx_btime.tv_sec as libc::time_t,
tv_nsec: ext.stx_btime.tv_nsec as _,
}))
} else {
Err(io::Error::new_const(
io::ErrorKind::Other,
&"creation time is not available for the filesystem",
))
};
}
}
Err(io::Error::new_const(
io::ErrorKind::Unsupported,
&"creation time is not available on this platform \
currently",
))
}
}
impl AsInner<stat64> for FileAttr {
fn as_inner(&self) -> &stat64 {
&self.stat
}
}
impl FilePermissions {
pub fn readonly(&self) -> bool {
// check if any class (owner, group, others) has write permission
self.mode & 0o222 == 0
}
pub fn set_readonly(&mut self, readonly: bool) {
if readonly {
// remove write permission for all classes; equivalent to `chmod a-w <file>`
self.mode &= !0o222;
} else {
// add write permission for all classes; equivalent to `chmod a+w <file>`
self.mode |= 0o222;
}
}
pub fn mode(&self) -> u32 {
self.mode as u32
}
}
impl FileType {
pub fn is_dir(&self) -> bool {
self.is(libc::S_IFDIR)
}
pub fn is_file(&self) -> bool {
self.is(libc::S_IFREG)
}
pub fn is_symlink(&self) -> bool {
self.is(libc::S_IFLNK)
}
pub fn is(&self, mode: mode_t) -> bool {
self.mode & libc::S_IFMT == mode
}
}
impl FromInner<u32> for FilePermissions {
fn from_inner(mode: u32) -> FilePermissions {
FilePermissions { mode: mode as mode_t }
}
}
impl fmt::Debug for ReadDir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
// Thus the result will be e g 'ReadDir("/home")'
fmt::Debug::fmt(&*self.inner.root, f)
}
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
#[cfg(any(
target_os = "solaris",
target_os = "fuchsia",
target_os = "redox",
target_os = "illumos"
))]
fn next(&mut self) -> Option<io::Result<DirEntry>> {
use crate::slice;
unsafe {
loop {
// Although readdir_r(3) would be a correct function to use here because
// of the thread safety, on Illumos and Fuchsia the readdir(3C) function
// is safe to use in threaded applications and it is generally preferred
// over the readdir_r(3C) function.
super::os::set_errno(0);
let entry_ptr = libc::readdir(self.inner.dirp.0);
if entry_ptr.is_null() {
// null can mean either the end is reached or an error occurred.
// So we had to clear errno beforehand to check for an error now.
return match super::os::errno() {
0 => None,
e => Some(Err(Error::from_raw_os_error(e))),
};
}
let name = (*entry_ptr).d_name.as_ptr();
let namelen = libc::strlen(name) as usize;
let ret = DirEntry {
entry: *entry_ptr,
name: slice::from_raw_parts(name as *const u8, namelen as usize)
.to_owned()
.into_boxed_slice(),
dir: Arc::clone(&self.inner),
};
if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
return Some(Ok(ret));
}
}
}
}
#[cfg(not(any(
target_os = "solaris",
target_os = "fuchsia",
target_os = "redox",
target_os = "illumos"
)))]
fn next(&mut self) -> Option<io::Result<DirEntry>> {
if self.end_of_stream {
return None;
} | unsafe {
let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
let mut entry_ptr = ptr::null_mut();
loop {
if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
if entry_ptr.is_null() {
// We encountered an error (which will be returned in this iteration), but
// we also reached the end of the directory stream. The `end_of_stream`
// flag is enabled to make sure that we return `None` in the next iteration
// (instead of looping forever)
self.end_of_stream = true;
}
return Some(Err(Error::last_os_error()));
}
if entry_ptr.is_null() {
return None;
}
if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
return Some(Ok(ret));
}
}
}
}
}
impl Drop for Dir {
fn drop(&mut self) {
let r = unsafe { libc::closedir(self.0) };
debug_assert_eq!(r, 0);
}
}
impl DirEntry {
pub fn path(&self) -> PathBuf {
self.dir.root.join(OsStr::from_bytes(self.name_bytes()))
}
pub fn file_name(&self) -> OsString {
OsStr::from_bytes(self.name_bytes()).to_os_string()
}
#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
pub fn metadata(&self) -> io::Result<FileAttr> {
let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
let name = self.entry.d_name.as_ptr();
cfg_has_statx! {
if let Some(ret) = unsafe { try_statx(
fd,
name,
libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
libc::STATX_ALL,
) } {
return ret;
}
}
let mut stat: stat64 = unsafe { mem::zeroed() };
cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
Ok(FileAttr::from_stat64(stat))
}
#[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
pub fn metadata(&self) -> io::Result<FileAttr> {
lstat(&self.path())
}
#[cfg(any(
target_os = "solaris",
target_os = "illumos",
target_os = "haiku",
target_os = "vxworks"
))]
pub fn file_type(&self) -> io::Result<FileType> {
lstat(&self.path()).map(|m| m.file_type())
}
#[cfg(not(any(
target_os = "solaris",
target_os = "illumos",
target_os = "haiku",
target_os = "vxworks"
)))]
pub fn file_type(&self) -> io::Result<FileType> {
match self.entry.d_type {
libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
_ => lstat(&self.path()).map(|m| m.file_type()),
}
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "linux",
target_os = "emscripten",
target_os = "android",
target_os = "solaris",
target_os = "illumos",
target_os = "haiku",
target_os = "l4re",
target_os = "fuchsia",
target_os = "redox",
target_os = "vxworks",
target_os = "espidf"
))]
pub fn ino(&self) -> u64 {
self.entry.d_ino as u64
}
#[cfg(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
))]
pub fn ino(&self) -> u64 {
self.entry.d_fileno as u64
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "netbsd",
target_os = "openbsd",
target_os = "freebsd",
target_os = "dragonfly"
))]
fn name_bytes(&self) -> &[u8] {
use crate::slice;
unsafe {
slice::from_raw_parts(
self.entry.d_name.as_ptr() as *const u8,
self.entry.d_namlen as usize,
)
}
}
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "emscripten",
target_os = "l4re",
target_os = "haiku",
target_os = "vxworks",
target_os = "espidf"
))]
fn name_bytes(&self) -> &[u8] {
unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() }
}
#[cfg(any(
target_os = "solaris",
target_os = "illumos",
target_os = "fuchsia",
target_os = "redox"
))]
fn name_bytes(&self) -> &[u8] {
&*self.name
}
}
impl OpenOptions {
pub fn new() -> OpenOptions {
OpenOptions {
// generic
read: false,
write: false,
append: false,
truncate: false,
create: false,
create_new: false,
// system-specific
custom_flags: 0,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) {
self.read = read;
}
pub fn write(&mut self, write: bool) {
self.write = write;
}
pub fn append(&mut self, append: bool) {
self.append = append;
}
pub fn truncate(&mut self, truncate: bool) {
self.truncate = truncate;
}
pub fn create(&mut self, create: bool) {
self.create = create;
}
pub fn create_new(&mut self, create_new: bool) {
self.create_new = create_new;
}
pub fn custom_flags(&mut self, flags: i32) {
self.custom_flags = flags;
}
pub fn mode(&mut self, mode: u32) {
self.mode = mode as mode_t;
}
fn get_access_mode(&self) -> io::Result<c_int> {
match (self.read, self.write, self.append) {
(true, false, false) => Ok(libc::O_RDONLY),
(false, true, false) => Ok(libc::O_WRONLY),
(true, true, false) => Ok(libc::O_RDWR),
(false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
(true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
(false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
}
}
fn get_creation_mode(&self) -> io::Result<c_int> {
match (self.write, self.append) {
(true, false) => {}
(false, false) => {
if self.truncate || self.create || self.create_new {
return Err(Error::from_raw_os_error(libc::EINVAL));
}
}
(_, true) => {
if self.truncate && !self.create_new {
return Err(Error::from_raw_os_error(libc::EINVAL));
}
}
}
Ok(match (self.create, self.truncate, self.create_new) {
(false, false, false) => 0,
(true, false, false) => libc::O_CREAT,
(false, true, false) => libc::O_TRUNC,
(true, true, false) => libc::O_CREAT | libc::O_TRUNC,
(_, _, true) => libc::O_CREAT | libc::O_EXCL,
})
}
}
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let path = cstr(path)?;
File::open_c(&path, opts)
}
pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
let flags = libc::O_CLOEXEC
| opts.get_access_mode()?
| opts.get_creation_mode()?
| (opts.custom_flags as c_int & !libc::O_ACCMODE);
// The third argument of `open64` is documented to have type `mode_t`. On
// some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
// However, since this is a variadic function, C integer promotion rules mean that on
// the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
Ok(File(FileDesc::new(fd)))
}
pub fn file_attr(&self) -> io::Result<FileAttr> {
let fd = self.0.raw();
cfg_has_statx! {
if let Some(ret) = unsafe { try_statx(
fd,
b"\0" as *const _ as *const libc::c_char,
libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
libc::STATX_ALL,
) } {
return ret;
}
}
let mut stat: stat64 = unsafe { mem::zeroed() };
cvt(unsafe { fstat64(fd, &mut stat) })?;
Ok(FileAttr::from_stat64(stat))
}
pub fn fsync(&self) -> io::Result<()> {
cvt_r(|| unsafe { os_fsync(self.0.raw()) })?;
return Ok(());
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe fn os_fsync(fd: c_int) -> c_int {
libc::fcntl(fd, libc::F_FULLFSYNC)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
unsafe fn os_fsync(fd: c_int) -> c_int {
libc::fsync(fd)
}
}
pub fn datasync(&self) -> io::Result<()> {
cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
return Ok(());
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe fn os_datasync(fd: c_int) -> c_int {
libc::fcntl(fd, libc::F_FULLFSYNC)
}
#[cfg(any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_os = "netbsd",
target_os = "openbsd"
))]
unsafe fn os_datasync(fd: c_int) -> c_int {
libc::fdatasync(fd)
}
#[cfg(not(any(
target_os = "android",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd"
)))]
unsafe fn os_datasync(fd: c_int) -> c_int {
libc::fsync(fd)
}
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
#[cfg(target_os = "android")]
return crate::sys::android::ftruncate64(self.0.raw(), size);
#[cfg(not(target_os = "android"))]
{
use crate::convert::TryInto;
let size: off64_t =
size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
cvt_r(|| unsafe { ftruncate64(self.0.raw(), size) }).map(drop)
}
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.0.read_vectored(bufs)
}
#[inline]
pub fn is_read_vectored(&self) -> bool {
self.0.is_read_vectored()
}
pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
self.0.read_at(buf, offset)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.0.write_vectored(bufs)
}
#[inline]
pub fn is_write_vectored(&self) -> bool {
self.0.is_write_vectored()
}
pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
self.0.write_at(buf, offset)
}
pub fn flush(&self) -> io::Result<()> {
Ok(())
}
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
let (whence, pos) = match pos {
// Casting to `i64` is fine, too large values will end up as
// negative which will cause an error in `lseek64`.
SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
SeekFrom::End(off) => (libc::SEEK_END, off),
SeekFrom::Current(off) => (libc::SEEK_CUR, off),
};
let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
Ok(n as u64)
}
pub fn duplicate(&self) -> io::Result<File> {
self.0.duplicate().map(File)
}
pub fn fd(&self) -> &FileDesc {
&self.0
}
pub fn into_fd(self) -> FileDesc {
self.0
}
pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
Ok(())
}
}
impl DirBuilder {
pub fn new() -> DirBuilder {
DirBuilder { mode: 0o777 }
}
pub fn mkdir(&self, p: &Path) -> io::Result<()> {
let p = cstr(p)?;
cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
Ok(())
}
pub fn set_mode(&mut self, mode: u32) {
self.mode = mode as mode_t;
}
}
fn cstr(path: &Path) -> io::Result<CString> {
Ok(CString::new(path.as_os_str().as_bytes())?)
}
impl FromInner<c_int> for File {
fn from_inner(fd: c_int) -> File {
File(FileDesc::new(fd))
}
}
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(target_os = "linux")]
fn get_path(fd: c_int) -> Option<PathBuf> {
let mut p = PathBuf::from("/proc/self/fd");
p.push(&fd.to_string());
readlink(&p).ok()
}
#[cfg(target_os = "macos")]
fn get_path(fd: c_int) -> Option<PathBuf> {
// FIXME: The use of PATH_MAX is generally not encouraged, but it
// is inevitable in this case because macOS defines `fcntl` with
// `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
// alternatives. If a better method is invented, it should be used
// instead.
let mut buf = vec![0; libc::PATH_MAX as usize];
let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
if n == -1 {
return None;
}
let l = buf.iter().position(|&c| c == 0).unwrap();
buf.truncate(l as usize);
buf.shrink_to_fit();
Some(PathBuf::from(OsString::from_vec(buf)))
}
#[cfg(target_os = "vxworks")]
fn get_path(fd: c_int) -> Option<PathBuf> {
let mut buf = vec![0; libc::PATH_MAX as usize];
let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
if n == -1 {
return None;
}
let l = buf.iter().position(|&c| c == 0).unwrap();
buf.truncate(l as usize);
Some(PathBuf::from(OsString::from_vec(buf)))
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
fn get_path(_fd: c_int) -> Option<PathBuf> {
// FIXME(#24570): implement this for other Unix platforms
None
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
fn get_mode(fd: c_int) -> Option<(bool, bool)> {
let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if mode == -1 {
return None;
}
match mode & libc::O_ACCMODE {
libc::O_RDONLY => Some((true, false)),
libc::O_RDWR => Some((true, true)),
libc::O_WRONLY => Some((false, true)),
_ => None,
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
// FIXME(#24570): implement this for other Unix platforms
None
}
let fd = self.0.raw();
let mut b = f.debug_struct("File");
b.field("fd", &fd);
if let Some(path) = get_path(fd) {
b.field("path", &path);
}
if let Some((read, write)) = get_mode(fd) {
b.field("read", &read).field("write", &write);
}
b.finish()
}
}
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = p.to_path_buf();
let p = cstr(p)?;
unsafe {
let ptr = libc::opendir(p.as_ptr());
if ptr.is_null() {
Err(Error::last_os_error())
} else {
let inner = InnerReadDir { dirp: Dir(ptr), root };
Ok(ReadDir {
inner: Arc::new(inner),
#[cfg(not(any(
target_os = "solaris",
target_os = "illumos",
target_os = "fuchsia",
target_os = "redox",
)))]
end_of_stream: false,
})
}
}
}
pub fn unlink(p: &Path) -> io::Result<()> {
let p = cstr(p)?;
cvt(unsafe { libc::unlink(p.as_ptr()) })?;
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let old = cstr(old)?;
let new = cstr(new)?;
cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
let p = cstr(p)?;
cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
let p = cstr(p)?;
cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
Ok(())
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let c_path = cstr(p)?;
let p = c_path.as_ptr();
let mut buf = Vec::with_capacity(256);
loop {
let buf_read =
cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
unsafe {
buf.set_len(buf_read);
}
if buf_read != buf.capacity() {
buf.shrink_to_fit();
return Ok(PathBuf::from(OsString::from_vec(buf)));
}
// Trigger the internal buffer resizing logic of `Vec` by requiring
// more space than the current capacity. The length is guaranteed to be
// the same as the capacity due to the if statement above.
buf.reserve(1);
}
}
pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
let original = cstr(original)?;
let link = cstr(link)?;
cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) })?;
Ok(())
}
pub fn link(original: &Path, link: &Path) -> io::Result<()> {
let original = cstr(original)?;
let link = cstr(link)?;
cfg_if::cfg_if! {
if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf"))] {
// VxWorks, Redox, ESP-IDF and old versions of Android lack `linkat`, so use
// `link` instead. POSIX leaves it implementation-defined whether
// `link` follows symlinks, so rely on the `symlink_hard_link` test
// in library/std/src/fs/tests.rs to check the behavior.
cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
} else {
// Use `linkat` with `AT_FDCWD` instead of `link` as `linkat` gives
// us a flag to specify how symlinks should be handled. Pass 0 as
// the flags argument, meaning don't follow symlinks.
cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
}
}
Ok(())
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let p = cstr(p)?;
cfg_has_statx! {
if let Some(ret) = unsafe { try_statx(
libc::AT_FDCWD,
p.as_ptr(),
libc::AT_STATX_SYNC_AS_STAT,
libc::STATX_ALL,
) } {
return ret;
}
}
let mut stat: stat64 = unsafe { mem::zeroed() };
cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
Ok(FileAttr::from_stat64(stat))
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let p = cstr(p)?;
cfg_has_statx! {
if let Some(ret) = unsafe { try_statx(
libc::AT_FDCWD,
p.as_ptr(),
libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
libc::STATX_ALL,
) } {
return ret;
}
}
let mut stat: stat64 = unsafe { mem::zeroed() };
cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
Ok(FileAttr::from_stat64(stat))
}
pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
let path = CString::new(p.as_os_str().as_bytes())?;
let buf;
unsafe {
let r = libc::realpath(path.as_ptr(), ptr::null_mut());
if r.is_null() {
return Err(io::Error::last_os_error());
}
buf = CStr::from_ptr(r).to_bytes().to_vec();
libc::free(r as *mut _);
}
Ok(PathBuf::from(OsString::from_vec(buf)))
}
fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
use crate::fs::File;
use crate::sys_common::fs::NOT_FILE_ERROR;
let reader = File::open(from)?;
let metadata = reader.metadata()?;
if !metadata.is_file() {
return Err(NOT_FILE_ERROR);
}
Ok((reader, metadata))
}
#[cfg(target_os = "espidf")]
fn open_to_and_set_permissions(
to: &Path,
reader_metadata: crate::fs::Metadata,
) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
use crate::fs::OpenOptions;
let writer = OpenOptions::new().open(to)?;
let writer_metadata = writer.metadata()?;
Ok((writer, writer_metadata))
}
#[cfg(not(target_os = "espidf"))]
fn open_to_and_set_permissions(
to: &Path,
reader_metadata: crate::fs::Metadata,
) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
use crate::fs::OpenOptions;
use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let perm = reader_metadata.permissions();
let writer = OpenOptions::new()
// create the file with the correct mode right away
.mode(perm.mode())
.write(true)
.create(true)
.truncate(true)
.open(to)?;
let writer_metadata = writer.metadata()?;
if writer_metadata.is_file() {
// Set the correct file permissions, in case the file already existed.
// Don't set the permissions on already existing non-files like
// pipes/FIFOs or device nodes.
writer.set_permissions(perm)?;
}
Ok((writer, writer_metadata))
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios"
)))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let (mut reader, reader_metadata) = open_from(from)?;
let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
io::copy(&mut reader, &mut writer)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let (mut reader, reader_metadata) = open_from(from)?;
let max_len = u64::MAX;
let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
use super::kernel_copy::{copy_regular_files, CopyResult};
match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
CopyResult::Ended(bytes) => Ok(bytes),
CopyResult::Error(e, _) => Err(e),
CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
Ok(bytes) => Ok(bytes + written),
Err(e) => Err(e),
},
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
use crate::sync::atomic::{AtomicBool, Ordering};
const COPYFILE_ACL: u32 = 1 << 0;
const COPYFILE_STAT: u32 = 1 << 1;
const COPYFILE_XATTR: u32 = 1 << 2;
const COPYFILE_DATA: u32 = 1 << 3;
const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
const COPYFILE_STATE_COPIED: u32 = 8;
#[allow(non_camel_case_types)]
type copyfile_state_t = *mut libc::c_void;
#[allow(non_camel_case_types)]
type copyfile_flags_t = u32;
extern "C" {
fn fcopyfile(
from: libc::c_int,
to: libc::c_int,
state: copyfile_state_t,
flags: copyfile_flags_t,
) -> libc::c_int;
fn copyfile_state_alloc() -> copyfile_state_t;
fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
fn copyfile_state_get(
state: copyfile_state_t,
flag: u32,
dst: *mut libc::c_void,
) -> libc::c_int;
}
struct FreeOnDrop(copyfile_state_t);
impl Drop for FreeOnDrop {
fn drop(&mut self) {
// The code below ensures that `FreeOnDrop` is never a null pointer
unsafe {
// `copyfile_state_free` returns -1 if the `to` or `from` files
// cannot be closed. However, this is not considered this an
// error.
copyfile_state_free(self.0);
}
}
}
// MacOS prior to 10.12 don't support `fclonefileat`
// We store the availability in a global to avoid unnecessary syscalls
static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
syscall! {
fn fclonefileat(
srcfd: libc::c_int,
dst_dirfd: libc::c_int,
dst: *const libc::c_char,
flags: libc::c_int
) -> libc::c_int
}
let (reader, reader_metadata) = open_from(from)?;
// Opportunistically attempt to create a copy-on-write clone of `from`
// using `fclonefileat`.
if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
let to = cstr(to)?;
let clonefile_result =
cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
match clonefile_result {
Ok(_) => return Ok(reader_metadata.len()),
Err(err) => match err.raw_os_error() {
// `fclonefileat` will fail on non-APFS volumes, if the
// destination already exists, or if the source and destination
// are on different devices. In all these cases `fcopyfile`
// should succeed.
Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
_ => return Err(err),
},
}
}
// Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
// We ensure that `FreeOnDrop` never contains a null pointer so it is
// always safe to call `copyfile_state_free`
let state = unsafe {
let state = copyfile_state_alloc();
if state.is_null() {
return Err(crate::io::Error::last_os_error());
}
FreeOnDrop(state)
};
let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
let mut bytes_copied: libc::off_t = 0;
cvt(unsafe {
copyfile_state_get(
state.0,
COPYFILE_STATE_COPIED,
&mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
)
})?;
Ok(bytes_copied as u64)
}
#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
pub fn chroot(dir: &Path) -> io::Result<()> {
let dir = cstr(dir)?;
cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
Ok(())
} | |
mod.rs | //! Implementation of Falcon code and data memory in SRAM.
use byteorder::{ByteOrder, LittleEndian};
pub use tlb::*;
mod tlb;
/// The size of a physical memory page in Falcon code space.
pub const PAGE_SIZE: usize = 0x100;
/// Representation of the Falcon memory space.
///
/// It consists of separate memory spaces for data and code,
/// where data is stored in a flat piece of memory and code
/// in virtual memory pages, translated by a hidden TLB.
pub struct Memory {
/// Representation of the Falcon data space.
///
/// This is a linear piece of memory with byte-oriented addressing,
/// used for variables and stack memory. It can be addressed in 8-bit,
/// 16-bit and 32-bit quantities where unaligned memory access leads
/// to data corruption.
pub data: Vec<u8>,
/// Representation of the Falcon code space.
///
/// Code segment uses primitive paging in 0x100 byte pages.
/// Address translation is done in hidden TLB memory, with one entry
/// for each physical page.
pub code: Vec<u8>,
/// Representation of the hidden Falcon TLB.
///
/// The TLB is used for address translation via an array of entries,
/// each representing a physical page index.
pub tlb: Tlb,
} | pub fn new() -> Self {
// TODO: Compute these values through UC_CAPS MMIO.
Memory {
data: vec![0; 0x4000],
code: vec![0; PAGE_SIZE * 0x80],
tlb: Tlb::new(),
}
}
/// Reads a byte from a given address in Falcon data space.
pub fn read_data_byte(&self, address: u32) -> u8 {
self.data[address as usize]
}
/// Reads a halfword from a given address in Falcon data space.
pub fn read_data_halfword(&self, mut address: u32) -> u16 {
// Enforce aligned memory access.
address &= !1;
LittleEndian::read_u16(&self.data[address as usize..])
}
/// Reads a word from a given address in Falcon data space.
pub fn read_data_word(&self, mut address: u32) -> u32 {
// Enforce aligned memory access.
address &= !3;
LittleEndian::read_u32(&self.data[address as usize..])
}
/// Reads a word from a given physical address in code space.
pub fn read_code_addr(&self, address: u16) -> u32 {
LittleEndian::read_u32(&self.code[address as usize..])
}
/// Writes a byte to a given address in Falcon data space.
pub fn write_data_byte(&mut self, address: u32, value: u8) {
self.data[address as usize] = value;
}
/// Writes a halfword to a given address in Falcon data space.
pub fn write_data_halfword(&mut self, mut address: u32, mut value: u16) {
// If the address is unaligned, fuck up the written value.
if (address & 1) != 0 {
value = (value & 0xFF) << (address as u16 & 1) * 8;
}
// Enforce aligned memory access.
address &= !1;
LittleEndian::write_u16(&mut self.data[address as usize..], value);
}
/// Writes a word to a given address in Falcon data space.
pub fn write_data_word(&mut self, mut address: u32, mut value: u32) {
// If the address is unaligned, fuck up the written value.
if (address & 1) != 0 {
value = (value & 0xFF) << (address & 3) * 8;
} else if (address & 2) != 0 {
value = (value & 0xFFFF) << (address & 3) * 8;
}
// Enforce aligned memory access.
address &= !3;
LittleEndian::write_u32(&mut self.data[address as usize..], value);
}
/// Writes a word to a given physical address in code space.
pub fn write_code_addr(&mut self, address: u16, value: u32) {
LittleEndian::write_u32(&mut self.code[address as usize..], value);
}
} |
impl Memory {
/// Creates a new instance of the memory, initialized to all zeroes by
/// default. |
withRouter.tsx | import React from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import qs from 'querystring';
const withRouter =
<P extends unknown>(WrapComponent: React.ComponentType<P>) =>
(props: P): JSX.Element => {
const params = useParams();
const location = useLocation();
const navigate = useNavigate();
const query = location.search ? qs.parse(location.search.substr(1)) : {};
const historyPush = (
pushProps: { pathname: string; state: Record<string, any> } | string,
state?: Record<string, any>
) => {
if (!pushProps) {
return;
}
if (typeof pushProps === 'object') {
navigate(pushProps?.pathname, { state: pushProps?.state });
return;
}
if (typeof pushProps === 'string') { | }
};
return (
<WrapComponent
{...props}
match={{ params }}
location={{ ...location, query }}
history={{
push: historyPush,
goBack: () => navigate(-1),
goForward: () => navigate(1),
go: (num: number) => navigate(num),
}}
/>
);
};
export default withRouter; | navigate(pushProps, state); |
neon.rs | //! ARMv7 NEON intrinsics
use core_arch::simd_llvm::*;
#[cfg(test)]
use stdsimd_test::assert_instr;
types! {
/// ARM-specific 64-bit wide vector of eight packed `i8`.
pub struct int8x8_t(i8, i8, i8, i8, i8, i8, i8, i8);
/// ARM-specific 64-bit wide vector of eight packed `u8`.
pub struct uint8x8_t(u8, u8, u8, u8, u8, u8, u8, u8);
/// ARM-specific 64-bit wide polynomial vector of eight packed `u8`.
pub struct poly8x8_t(u8, u8, u8, u8, u8, u8, u8, u8);
/// ARM-specific 64-bit wide vector of four packed `i16`.
pub struct int16x4_t(i16, i16, i16, i16);
/// ARM-specific 64-bit wide vector of four packed `u16`.
pub struct uint16x4_t(u16, u16, u16, u16);
// FIXME: ARM-specific 64-bit wide vector of four packed `f16`.
// pub struct float16x4_t(f16, f16, f16, f16);
/// ARM-specific 64-bit wide vector of four packed `u16`.
pub struct poly16x4_t(u16, u16, u16, u16);
/// ARM-specific 64-bit wide vector of two packed `i32`.
pub struct int32x2_t(i32, i32);
/// ARM-specific 64-bit wide vector of two packed `u32`.
pub struct uint32x2_t(u32, u32);
/// ARM-specific 64-bit wide vector of two packed `f32`.
pub struct float32x2_t(f32, f32);
/// ARM-specific 64-bit wide vector of one packed `i64`.
pub struct int64x1_t(i64);
/// ARM-specific 64-bit wide vector of one packed `u64`.
pub struct uint64x1_t(u64);
/// ARM-specific 128-bit wide vector of sixteen packed `i8`.
pub struct int8x16_t(
i8, i8 ,i8, i8, i8, i8 ,i8, i8,
i8, i8 ,i8, i8, i8, i8 ,i8, i8,
);
/// ARM-specific 128-bit wide vector of sixteen packed `u8`.
pub struct uint8x16_t(
u8, u8 ,u8, u8, u8, u8 ,u8, u8,
u8, u8 ,u8, u8, u8, u8 ,u8, u8,
);
/// ARM-specific 128-bit wide vector of sixteen packed `u8`.
pub struct poly8x16_t(
u8, u8, u8, u8, u8, u8, u8, u8,
u8, u8, u8, u8, u8, u8, u8, u8
);
/// ARM-specific 128-bit wide vector of eight packed `i16`.
pub struct int16x8_t(i16, i16, i16, i16, i16, i16, i16, i16);
/// ARM-specific 128-bit wide vector of eight packed `u16`.
pub struct uint16x8_t(u16, u16, u16, u16, u16, u16, u16, u16);
// FIXME: ARM-specific 128-bit wide vector of eight packed `f16`.
// pub struct float16x8_t(f16, f16, f16, f16, f16, f16, f16);
/// ARM-specific 128-bit wide vector of eight packed `u16`.
pub struct poly16x8_t(u16, u16, u16, u16, u16, u16, u16, u16);
/// ARM-specific 128-bit wide vector of four packed `i32`.
pub struct int32x4_t(i32, i32, i32, i32);
/// ARM-specific 128-bit wide vector of four packed `u32`.
pub struct uint32x4_t(u32, u32, u32, u32);
/// ARM-specific 128-bit wide vector of four packed `f32`.
pub struct float32x4_t(f32, f32, f32, f32);
/// ARM-specific 128-bit wide vector of two packed `i64`.
pub struct int64x2_t(i64, i64);
/// ARM-specific 128-bit wide vector of two packed `u64`.
pub struct uint64x2_t(u64, u64);
}
/// ARM-specific type containing two `int8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct int8x8x2_t(pub int8x8_t, pub int8x8_t);
/// ARM-specific type containing three `int8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct int8x8x3_t(pub int8x8_t, pub int8x8_t, pub int8x8_t);
/// ARM-specific type containing four `int8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct int8x8x4_t(pub int8x8_t, pub int8x8_t, pub int8x8_t, pub int8x8_t);
/// ARM-specific type containing two `uint8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct uint8x8x2_t(pub uint8x8_t, pub uint8x8_t);
/// ARM-specific type containing three `uint8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct uint8x8x3_t(pub uint8x8_t, pub uint8x8_t, pub uint8x8_t);
/// ARM-specific type containing four `uint8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct uint8x8x4_t(pub uint8x8_t, pub uint8x8_t, pub uint8x8_t, pub uint8x8_t);
/// ARM-specific type containing two `poly8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct poly8x8x2_t(pub poly8x8_t, pub poly8x8_t);
/// ARM-specific type containing three `poly8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct poly8x8x3_t(pub poly8x8_t, pub poly8x8_t, pub poly8x8_t);
/// ARM-specific type containing four `poly8x8_t` vectors.
#[derive(Copy, Clone)]
pub struct poly8x8x4_t(pub poly8x8_t, pub poly8x8_t, pub poly8x8_t, pub poly8x8_t);
#[allow(improper_ctypes)]
extern "C" {
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.frsqrte.v2f32")]
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vrsqrte.v2f32")]
fn frsqrte_v2f32(a: float32x2_t) -> float32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmins.v8i8")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.sminp.v8i8")]
fn vpmins_v8i8(a: int8x8_t, b: int8x8_t) -> int8x8_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmins.v4i16")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.sminp.v4i16")]
fn vpmins_v4i16(a: int16x4_t, b: int16x4_t) -> int16x4_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmins.v2i32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.sminp.v2i32")]
fn vpmins_v2i32(a: int32x2_t, b: int32x2_t) -> int32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpminu.v8i8")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.uminp.v8i8")]
fn vpminu_v8i8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpminu.v4i16")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.uminp.v4i16")]
fn vpminu_v4i16(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpminu.v2i32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.uminp.v2i32")]
fn vpminu_v2i32(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmins.v2f32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.fminp.v2f32")]
fn vpminf_v2f32(a: float32x2_t, b: float32x2_t) -> float32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxs.v8i8")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.smaxp.v8i8")]
fn vpmaxs_v8i8(a: int8x8_t, b: int8x8_t) -> int8x8_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxs.v4i16")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.smaxp.v4i16")]
fn vpmaxs_v4i16(a: int16x4_t, b: int16x4_t) -> int16x4_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxs.v2i32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.smaxp.v2i32")]
fn vpmaxs_v2i32(a: int32x2_t, b: int32x2_t) -> int32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxu.v8i8")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.umaxp.v8i8")]
fn vpmaxu_v8i8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxu.v4i16")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.umaxp.v4i16")]
fn vpmaxu_v4i16(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxu.v2i32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.umaxp.v2i32")]
fn vpmaxu_v2i32(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t;
#[cfg_attr(target_arch = "arm", link_name = "llvm.arm.neon.vpmaxs.v2f32")]
#[cfg_attr(target_arch = "aarch64", link_name = "llvm.aarch64.neon.fmaxp.v2f32")]
fn vpmaxf_v2f32(a: float32x2_t, b: float32x2_t) -> float32x2_t;
}
#[cfg(target_arch = "arm")]
#[allow(improper_ctypes)]
extern "C" {
#[link_name = "llvm.arm.neon.vtbl1"]
fn vtbl1(a: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl2"]
fn vtbl2(a: int8x8_t, b: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl3"]
fn vtbl3(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbl4"]
fn vtbl4(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t, d: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx1"]
fn vtbx1(a: int8x8_t, b: int8x8_t, b: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx2"]
fn vtbx2(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx3"]
fn vtbx3(a: int8x8_t, b: int8x8_t, b: int8x8_t, c: int8x8_t, d: int8x8_t) -> int8x8_t;
#[link_name = "llvm.arm.neon.vtbx4"]
fn vtbx4(
a: int8x8_t,
b: int8x8_t,
b: int8x8_t,
c: int8x8_t,
d: int8x8_t,
e: int8x8_t,
) -> int8x8_t;
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_s8(a: int8x8_t, b: int8x8_t) -> int8x8_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_s8(a: int8x16_t, b: int8x16_t) -> int8x16_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_s16(a: int16x4_t, b: int16x4_t) -> int16x4_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_s16(a: int16x8_t, b: int16x8_t) -> int16x8_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_s32(a: int32x2_t, b: int32x2_t) -> int32x2_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_s32(a: int32x4_t, b: int32x4_t) -> int32x4_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_s64(a: int64x2_t, b: int64x2_t) -> int64x2_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_u8(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_u16(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_u16(a: uint16x8_t, b: uint16x8_t) -> uint16x8_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vadd_u32(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_u32(a: uint32x4_t, b: uint32x4_t) -> uint32x4_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(add))]
pub unsafe fn vaddq_u64(a: uint64x2_t, b: uint64x2_t) -> uint64x2_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(fadd))]
pub unsafe fn vadd_f32(a: float32x2_t, b: float32x2_t) -> float32x2_t {
simd_add(a, b)
}
/// Vector add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vadd))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(fadd))]
pub unsafe fn vaddq_f32(a: float32x4_t, b: float32x4_t) -> float32x4_t {
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(saddl))]
pub unsafe fn vaddl_s8(a: int8x8_t, b: int8x8_t) -> int16x8_t {
let a: int16x8_t = simd_cast(a);
let b: int16x8_t = simd_cast(b);
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(saddl))]
pub unsafe fn vaddl_s16(a: int16x4_t, b: int16x4_t) -> int32x4_t {
let a: int32x4_t = simd_cast(a);
let b: int32x4_t = simd_cast(b);
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(saddl))]
pub unsafe fn vaddl_s32(a: int32x2_t, b: int32x2_t) -> int64x2_t {
let a: int64x2_t = simd_cast(a);
let b: int64x2_t = simd_cast(b);
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uaddl))]
pub unsafe fn vaddl_u8(a: uint8x8_t, b: uint8x8_t) -> uint16x8_t {
let a: uint16x8_t = simd_cast(a);
let b: uint16x8_t = simd_cast(b);
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uaddl))]
pub unsafe fn vaddl_u16(a: uint16x4_t, b: uint16x4_t) -> uint32x4_t {
let a: uint32x4_t = simd_cast(a);
let b: uint32x4_t = simd_cast(b);
simd_add(a, b)
}
/// Vector long add.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vaddl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uaddl))]
pub unsafe fn vaddl_u32(a: uint32x2_t, b: uint32x2_t) -> uint64x2_t {
let a: uint64x2_t = simd_cast(a);
let b: uint64x2_t = simd_cast(b);
simd_add(a, b)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_s16(a: int16x8_t) -> int8x8_t {
simd_cast(a)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_s32(a: int32x4_t) -> int16x4_t {
simd_cast(a)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_s64(a: int64x2_t) -> int32x2_t {
simd_cast(a)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_u16(a: uint16x8_t) -> uint8x8_t {
simd_cast(a)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_u32(a: uint32x4_t) -> uint16x4_t {
simd_cast(a)
}
/// Vector narrow integer.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovn))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(xtn))]
pub unsafe fn vmovn_u64(a: uint64x2_t) -> uint32x2_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sxtl))]
pub unsafe fn vmovl_s8(a: int8x8_t) -> int16x8_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sxtl))]
pub unsafe fn vmovl_s16(a: int16x4_t) -> int32x4_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sxtl))]
pub unsafe fn vmovl_s32(a: int32x2_t) -> int64x2_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uxtl))]
pub unsafe fn vmovl_u8(a: uint8x8_t) -> uint16x8_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uxtl))]
pub unsafe fn vmovl_u16(a: uint16x4_t) -> uint32x4_t {
simd_cast(a)
}
/// Vector long move.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vmovl))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uxtl))]
pub unsafe fn vmovl_u32(a: uint32x2_t) -> uint64x2_t {
simd_cast(a)
}
/// Reciprocal square-root estimate.
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(frsqrte))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vrsqrte))]
pub unsafe fn vrsqrte_f32(a: float32x2_t) -> float32x2_t {
frsqrte_v2f32(a)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sminp))]
pub unsafe fn vpmin_s8(a: int8x8_t, b: int8x8_t) -> int8x8_t {
vpmins_v8i8(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sminp))]
pub unsafe fn vpmin_s16(a: int16x4_t, b: int16x4_t) -> int16x4_t {
vpmins_v4i16(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(sminp))]
pub unsafe fn vpmin_s32(a: int32x2_t, b: int32x2_t) -> int32x2_t {
vpmins_v2i32(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uminp))]
pub unsafe fn vpmin_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
vpminu_v8i8(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uminp))]
pub unsafe fn vpmin_u16(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t {
vpminu_v4i16(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(uminp))]
pub unsafe fn vpmin_u32(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t {
vpminu_v2i32(a, b)
}
/// Folding minimum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmin))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(fminp))]
pub unsafe fn vpmin_f32(a: float32x2_t, b: float32x2_t) -> float32x2_t {
vpminf_v2f32(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(smaxp))]
pub unsafe fn vpmax_s8(a: int8x8_t, b: int8x8_t) -> int8x8_t {
vpmaxs_v8i8(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(smaxp))]
pub unsafe fn vpmax_s16(a: int16x4_t, b: int16x4_t) -> int16x4_t {
vpmaxs_v4i16(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(smaxp))]
pub unsafe fn vpmax_s32(a: int32x2_t, b: int32x2_t) -> int32x2_t {
vpmaxs_v2i32(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(umaxp))]
pub unsafe fn vpmax_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
vpmaxu_v8i8(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(umaxp))]
pub unsafe fn vpmax_u16(a: uint16x4_t, b: uint16x4_t) -> uint16x4_t {
vpmaxu_v4i16(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(umaxp))]
pub unsafe fn vpmax_u32(a: uint32x2_t, b: uint32x2_t) -> uint32x2_t {
vpmaxu_v2i32(a, b)
}
/// Folding maximum of adjacent pairs
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(target_arch = "arm", target_feature(enable = "v7"))]
#[cfg_attr(all(test, target_arch = "arm"), assert_instr(vpmax))]
#[cfg_attr(all(test, target_arch = "aarch64"), assert_instr(fmaxp))]
pub unsafe fn vpmax_f32(a: float32x2_t, b: float32x2_t) -> float32x2_t {
vpmaxf_v2f32(a, b)
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_s8(a: int8x8_t, b: int8x8_t) -> int8x8_t {
vtbl1(a, b)
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_u8(a: uint8x8_t, b: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbl1(::mem::transmute(a), ::mem::transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl1_p8(a: poly8x8_t, b: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbl1(::mem::transmute(a), ::mem::transmute(b)))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_s8(a: int8x8x2_t, b: int8x8_t) -> int8x8_t {
vtbl2(a.0, a.1, b)
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_u8(a: uint8x8x2_t, b: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbl2(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl2_p8(a: poly8x8x2_t, b: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbl2(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_s8(a: int8x8x3_t, b: int8x8_t) -> int8x8_t {
vtbl3(a.0, a.1, a.2, b)
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_u8(a: uint8x8x3_t, b: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbl3(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(a.2),
::mem::transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl3_p8(a: poly8x8x3_t, b: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbl3(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(a.2),
::mem::transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_s8(a: int8x8x4_t, b: int8x8_t) -> int8x8_t {
vtbl4(a.0, a.1, a.2, a.3, b)
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_u8(a: uint8x8x4_t, b: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbl4(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(a.2),
::mem::transmute(a.3),
::mem::transmute(b),
))
}
/// Table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbl))]
pub unsafe fn vtbl4_p8(a: poly8x8x4_t, b: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbl4(
::mem::transmute(a.0),
::mem::transmute(a.1),
::mem::transmute(a.2),
::mem::transmute(a.3),
::mem::transmute(b),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_s8(a: int8x8_t, b: int8x8_t, c: int8x8_t) -> int8x8_t {
vtbx1(a, b, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_u8(a: uint8x8_t, b: uint8x8_t, c: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbx1(
::mem::transmute(a),
::mem::transmute(b),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx1_p8(a: poly8x8_t, b: poly8x8_t, c: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbx1(
::mem::transmute(a),
::mem::transmute(b),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_s8(a: int8x8_t, b: int8x8x2_t, c: int8x8_t) -> int8x8_t {
vtbx2(a, b.0, b.1, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_u8(a: uint8x8_t, b: uint8x8x2_t, c: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbx2(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx2_p8(a: poly8x8_t, b: poly8x8x2_t, c: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbx2(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_s8(a: int8x8_t, b: int8x8x3_t, c: int8x8_t) -> int8x8_t |
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_u8(a: uint8x8_t, b: uint8x8x3_t, c: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbx3(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(b.2),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx3_p8(a: poly8x8_t, b: poly8x8x3_t, c: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbx3(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(b.2),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_s8(a: int8x8_t, b: int8x8x4_t, c: int8x8_t) -> int8x8_t {
vtbx4(a, b.0, b.1, b.2, b.3, c)
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_u8(a: uint8x8_t, b: uint8x8x4_t, c: uint8x8_t) -> uint8x8_t {
::mem::transmute(vtbx4(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(b.2),
::mem::transmute(b.3),
::mem::transmute(c),
))
}
/// Extended table look-up
#[inline]
#[cfg(target_arch = "arm")]
#[cfg(target_endian = "little")]
#[target_feature(enable = "neon,v7")]
#[cfg_attr(test, assert_instr(vtbx))]
pub unsafe fn vtbx4_p8(a: poly8x8_t, b: poly8x8x4_t, c: uint8x8_t) -> poly8x8_t {
::mem::transmute(vtbx4(
::mem::transmute(a),
::mem::transmute(b.0),
::mem::transmute(b.1),
::mem::transmute(b.2),
::mem::transmute(b.3),
::mem::transmute(c),
))
}
#[cfg(test)]
mod tests {
use core_arch::arm::*;
use core_arch::simd::*;
use std::mem;
use stdsimd_test::simd_test;
#[simd_test(enable = "neon")]
unsafe fn test_vadd_s8() {
let a = i8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = i8x8::new(8, 7, 6, 5, 4, 3, 2, 1);
let e = i8x8::new(9, 9, 9, 9, 9, 9, 9, 9);
let r: i8x8 = ::mem::transmute(vadd_s8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_s8() {
let a = i8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
let b = i8x16::new(8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1);
let e = i8x16::new(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9);
let r: i8x16 = ::mem::transmute(vaddq_s8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_s16() {
let a = i16x4::new(1, 2, 3, 4);
let b = i16x4::new(8, 7, 6, 5);
let e = i16x4::new(9, 9, 9, 9);
let r: i16x4 = ::mem::transmute(vadd_s16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_s16() {
let a = i16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = i16x8::new(8, 7, 6, 5, 4, 3, 2, 1);
let e = i16x8::new(9, 9, 9, 9, 9, 9, 9, 9);
let r: i16x8 = ::mem::transmute(vaddq_s16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_s32() {
let a = i32x2::new(1, 2);
let b = i32x2::new(8, 7);
let e = i32x2::new(9, 9);
let r: i32x2 = ::mem::transmute(vadd_s32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_s32() {
let a = i32x4::new(1, 2, 3, 4);
let b = i32x4::new(8, 7, 6, 5);
let e = i32x4::new(9, 9, 9, 9);
let r: i32x4 = ::mem::transmute(vaddq_s32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_u8() {
let a = u8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = u8x8::new(8, 7, 6, 5, 4, 3, 2, 1);
let e = u8x8::new(9, 9, 9, 9, 9, 9, 9, 9);
let r: u8x8 = ::mem::transmute(vadd_u8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_u8() {
let a = u8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
let b = u8x16::new(8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1);
let e = u8x16::new(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9);
let r: u8x16 = ::mem::transmute(vaddq_u8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_u16() {
let a = u16x4::new(1, 2, 3, 4);
let b = u16x4::new(8, 7, 6, 5);
let e = u16x4::new(9, 9, 9, 9);
let r: u16x4 = ::mem::transmute(vadd_u16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_u16() {
let a = u16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = u16x8::new(8, 7, 6, 5, 4, 3, 2, 1);
let e = u16x8::new(9, 9, 9, 9, 9, 9, 9, 9);
let r: u16x8 = ::mem::transmute(vaddq_u16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_u32() {
let a = u32x2::new(1, 2);
let b = u32x2::new(8, 7);
let e = u32x2::new(9, 9);
let r: u32x2 = ::mem::transmute(vadd_u32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_u32() {
let a = u32x4::new(1, 2, 3, 4);
let b = u32x4::new(8, 7, 6, 5);
let e = u32x4::new(9, 9, 9, 9);
let r: u32x4 = ::mem::transmute(vaddq_u32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vadd_f32() {
let a = f32x2::new(1., 2.);
let b = f32x2::new(8., 7.);
let e = f32x2::new(9., 9.);
let r: f32x2 = ::mem::transmute(vadd_f32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddq_f32() {
let a = f32x4::new(1., 2., 3., 4.);
let b = f32x4::new(8., 7., 6., 5.);
let e = f32x4::new(9., 9., 9., 9.);
let r: f32x4 = ::mem::transmute(vaddq_f32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_s8() {
let v = ::std::i8::MAX;
let a = i8x8::new(v, v, v, v, v, v, v, v);
let v = 2 * (v as i16);
let e = i16x8::new(v, v, v, v, v, v, v, v);
let r: i16x8 = ::mem::transmute(vaddl_s8(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_s16() {
let v = ::std::i16::MAX;
let a = i16x4::new(v, v, v, v);
let v = 2 * (v as i32);
let e = i32x4::new(v, v, v, v);
let r: i32x4 = ::mem::transmute(vaddl_s16(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_s32() {
let v = ::std::i32::MAX;
let a = i32x2::new(v, v);
let v = 2 * (v as i64);
let e = i64x2::new(v, v);
let r: i64x2 = ::mem::transmute(vaddl_s32(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_u8() {
let v = ::std::u8::MAX;
let a = u8x8::new(v, v, v, v, v, v, v, v);
let v = 2 * (v as u16);
let e = u16x8::new(v, v, v, v, v, v, v, v);
let r: u16x8 = ::mem::transmute(vaddl_u8(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_u16() {
let v = ::std::u16::MAX;
let a = u16x4::new(v, v, v, v);
let v = 2 * (v as u32);
let e = u32x4::new(v, v, v, v);
let r: u32x4 = ::mem::transmute(vaddl_u16(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddl_u32() {
let v = ::std::u32::MAX;
let a = u32x2::new(v, v);
let v = 2 * (v as u64);
let e = u64x2::new(v, v);
let r: u64x2 = ::mem::transmute(vaddl_u32(::mem::transmute(a), ::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_s16() {
let a = i16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let e = i8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let r: i8x8 = ::mem::transmute(vmovn_s16(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_s32() {
let a = i32x4::new(1, 2, 3, 4);
let e = i16x4::new(1, 2, 3, 4);
let r: i16x4 = ::mem::transmute(vmovn_s32(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_s64() {
let a = i64x2::new(1, 2);
let e = i32x2::new(1, 2);
let r: i32x2 = ::mem::transmute(vmovn_s64(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_u16() {
let a = u16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let e = u8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let r: u8x8 = ::mem::transmute(vmovn_u16(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_u32() {
let a = u32x4::new(1, 2, 3, 4);
let e = u16x4::new(1, 2, 3, 4);
let r: u16x4 = ::mem::transmute(vmovn_u32(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovn_u64() {
let a = u64x2::new(1, 2);
let e = u32x2::new(1, 2);
let r: u32x2 = ::mem::transmute(vmovn_u64(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_s8() {
let e = i16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let a = i8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let r: i16x8 = ::mem::transmute(vmovl_s8(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_s16() {
let e = i32x4::new(1, 2, 3, 4);
let a = i16x4::new(1, 2, 3, 4);
let r: i32x4 = ::mem::transmute(vmovl_s16(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_s32() {
let e = i64x2::new(1, 2);
let a = i32x2::new(1, 2);
let r: i64x2 = ::mem::transmute(vmovl_s32(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_u8() {
let e = u16x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let a = u8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let r: u16x8 = ::mem::transmute(vmovl_u8(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_u16() {
let e = u32x4::new(1, 2, 3, 4);
let a = u16x4::new(1, 2, 3, 4);
let r: u32x4 = ::mem::transmute(vmovl_u16(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vmovl_u32() {
let e = u64x2::new(1, 2);
let a = u32x2::new(1, 2);
let r: u64x2 = ::mem::transmute(vmovl_u32(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vrsqrt_f32() {
let a = f32x2::new(1.0, 2.0);
let e = f32x2::new(0.9980469, 0.7050781);
let r: f32x2 = ::mem::transmute(vrsqrte_f32(::mem::transmute(a)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_s8() {
let a = i8x8::new(1, -2, 3, -4, 5, 6, 7, 8);
let b = i8x8::new(0, 3, 2, 5, 4, 7, 6, 9);
let e = i8x8::new(-2, -4, 5, 7, 0, 2, 4, 6);
let r: i8x8 = ::mem::transmute(vpmin_s8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_s16() {
let a = i16x4::new(1, 2, 3, -4);
let b = i16x4::new(0, 3, 2, 5);
let e = i16x4::new(1, -4, 0, 2);
let r: i16x4 = ::mem::transmute(vpmin_s16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_s32() {
let a = i32x2::new(1, -2);
let b = i32x2::new(0, 3);
let e = i32x2::new(-2, 0);
let r: i32x2 = ::mem::transmute(vpmin_s32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_u8() {
let a = u8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = u8x8::new(0, 3, 2, 5, 4, 7, 6, 9);
let e = u8x8::new(1, 3, 5, 7, 0, 2, 4, 6);
let r: u8x8 = ::mem::transmute(vpmin_u8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_u16() {
let a = u16x4::new(1, 2, 3, 4);
let b = u16x4::new(0, 3, 2, 5);
let e = u16x4::new(1, 3, 0, 2);
let r: u16x4 = ::mem::transmute(vpmin_u16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_u32() {
let a = u32x2::new(1, 2);
let b = u32x2::new(0, 3);
let e = u32x2::new(1, 0);
let r: u32x2 = ::mem::transmute(vpmin_u32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmin_f32() {
let a = f32x2::new(1., -2.);
let b = f32x2::new(0., 3.);
let e = f32x2::new(-2., 0.);
let r: f32x2 = ::mem::transmute(vpmin_f32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_s8() {
let a = i8x8::new(1, -2, 3, -4, 5, 6, 7, 8);
let b = i8x8::new(0, 3, 2, 5, 4, 7, 6, 9);
let e = i8x8::new(1, 3, 6, 8, 3, 5, 7, 9);
let r: i8x8 = ::mem::transmute(vpmax_s8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_s16() {
let a = i16x4::new(1, 2, 3, -4);
let b = i16x4::new(0, 3, 2, 5);
let e = i16x4::new(2, 3, 3, 5);
let r: i16x4 = ::mem::transmute(vpmax_s16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_s32() {
let a = i32x2::new(1, -2);
let b = i32x2::new(0, 3);
let e = i32x2::new(1, 3);
let r: i32x2 = ::mem::transmute(vpmax_s32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_u8() {
let a = u8x8::new(1, 2, 3, 4, 5, 6, 7, 8);
let b = u8x8::new(0, 3, 2, 5, 4, 7, 6, 9);
let e = u8x8::new(2, 4, 6, 8, 3, 5, 7, 9);
let r: u8x8 = ::mem::transmute(vpmax_u8(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_u16() {
let a = u16x4::new(1, 2, 3, 4);
let b = u16x4::new(0, 3, 2, 5);
let e = u16x4::new(2, 4, 3, 5);
let r: u16x4 = ::mem::transmute(vpmax_u16(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_u32() {
let a = u32x2::new(1, 2);
let b = u32x2::new(0, 3);
let e = u32x2::new(2, 3);
let r: u32x2 = ::mem::transmute(vpmax_u32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vpmax_f32() {
let a = f32x2::new(1., -2.);
let b = f32x2::new(0., 3.);
let e = f32x2::new(1., 3.);
let r: f32x2 = ::mem::transmute(vpmax_f32(::mem::transmute(a), ::mem::transmute(b)));
assert_eq!(r, e);
}
}
#[cfg(test)]
#[cfg(target_endian = "little")]
#[path = "table_lookup_tests.rs"]
mod table_lookup_tests;
| {
vtbx3(a, b.0, b.1, b.2, c)
} |
event_publisher.py | import json
import pika
import ssl
import logging
from os import environ
from datetime import datetime
from .config import Config
logging.basicConfig()
config = Config.get_instance()
ssl.match_hostname = lambda cert, hostname: True
PAYMENT_EXCHANGE = "payment_events"
class Publisher(object):
def __init__(self, reply_exchange=None, reply_topic=None):
self.create_connection()
self.reply_exchange=reply_exchange
self.reply_topic=reply_topic
def create_connection(self):
context = ssl.create_default_context(
cafile=config.CA_CERTS)
context.load_cert_chain(config.CERTFILE,
config.KEYFILE)
ssl_options = pika.SSLOptions(context, config.RABBITMQ_IP)
credentials = pika.PlainCredentials(
config.RABBITMQ_USER, config.RABBITMQ_PASS)
parameters = pika.ConnectionParameters(
ssl_options=ssl_options,
host=config.RABBITMQ_IP, port=config.RABBITMQ_PORT, virtual_host='/', credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# Default exchanges declared
channel.exchange_declare(exchange=PAYMENT_EXCHANGE, exchange_type='topic')
channel.exchange_declare(exchange="LogExchange", exchange_type='topic')
self.connection = connection
self.channel = channel
def close(self):
self.connection.close()
def send_reserve_response(self, order_id, response, pub_exchange, pub_topic):
body = {"publisherCode": "PAYMENT", "orderId": order_id, "response": response}
self.channel.exchange_declare(exchange=pub_exchange, exchange_type='topic')
self.channel.basic_publish(exchange=pub_exchange,
routing_key=pub_topic,
body=json.dumps(body))
self.send_log("Payment Reserve Response: " + str(body))
print(" [x] Sent " + str(body) + "to " + pub_topic + " topic")
def send_order_cancelled_response(self, order_id, response, pub_exchange, pub_topic):
body = {"publisherCode": "PAYMENT", "orderId": order_id, "response": response}
self.channel.exchange_declare(exchange=pub_exchange, exchange_type='topic')
self.channel.basic_publish(exchange=pub_exchange,
routing_key=pub_topic,
body=json.dumps(body))
self.send_log("Payment Order Cancelled Response: " + str(body))
print(" [x] Sent " + str(body) + "to " + pub_topic + " topic")
def send_log(self, msg):
| log_msg = dict()
log_msg["timestamp"] = str(datetime.now())
log_msg["level"] = "INFO"
log_msg["service_name"] = "Delivery"
log_msg["msg"] = msg
self.channel.basic_publish(exchange="LogExchange",
routing_key="INFO",
body=json.dumps(log_msg)) |
|
app.ts | /*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
"use strict";
import { INewAsset } from "./types/asset";
import { Gateway, Wallets } from "fabric-network";
import FabricCAServices from "fabric-ca-client";
import {
buildCAClient,
enrollAdmin,
registerAndEnrollUser,
} from "./util/CAUtil.js";
import { buildCCPOrg1, buildWallet } from "./util/AppUtil.js";
import path from "path";
// import eventHandlers from "./eventHandlers/eventHandlers";
const channelName = "mychannel";
const chaincodeName = "basic";
const mspOrg1 = "Org1MSP";
const walletPath = path.join(__dirname, "wallet");
const org1UserId = "3";
function | (inputString: string) {
return JSON.stringify(JSON.parse(inputString), null, 2);
}
class LedgerClient {
ccp: any;
caClient: any;
wallet: any;
gateway: any;
network: any;
contract: any;
initInstance = async () => {
try {
this.ccp = buildCCPOrg1();
this.caClient = buildCAClient(
FabricCAServices,
this.ccp,
"ca.org1.example.com"
);
this.wallet = await buildWallet(Wallets, walletPath);
await enrollAdmin(this.caClient, this.wallet, mspOrg1);
await registerAndEnrollUser(
this.caClient,
this.wallet,
mspOrg1,
org1UserId,
"org1.department1"
);
this.gateway = new Gateway();
await this.gateway.connect(this.ccp, {
wallet: this.wallet,
identity: org1UserId,
discovery: { enabled: true, asLocalhost: true },
});
this.network = await this.gateway.getNetwork(channelName);
this.contract = this.network.getContract(chaincodeName);
// await this.contract.addContractListener(eventHandlers);
} catch (error) {
console.error(`******** FAILED to run the application: ${error}`);
}
};
initLedger = async () => {
try {
await this.contract.submitTransaction("InitLedger");
} catch (err) {
console.log(err);
}
console.log("*** Result: committed");
};
queryAll = async () => {
console.log(
"\n--> Evaluate Transaction: GetAllAssets, function returns all the current assets on the ledger"
);
let result = await this.contract.evaluateTransaction("GetAllAssets");
return JSON.parse(result);
};
queryAsset = async (ID: string) => {
const result = await this.contract.evaluateTransaction("ReadAsset", ID);
return JSON.parse(result);
};
queryAssetHistory = async (ID: string) => {
const result = await this.contract.evaluateTransaction(
"GetHistoryOfAsset",
ID
);
return JSON.parse(result);
};
createAsset = async (newAsset: INewAsset) => {
const newAssetString = JSON.stringify(newAsset);
try {
await this.contract.submitTransaction("CreateAsset", newAssetString);
return true;
} catch (err) {
return false;
}
};
transferAsset = async (
TXID: string,
IDs: string,
newOwner: string,
oldOwner: string
) => {
try {
await this.contract.submitTransaction(
"TransferAsset",
TXID,
IDs,
newOwner,
oldOwner
);
return true;
} catch (err) {
return false;
}
};
}
const instance = new LedgerClient();
export default instance;
| prettyJSONString |
AppendAnyValue.py | from typing import Any, List
from boa3.builtin import public
@public
def Main() -> List[Any]:
| a: List[Any] = [1, 2, 3]
a.append('4')
return a |
|
AbstractHandler.ts | import { RequestInit, Response } from 'node-fetch';
import { ClientCookie } from './ClientCookie';
import { ClientInfo } from './ClientInfo';
| export abstract class AbstractHandler {
abstract handle(
clientInfo: ClientInfo,
clientCookie: ClientCookie,
response: Response,
resource: string,
init: RequestInit
): Promise<Response>;
} | |
ditrit.py | #!/usr/bin/python2
#
# ditrit.py
# Copyright 2006 Ryan Barrett <[email protected]>
# http://snarfed.org/ditrit
#
# See docstring for usage details.
#
# Ideas:
# url open in browser, whois, alexa/netcraft
# email address compose in mail client, add to address book
# email mailing list go to archive page, subscription page
# address map it
# zip code map it
# phone number call, add to phonebook
# person name google, email, call
# ups/fedex/etc package number track
# rpm install
# date ?
# filename find rpm/deb that provides it
# stock symbol quote, charts
# movie name showtimes, reviews, imdb
# song name lyrics, itunes
# musician discography
# actor imdb
# project name show fm, sf
# program name (w/parens) show man page
# aim user name add to buddy list, im
# jabber username add to buddy list, im
# icq uin add to buddy list, im
# local filename open
# tv show tv listings
# author, book title isbn.nu, amazon
# citation citeseer
# misspelling spell correct
#
# google:
# - bug number
# - changelist number
# - username
# - filename
#
#
#
#
# matching
# ==
# 1. regexp
# 2. local file existence test
# 3. local domain tests (in email phonebook, in buddy list, in phonebook, in
# emacs/eclipse/idea tags file?)
# 3. web queries (check for results).
# - do in parallel?
# - use beautiful soup
#
#
# acting
# ==
# provide dotfile with regexp, command line
#
# offer multiple actions and choose one?
#
# web service to provide updated configs?
#
# remember actions for exact strings? regexps?
#
# platform independence! x selection vs windows clipboard (mac os x?),
# wxpython for ui
#
#
# longer-term
# ==
# learn from keywords in top google search results ("film" or "movie"? "song"
# or "artist"? "download"? "program"? etc.) to determine type.
#
# store mappings on server, use web service to determine action.
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
USAGE = """A programmable application launcher. Reads input from stdin or
the X primary selection (aka clipboard), finds a template in the config file
that matches it, and runs the corresponding command. The input may be wholly
or partially inserted into the command string.
Options:
-c <file> Read config from file, not ~/.ditritrc
-t Don't actually run the command, just print it
-X Read input from the X primary selection (ie clipboard)
-v Display verbose debugging messages
-V Print version information and exit
-h, --help Display this message
Web: http://snarfed.org/ditrit"""
import getopt
import os
import re
import string
import sys
# constants
VERSION = 'ditrit 0.1'
# default command-line options
CONFIG_FILE = None # defaults to ~/.ditritrc in parse_args
TEST = False
VERBOSE = False
X_SELECTION = False
def main():
templates = read_config()
if X_SELECTION:
input = get_x_selection()
else:
input = sys.stdin.read()
input = input.strip()
log('Read input "%s"' % input)
for (template, cmd) in templates.items():
match = re.search(template, input)
if match:
log('Matched template "%s" with command "%s"' % (template, cmd))
cmd = match.expand(cmd).split()
cmd_string = ' '.join(cmd)
log('Expanded command to "%s"' % cmd_string)
if TEST:
print cmd_string
else:
os.spawnvp(os.P_NOWAIT, cmd[0], cmd)
sys.exit(0)
log('No matching template found.', error=True)
sys.exit(1)
def read_config():
""" Reads the config file from CONFIG_FILE. Returns a dictionary mapping
template regexps to commands. Doesn't use ConfigParser because it splits
at the first : or = it finds, and I need to allow those in templates.
"""
log('Using config file %s' % CONFIG_FILE)
templates = {}
for (line, linenum) in zip(file(CONFIG_FILE), xrange(1, sys.maxint)):
line = line.strip()
if not line or line[0] == '#':
continue
# this regexp matches a line in the ditrit config file. e.g.:
#
# Xtemplate regexpX command # optional comment
#
# where the delimiter X is any character (usually a double quote).
#
# \1 is the delimiter, \2 is the template, \3 is the command.
#
# this question marks means to match non-greedy, so that it stops at
# the first delimiter it sees.
# v
match = re.match(r'^(.)(.+?)\1 ([^#]+)#?', line)
if not match:
log('Error in %s, line %d:\n%s' % (CONFIG_FILE, linenum, line),
error=True)
sys.exit(1)
templates[match.group(2)] = match.group(3).strip()
log('Read config:\n' + str(templates))
return templates
def get_x_selection():
import Xlib.display # from the python X library, http://python-xlib.sf.net/
import Xlib.X
import Xlib.Xatom
display = Xlib.display.Display()
xsel_data_atom = display.intern_atom("XSEL_DATA")
screen = display.screen()
w = screen.root.create_window(0, 0, 2, 2, 0, screen.root_depth)
w.convert_selection(Xlib.Xatom.PRIMARY, # selection
Xlib.Xatom.STRING, # target
xsel_data_atom, # property
Xlib.X.CurrentTime) # time
while True:
e = display.next_event()
if e.type == Xlib.X.SelectionNotify:
break
assert e.property == xsel_data_atom
assert e.target == Xlib.Xatom.STRING
reply = w.get_full_property(xsel_data_atom, Xlib.X.AnyPropertyType)
return reply.value
def parse_args(args):
""" Parse command-line args. See doc comment for details.
"""
global CONFIG_FILE, TEST, VERBOSE, X_SELECTION
try:
options, args = getopt.getopt(args, 'c:tXvVh', 'help')
except getopt.GetoptError:
type, value, traceback = sys.exc_info()
log(value.msg, error=True)
usage()
sys.exit(2)
for option, arg in options:
if option == '-c':
CONFIG_FILE = arg
elif option == '-t':
TEST = True
elif option == '-X':
X_SELECTION = True
elif option == '-v':
VERBOSE = True
elif option == '-V':
version()
sys.exit(0)
elif option in ('-h', '--help'):
usage()
sys.exit(0)
if args:
usage()
sys.exit(2) |
if not CONFIG_FILE:
CONFIG_FILE = os.path.join(os.getenv('HOME'), '.ditritrc')
return args
def log(message, error=False):
""" Overly simple logging facility. If anyone knows of a more fully
featured logging facility that *ships with Python*, please let me know!
"""
if error:
print >> sys.stderr, message
elif VERBOSE:
print message
def usage():
print USAGE
def version():
print VERSION
if __name__ == '__main__':
args = parse_args(sys.argv[1:])
main() | |
main.rs | fn main()
{
let input = include_str!("../input.txt").trim_end();
let mut cups_one = vec![0 ; input.len()+1];
let mut prev = 0;
for i in input.bytes().map(|b| (b - b'0') as u32)
{
cups_one[prev] = i;
prev = i as usize;
}
let mut cups_two = cups_one.clone();
cups_one[prev] = cups_one[0];
crab_cups(&mut cups_one, 100);
let mut current = cups_one[1];
while current != 1
{
print!("{}", current);
current = cups_one[current as usize];
}
println!();
cups_two[prev] = input.len() as u32 + 1;
cups_two.extend(input.len() as u32 + 2 ..= 1_000_000);
cups_two.push(cups_two[0]);
crab_cups(&mut cups_two, 10_000_000);
println!("{}", { let x = cups_two[1]; x as u64 * cups_two[x as usize] as u64 });
}
fn | (cups : &mut [u32], iterations : u32)
{
let mut current = cups[0] as usize;
let mut claw = Vec::with_capacity(3);
for _ in 0 .. iterations
{
let mut next = current;
for _ in 0 .. 3
{
next = cups[next] as usize;
claw.push(next);
}
let mut destination = current;
loop
{
destination = if destination == 1 { cups.len() - 1 } else { destination - 1 };
if !claw.contains(&destination) { break }
}
cups[current] = cups[claw[2]];
cups[claw[2]] = cups[destination];
cups[destination] = claw[0] as u32;
current = cups[current] as usize;
claw.clear();
}
cups[0] = current as u32;
}
| crab_cups |
create.go | package ufwhandler
import (
"bytes"
"fmt"
"log"
"net"
"os/exec"
"strconv"
"strings"
"github.com/docker/docker/api/types"
)
func checkIP(ip string) bool {
return net.ParseIP(ip) != nil
}
func checkCIDR(cidr string) bool |
func CreateUfwRule(ch <-chan *types.ContainerJSON, trackedContainers map[string]*TrackedContainer) {
for container := range ch {
containerName := strings.Replace(container.Name, "/", "", 1) // container name appears with prefix "/"
containerIP := container.NetworkSettings.IPAddress
containerID := container.ID[:12]
// If docker-compose, container IP is defined here
if containerIP == "" {
networkMode := container.HostConfig.NetworkMode.NetworkName()
if ip, ok := container.NetworkSettings.Networks[networkMode]; ok {
containerIP = ip.IPAddress
} else {
log.Println("ufw-docker-automated: Couldn't detect the container IP address.")
continue
}
}
trackedContainers[containerID] = &TrackedContainer{
Name: containerName,
IPAddress: containerIP,
Labels: container.Config.Labels,
}
c := trackedContainers[containerID]
// Handle inbound rules
for port, portMaps := range container.HostConfig.PortBindings {
// List is non empty if port is published
if len(portMaps) > 0 {
ufwRules := []UfwRule{}
if container.Config.Labels["UFW_ALLOW_FROM"] != "" {
ufwAllowFromLabelParsed := strings.Split(container.Config.Labels["UFW_ALLOW_FROM"], ";")
for _, allowFrom := range ufwAllowFromLabelParsed {
ip := strings.Split(allowFrom, "-")
// First element should be always valid IP Address or CIDR
if !checkIP(ip[0]) {
if !checkCIDR(ip[0]) {
log.Printf("ufw-docker-automated: Address %s is not valid!\n", ip[0])
continue
}
}
// Example: 172.10.5.0-LAN or 172.10.5.0-80
if len(ip) == 2 {
if _, err := strconv.Atoi(ip[1]); err == nil {
// case: 172.10.5.0-80
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: ip[1], Proto: port.Proto()})
} else {
// case: 172.10.5.0-LAN
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: port.Port(), Proto: port.Proto(), Comment: fmt.Sprintf(" %s", ip[1])})
}
// Example: 172.10.5.0-80-LAN
} else if len(ip) == 3 {
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: ip[1], Proto: port.Proto(), Comment: fmt.Sprintf(" %s", ip[2])})
} else {
// Example: 172.10.5.0
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: port.Port(), Proto: port.Proto()})
}
}
} else {
ufwRules = append(ufwRules, UfwRule{CIDR: "any", Port: port.Port(), Proto: port.Proto()})
}
for _, rule := range ufwRules {
cmd := exec.Command("sudo", "ufw", "route", "allow", "proto", rule.Proto, "from", rule.CIDR, "to", containerIP, "port", rule.Port, "comment", containerName+":"+containerID+rule.Comment)
log.Println("ufw-docker-automated: Adding rule:", cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
} else {
log.Println("ufw:", stdout.String())
}
}
c.UfwInboundRules = append(c.UfwInboundRules, ufwRules...)
// ufw route allow proto tcp from any to 172.17.0.2 port 80 comment "Comment"
// ufw route allow proto <tcp|udp> <source> to <container_ip> port <port> comment <comment>
// ufw route delete allow proto tcp from any to 172.17.0.2 port 80 comment "Comment"
// ufw route delete allow proto <tcp|udp> <source> to <container_ip> port <port> comment <comment>
}
}
// Handle outbound rules
if container.Config.Labels["UFW_DENY_OUT"] == "TRUE" {
if container.Config.Labels["UFW_ALLOW_TO"] != "" {
ufwRules := []UfwRule{}
ufwAllowToLabelParsed := strings.Split(container.Config.Labels["UFW_ALLOW_TO"], ";")
for _, allowTo := range ufwAllowToLabelParsed {
ip := strings.Split(allowTo, "-")
// First element should be always valid IP Address or CIDR
if !checkIP(ip[0]) {
if !checkCIDR(ip[0]) {
log.Printf("ufw-docker-automated: Address %s is not valid!\n", ip[0])
continue
}
}
// Example: 172.10.5.0-LAN or 172.10.5.0-80
if len(ip) == 2 {
if _, err := strconv.Atoi(ip[1]); err == nil {
// case: 172.10.5.0-80
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: ip[1]})
} else {
// case: 172.10.5.0-LAN
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Comment: fmt.Sprintf(" %s", ip[1])})
}
// Example: 172.10.5.0-80-LAN
} else if len(ip) == 3 {
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0], Port: ip[1], Comment: fmt.Sprintf(" %s", ip[2])})
} else {
// Example: 172.10.5.0
ufwRules = append(ufwRules, UfwRule{CIDR: ip[0]})
}
}
for _, rule := range ufwRules {
var cmd *exec.Cmd
if rule.Port == "" {
cmd = exec.Command("sudo", "ufw", "route", "allow", "from", containerIP, "to", rule.CIDR, "comment", containerName+":"+containerID+rule.Comment)
} else {
cmd = exec.Command("sudo", "ufw", "route", "allow", "from", containerIP, "to", rule.CIDR, "port", rule.Port, "comment", containerName+":"+containerID+rule.Comment)
}
log.Println("ufw-docker-automated: Adding rule:", cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
} else {
log.Println("ufw:", stdout.String())
}
}
c.UfwOutboundRules = append(c.UfwOutboundRules, ufwRules...)
}
// Handle deny all out
cmd := exec.Command("sudo", "ufw", "route", "deny", "from", containerIP, "to", "any", "comment", containerName+":"+containerID)
log.Println("ufw-docker-automated: Adding rule:", cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
} else {
log.Println("ufw:", stdout.String())
}
}
}
}
| {
_, _, err := net.ParseCIDR(cidr)
return err == nil
} |
handshake_server.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/subtle"
"crypto/x509"
"encoding/asn1"
"errors"
"io"
)
// serverHandshakeState contains details of a server handshake in progress.
// It's discarded once the handshake has completed.
type serverHandshakeState struct {
c *Conn
clientHello *clientHelloMsg
hello *serverHelloMsg
suite *cipherSuite
ellipticOk bool
ecdsaOk bool
sessionState *sessionState
finishedHash finishedHash
masterSecret []byte
certsFromClient [][]byte
cert *Certificate
}
// serverHandshake performs a TLS handshake as a server.
func (c *Conn) serverHandshake() error {
config := c.config
// If this is the first server handshake, we generate a random key to
// encrypt the tickets with.
config.serverInitOnce.Do(config.serverInit)
hs := serverHandshakeState{
c: c,
}
isResume, err := hs.readClientHello()
if err != nil {
return err
}
// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
if isResume {
// The client has included a session ticket and so we do an abbreviated handshake.
if err := hs.doResumeHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
if err := hs.sendFinished(); err != nil {
return err
}
if err := hs.readFinished(); err != nil {
return err
}
c.didResume = true
} else {
// The client didn't include a session ticket, or it wasn't
// valid so we do a full handshake.
if err := hs.doFullHandshake(); err != nil {
return err
}
if err := hs.establishKeys(); err != nil {
return err
}
if err := hs.readFinished(); err != nil |
if err := hs.sendSessionTicket(); err != nil {
return err
}
if err := hs.sendFinished(); err != nil {
return err
}
}
c.handshakeComplete = true
return nil
}
// readClientHello reads a ClientHello message from the client and decides
// whether we will perform session resumption.
func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
config := hs.c.config
c := hs.c
msg, err := c.readHandshake()
if err != nil {
return false, err
}
var ok bool
hs.clientHello, ok = msg.(*clientHelloMsg)
if !ok {
return false, c.sendAlert(alertUnexpectedMessage)
}
c.vers, ok = config.mutualVersion(hs.clientHello.vers)
if !ok {
return false, c.sendAlert(alertProtocolVersion)
}
c.haveVers = true
hs.finishedHash = newFinishedHash(c.vers)
hs.finishedHash.Write(hs.clientHello.marshal())
hs.hello = new(serverHelloMsg)
supportedCurve := false
Curves:
for _, curve := range hs.clientHello.supportedCurves {
switch curve {
case curveP256, curveP384, curveP521:
supportedCurve = true
break Curves
}
}
supportedPointFormat := false
for _, pointFormat := range hs.clientHello.supportedPoints {
if pointFormat == pointFormatUncompressed {
supportedPointFormat = true
break
}
}
hs.ellipticOk = supportedCurve && supportedPointFormat
foundCompression := false
// We only support null compression, so check that the client offered it.
for _, compression := range hs.clientHello.compressionMethods {
if compression == compressionNone {
foundCompression = true
break
}
}
if !foundCompression {
return false, c.sendAlert(alertHandshakeFailure)
}
hs.hello.vers = c.vers
t := uint32(config.time().Unix())
hs.hello.random = make([]byte, 32)
hs.hello.random[0] = byte(t >> 24)
hs.hello.random[1] = byte(t >> 16)
hs.hello.random[2] = byte(t >> 8)
hs.hello.random[3] = byte(t)
_, err = io.ReadFull(config.rand(), hs.hello.random[4:])
if err != nil {
return false, c.sendAlert(alertInternalError)
}
hs.hello.compressionMethod = compressionNone
if len(hs.clientHello.serverName) > 0 {
c.serverName = hs.clientHello.serverName
}
// Although sending an empty NPN extension is reasonable, Firefox has
// had a bug around this. Best to send nothing at all if
// config.NextProtos is empty. See
// https://code.google.com/p/go/issues/detail?id=5445.
if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 {
hs.hello.nextProtoNeg = true
hs.hello.nextProtos = config.NextProtos
}
if len(config.Certificates) == 0 {
return false, c.sendAlert(alertInternalError)
}
hs.cert = &config.Certificates[0]
if len(hs.clientHello.serverName) > 0 {
hs.cert = config.getCertificateForName(hs.clientHello.serverName)
}
_, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey)
if hs.checkForResumption() {
return true, nil
}
var preferenceList, supportedList []uint16
if c.config.PreferServerCipherSuites {
preferenceList = c.config.cipherSuites()
supportedList = hs.clientHello.cipherSuites
} else {
preferenceList = hs.clientHello.cipherSuites
supportedList = c.config.cipherSuites()
}
for _, id := range preferenceList {
if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil {
break
}
}
if hs.suite == nil {
return false, c.sendAlert(alertHandshakeFailure)
}
return false, nil
}
// checkForResumption returns true if we should perform resumption on this connection.
func (hs *serverHandshakeState) checkForResumption() bool {
c := hs.c
var ok bool
if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok {
return false
}
if hs.sessionState.vers > hs.clientHello.vers {
return false
}
if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers {
return false
}
cipherSuiteOk := false
// Check that the client is still offering the ciphersuite in the session.
for _, id := range hs.clientHello.cipherSuites {
if id == hs.sessionState.cipherSuite {
cipherSuiteOk = true
break
}
}
if !cipherSuiteOk {
return false
}
// Check that we also support the ciphersuite from the session.
hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk)
if hs.suite == nil {
return false
}
sessionHasClientCerts := len(hs.sessionState.certificates) != 0
needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
if needClientCerts && !sessionHasClientCerts {
return false
}
if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
return false
}
return true
}
func (hs *serverHandshakeState) doResumeHandshake() error {
c := hs.c
hs.hello.cipherSuite = hs.suite.id
// We echo the client's session ID in the ServerHello to let it know
// that we're doing a resumption.
hs.hello.sessionId = hs.clientHello.sessionId
hs.finishedHash.Write(hs.hello.marshal())
c.writeRecord(recordTypeHandshake, hs.hello.marshal())
if len(hs.sessionState.certificates) > 0 {
if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
return err
}
}
hs.masterSecret = hs.sessionState.masterSecret
return nil
}
func (hs *serverHandshakeState) doFullHandshake() error {
config := hs.c.config
c := hs.c
if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
hs.hello.ocspStapling = true
}
hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled
hs.hello.cipherSuite = hs.suite.id
hs.finishedHash.Write(hs.hello.marshal())
c.writeRecord(recordTypeHandshake, hs.hello.marshal())
certMsg := new(certificateMsg)
certMsg.certificates = hs.cert.Certificate
hs.finishedHash.Write(certMsg.marshal())
c.writeRecord(recordTypeHandshake, certMsg.marshal())
if hs.hello.ocspStapling {
certStatus := new(certificateStatusMsg)
certStatus.statusType = statusTypeOCSP
certStatus.response = hs.cert.OCSPStaple
hs.finishedHash.Write(certStatus.marshal())
c.writeRecord(recordTypeHandshake, certStatus.marshal())
}
keyAgreement := hs.suite.ka(c.vers)
skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello)
if err != nil {
c.sendAlert(alertHandshakeFailure)
return err
}
if skx != nil {
hs.finishedHash.Write(skx.marshal())
c.writeRecord(recordTypeHandshake, skx.marshal())
}
if config.ClientAuth >= RequestClientCert {
// Request a client certificate
certReq := new(certificateRequestMsg)
certReq.certificateTypes = []byte{
byte(certTypeRSASign),
byte(certTypeECDSASign),
}
if c.vers >= VersionTLS12 {
certReq.hasSignatureAndHash = true
certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms
}
// An empty list of certificateAuthorities signals to
// the client that it may send any certificate in response
// to our request. When we know the CAs we trust, then
// we can send them down, so that the client can choose
// an appropriate certificate to give to us.
if config.ClientCAs != nil {
certReq.certificateAuthorities = config.ClientCAs.Subjects()
}
hs.finishedHash.Write(certReq.marshal())
c.writeRecord(recordTypeHandshake, certReq.marshal())
}
helloDone := new(serverHelloDoneMsg)
hs.finishedHash.Write(helloDone.marshal())
c.writeRecord(recordTypeHandshake, helloDone.marshal())
var pub crypto.PublicKey // public key for client auth, if any
msg, err := c.readHandshake()
if err != nil {
return err
}
var ok bool
// If we requested a client certificate, then the client must send a
// certificate message, even if it's empty.
if config.ClientAuth >= RequestClientCert {
if certMsg, ok = msg.(*certificateMsg); !ok {
return c.sendAlert(alertHandshakeFailure)
}
hs.finishedHash.Write(certMsg.marshal())
if len(certMsg.certificates) == 0 {
// The client didn't actually send a certificate
switch config.ClientAuth {
case RequireAnyClientCert, RequireAndVerifyClientCert:
c.sendAlert(alertBadCertificate)
return errors.New("tls: client didn't provide a certificate")
}
}
pub, err = hs.processCertsFromClient(certMsg.certificates)
if err != nil {
return err
}
msg, err = c.readHandshake()
if err != nil {
return err
}
}
// Get client key exchange
ckx, ok := msg.(*clientKeyExchangeMsg)
if !ok {
return c.sendAlert(alertUnexpectedMessage)
}
hs.finishedHash.Write(ckx.marshal())
// If we received a client cert in response to our certificate request message,
// the client will send us a certificateVerifyMsg immediately after the
// clientKeyExchangeMsg. This message is a digest of all preceding
// handshake-layer messages that is signed using the private key corresponding
// to the client's certificate. This allows us to verify that the client is in
// possession of the private key of the certificate.
if len(c.peerCertificates) > 0 {
msg, err = c.readHandshake()
if err != nil {
return err
}
certVerify, ok := msg.(*certificateVerifyMsg)
if !ok {
return c.sendAlert(alertUnexpectedMessage)
}
switch key := pub.(type) {
case *ecdsa.PublicKey:
ecdsaSig := new(ecdsaSignature)
if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
break
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
err = errors.New("ECDSA signature contained zero or negative values")
break
}
digest, _, _ := hs.finishedHash.hashForClientCertificate(signatureECDSA)
if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
err = errors.New("ECDSA verification failure")
break
}
case *rsa.PublicKey:
digest, hashFunc, _ := hs.finishedHash.hashForClientCertificate(signatureRSA)
err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
}
if err != nil {
c.sendAlert(alertBadCertificate)
return errors.New("could not validate signature of connection nonces: " + err.Error())
}
hs.finishedHash.Write(certVerify.marshal())
}
preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers)
if err != nil {
c.sendAlert(alertHandshakeFailure)
return err
}
hs.masterSecret = masterFromPreMasterSecret(c.vers, preMasterSecret, hs.clientHello.random, hs.hello.random)
return nil
}
func (hs *serverHandshakeState) establishKeys() error {
c := hs.c
clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
keysFromMasterSecret(c.vers, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
var clientCipher, serverCipher interface{}
var clientHash, serverHash macFunction
if hs.suite.aead == nil {
clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
clientHash = hs.suite.mac(c.vers, clientMAC)
serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
serverHash = hs.suite.mac(c.vers, serverMAC)
} else {
clientCipher = hs.suite.aead(clientKey, clientIV)
serverCipher = hs.suite.aead(serverKey, serverIV)
}
c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
return nil
}
func (hs *serverHandshakeState) readFinished() error {
c := hs.c
c.readRecord(recordTypeChangeCipherSpec)
if err := c.error(); err != nil {
return err
}
if hs.hello.nextProtoNeg {
msg, err := c.readHandshake()
if err != nil {
return err
}
nextProto, ok := msg.(*nextProtoMsg)
if !ok {
return c.sendAlert(alertUnexpectedMessage)
}
hs.finishedHash.Write(nextProto.marshal())
c.clientProtocol = nextProto.proto
}
msg, err := c.readHandshake()
if err != nil {
return err
}
clientFinished, ok := msg.(*finishedMsg)
if !ok {
return c.sendAlert(alertUnexpectedMessage)
}
verify := hs.finishedHash.clientSum(hs.masterSecret)
if len(verify) != len(clientFinished.verifyData) ||
subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
return c.sendAlert(alertHandshakeFailure)
}
hs.finishedHash.Write(clientFinished.marshal())
return nil
}
func (hs *serverHandshakeState) sendSessionTicket() error {
if !hs.hello.ticketSupported {
return nil
}
c := hs.c
m := new(newSessionTicketMsg)
var err error
state := sessionState{
vers: c.vers,
cipherSuite: hs.suite.id,
masterSecret: hs.masterSecret,
certificates: hs.certsFromClient,
}
m.ticket, err = c.encryptTicket(&state)
if err != nil {
return err
}
hs.finishedHash.Write(m.marshal())
c.writeRecord(recordTypeHandshake, m.marshal())
return nil
}
func (hs *serverHandshakeState) sendFinished() error {
c := hs.c
c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
finished := new(finishedMsg)
finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
hs.finishedHash.Write(finished.marshal())
c.writeRecord(recordTypeHandshake, finished.marshal())
c.cipherSuite = hs.suite.id
return nil
}
// processCertsFromClient takes a chain of client certificates either from a
// Certificates message or from a sessionState and verifies them. It returns
// the public key of the leaf certificate.
func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
c := hs.c
hs.certsFromClient = certificates
certs := make([]*x509.Certificate, len(certificates))
var err error
for i, asn1Data := range certificates {
if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
}
}
if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
opts := x509.VerifyOptions{
Roots: c.config.ClientCAs,
CurrentTime: c.config.time(),
Intermediates: x509.NewCertPool(),
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
chains, err := certs[0].Verify(opts)
if err != nil {
c.sendAlert(alertBadCertificate)
return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
}
ok := false
for _, ku := range certs[0].ExtKeyUsage {
if ku == x509.ExtKeyUsageClientAuth {
ok = true
break
}
}
if !ok {
c.sendAlert(alertHandshakeFailure)
return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication")
}
c.verifiedChains = chains
}
if len(certs) > 0 {
var pub crypto.PublicKey
switch key := certs[0].PublicKey.(type) {
case *ecdsa.PublicKey, *rsa.PublicKey:
pub = key
default:
return nil, c.sendAlert(alertUnsupportedCertificate)
}
c.peerCertificates = certs
return pub, nil
}
return nil, nil
}
// tryCipherSuite returns a cipherSuite with the given id if that cipher suite
// is acceptable to use.
func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite {
for _, supported := range supportedCipherSuites {
if id == supported {
var candidate *cipherSuite
for _, s := range cipherSuites {
if s.id == id {
candidate = s
break
}
}
if candidate == nil {
continue
}
// Don't select a ciphersuite which we can't
// support for this client.
if (candidate.flags&suiteECDHE != 0) && !ellipticOk {
continue
}
if (candidate.flags&suiteECDSA != 0) != ecdsaOk {
continue
}
if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
continue
}
return candidate
}
}
return nil
}
| {
return err
} |
main.go | // Source: http://bit.ly/learning-go-00004package main
// Author: Vladimir Vivien
package main
// Sample Pointers:
var valPtr *float32
var countPtr *int
type person struct{name string, age int}
var prsn *person
var matrix *[1024]int
var row []*int64
func main() | {
//Each pointer type is unique:
var intPtr *int
var int32Ptr *int32
intPtr = int32Ptr
// $> cannot use int32Ptr (type *int32) as type *int in assignment
} |
|
utils.js | /**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* global console:false */
import AssertionError from 'assertion-error';
import { html_beautify as beautify } from 'js-beautify/js/lib/beautify-html';
import EmitterMixin from '../../src/emittermixin';
import CKEditorError from '../../src/ckeditorerror';
import areConnectedThroughProperties from '../../src/areconnectedthroughproperties';
/**
* Creates an instance inheriting from {@link module:utils/emittermixin~EmitterMixin} with one additional method `observe()`.
* It allows observing changes to attributes in objects being {@link module:utils/observablemixin~Observable observable}.
*
* The `observe()` method accepts:
*
* * `{String} observableName` – Identifier for the observable object. E.g. `"Editable"` when
* you observe one of editor's editables. This name will be displayed on the console.
* * `{utils.Observable observable} – The object to observe.
* * `{Array.<String>} filterNames` – Array of property names to be observed.
*
* Typical usage:
*
* const observer = utils.createObserver();
* observer.observe( 'Editable', editor.editables.current );
*
* // Stop listening (method from the EmitterMixin):
* observer.stopListening();
*
* @returns {Emitter} The observer.
*/
export function createObserver() {
const observer = Object.create( EmitterMixin, {
observe: {
value: function observe( observableName, observable, filterNames ) {
observer.listenTo( observable, 'change', ( evt, propertyName, value, oldValue ) => {
if ( !filterNames || filterNames.includes( propertyName ) ) {
console.log( `[Change in ${ observableName }] ${ propertyName } = '${ value }' (was '${ oldValue }')` );
}
} );
return observer;
}
}
} );
return observer;
}
/**
* Checks whether observable properties are properly bound to each other.
*
* Syntax given that observable `A` is bound to observables [`B`, `C`, ...]:
*
* assertBinding( A,
* { initial `A` attributes },
* [
* [ B, { new `B` attributes } ],
* [ C, { new `C` attributes } ],
* ...
* ],
* { `A` attributes after [`B`, 'C', ...] changed }
* );
*/
export function assertBinding( observable, stateBefore, data, stateAfter ) {
let key, boundObservable, attrs;
for ( key in stateBefore ) {
expect( observable[ key ] ).to.be.equal( stateBefore[ key ] );
}
// Change attributes of bound observables.
for ( [ boundObservable, attrs ] of data ) {
for ( key in attrs ) {
if ( !boundObservable.hasOwnProperty( key ) ) {
boundObservable.set( key, attrs[ key ] );
} else {
boundObservable[ key ] = attrs[ key ];
}
}
}
for ( key in stateAfter ) {
expect( observable[ key ] ).to.be.equal( stateAfter[ key ] );
}
}
/**
* An assertion util to test whether the given function throws error that has correct message,
* data and whether the context of the error and the `editorThatShouldBeFindableFromContext`
* have common props (So the watchdog will be able to find the correct editor instance and restart it).
*
* @param {Function} fn Tested function that should throw a `CKEditorError`.
* @param {RegExp|String} message Expected message of the error.
* @param {*} editorThatShouldBeFindableFromContext An editor instance that should be findable from the error context.
* @param {Object} [data] Error data.
*/
export function expectToThrowCKEditorError( fn, message, editorThatShouldBeFindableFromContext, data ) {
let err = null;
try {
fn();
} catch ( _err ) {
err = _err;
assertCKEditorError( err, message, editorThatShouldBeFindableFromContext, data );
}
expect( err ).to.not.equal( null, 'Function did not throw any error' );
}
/**
* An assertion util to test whether a given error has correct message, data and whether the context of the
* error and the `editorThatShouldBeFindableFromContext` have common props (So the watchdog will be able to
* find the correct editor instance and restart it).
*
* @param {module:utils/ckeditorerror~CKEditorError} err The tested error.
* @param {RegExp|String} message Expected message of the error.
* @param {*} [editorThatShouldBeFindableFromContext] An editor instance that should be findable from the error context.
* @param {Object} [data] Error data.
*/
export function assertCKEditorError( err, message, editorThatShouldBeFindableFromContext, data ) {
if ( typeof message === 'string' ) {
message = new RegExp( message );
}
expect( message ).to.be.a( 'regexp', 'Error message should be a string or a regexp.' );
expect( err ).to.be.instanceOf( CKEditorError );
expect( err.message ).to.match( message, 'Error message does not match the provided one.' );
// TODO: The `editorThatShouldBeFindableFromContext` is optional but should be required in the future.
if ( editorThatShouldBeFindableFromContext === null ) {
expect( err.context ).to.equal( null, 'Error context was expected to be `null`' );
} else if ( editorThatShouldBeFindableFromContext !== undefined ) {
expect( areConnectedThroughProperties( editorThatShouldBeFindableFromContext, err.context ) )
.to.equal( true, 'Editor cannot be find from the error context' );
}
if ( data ) {
expect( err.data ).to.deep.equal( data );
}
} | /**
* An assertion util test whether two given strings containing markup language are equal.
* Unlike `expect().to.equal()` form Chai assertion library, this util formats the markup before showing a diff.
*
* This util can be used to test HTML strings and string containing serialized model.
*
* // Will throw an error that is handled as assertion error by Chai.
* assertEqualMarkup(
* '<paragraph><$text foo="bar">baz</$text></paragraph>',
* '<paragraph><$text foo="bar">baaz</$text></paragraph>',
* );
*
* @param {String} actual An actual string.
* @param {String} expected An expected string.
* @param {String} [message="Expected two markup strings to be equal"] Optional error message.
*/
export function assertEqualMarkup( actual, expected, message = 'Expected markup strings to be equal' ) {
if ( actual != expected ) {
throw new AssertionError( message, {
actual: formatMarkup( actual ),
expected: formatMarkup( expected ),
showDiff: true
} );
}
}
// Renames the $text occurrences as it is not properly formatted by the beautifier - it is tread as a block.
const TEXT_TAG_PLACEHOLDER = 'span data-cke="true"';
const TEXT_TAG_PLACEHOLDER_REGEXP = new RegExp( TEXT_TAG_PLACEHOLDER, 'g' );
function formatMarkup( string ) {
const htmlSafeString = string.replace( /\$text/g, TEXT_TAG_PLACEHOLDER );
const beautifiedMarkup = beautify( htmlSafeString, {
indent_size: 2,
space_in_empty_paren: true
} );
return beautifiedMarkup.replace( TEXT_TAG_PLACEHOLDER_REGEXP, '$text' );
} | |
neptune.py | #!/usr/bin/env python3
#
# ISC License
#
# Copyright (C) 2021 DS-Homebrew
# Copyright (C) 2021-present lifehackerhansol
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
import discord
import aiohttp
import asyncio
import settings
from discord.ext import commands
from utils.utils import create_error_embed
from tortoise import Tortoise
cogs = [
'cogs.mod',
'cogs.roles',
'cogs.load',
'jishaku'
]
async def init():
await Tortoise.init(
db_url='sqlite://neptune.db',
modules={'models': ['utils.models']}
)
# Generate the schema
await Tortoise.generate_schemas()
class Neptune(commands.Bot):
def __init__(self, command_prefix, description):
intents = discord.Intents(guilds=True, members=True, bans=True, messages=True)
allowed_mentions = discord.AllowedMentions(everyone=False, roles=False)
activity = discord.Game(settings.STATUS)
status = discord.Status.online
super().__init__(
command_prefix=command_prefix,
description=description,
intents=intents,
allowed_mentions=allowed_mentions,
activity=activity,
status=status,
case_insensitive=True
)
self.session = aiohttp.ClientSession()
def load_cogs(self):
for cog in cogs:
try:
self.load_extension(cog)
print(f"Loaded cog {cog}")
except Exception as e:
exc = "{}: {}".format(type(e).__name__, e)
print("Failed to load cog {}\n{}".format(cog, exc))
async def close(self):
await Tortoise.close_connections()
await super().close()
await self.session.close()
async def is_owner(self, user: discord.User):
if settings.GUILD:
g = self.get_guild(settings.GUILD)
if g:
member = g.get_member(user.id)
if member and any(role.id in settings.staff_roles for role in member.roles):
|
return await super().is_owner(user)
async def on_ready(self):
print("Neptune ready.")
async def on_command_error(self, ctx: commands.Context, exc: commands.CommandInvokeError):
author: discord.Member = ctx.author
command: commands.Command = ctx.command or '<unknown cmd>'
exc = getattr(exc, 'original', exc)
channel = ctx.channel
if isinstance(exc, commands.CommandNotFound):
return
elif isinstance(exc, commands.ArgumentParsingError):
await ctx.send_help(ctx.command)
elif isinstance(exc, commands.NoPrivateMessage):
await ctx.send(f'`{command}` cannot be used in direct messages.')
elif isinstance(exc, commands.MissingPermissions):
await ctx.send(f"{author.mention} You don't have permission to use `{command}`.")
elif isinstance(exc, commands.CheckFailure):
await ctx.send(f'{author.mention} You cannot use `{command}`.')
elif isinstance(exc, commands.BadArgument):
await ctx.send(f'{author.mention} A bad argument was given: `{exc}`\n')
await ctx.send_help(ctx.command)
elif isinstance(exc, commands.BadUnionArgument):
await ctx.send(f'{author.mention} A bad argument was given: `{exc}`\n')
elif isinstance(exc, commands.BadLiteralArgument):
await ctx.send(f'{author.mention} A bad argument was given, expected one of {", ".join(exc.literals)}')
elif isinstance(exc, commands.MissingRequiredArgument):
await ctx.send(f'{author.mention} You are missing required argument {exc.param.name}.\n')
await ctx.send_help(ctx.command)
elif isinstance(exc, discord.NotFound):
await ctx.send("ID not found.")
elif isinstance(exc, discord.Forbidden):
await ctx.send(f"💢 I can't help you if you don't let me!\n`{exc.text}`.")
elif isinstance(exc, commands.CommandInvokeError):
await ctx.send(f'{author.mention} `{command}` raised an exception during usage')
embed = create_error_embed(ctx, exc)
await channel.send(embed=embed)
else:
await ctx.send(f'{author.mention} Unexpected exception occurred while using the command `{command}`')
embed = create_error_embed(ctx, exc)
await channel.send(embed=embed)
async def startup():
bot = Neptune(settings.PREFIX, description="Neptune, the 777 Air Cadets Discord bot")
bot.help_command = commands.DefaultHelpCommand()
print('Starting Neptune...')
bot.load_cogs()
await init()
await bot.start(settings.TOKEN)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(startup())
| return True |
userCtrl.js | angular.module('userCtrl', ['userService'])
.controller('userController', function(User){
var vm = this;
//set a processing variable to show loading things
vm.processing = true;
vm.deleteUser = function(id) {
vm.processing = true;
//accepts the user id as a parameter
User.delete(id)
.success(function(data){
//get all users to update the table and set up the api to return a list of users with the delete call
User.all()
.success(function(data){
vm.processing = false;
vm.users = data;
});
});
};
User.all()
.success(function(data){
//when all users come back remove the processing var
vm.processing = false;
//bind the users that come back to vm.users
vm.users = data; | })
.controller('userCreateController', function(User){
var vm = this;
//variable to hide/show elements of the view and differntiates between create or edit pages
vm.type = 'create';
//function to create a user
vm.saveUser = function() {
vm.processing = true;
//clear the messages
vm.message = '';
//use create function in the userService
User.create(vm.userData)
.success(function(data){
vm.processing = false;
//clear the form
vm.userData = {};
vm.message = data.message;
});
};
})
.controller('userEditController', function($routeParams, User){
var vm = this;
//var to hide/show elements of the view and differentiate between create or edit pg
vm.type = 'edit';
//get the user data for the user you want to edit/ use $routeParams to grab data from url
User.get($routeParams.user_id)
.success(function(data){
vm.userData = data;
});
//function to save the user
vm.saveUser = function() {
vm.processing = true;
vm.message = '';
//call the userService update function
User.update($routeParams.user_id, vm.userData)
.success(function(data){
vm.processing = false;
//clear the form
vm.userData = {};
//bind the message from our API to vm.message
vm.message = data.message;
});
};
}) | }); |
main.py | # coding: utf-8
# https://hskhsk.pythonanywhere.com
# Alan Davies [email protected]
import sys
import threading
import time
from flask import Flask, render_template
from pages.cidian import cidian_page
from pages.deprecated import frequency_order_word_link, frequency_order_char_link
from pages.flashcards import flashcards_download
from pages.mandarin_comp import mandarin_companion_page
from pages.vocab_analysis import vocab_analysis_page
from pages.sets import sets_page
from pages.vocab_diff import vocab_diff_page
from pages.radicals import radicals_page
from pages.homophones import homophones_page
from pages.search import search_page
from common.util import create_context, get_parameter
from init import init_resources
from common.hsk import hsk_words, hsk_chars, hsk_words_2010, hsk_chars_2010
from common.pinyin import fix_pinyin
from pages.vocab_list import list_page_words1000, list_page_chars1000, hsk_vocabulary_page
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
@app.route('/hsk', methods=['GET', 'POST'])
def handle_root():
start_time = time.time()
context = create_context(start_time)
return render_template("root.html", **context)
@app.route('/pinyinfix', methods=['GET', 'POST'])
def handle_pinyinfix():
start_time = time.time()
pinyin = get_parameter("pinyin", "")
if len(pinyin) > 100000:
context = create_context(
start_time,
error="Sorry, that text is too big; It will consume too much server CPU time to process. " \
"You can try reaching out to [email protected] or set this script up on your own dedicated server."
)
return render_template("error.html", **context)
fixed, fixed_count = fix_pinyin(pinyin)
context = create_context(
start_time,
pinyin=pinyin,
fixed=fixed,
fixed_count=fixed_count
)
return render_template("pinyinfix.html", **context)
@app.route('/homophones', methods=['GET', 'POST'])
def handle_homophones():
start_time = time.time()
num_chars = int(get_parameter("chars", "2"))
expand = get_parameter("expand", "no") == "yes"
match_tones = get_parameter("tones", "no") == "yes"
hsk_only = get_parameter("hsk", "no") == "yes"
init_resources()
return homophones_page(expand, hsk_only, match_tones, num_chars, start_time)
@app.route('/radicals', methods=['GET', 'POST'])
def handle_radicals():
start_time = time.time()
init_resources()
expand = get_parameter("expand")
hsk_level = int(get_parameter("hsk", 0)) # 1, 2, .. 6 but can be two levels e.g. 12, 14 etc.
return radicals_page(expand, hsk_level, start_time)
@app.route('/mandcomp', methods=['GET', 'POST'])
def handle_mandcomp():
start_time = time.time()
init_resources()
expand = get_parameter("expand")
return mandarin_companion_page(start_time, expand)
@app.route('/dict', methods=['GET', 'POST'])
def handle_dict():
return handle_cidian()
@app.route('/cidian', methods=['GET', 'POST'])
def handle_cidian():
start_time = time.time()
init_resources()
results = []
query = get_parameter("q")
expand = get_parameter("expand")
return cidian_page(expand, query, results, start_time)
@app.route('/search', methods=['GET', 'POST'])
def | ():
start_time = time.time()
init_resources()
return search_page(start_time)
@app.route('/flash', methods=['GET', 'POST'])
def handle_flashcards():
init_resources()
return flashcards_download()
@app.route('/hskwords', methods=['GET', 'POST'])
@app.route('/hskwords2012', methods=['GET', 'POST'])
@app.route('/hskwords2013', methods=['GET', 'POST'])
@app.route('/hskwords2014', methods=['GET', 'POST'])
@app.route('/hskwords2015', methods=['GET', 'POST'])
@app.route('/hskwords2016', methods=['GET', 'POST'])
@app.route('/hskwords2017', methods=['GET', 'POST'])
@app.route('/hskwords2018', methods=['GET', 'POST'])
@app.route('/hskwords2019', methods=['GET', 'POST'])
@app.route('/hskwords2020', methods=['GET', 'POST'])
def handle_hskwords():
init_resources()
extralink = ""
expand = get_parameter("expand")
return hsk_vocabulary_page(
"/hskwords",
"HSK Words for 2012-2020",
extralink,
"words",
"/hskchars",
"characters",
hsk_words,
frequency_order_word_link,
expand)
@app.route('/hskwords2010', methods=['GET', 'POST'])
@app.route('/hskwords2011', methods=['GET', 'POST'])
def handle_hskwords2010():
init_resources()
expand = get_parameter("expand")
return hsk_vocabulary_page(
"/hskwords2010",
"HSK Words for 2010 (outdated)",
' <a href="/hskwords">HSK Words for 2012-2020</a>',
"words",
"/hskchars2010",
"characters",
hsk_words_2010,
frequency_order_word_link,
expand)
@app.route('/hskchars', methods=['GET', 'POST'])
@app.route('/hskchars2012', methods=['GET', 'POST'])
@app.route('/hskchars2013', methods=['GET', 'POST'])
@app.route('/hskchars2014', methods=['GET', 'POST'])
@app.route('/hskchars2015', methods=['GET', 'POST'])
@app.route('/hskchars2016', methods=['GET', 'POST'])
@app.route('/hskchars2017', methods=['GET', 'POST'])
@app.route('/hskchars2018', methods=['GET', 'POST'])
@app.route('/hskchars2019', methods=['GET', 'POST'])
@app.route('/hskchars2020', methods=['GET', 'POST'])
def handle_hskchars():
init_resources()
extralink = ""
expand = get_parameter("expand")
return hsk_vocabulary_page(
"/hskchars",
"HSK Characters for 2012-2020",
extralink,
"characters",
"/hskwords",
"words",
hsk_chars,
frequency_order_char_link,
expand)
@app.route('/hskchars2010', methods=['GET', 'POST'])
@app.route('/hskchars2011', methods=['GET', 'POST'])
def handle_hskchars2010():
init_resources()
expand = get_parameter("expand")
return hsk_vocabulary_page(
'/hskchars2010',
"HSK Characters for 2010 (outdated)",
'<a href="/hskchars">HSK Characters 2012-2020</a>',
"characters",
"/hskwords2010",
"words",
hsk_chars_2010,
frequency_order_char_link,
expand)
@app.route('/words1000', methods=['GET', 'POST'])
def handle_words1000():
start_time = time.time()
init_resources()
expand = get_parameter("expand")
return list_page_words1000(expand, start_time)
@app.route('/chars1000', methods=['GET', 'POST'])
def handle_chars1000():
start_time = time.time()
init_resources()
expand = get_parameter("expand")
return list_page_chars1000(expand, start_time)
@app.route('/hskwords20102012', methods=['GET', 'POST'])
@app.route('/hskwords20102013', methods=['GET', 'POST'])
@app.route('/hskwords20102014', methods=['GET', 'POST'])
@app.route('/hskwords20102015', methods=['GET', 'POST'])
@app.route('/hskwords20102016', methods=['GET', 'POST'])
@app.route('/hskwords20102017', methods=['GET', 'POST'])
@app.route('/hskwords20102018', methods=['GET', 'POST'])
@app.route('/hskwords20102019', methods=['GET', 'POST'])
@app.route('/hskwords20102020', methods=['GET', 'POST'])
def handle_hskwords20102012():
return vocab_diff_page(
"/hskwords2010",
"/hskwords2020",
"/hskwords20102020",
"words",
"/hskchars20102020",
"characters",
hsk_words_2010,
hsk_words,
frequency_order_word_link)
@app.route('/hskchars20102012', methods=['GET', 'POST'])
@app.route('/hskchars20102013', methods=['GET', 'POST'])
@app.route('/hskchars20102014', methods=['GET', 'POST'])
@app.route('/hskchars20102015', methods=['GET', 'POST'])
@app.route('/hskchars20102016', methods=['GET', 'POST'])
@app.route('/hskchars20102017', methods=['GET', 'POST'])
@app.route('/hskchars20102018', methods=['GET', 'POST'])
@app.route('/hskchars20102019', methods=['GET', 'POST'])
@app.route('/hskchars20102020', methods=['GET', 'POST'])
def handle_hskchars20102012():
return vocab_diff_page(
"/hskchars2010",
"/hskchars2020",
"/hskchars20102020",
"characters",
"/hskwords20102020",
"words",
hsk_chars_2010,
hsk_chars,
frequency_order_char_link)
@app.route('/hanzi', methods=['GET', 'POST'])
def handle_hanzi():
start_time = time.time()
expand = get_parameter("expand")
return vocab_analysis_page(expand, start_time)
@app.route('/sets', methods=['GET', 'POST'])
def handle_sets():
start_time = time.time()
expand = get_parameter("expand")
output_one_per_line_checked = "checked" if get_parameter("outputformat") == "oneperline" else ""
output_comma_sep_checked = "checked" if get_parameter("outputformat") == "commasep" else ""
output_tab_sep_checked = "checked" if get_parameter("outputformat") == "tabsep" else ""
output_space_sep_checked = "checked" if get_parameter("outputformat") == "spacesep" else ""
if output_one_per_line_checked == "" and output_comma_sep_checked == "" and output_space_sep_checked == "":
output_one_per_line_checked = "checked"
one_per_line_checked_a = ""
block_checked_a = "checked" if get_parameter("formatA") == "block" else ""
comma_sep_checked_a = "checked" if get_parameter("formatA") == "commasep" else ""
if block_checked_a == "" and comma_sep_checked_a == "":
one_per_line_checked_a = "checked"
one_per_line_checked_b = ""
block_checked_b = "checked" if get_parameter("formatB") == "block" else ""
comma_sep_checked_b = "checked" if get_parameter("formatB") == "commasep" else ""
if block_checked_b == "" and comma_sep_checked_b == "":
one_per_line_checked_b = "checked"
hanzi_a = get_parameter("hanziA", "")
hanzi_b = get_parameter("hanziB", "")
if (block_checked_a and len(hanzi_a) > 10000) or (block_checked_b and len(hanzi_b) > 10000):
return "Sorry, that text is too big; It will consume too much server CPU time to process." \
"If you want to set up this script on a dedicated server you can find the source" \
"at https://github.com/glxxyz/hskhsk.com/tree/master/cidian"
return sets_page(block_checked_a, block_checked_b, comma_sep_checked_a, comma_sep_checked_b, expand, hanzi_a,
hanzi_b, one_per_line_checked_a, one_per_line_checked_b, output_comma_sep_checked,
output_one_per_line_checked, output_space_sep_checked, output_tab_sep_checked, start_time)
global_varnames = """
cedict_traditional
cedict_pinyintonemarks
cedict_pinyintonenum
toneless_pinyin
toned_pinyin
tonenum_pinyin
cedict_definition
english_words
cedict_word_set
variant_trad
variant_simp
radical_freq
radical_frequency_index
hsk_radical_level
cc_components
cc_composes
cc_radicals
cc_radicalof
cc_strokes
subtlex_word_set
word_freq
word_frequency_index
word_frequency_ordered
part_of_multichar_word
char_componentof
char_freq
char_frequency_index
char_frequency_ordered
mc_words""".split()
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
from common.dictionary import *
from common.frequency import *
from common.mandarin_comp_parse import *
@app.route('/profile', methods=['GET', 'POST'])
def handle_profile():
variables = [(get_size(eval(name)), name) for name in global_varnames]
variables.sort(reverse=True)
total_str = "Total: {}<br /><br />\n".format(sum(v[0] for v in variables))
return total_str + "<br />\n".join("{}: {}".format(v[1], v[0]) for v in variables)
threading.Thread(target=lambda: init_resources).start()
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
# Flask's development server will automatically serve static files in
# the "static" directory. See:
# http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
# App Engine itself will serve those files as configured in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [START gae_python37_render_template]
| handle_search |
signal.rs | // Copyright (c) Microsoft. All rights reserved.
// Adapted from the conduit proxy signal handling:
// https://github.com/runconduit/conduit/blob/master/proxy/src/signal.rs
use futures::Future;
use tokio_core::reactor::Handle;
type ShutdownSignal = Box<Future<Item = (), Error = ()> + Send>;
pub fn shutdown(handle: &Handle) -> ShutdownSignal {
imp::shutdown(handle)
}
#[cfg(unix)]
mod imp {
use std::fmt;
use futures::{future, Future, Stream};
use tokio_core::reactor::Handle;
use tokio_signal::unix::{Signal, SIGINT, SIGTERM};
use super::ShutdownSignal;
pub(super) fn shutdown(handle: &Handle) -> ShutdownSignal {
let signals = [SIGINT, SIGTERM].into_iter().map(|&sig| {
Signal::new(sig, handle)
.flatten_stream()
.into_future()
.map(move |_| {
info!(
target: "iotedged::signal",
"Received {}, starting shutdown",
DisplaySignal(sig),
);
})
});
let on_any_signal = future::select_all(signals)
.map(|_| ())
.map_err(|_| unreachable!("Signal never returns an error"));
Box::new(on_any_signal)
}
struct | (i32);
impl fmt::Display for DisplaySignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self.0 {
SIGINT => "SIGINT",
SIGTERM => "SIGTERM",
other => return write!(f, "signal {}", other),
};
f.write_str(s)
}
}
}
#[cfg(not(unix))]
mod imp {
use futures::{Future, Stream};
use tokio_core::reactor::Handle;
use tokio_signal;
use super::ShutdownSignal;
pub(super) fn shutdown(handle: &Handle) -> ShutdownSignal {
let on_ctrl_c = tokio_signal::ctrl_c(handle)
.flatten_stream()
.into_future()
.map(|_| {
info!(
target: "iotedged::signal",
"Received Ctrl+C, starting shutdown",
);
})
.map_err(|_| unreachable!("ctrl_c never returns errors"));
Box::new(on_ctrl_c)
}
}
| DisplaySignal |
status.go | // Copyright 2020 Fugue, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package project
// Code indicates the scheduling result for a Rule
type Code int
const (
| Error Code = iota
// Skipped indicates the Rule was skipped due to a conditional
Skipped
// ExecError indicates Rule execution was attempted but failed
ExecError
// MissingOutputError indicates a Rule output was not produced
MissingOutputError
// OK indicates that the Rule executed successfully
OK
// Cached indicates the Rule artifact was cached
Cached
) | // Error indicates the Rule could not be run |
launchEditor.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import {execSync, spawn, ChildProcess} from 'child_process';
// @ts-ignore @types not installed
import shellQuote from 'shell-quote';
import logger from './logger';
function isTerminalEditor(editor: string) {
switch (editor) {
case 'vim':
case 'emacs':
case 'nano':
return true;
default:
return false;
}
}
// Map from full process name to binary that starts the process
// We can't just re-use full process name, because it will spawn a new instance
// of the app every time
const COMMON_EDITORS: Record<string, string> = {
'/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
'/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
'/Applications/IntelliJ IDEA.app/Contents/MacOS/idea': 'idea',
'/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
'/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
'/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
'/Applications/WebStorm.app/Contents/MacOS/webstorm': 'webstorm',
};
// Transpiled version of: /^([a-zA-Z]+:)?[\p{L}0-9/.\-_\\]+$/u
// Non-transpiled version requires support for Unicode property regex. Allows
// alphanumeric characters, periods, dashes, slashes, and underscores, with an optional drive prefix
const WINDOWS_FILE_NAME_WHITELIST = /^([a-zA-Z]+:)?(?:[\x2D-9A-Z\\_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7B9\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDF00-\uDF1C\uDF27\uDF30-\uDF45]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF1A]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFF1]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])+$/;
function addWorkspaceToArgumentsIfExists(args: string[], workspace: string) {
if (workspace) {
args.unshift(workspace);
}
return args;
}
function getArgumentsForLineNumber(
editor: string,
fileName: string,
lineNumber: number,
workspace: any,
) {
switch (path.basename(editor)) {
case 'vim':
case 'mvim':
return [fileName, `+${lineNumber}`];
case 'atom':
case 'Atom':
case 'Atom Beta':
case 'subl':
case 'sublime':
case 'webstorm':
case 'wstorm':
case 'appcode':
case 'charm':
case 'idea':
return [`${fileName}:${lineNumber}`];
case 'joe':
case 'emacs':
case 'emacsclient':
return [`+${lineNumber}`, fileName];
case 'rmate':
case 'mate':
case 'mine':
return ['--line', lineNumber, fileName];
case 'code':
return addWorkspaceToArgumentsIfExists(
['-g', `${fileName}:${lineNumber}`],
workspace,
);
// For all others, drop the lineNumber until we have
// a mapping above, since providing the lineNumber incorrectly
// can result in errors or confusing behavior.
default:
return [fileName];
}
}
function guessEditor() {
// Explicit config always wins
if (process.env.REACT_EDITOR) {
return shellQuote.parse(process.env.REACT_EDITOR);
}
// Using `ps x` on OSX we can find out which editor is currently running.
// Potentially we could use similar technique for Windows and Linux
if (process.platform === 'darwin') {
try {
const output = execSync('ps x').toString();
const processNames = Object.keys(COMMON_EDITORS);
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (output.indexOf(processName) !== -1) { | } catch (error) {
// Ignore...
}
}
// Last resort, use old skool env vars
if (process.env.VISUAL) {
return [process.env.VISUAL];
}
if (process.env.EDITOR) {
return [process.env.EDITOR];
}
return [null];
}
function printInstructions(title: string) {
logger.info(
[
'',
chalk.bgBlue.white.bold(` ${title} `),
' When you see Red Box with stack trace, you can click any ',
' stack frame to jump to the source file. The packager will launch your ',
' editor of choice. It will first look at REACT_EDITOR environment ',
' variable, then at EDITOR. To set it up, you can add something like ',
' export REACT_EDITOR=atom to your ~/.bashrc or ~/.zshrc depending on ',
' which shell you use.',
'',
].join('\n'),
);
}
function transformToAbsolutePathIfNeeded(pathName: string) {
if (!path.isAbsolute(pathName)) {
return path.resolve(process.cwd(), pathName);
}
return pathName;
}
function findRootForFile(
projectRoots: ReadonlyArray<string>,
fileName: string,
) {
const absoluteFileName = transformToAbsolutePathIfNeeded(fileName);
return projectRoots.find(root => {
const absoluteRoot = transformToAbsolutePathIfNeeded(root);
return absoluteFileName.startsWith(absoluteRoot + path.sep);
});
}
let _childProcess: ChildProcess | null = null;
function launchEditor(
fileName: string,
lineNumber: number,
projectRoots: ReadonlyArray<string>,
) {
if (!fs.existsSync(fileName)) {
return;
}
// Sanitize lineNumber to prevent malicious use on win32
// via: https://github.com/nodejs/node/blob/c3bb4b1aa5e907d489619fb43d233c3336bfc03d/lib/child_process.js#L333
if (lineNumber && isNaN(lineNumber)) {
return;
}
let [editor, ...args] = guessEditor();
if (!editor) {
printInstructions('PRO TIP');
return;
}
const workspace = findRootForFile(projectRoots, fileName);
if (lineNumber) {
args = args.concat(
getArgumentsForLineNumber(editor, fileName, lineNumber, workspace),
);
} else {
args.push(fileName);
}
// cmd.exe on Windows is vulnerable to RCE attacks given a file name of the
// form "C:\Users\myusername\Downloads\& curl 172.21.93.52". Use a whitelist
// to validate user-provided file names. This doesn't cover the entire range
// of valid file names but should cover almost all of them in practice.
if (
process.platform === 'win32' &&
!WINDOWS_FILE_NAME_WHITELIST.test(fileName.trim())
) {
logger.error(`Could not open ${path.basename(fileName)} in the editor.`);
logger.info(
'When running on Windows, file names are checked against a whitelist ' +
'to protect against remote code execution attacks. File names may ' +
'consist only of alphanumeric characters (all languages), periods, ' +
'dashes, slashes, and underscores.',
);
return;
}
logger.info(
`Opening ${chalk.underline(fileName)} with ${chalk.bold(editor)}`,
);
if (_childProcess && isTerminalEditor(editor)) {
// There's an existing editor process already and it's attached
// to the terminal, so go kill it. Otherwise two separate editor
// instances attach to the stdin/stdout which gets confusing.
_childProcess.kill('SIGKILL');
}
if (process.platform === 'win32') {
// On Windows, launch the editor in a shell because spawn can only
// launch .exe files.
_childProcess = spawn('cmd.exe', ['/C', editor].concat(args), {
stdio: 'inherit',
});
} else {
_childProcess = spawn(editor, args, {stdio: 'inherit'});
}
_childProcess.on('exit', errorCode => {
_childProcess = null;
if (errorCode) {
logger.error('Your editor exited with an error!');
printInstructions('Keep these instructions in mind:');
}
});
_childProcess.on('error', error => {
logger.error(error.message);
printInstructions('How to fix:');
});
}
export default launchEditor; | return [COMMON_EDITORS[processName]];
}
} |
Error.go | // Baseline Application Error Type.
//
// Given an understading that we need error codes, human-readable messages, and
// logical stack trace, we can construct a simple error type to handle most of our
// application's errors.
package error
import (
"bytes"
"encoding/json"
"fmt"
)
// Error is the center of this package and is a concrete representation of our errors.
// it has many fields, any of which can be left unset.
//
// Implements ClientError interface and is the baseline error type for this application.
//
// Kind and Message fields provide communication to our application and end user
// roles. Op and Err fields allow us to chain errors together so that we can build
// the logical stack trace for our operator.
type Error struct {
// Machine-readable error code.
// Example: ENOTFOUND, EEXISTS.
Kind string
// HTTP status code.
Status int
// Error message.
// This could be human-readable, or a JSON response. Ex: { "detail": "Wrong password" }.
Message string
// Op is a logical operation. It denotes the operation being performed.
// Typically holds the name of the method or function reporting the error.
Op string
// Err is the original error (unmarshall errors, network errors...) which
// caused this error, set it to nil if there isn't any.
Err error
}
func (e *Error) ResponseBody() ([]byte, error) {
body, err := json.Marshal(e)
if err != nil {
return nil, fmt.Errorf("Error while parsing response body: %v", err)
}
return body, nil
}
func (e *Error) ResponseHeaders() (string, map[string]string) {
return e.Kind, map[string]string{
"Content-Type": "application/json; charset=utf-8",
"X-Content-Type-Options": "nosniff",
}
}
// Error method is used to return an error string suitable for operators.
// There's no definitive standard for how to format this message, but
// these are formatted here with these goals in mind:
//
// 1. Show the logical stack trace first. It provides context for the rest
// of the message. It also allows us to sort error lines to group them together.
// 2. Show Kind, Message at the end.
// 3. Print on a single line so it's easy to grep.
//
// NOTE(truescotian): This implementation assumes that Err cannot coexist with Kind
// or Message on any given error.
//
// Error returns the string representation of the error message.
func (e *Error) Error() string {
var buf bytes.Buffer
// Print the current operation in our stack, if any.
if e.Op != "" {
fmt.Fprintf(&buf, "%s: ", e.Op)
}
// If wrapping an error, print its Error() message.
// Otherwise print the error kind & message.
if e.Err != nil {
buf.WriteString(e.Err.Error())
} else {
if e.Kind != "" {
fmt.Fprintf(&buf, "<%s> ", e.Kind)
}
buf.WriteString(e.Message)
}
return buf.String()
}
// NewError returns an Error using the passed arguments.
func NewError(op string, status int, message string, kind string, err error) *Error {
return &Error{
Op: op,
Status: status,
Message: message,
Kind: kind,
Err: err,
}
}
// ErrorKind returns the kind of the root error if available.
// Otherwise returns EINTERNAL.
//
// This function allows for working with Error effectively,
// avoiding issues such as type asserting
// whenever we want to access Error.Kind. This and other
// issues are solved by the following:
//
// 1. Return no error kind for nil errors.
// 2. Search the chain of Error.Err until a defined Kind is found.
// 3. If no kind is defined then return an internal error kind (EINTERNAL).
func ErrorKind(err error) string |
// ErrorMessage is a utility function to extract error messages from error
// values.
//
// This is similar to ErrorKind except for the following rules:
//
// 1. Returns no error message for nil errors.
// 2. Searches the chain of Error.Err until a defined Message is found.
// 3. If no message is defined then return a generic error message.
//
// Returns the human-readable message of the error, if available.
// Otherwise returns a generic error message.
func ErrorMessage(err error) string {
if err == nil {
return ""
} else if e, ok := err.(*Error); ok && e.Message != "" {
return e.Message
} else if ok && e.Err != nil {
return ErrorMessage(e.Err)
}
return "An internal error has occurred. Please contact technical support."
}
// Is reports whether err is an *Error of the given Kind.
// If err is nil then Is returns false.
//
// Source: https://upspin.googlesource.com/upspin/+/033a63d02f07/errors/errors.go#484
func Is(kind string, err error) bool {
e, ok := err.(*Error)
if !ok {
return false
}
if e.Kind != OTHER {
return e.Kind == kind
}
if e.Err != nil {
return Is(kind, e.Err)
}
return false
}
| {
if err == nil {
return ""
} else if e, ok := err.(*Error); ok && e.Kind != "" {
return e.Kind
} else if ok && e.Err != nil {
return ErrorKind(e.Err)
}
return EINTERNAL
} |
main_test.go | // Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package domain_test
import (
"testing"
"github.com/pingcap/tidb/util/testbridge"
"go.uber.org/goleak"
)
func TestMain(m *testing.M) | {
testbridge.SetupForCommonTest()
opts := []goleak.Option{
goleak.IgnoreTopFunction("go.etcd.io/etcd/client/pkg/v3/logutil.(*MergeLogger).outputLoop"),
goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
}
goleak.VerifyTestMain(m, opts...)
} |
|
tests.rs | #[test]
fn test_aead_parsing() {
for test in wycheproof::aead::TestName::all() {
let _kat = wycheproof::aead::TestSet::load(test).unwrap();
}
}
#[test]
fn test_cipher_parsing() {
for test in wycheproof::cipher::TestName::all() {
let _kat = wycheproof::cipher::TestSet::load(test).unwrap();
}
}
#[test]
fn test_daead_parsing() {
for test in wycheproof::daead::TestName::all() {
let _kat = wycheproof::daead::TestSet::load(test).unwrap();
}
}
#[test]
fn test_dsa_parsing() {
for test in wycheproof::dsa::TestName::all() {
let _kat = wycheproof::dsa::TestSet::load(test).unwrap();
}
}
#[test]
fn test_ecdh_parsing() {
for test in wycheproof::ecdh::TestName::all() {
let _kat = wycheproof::ecdh::TestSet::load(test).unwrap();
}
}
#[test]
fn test_ecdsa_parsing() {
for test in wycheproof::ecdsa::TestName::all() {
let _kat = wycheproof::ecdsa::TestSet::load(test).unwrap();
}
}
#[test]
fn test_eddsa_parsing() {
for test in wycheproof::eddsa::TestName::all() {
let _kat = wycheproof::eddsa::TestSet::load(test).unwrap();
}
}
#[test]
fn test_hkdf_parsing() {
for test in wycheproof::hkdf::TestName::all() {
let _kat = wycheproof::hkdf::TestSet::load(test).unwrap();
}
}
#[test]
fn test_keywrap_parsing() {
for test in wycheproof::keywrap::TestName::all() {
let _kat = wycheproof::keywrap::TestSet::load(test).unwrap();
}
}
#[test]
fn test_mac_parsing() {
for test in wycheproof::mac::TestName::all() {
let _kat = wycheproof::mac::TestSet::load(test).unwrap();
}
}
#[test]
fn test_mac_with_iv_parsing() |
#[test]
fn test_primality_parsing() {
for test in wycheproof::primality::TestName::all() {
let _kat = wycheproof::primality::TestSet::load(test).unwrap();
}
}
#[test]
fn test_rsa_oaep_parsing() {
for test in wycheproof::rsa_oaep::TestName::all() {
let _kat = wycheproof::rsa_oaep::TestSet::load(test).unwrap();
}
}
#[test]
fn test_rsa_pkcs1_decrypt_parsing() {
for test in wycheproof::rsa_pkcs1_decrypt::TestName::all() {
let _kat = wycheproof::rsa_pkcs1_decrypt::TestSet::load(test).unwrap();
}
}
#[test]
fn test_rsa_pkcs1_sign_parsing() {
for test in wycheproof::rsa_pkcs1_sign::TestName::all() {
let _kat = wycheproof::rsa_pkcs1_sign::TestSet::load(test).unwrap();
}
}
#[test]
fn test_rsa_pkcs1_verify_parsing() {
for test in wycheproof::rsa_pkcs1_verify::TestName::all() {
let _kat = wycheproof::rsa_pkcs1_verify::TestSet::load(test).unwrap();
}
}
#[test]
fn test_rsa_pss_verify_parsing() {
for test in wycheproof::rsa_pss_verify::TestName::all() {
let _kat = wycheproof::rsa_pss_verify::TestSet::load(test).unwrap();
}
}
#[test]
fn test_xdh_parsing() {
for test in wycheproof::xdh::TestName::all() {
let _kat = wycheproof::xdh::TestSet::load(test).unwrap();
}
}
| {
for test in wycheproof::mac_with_iv::TestName::all() {
let _kat = wycheproof::mac_with_iv::TestSet::load(test).unwrap();
}
} |
pddl_reconfig_controller_launch.py | # Copyright 2019 Intelligent Robotics Lab
#
# 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 os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, SetEnvironmentVariable
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
import launch
import launch.actions
import launch.events
import launch_ros.actions
import launch_ros.events
import launch_ros.events.lifecycle
def | ():
# Get the launch directory
example_dir = get_package_share_directory('navigation_experiments_mc_pddl')
stdout_linebuf_envvar = SetEnvironmentVariable(
'RCUTILS_CONSOLE_STDOUT_LINE_BUFFERED', '1')
plansys2_cmd = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(
get_package_share_directory('plansys2_bringup'),
'launch',
'plansys2_bringup_launch_distributed.py')),
launch_arguments={'model_file': example_dir + '/pddl/patrol_w_recharge_reconfig.pddl'}.items()
)
# Specify the actions
move_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='move_action_node',
name='move_action_node',
output='screen',
parameters=[])
patrol_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='patrol_action_node',
name='patrol_action_node',
output='screen',
parameters=[])
charge_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='charge_action_node',
name='charge_action_node',
output='screen',
parameters=[])
ask_charge_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='ask_charge_action_node',
name='ask_charge_action_node',
output='screen',
parameters=[])
degraded_move_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='degraded_move_action_node',
name='degraded_move_action_node',
output='screen',
parameters=[])
reconfigure_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='reconfigure_action_node',
name='reconfigure_action_node',
output='screen',
parameters=[])
recover_nav_sensor_cmd = Node(
package='navigation_experiments_mc_pddl',
executable='recover_nav_sensor_node',
name='recover_nav_sensor_node',
output='screen',
parameters=[])
#pddl_controller_cmd = Node(
# package='navigation_experiments_mc_pddl',
# executable='patrolling_controller_node',
# name='patrolling_controller_node',
# output='screen',
# parameters=[])
# Create the launch description and populate
ld = LaunchDescription()
# Set environment variables
ld.add_action(stdout_linebuf_envvar)
# Declare the launch options
ld.add_action(plansys2_cmd)
ld.add_action(move_cmd)
ld.add_action(patrol_cmd)
ld.add_action(charge_cmd)
ld.add_action(ask_charge_cmd)
ld.add_action(degraded_move_cmd)
ld.add_action(reconfigure_cmd)
ld.add_action(recover_nav_sensor_cmd)
#ld.add_action(pddl_controller_cmd)
return ld
| generate_launch_description |
serde_json.rs | use crate::{
Clear, Collection, CollectionMut, CollectionRef, Get, GetKeyValue, GetMut, Keyed, KeyedRef,
Len, MapInsert, MapIter, MapIterMut, Remove,
};
use std::{borrow::Borrow, cmp::Ord, hash::Hash};
impl Collection for serde_json::Map<String, serde_json::Value> {
type Item = serde_json::Value;
}
impl CollectionRef for serde_json::Map<String, serde_json::Value> {
type ItemRef<'a> = &'a serde_json::Value;
crate::covariant_item_ref!();
}
impl CollectionMut for serde_json::Map<String, serde_json::Value> {
type ItemMut<'a> = &'a mut serde_json::Value;
crate::covariant_item_mut!();
}
impl Keyed for serde_json::Map<String, serde_json::Value> {
type Key = String;
}
impl KeyedRef for serde_json::Map<String, serde_json::Value> {
type KeyRef<'a> = &'a String;
crate::covariant_key_ref!();
}
impl Len for serde_json::Map<String, serde_json::Value> {
#[inline(always)]
fn len(&self) -> usize { |
#[inline(always)]
fn is_empty(&self) -> bool {
self.is_empty()
}
}
impl MapIter for serde_json::Map<String, serde_json::Value> {
type Iter<'a> = serde_json::map::Iter<'a>;
#[inline(always)]
fn iter(&self) -> Self::Iter<'_> {
self.iter()
}
}
impl MapIterMut for serde_json::Map<String, serde_json::Value> {
type IterMut<'a> = serde_json::map::IterMut<'a>;
#[inline(always)]
fn iter_mut(&mut self) -> Self::IterMut<'_> {
self.iter_mut()
}
}
impl<'a, Q: ?Sized> Get<&'a Q> for serde_json::Map<String, serde_json::Value>
where
String: Borrow<Q>,
Q: Ord + Hash,
{
#[inline(always)]
fn get(&self, q: &'a Q) -> Option<&serde_json::Value> {
self.get(q)
}
}
impl<'a, Q: ?Sized> GetMut<&'a Q> for serde_json::Map<String, serde_json::Value>
where
String: Borrow<Q>,
Q: Ord + Hash,
{
#[inline(always)]
fn get_mut(&mut self, q: &'a Q) -> Option<&mut serde_json::Value> {
self.get_mut(q)
}
}
impl<'a, Q: ?Sized> GetKeyValue<&'a Q> for serde_json::Map<String, serde_json::Value>
where
String: Borrow<Q>,
Q: Ord + Hash,
{
#[inline(always)]
#[deny(unconditional_recursion)]
fn get_key_value(&self, q: &'a Q) -> Option<(&String, &serde_json::Value)> {
self.get_key_value(q)
}
}
impl MapInsert<String> for serde_json::Map<String, serde_json::Value> {
type Output = Option<serde_json::Value>;
#[inline(always)]
fn insert(&mut self, key: String, value: serde_json::Value) -> Option<serde_json::Value> {
self.insert(key, value)
}
}
impl<'a, Q: ?Sized> Remove<&'a Q> for serde_json::Map<String, serde_json::Value>
where
String: Borrow<Q>,
Q: Ord + Hash,
{
#[inline(always)]
fn remove(&mut self, key: &'a Q) -> Option<serde_json::Value> {
self.remove(key)
}
}
impl Clear for serde_json::Map<String, serde_json::Value> {
#[inline(always)]
fn clear(&mut self) {
self.clear()
}
} | self.len()
} |
task-not-declared.rs | #![no_main]
#[mock::app]
const APP: () = {
#[init(spawn = [foo])]
fn | (_: init::Context) {}
};
| init |
main.py | import argparse
import os
from .vscode_extensions import *
from .extensions_json import *
from .vscode_cli import code_open
from .utils import extension_base_name, get_work_dir
| group = parser.add_mutually_exclusive_group()
group.add_argument("-i", "--install", nargs='?', const="")
group.add_argument("-u", "--uninstall")
group.add_argument("-l", "--list", action='store_true')
group.add_argument("-r", "--generate-required", action='store_true')
group.add_argument("-h", "--help", action='store_true')
def main():
args = parser.parse_args()
path = args.path
work_dir = get_work_dir(path)
dot_vscode_dir = os.path.join(work_dir, '.vscode')
extensions_dir = os.path.join(dot_vscode_dir, 'extensions')
install_ext = args.install
uninstall_ext = args.uninstall
list_ext = args.list
gen_required = args.generate_required
show_help = args.help
if install_ext is not None:
install(install_ext, extensions_dir)
elif uninstall_ext is not None:
uninstall(uninstall_ext, extensions_dir)
elif list_ext:
list_extensions(extensions_dir)
elif gen_required:
generate_required(extensions_dir)
elif show_help:
print_help()
else:
print("Current working directory: %s" % work_dir)
install_required(extensions_dir)
print("Launching Visual Studio Code...")
code_open(path, extensions_dir)
# --install
def install(extension, extensions_dir):
local_extensions = get_extensions(extensions_dir)
if extension:
if extension in local_extensions:
print("Extension '" + extension + "' is already installed.")
else:
install_extension(extension, extensions_dir)
else:
# no param passed, install required from extensions.json
install_required(extensions_dir)
# --unistall
def uninstall(extension, extensions_dir):
uninstall_extension(extension, extensions_dir)
# --list
def list_extensions(extensions_dir):
extensions = get_extensions(extensions_dir)
for extension in extensions:
base_name = extension_base_name(extension)
print(base_name)
# --generate-required
def generate_required(extensions_dir):
extensions = get_extensions(extensions_dir)
# keep only base name
extensions = [extension_base_name(ext) for ext in extensions]
extensions_json_path = os.path.join(os.path.dirname(extensions_dir), "extensions.json")
if extensions:
extend_required_extensions(extensions_json_path, extensions)
print("Added %d extensions to required extensions:" % len(extensions))
for ext in extensions:
print(ext)
else:
print("No extension added to required extensions.")
# --help
# because argparse help message is formatted ugly
def print_help():
help_file_path = os.path.join(os.path.dirname(__file__), "help.txt")
try:
with open(help_file_path, 'r') as help_file:
print(help_file.read())
except IOError:
try:
ans = input("Did you remove 'help.txt' ?? [y/n]: ")
if ans == 'y':
print("https://i.imgur.com/Br00TCn.gif")
except KeyboardInterrupt:
print("iao!")
def install_required(extensions_dir):
'''
Install required extension (found in extensions.json)
'''
extensions_json_path = extensions_dir + ".json"
required_extensions = get_required_extensions(extensions_json_path)
installed_extensions = get_extensions(extensions_dir)
# keep only base name (remove version) from installed extensions
installed_extensions = [extension_base_name(ext) for ext in installed_extensions]
# install only required extensions that are not already installed
extensions_to_install = list(set(required_extensions) - set(installed_extensions))
if extensions_to_install:
print("Found %d extensions to install:" % len(extensions_to_install))
for ext_to_install in extensions_to_install:
print(ext_to_install)
else:
print("No extension to install.")
for ext in extensions_to_install:
install_extension(ext, extensions_dir) | parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("path", nargs='?', default=os.getcwd()) |
c22.rs | use crate::rng::mt19937::Mt19937;
use std::time::{SystemTime, UNIX_EPOCH};
fn mt19937_first_output_to_seed(output: u64) -> u64 |
#[cfg(test)]
mod tests {
use super::*;
use rand::{self, Rng};
#[test]
fn test_mt19937_brute_force() {
let mut rng = rand::thread_rng();
for _ in 0..100 {
let timestamp_curr = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time to exist");
let timestamp = timestamp_curr.as_secs() - rng.gen_range(40, 1000);
let mut mt = Mt19937::new(timestamp);
assert_eq!(timestamp, mt19937_first_output_to_seed(mt.extract()))
}
}
}
| {
let timestamp_curr = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time to exist");
let timestamp = timestamp_curr.as_secs();
for i in timestamp - 2000..(timestamp) {
let mut mt = Mt19937::new(i);
if mt.extract() == output {
return i
}
}
0
} |
pinger.rs | //! Implements two-state "pinger" task that drives sending pings to the server to check liveness of
//! the connection.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::timeout;
use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::StreamExt;
pub(crate) struct Pinger {
snd_rst: mpsc::Sender<()>,
}
#[derive(Debug)]
pub(crate) enum Event {
SendPing,
Disconnect,
}
enum PingerState {
/// Signal a "ping" on timeout. State moves to `ExpectPong`.
SendPing,
/// Signal a "disconnect" on timeout.
ExpectPong,
}
async fn | (rcv_rst: mpsc::Receiver<()>, snd_ev: mpsc::Sender<Event>) {
let mut rcv_rst_fused = ReceiverStream::new(rcv_rst).fuse();
let mut state = PingerState::SendPing;
loop {
match timeout(Duration::from_secs(60), rcv_rst_fused.next()).await {
Err(_) => match state {
PingerState::SendPing => {
state = PingerState::ExpectPong;
snd_ev.try_send(Event::SendPing).unwrap();
}
PingerState::ExpectPong => {
snd_ev.try_send(Event::Disconnect).unwrap();
return;
}
},
Ok(cmd) => match cmd {
None => {
return;
}
Some(()) => {
state = PingerState::SendPing;
}
},
}
}
}
impl Pinger {
pub(crate) fn new() -> (Pinger, mpsc::Receiver<Event>) {
let (snd_ev, rcv_ev) = mpsc::channel(1);
// No need for sending another "reset" when there's already one waiting to be processed
let (snd_rst, rcv_rst) = mpsc::channel(1);
tokio::task::spawn_local(pinger_task(rcv_rst, snd_ev));
(Pinger { snd_rst }, rcv_ev)
}
pub(crate) fn reset(&mut self) {
// Ignore errors: no need to send another "reset" when there's already one waiting to be
// processed
let _ = self.snd_rst.try_send(());
}
}
| pinger_task |
logic_blocks.py | """Logic Blocks devices."""
from typing import Any, List
from mpf.core.delays import DelayManager
from mpf.core.device_monitor import DeviceMonitor
from mpf.core.events import event_handler
from mpf.core.machine import MachineController
from mpf.core.mode import Mode
from mpf.core.mode_device import ModeDevice
from mpf.core.player import Player
from mpf.core.system_wide_device import SystemWideDevice
from mpf.core.utility_functions import Util
class LogicBlockState:
"""Represents the state of a logic_block."""
__slots__ = ["enabled", "completed", "value"]
def __init__(self, start_value):
"""Initialise state."""
self.enabled = False
self.completed = False
self.value = start_value
@DeviceMonitor("value", "enabled", "completed")
class LogicBlock(SystemWideDevice, ModeDevice):
"""Parent class for each of the logic block classes."""
__slots__ = ["_state", "_start_enabled", "player_state_variable"]
def __init__(self, machine: MachineController, name: str) -> None:
"""Initialize logic block."""
super().__init__(machine, name)
self._state = None # type: LogicBlockState
self._start_enabled = None # type: bool
self.player_state_variable = "{}_state".format(self.name)
'''player_var: (logic_block)_state
desc: A dictionary that stores the internal state of the logic block
with the name (logic_block). (In other words, a logic block called
*mode1_hit_counter* will store its state in a player variable called
``mode1_hit_counter_state``).
The state that's stored in this variable include whether the logic
block is enabled and whether it's complete.
'''
async def _initialize(self):
await super()._initialize()
if self.config['start_enabled'] is not None:
self._start_enabled = self.config['start_enabled']
else:
self._start_enabled = not self.config['enable_events']
def add_control_events_in_mode(self, mode: Mode) -> None:
"""Do not auto enable this device in modes."""
def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict:
"""Validate logic block config."""
del is_mode_config
del debug_prefix
if 'events_when_complete' not in config:
config['events_when_complete'] = ['logicblock_' + self.name + '_complete']
if 'events_when_hit' not in config:
config['events_when_hit'] = ['logicblock_' + self.name + '_hit']
self.machine.config_validator.validate_config(
self.config_section, config, self.name, ("device", "logic_blocks_common"))
self._configure_device_logging(config)
return config
def can_exist_outside_of_game(self) -> bool:
"""Return true if persist_state is not set."""
return not bool(self.config['persist_state'])
def get_start_value(self) -> Any:
"""Return the start value for this block."""
raise NotImplementedError("implement")
async def device_added_system_wide(self):
"""Initialise internal state."""
self._state = LogicBlockState(self.get_start_value())
await super().device_added_system_wide()
if not self.config['enable_events']:
self.enable()
if self.config['persist_state']:
self.raise_config_error("Cannot set persist_state for system-wide logic_blocks", 1)
self.post_update_event()
def device_loaded_in_mode(self, mode: Mode, player: Player):
"""Restore internal state from player if persist_state is set or create new state."""
super().device_loaded_in_mode(mode, player)
if self.config['persist_state']:
if not player.is_player_var(self.player_state_variable):
player[self.player_state_variable] = LogicBlockState(self.get_start_value())
# enable device ONLY when we create a new entry in the player
if self._start_enabled:
mode.add_mode_event_handler("mode_{}_starting".format(mode.name),
self.event_enable, priority=mode.priority + 1)
self._state = player[self.player_state_variable]
else:
self._state = LogicBlockState(self.get_start_value())
if self._start_enabled:
mode.add_mode_event_handler("mode_{}_starting".format(mode.name),
self.event_enable, priority=mode.priority + 1)
mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.post_update_event)
def device_removed_from_mode(self, mode: Mode):
"""Unset internal state to prevent leakage."""
super().device_removed_from_mode(mode)
self._state = None
@property
def value(self):
"""Return value or None if that is currently not possible."""
if self._state:
return self._state.value
return None
@property
def enabled(self):
"""Return if enabled."""
return self._state and self._state.enabled
@enabled.setter
def enabled(self, value):
"""Set enable."""
self._state.enabled = value
@property
def completed(self):
"""Return if completed."""
return self._state and self._state.completed
@completed.setter
def completed(self, value):
"""Set if completed."""
self._state.completed = value
def post_update_event(self, **kwargs):
"""Post an event to notify about changes."""
del kwargs
value = self._state.value
enabled = self._state.enabled
self.machine.events.post("logicblock_{}_updated".format(self.name), value=value, enabled=enabled)
'''event: logicblock_(name)_updated
desc: The logic block called "name" has changed.
This might happen when the block advanced, it was resetted or restored.
args:
value: The current value of this block.
enabled: Whatever this block is enabled or not.
'''
def enable(self):
"""Enable this logic block.
Automatically called when one of the
enable_event events is posted. Can also manually be called.
"""
super().enable()
self.debug_log("Enabling")
self.enabled = True
self.post_update_event()
def _post_hit_events(self, **kwargs):
self.post_update_event()
for event in self.config['events_when_hit']:
self.machine.events.post(event, **kwargs)
'''event: logicblock_(name)_hit
desc: The logic block "name" was just hit.
Note that this is the default hit event for logic blocks,
but this can be changed in a logic block's "events_when_hit:"
setting, so this might not be the actual event that's posted for
all logic blocks in your machine.
args: depend on the type
'''
@event_handler(0)
def event_disable(self, **kwargs):
"""Event handler for disable event."""
del kwargs
self.disable()
def disable(self):
"""Disable this logic block.
Automatically called when one of the
disable_event events is posted. Can also manually be called.
"""
self.debug_log("Disabling")
self.enabled = False
self.post_update_event()
@event_handler(4)
def event_reset(self, **kwargs):
"""Event handler for reset event."""
del kwargs
self.reset()
def reset(self):
"""Reset the progress towards completion of this logic block.
Automatically called when one of the reset_event events is called.
Can also be manually called.
"""
self.completed = False
self._state.value = self.get_start_value()
self.debug_log("Resetting")
self.post_update_event()
@event_handler(5)
def event_restart(self, **kwargs):
"""Event handler for restart event."""
del kwargs
self.restart()
def restart(self):
"""Restart this logic block by calling reset() and enable().
Automatically called when one of the restart_event events is called.
Can also be manually called.
"""
self.debug_log("Restarting (resetting then enabling)")
self.reset()
self.enable()
def complete(self):
"""Mark this logic block as complete.
Posts the 'events_when_complete'
events and optionally restarts this logic block or disables it,
depending on this block's configuration settings.
"""
# if already completed do not complete again
if self.completed:
return
# otherwise mark as completed
self.completed = True
self.debug_log("Complete")
if self.config['events_when_complete']:
for event in self.config['events_when_complete']:
self.machine.events.post(event)
'''event: logicblock_(name)_complete
desc: The logic block called "name" has just been completed.
Note that this is the default completion event for logic blocks, but
this can be changed in a logic block's "events_when_complete:" setting,
so this might not be the actual event that's posted for all logic
blocks in your machine.
'''
# call reset to reset completion
if self.config['reset_on_complete']:
self.reset()
# disable block
if self.config['disable_on_complete']:
self.disable()
class Counter(LogicBlock):
"""A type of LogicBlock that tracks multiple hits of a single event.
This counter can be configured to track hits towards a specific end-goal
(like number of tilt hits to tilt), or it can be an open-ended count (like
total number of ramp shots).
It can also be configured to count up or to count down, and can have a
configurable counting interval.
"""
config_section = 'counters'
collection = 'counters'
class_label = 'counter'
__slots__ = ["delay", "ignore_hits", "hit_value"]
def __init__(self, machine: MachineController, name: str) -> None:
"""Initialise counter."""
super().__init__(machine, name)
self.debug_log("Creating Counter LogicBlock")
self.delay = DelayManager(self.machine)
self.ignore_hits = False
self.hit_value = -1
async def _initialize(self):
await super()._initialize()
self.hit_value = self.config['count_interval']
if self.config['direction'] == 'down' and self.hit_value > 0:
self.hit_value *= -1
elif self.config['direction'] == 'up' and self.hit_value < 0:
self.hit_value *= -1
# Add control events if included in the config
if self.config['control_events']:
self._setup_control_events(self.config['control_events'])
def add_control_events_in_mode(self, mode: Mode) -> None:
"""Do not auto enable this device in modes."""
def _setup_control_events(self, event_list):
self.debug_log("Setting up control events")
kwargs = {}
for entry in event_list:
if entry['action'] in ('add', 'subtract', 'jump'):
handler = getattr(self, "event_{}".format(entry['action']))
kwargs = {'value': entry['value']}
else:
raise AssertionError("Invalid control_event action {} in mode".
format(entry['action']), self.name)
self.machine.events.add_handler(entry['event'], handler, **kwargs)
def check_complete(self, count_complete_value=None):
"""Check if counter is completed.
Return true if the counter has reached or surpassed its specified
completion value, return False if no completion criteria or is
not complete.
"""
# If count_complete_value was not passed, obtain it
if count_complete_value is None and self.config.get("count_complete_value"):
count_complete_value = self.config["count_complete_value"].evaluate([])
if count_complete_value is not None:
if self.config['direction'] == 'up':
return self._state.value >= count_complete_value
if self.config['direction'] == 'down':
return self._state.value <= count_complete_value
return False
def event_add(self, value, **kwargs):
|
def event_subtract(self, value, **kwargs):
"""Subtract from the value of this counter.
Args:
value: Value to subtract from the counter.
kwargs: Additional arguments.
"""
evaluated_value = value.evaluate_or_none(kwargs)
if evaluated_value is None:
self.log.warning("Placeholder %s for counter substract did not evaluate with args %s", value, kwargs)
return
# Subtract from the counter the specified value
self._state.value -= evaluated_value
# Check if count is complete given the updated value
if self.check_complete():
self.complete()
def event_jump(self, value, **kwargs):
"""Set the internal value of the counter.
Args:
value: Value to add to jump to.
kwargs: Additional arguments.
"""
evaluated_value = value.evaluate_or_none(kwargs)
if evaluated_value is None:
self.log.warning("Placeholder %s for counter jump did not evaluate with args %s", value, kwargs)
return
# Set the internal value of the counter to the specified value
self._state.value = evaluated_value
# Check if count is complete given the updated value
if self.check_complete():
self.complete()
def get_start_value(self) -> int:
"""Return start count."""
return self.config['starting_count'].evaluate([])
def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict:
"""Validate logic block config."""
if 'events_when_hit' not in config:
# for compatibility post the same default as previously for
# counters. This one is deprecated.
config['events_when_hit'] = ['counter_' + self.name + '_hit']
# this is the one moving forward
config['events_when_hit'].append('logicblock_' + self.name + '_hit')
return super().validate_and_parse_config(config, is_mode_config, debug_prefix)
@event_handler(0)
def event_count(self, **kwargs):
"""Event handler for count events."""
del kwargs
self.count()
def count(self):
"""Increase the hit progress towards completion.
This method is also automatically called when one of the
``count_events`` is posted.
"""
if not self.enabled:
return
count_complete_value = self.config['count_complete_value'].evaluate([]) if self.config['count_complete_value']\
is not None else None
if not self.ignore_hits:
self._state.value += self.hit_value
self.debug_log("Processing Count change. Total: %s", self._state.value)
args = {
"count": self._state.value
}
if count_complete_value is not None:
args['remaining'] = count_complete_value - self._state.value
self._post_hit_events(**args)
if self.check_complete(count_complete_value):
self.complete()
if self.config['multiple_hit_window']:
self.debug_log("Beginning Ignore Hits")
self.ignore_hits = True
self.delay.add(name='ignore_hits_within_window',
ms=self.config['multiple_hit_window'],
callback=self.stop_ignoring_hits)
def stop_ignoring_hits(self, **kwargs):
"""Cause the Counter to stop ignoring subsequent hits that occur within the 'multiple_hit_window'.
Automatically called when the window time expires. Can safely be manually called.
"""
del kwargs
self.debug_log("Ending Ignore hits")
self.ignore_hits = False
class Accrual(LogicBlock):
"""A type of LogicBlock which tracks many different events (steps) towards a goal.
The steps are able to happen in any order.
"""
config_section = 'accruals'
collection = 'accruals'
class_label = 'accrual'
__slots__ = []
@property
def config_section_name(self):
"""Return config section."""
return "accrual"
def __init__(self, machine, name):
"""Initialise Accrual."""
super().__init__(machine, name)
self.debug_log("Creating Accrual LogicBlock")
async def _initialize(self):
await super()._initialize()
self.setup_event_handlers()
def get_start_value(self) -> List[bool]:
"""Return start states."""
return [False] * len(self.config['events'])
def setup_event_handlers(self):
"""Add event handlers."""
for step, events in enumerate(self.config['events']):
for event in Util.string_to_list(events):
self.machine.events.add_handler(event, self.hit, step=step)
def hit(self, step: int, **kwargs):
"""Increase the hit progress towards completion.
Automatically called
when one of the `count_events` is posted. Can also manually be
called.
Args:
step: Integer of the step number (0 indexed) that was just hit.
"""
del kwargs
if not self.enabled:
return
self.debug_log("Processing hit for step: %s", step)
if not self._state.value[step]:
self._state.value[step] = True
self.debug_log("Status: %s", self._state.value)
self._post_hit_events(step=step)
if self._state.value.count(True) == len(self._state.value):
self.complete()
class Sequence(LogicBlock):
"""A type of LogicBlock which tracks many different events (steps) towards a goal.
The steps have to happen in order.
"""
config_section = 'sequences'
collection = 'sequences'
class_label = 'sequence'
__slots__ = []
@property
def config_section_name(self):
"""Return config section."""
return "sequence"
def __init__(self, machine: MachineController, name: str) -> None:
"""Initialise sequence."""
super().__init__(machine, name)
self.debug_log("Creating Sequence LogicBlock")
async def _initialize(self):
"""Initialise sequence."""
await super()._initialize()
self.setup_event_handlers()
def get_start_value(self) -> int:
"""Return start step."""
return 0
def setup_event_handlers(self):
"""Add the handlers for the current step."""
for step, events in enumerate(self.config['events']):
for event in Util.string_to_list(events):
# increase priority with steps to prevent advancing multiple steps at once
self.machine.events.add_handler(event, self.hit, step=step, priority=step)
def hit(self, step: int = None, **kwargs):
"""Increase the hit progress towards completion.
Automatically called
when one of the `count_events` is posted. Can also manually be
called.
"""
del kwargs
if not self.enabled:
return
if step is not None and step != self._state.value:
# got this for another state
return
self.debug_log("Processing Hit")
self._state.value += 1
self._post_hit_events(step=self._state.value)
if self._state.value >= len(self.config['events']):
self.complete()
| """Add to the value of this counter.
Args:
value: Value to add to the counter.
kwargs: Additional arguments.
"""
evaluated_value = value.evaluate_or_none(kwargs)
if evaluated_value is None:
self.log.warning("Placeholder %s for counter add did not evaluate with args %s", value, kwargs)
return
# Add to the counter the specified value
self._state.value += evaluated_value
# Check if count is complete given the updated value
if self.check_complete():
self.complete() |
ovf2vtk.py | import argparse
import discretisedfield as df
def convert_files(input_files, output_files):
for input_file, output_file in zip(input_files, output_files):
field = df.Field.fromfile(input_file)
field.write(output_file)
| description='ovf2vtk - ovf to VTK format conversion'
)
parser.add_argument('--infile', type=argparse.FileType('r'),
help='One or more input files', nargs='+',
required=True)
parser.add_argument('--outfile', type=argparse.FileType('w'), nargs='+',
help='One or more output files, optional')
args = parser.parse_args()
if args.outfile:
if len(args.infile) == len(args.outfile):
input_files = [f.name for f in args.infile]
output_files = [f.name for f in args.outfile]
else:
print('\nError: The number of input and output '
'files does not match.')
return 0
else:
input_files = [f.name for f in args.infile]
output_files = [f'{f.split(".")[0]}.vtk' for f in input_files]
convert_files(input_files, output_files)
if __name__ == "__main__":
main() |
def main():
parser = argparse.ArgumentParser(
prog='ovf2vtk', |
window.py | from PySide2.QtWidgets import QPushButton, QMainWindow, QLabel, QLineEdit, QGroupBox
from math import ceil
import source
class MainWindow(QMainWindow):
| def __init__(self, screen_width, screen_height):
self.screen_width = screen_width
self.screen_height = screen_height
self.screen_ratio = screen_width / 3840
self.half_screen_ratio = 0.45 + self.screen_ratio / 2
self.production_speed_ratio = 1
self.window = QMainWindow()
self.window.resize(self.screen_width, self.screen_height)
self.window.setWindowTitle('戴森球计划产量计算器 ver.0.1')
self.grid_width = 75 * self.screen_ratio
self.grid_height = 50 * self.screen_ratio
self.init_bias = 50 * self.screen_ratio
self.interval = 0 * self.screen_ratio
self.box_width = self.grid_width * 4 + self.interval + 5 * self.screen_ratio
self.box_height = self.grid_height * 2 + self.init_bias + 5 * self.screen_ratio
# Subtitle: app name - author
self.subtitle_font_size = 50 * self.screen_ratio
if self.screen_ratio > 0.7:
self.subtitle_font_size = 50 * self.screen_ratio / 1.5
subtitle = QLabel(self.window)
subtitle.setText('戴森球计划 材料生产计算器 -- by 魂月')
subtitle.setStyleSheet('QLabel {font: 75 ' + str(int(self.subtitle_font_size)) + 'pt "宋体";}')
subtitle.move(1000 * self.screen_ratio, int(25 * self.screen_ratio))
subtitle.resize(1840 * self.screen_ratio, self.box_height * self.screen_ratio)
# Bottom: 取整机器数量
self.button = QPushButton('取整机器数量', self.window)
self.button.move(2840 * self.screen_ratio, int(25 * self.screen_ratio) + int(self.box_height / 3))
self.button.resize(400 * self.screen_ratio, int(self.box_height / 3))
self.button.setStyleSheet('QPushButton {font: ' + str(int(self.subtitle_font_size / 2)) + 'pt "宋体";}')
self.button.clicked.connect(self.ceil_machine_number)
self.ox = (self.screen_width - 12 * self.box_width) / 2
self.oy = self.box_height + 50 * self.screen_ratio
self.font_size = 14 * self.half_screen_ratio
self.line_edit_font_size = self.font_size * 0.9 * 0.75
self.element = source.element
self.production = source.production
self.supporter = source.support
self.bi_material = source.bi_material
self.sorted_element = source.sorted_element
self.element_box = [[[None, None, None, None] for _ in range(len(self.element[0]))] for _ in range(len(self.element))]
self.element_amount = [[[0, 0, 0, 0] for _ in range(len(self.element[0]))] for _ in range(len(self.element))]
self.table_gen()
for resource in self.sorted_element:
i, j = self.get_idx(resource)
for k in range(4):
self.element_box[i][j][k].editingFinished.connect(self.update_element_amount)
def table_gen(self):
nrows = len(self.element)
ncols = len(self.element[0])
for i in range(nrows):
for j in range(ncols):
foo = self.box_gen(self.ox + j * self.box_width, self.oy + i * self.box_height, self.element[i][j])
if len(foo) == 4:
for k in range(4):
self.element_box[i][j][k] = foo[k]
def box_gen(self, x, y, resource=''):
group_box = QGroupBox(self.window)
group_box.move(x, y)
group_box.resize(self.box_width, self.box_height)
if resource == '':
return []
group_box.setTitle('')
group_box.setStyleSheet('QGroupBox { background-color: \
rgb(255, 255, 255); border: 3px solid rgb(122, 255, 100); } \
QGroupBox::title{font: 75 ' + str(100 * self.screen_ratio) + 'pt "宋体"; color: rgb(255, 0, 0)}')
label_again = QLabel(group_box)
label_again.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"; color: rgb(255, 0, 0)}')
label_again.setText(resource)
label_again.move(int(self.grid_width * 0.7), 5 * self.screen_ratio)
label_again.resize(int(self.grid_width * 3.3), self.init_bias - 5)
product_label00 = QLabel(group_box)
product_label00.setText('产量')
product_label00.move(3, self.init_bias)
product_label00.resize(self.grid_width, self.grid_height)
product_label00.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}')
product00 = QLineEdit(group_box)
product00.setText('0')
product00.move(self.grid_width, self.init_bias)
product00.resize(self.grid_width, self.grid_height)
product00.setEnabled(False)
product00.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}')
product_label10 = QLabel(group_box)
product_label10.setText('额外')
product_label10.move(3, self.grid_height + self.init_bias)
product_label10.resize(self.grid_width, self.grid_height)
product_label10.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}')
product10 = QLineEdit(group_box)
product10.setText('0')
product10.move(self.grid_width, self.grid_height + self.init_bias)
product10.resize(self.grid_width, self.grid_height)
product10.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}')
product_label01 = QLabel(group_box)
product_label01.setText('机器')
product_label01.move(self.grid_width * 2 + self.interval, self.init_bias)
product_label01.resize(self.grid_width, self.grid_height)
product_label01.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}')
product01 = QLineEdit(group_box)
product01.setText('0.0')
product01.move(self.grid_width * 3 + self.interval, self.init_bias)
product01.resize(self.grid_width, self.grid_height)
product01.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}')
product01.setEnabled(False)
product_label11 = QLabel(group_box)
product_label11.setText('已有')
product_label11.move(self.grid_width * 2 + self.interval, self.grid_height + self.init_bias)
product_label11.resize(self.grid_width, self.grid_height)
product_label11.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}')
product11 = QLineEdit(group_box)
product11.setText('0')
product11.move(self.grid_width * 3 + self.interval, self.grid_height + self.init_bias)
product11.resize(self.grid_width, self.grid_height)
product11.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}')
if resource in self.supporter:
product11.setEnabled(True)
else:
product11.setEnabled(False)
return [product00, product01, product10, product11]
# update the window by the values of the self.element_amount.
def update_view(self, is_int=[True, False, True, True]):
for resource in self.sorted_element:
i, j = self.get_idx(resource)
for k in range(4):
amount = round(self.element_amount[i][j][k], 1)
if is_int[k]:
amount = int(self.element_amount[i][j][k])
self.element_box[i][j][k].setText(str(amount))
def get_idx(self, resource):
idx = None
if resource != '':
for i in range(len(self.element)):
for j in range(len(self.element[0])):
if resource == self.element[i][j]:
idx = [i, j]
return idx
def produce_resource(self, resource, increase_production_number):
# Add resource amount in self.element_amount.
idx = self.get_idx(resource)
if not idx:
exit(1)
else:
i, j = idx
self.element_amount[i][j][0] += increase_production_number
production_speed = self.production[resource][0][0]
self.element_amount[i][j][1] += increase_production_number / production_speed
# Start to product required amount of the resource.
component = self.production[resource][1:]
if not component:
return
for obj_resource in component:
production_name = obj_resource[0]
production_number = increase_production_number * obj_resource[1]
self.produce_resource(production_name, production_number)
def calculate_supporter(self):
for supporter, properties in self.supporter.items():
i, j = self.get_idx(supporter)
amount = self.element_amount[i][j][3]
for production in properties:
i, j = self.get_idx(production[0])
production_amount = self.element_amount[i][j][0]
convert_amount_to_production_amount = amount * production[1]
need_negative_production = convert_amount_to_production_amount - production_amount
if need_negative_production > 0:
self.produce_resource(production[0], -1 * production_amount)
else:
self.produce_resource(production[0], -1 * convert_amount_to_production_amount)
def calculate_bi_raw_material(self):
# Calculate the need of the bi_raw_materials.
for material, properties in self.bi_material.items():
# production1
production1 = properties[0][0]
i, j = self.get_idx(production1)
production1_amount = properties[0][1]
need_production1_amount = self.element_amount[i][j][0]
need_material_amount1 = need_production1_amount / production1_amount
# production2
production2 = properties[1][0]
i, j = self.get_idx(production2)
production2_amount = properties[1][1]
need_production2_amount = self.element_amount[i][j][0]
need_material_amount2 = need_production2_amount / production2_amount
# Calculate the need of the material
need_material_amount = max(need_material_amount1, need_material_amount2)
i, j = self.get_idx(material)
self.element_amount[i][j][0] = need_material_amount
material_production_speed = self.production[material][0][0]
self.element_amount[i][j][1] = need_material_amount / material_production_speed
def update_element_amount(self, has_supporter=True):
# Read all LineEdit boxes.
for resource in self.sorted_element:
i, j = self.get_idx(resource)
for k in range(4):
input_value = self.element_box[i][j][k].text()
if k == 0 or k == 1 or input_value == '':
self.element_amount[i][j][k] = 0.0
else:
self.element_amount[i][j][k] = float(input_value)
# Produce the required amount of all resources.
for resource in self.sorted_element:
i, j = self.get_idx(resource)
production_amount = self.element_amount[i][j][2] - self.element_amount[i][j][3]
if production_amount < 0:
self.produce_resource(resource, 0)
else:
self.produce_resource(resource, production_amount)
# Calculate the second product of the special supporter.
if has_supporter:
self.calculate_supporter()
# Calculate the need of the bi_raw_material.
self.calculate_bi_raw_material()
# Update the view of the app.
self.update_view()
def ceil_machine_number(self):
# Re-update element amount without considering supporter.
self.update_element_amount(False)
# Calculate supporter.
supporter_stack = dict()
for support, products in self.supporter.items():
i, j = self.get_idx(support)
support_amount = self.element_amount[i][j][3]
for product in products:
product_name = product[0]
product_amount = product[1]
supporter_stack[product_name] = support_amount * product_amount
# Ceil machine amount and produce the required amount of the resources.
for resource in self.sorted_element:
if resource not in self.supporter:
i, j = self.get_idx(resource)
production_speed = self.production[resource][0][0]
if resource in supporter_stack:
cur_resource_amount = self.element_amount[i][j][0]
real_resource_amount = cur_resource_amount - supporter_stack[resource]
if real_resource_amount > 0:
cur_machine_amount = real_resource_amount / production_speed
new_machine_amount = ceil(cur_machine_amount)
else:
new_machine_amount = 0
else:
cur_machine_amount = self.element_amount[i][j][1]
new_machine_amount = ceil(cur_machine_amount)
cur_resource_amount = self.element_amount[i][j][0]
incre_resource_amount = new_machine_amount * production_speed - cur_resource_amount
self.produce_resource(resource, incre_resource_amount)
self.element_amount[i][j][1] = new_machine_amount
# Calculate the need of the bi_raw_material.
self.calculate_bi_raw_material()
# Update the view of the app.
# Production amount is allowed to be float since its unit is piece/min.
self.update_view([False, True, True, True])
def show(self):
self.window.show()
|
|
kill.rs | use std::{time::Duration, sync::atomic::{AtomicBool, Ordering}};
use tokio::sync::mpsc::{Receiver, Sender, channel};
pub struct Kill {
rx: Receiver<()>,
tx: Sender<()>,
}
impl Kill {
pub fn new() -> Kill {
let (tx, rx) = channel(1);
return Kill {
rx,
tx,
};
}
pub async fn kill(&mut self) {
match self.tx.send(()).await {
_ => {}
}
}
pub async fn wait_for_kill_signal(&mut self) |
}
pub struct Timeout {
pub timedout: AtomicBool,
kill: Kill,
}
impl Timeout {
pub fn new() -> Timeout {
return Timeout {
timedout: AtomicBool::new(false),
kill: Kill::new(),
}
}
pub async fn timeout(&mut self, timeout: Duration) -> bool {
tokio::select! {
_ = tokio::time::sleep(timeout) => {
self.timedout.store(true, Ordering::Relaxed);
},
_ = self.kill.wait_for_kill_signal() => { }
}
return self.timedout.load(Ordering::Relaxed);
}
pub async fn finish(&mut self) {
self.kill.kill().await;
}
}
| {
self.rx.recv().await;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.